Best JavaScript code snippet using fast-check-monorepo
readmdir.py
Source:readmdir.py
1#!/usr/bin/env python32import struct3import binascii4import sys5import itertools as it6TAG_TYPES = {7 'splice': (0x700, 0x400),8 'create': (0x7ff, 0x401),9 'delete': (0x7ff, 0x4ff),10 'name': (0x700, 0x000),11 'reg': (0x7ff, 0x001),12 'dir': (0x7ff, 0x002),13 'superblock': (0x7ff, 0x0ff),14 'struct': (0x700, 0x200),15 'dirstruct': (0x7ff, 0x200),16 'ctzstruct': (0x7ff, 0x202),17 'inlinestruct': (0x7ff, 0x201),18 'userattr': (0x700, 0x300),19 'tail': (0x700, 0x600),20 'softtail': (0x7ff, 0x600),21 'hardtail': (0x7ff, 0x601),22 'gstate': (0x700, 0x700),23 'movestate': (0x7ff, 0x7ff),24 'crc': (0x700, 0x500),25}26class Tag:27 def __init__(self, *args):28 if len(args) == 1:29 self.tag = args[0]30 elif len(args) == 3:31 if isinstance(args[0], str):32 type = TAG_TYPES[args[0]][1]33 else:34 type = args[0]35 if isinstance(args[1], str):36 id = int(args[1], 0) if args[1] not in 'x.' else 0x3ff37 else:38 id = args[1]39 if isinstance(args[2], str):40 size = int(args[2], str) if args[2] not in 'x.' else 0x3ff41 else:42 size = args[2]43 self.tag = (type << 20) | (id << 10) | size44 else:45 assert False46 @property47 def isvalid(self):48 return not bool(self.tag & 0x80000000)49 @property50 def isattr(self):51 return not bool(self.tag & 0x40000000)52 @property53 def iscompactable(self):54 return bool(self.tag & 0x20000000)55 @property56 def isunique(self):57 return not bool(self.tag & 0x10000000)58 @property59 def type(self):60 return (self.tag & 0x7ff00000) >> 2061 @property62 def type1(self):63 return (self.tag & 0x70000000) >> 2064 @property65 def type3(self):66 return (self.tag & 0x7ff00000) >> 2067 @property68 def id(self):69 return (self.tag & 0x000ffc00) >> 1070 @property71 def size(self):72 return (self.tag & 0x000003ff) >> 073 @property74 def dsize(self):75 return 4 + (self.size if self.size != 0x3ff else 0)76 @property77 def chunk(self):78 return self.type & 0xff79 @property80 def schunk(self):81 return struct.unpack('b', struct.pack('B', self.chunk))[0]82 def is_(self, type):83 return (self.type & TAG_TYPES[type][0]) == TAG_TYPES[type][1]84 def mkmask(self):85 return Tag(86 0x700 if self.isunique else 0x7ff,87 0x3ff if self.isattr else 0,88 0)89 def chid(self, nid):90 ntag = Tag(self.type, nid, self.size)91 if hasattr(self, 'off'): ntag.off = self.off92 if hasattr(self, 'data'): ntag.data = self.data93 if hasattr(self, 'crc'): ntag.crc = self.crc94 return ntag95 def typerepr(self):96 if self.is_('crc') and getattr(self, 'crc', 0xffffffff) != 0xffffffff:97 return 'crc (bad)'98 reverse_types = {v: k for k, v in TAG_TYPES.items()}99 for prefix in range(12):100 mask = 0x7ff & ~((1 << prefix)-1)101 if (mask, self.type & mask) in reverse_types:102 type = reverse_types[mask, self.type & mask]103 if prefix > 0:104 return '%s %#0*x' % (105 type, prefix//4, self.type & ((1 << prefix)-1))106 else:107 return type108 else:109 return '%02x' % self.type110 def idrepr(self):111 return repr(self.id) if self.id != 0x3ff else '.'112 def sizerepr(self):113 return repr(self.size) if self.size != 0x3ff else 'x'114 def __repr__(self):115 return 'Tag(%r, %d, %d)' % (self.typerepr(), self.id, self.size)116 def __lt__(self, other):117 return (self.id, self.type) < (other.id, other.type)118 def __bool__(self):119 return self.isvalid120 def __int__(self):121 return self.tag122 def __index__(self):123 return self.tag124class MetadataPair:125 def __init__(self, blocks):126 if len(blocks) > 1:127 self.pair = [MetadataPair([block]) for block in blocks]128 self.pair = sorted(self.pair, reverse=True)129 self.data = self.pair[0].data130 self.rev = self.pair[0].rev131 self.tags = self.pair[0].tags132 self.ids = self.pair[0].ids133 self.log = self.pair[0].log134 self.all_ = self.pair[0].all_135 return136 self.pair = [self]137 self.data = blocks[0]138 block = self.data139 self.rev, = struct.unpack('<I', block[0:4])140 crc = binascii.crc32(block[0:4])141 # parse tags142 corrupt = False143 tag = Tag(0xffffffff)144 off = 4145 self.log = []146 self.all_ = []147 while len(block) - off >= 4:148 ntag, = struct.unpack('>I', block[off:off+4])149 tag = Tag(int(tag) ^ ntag)150 tag.off = off + 4151 tag.data = block[off+4:off+tag.dsize]152 if tag.is_('crc'):153 crc = binascii.crc32(block[off:off+4+4], crc)154 else:155 crc = binascii.crc32(block[off:off+tag.dsize], crc)156 tag.crc = crc157 off += tag.dsize158 self.all_.append(tag)159 if tag.is_('crc'):160 # is valid commit?161 if crc != 0xffffffff:162 corrupt = True163 if not corrupt:164 self.log = self.all_.copy()165 # reset tag parsing166 crc = 0167 tag = Tag(int(tag) ^ ((tag.type & 1) << 31))168 # find active ids169 self.ids = list(it.takewhile(170 lambda id: Tag('name', id, 0) in self,171 it.count()))172 # find most recent tags173 self.tags = []174 for tag in self.log:175 if tag.is_('crc') or tag.is_('splice'):176 continue177 elif tag.id == 0x3ff:178 if tag in self and self[tag] is tag:179 self.tags.append(tag)180 else:181 # id could have change, I know this is messy and slow182 # but it works183 for id in self.ids:184 ntag = tag.chid(id)185 if ntag in self and self[ntag] is tag:186 self.tags.append(ntag)187 self.tags = sorted(self.tags)188 def __bool__(self):189 return bool(self.log)190 def __lt__(self, other):191 # corrupt blocks don't count192 if not self or not other:193 return bool(other)194 # use sequence arithmetic to avoid overflow195 return not ((other.rev - self.rev) & 0x80000000)196 def __contains__(self, args):197 try:198 self[args]199 return True200 except KeyError:201 return False202 def __getitem__(self, args):203 if isinstance(args, tuple):204 gmask, gtag = args205 else:206 gmask, gtag = args.mkmask(), args207 gdiff = 0208 for tag in reversed(self.log):209 if (gmask.id != 0 and tag.is_('splice') and210 tag.id <= gtag.id - gdiff):211 if tag.is_('create') and tag.id == gtag.id - gdiff:212 # creation point213 break214 gdiff += tag.schunk215 if ((int(gmask) & int(tag)) ==216 (int(gmask) & int(gtag.chid(gtag.id - gdiff)))):217 if tag.size == 0x3ff:218 # deleted219 break220 return tag221 raise KeyError(gmask, gtag)222 def _dump_tags(self, tags, f=sys.stdout, truncate=True):223 f.write("%-8s %-8s %-13s %4s %4s" % (224 'off', 'tag', 'type', 'id', 'len'))225 if truncate:226 f.write(' data (truncated)')227 f.write('\n')228 for tag in tags:229 f.write("%08x: %08x %-13s %4s %4s" % (230 tag.off, tag,231 tag.typerepr(), tag.idrepr(), tag.sizerepr()))232 if truncate:233 f.write(" %-23s %-8s\n" % (234 ' '.join('%02x' % c for c in tag.data[:8]),235 ''.join(c if c >= ' ' and c <= '~' else '.'236 for c in map(chr, tag.data[:8]))))237 else:238 f.write("\n")239 for i in range(0, len(tag.data), 16):240 f.write(" %08x: %-47s %-16s\n" % (241 tag.off+i,242 ' '.join('%02x' % c for c in tag.data[i:i+16]),243 ''.join(c if c >= ' ' and c <= '~' else '.'244 for c in map(chr, tag.data[i:i+16]))))245 def dump_tags(self, f=sys.stdout, truncate=True):246 self._dump_tags(self.tags, f=f, truncate=truncate)247 def dump_log(self, f=sys.stdout, truncate=True):248 self._dump_tags(self.log, f=f, truncate=truncate)249 def dump_all(self, f=sys.stdout, truncate=True):250 self._dump_tags(self.all_, f=f, truncate=truncate)251def main(args):252 blocks = []253 with open(args.disk, 'rb') as f:254 for block in [args.block1, args.block2]:255 if block is None:256 continue257 f.seek(block * args.block_size)258 blocks.append(f.read(args.block_size)259 .ljust(args.block_size, b'\xff'))260 # find most recent pair261 mdir = MetadataPair(blocks)262 try:263 mdir.tail = mdir[Tag('tail', 0, 0)]264 if mdir.tail.size != 8 or mdir.tail.data == 8*b'\xff':265 mdir.tail = None266 except KeyError:267 mdir.tail = None268 print("mdir {%s} rev %d%s%s%s" % (269 ', '.join('%#x' % b270 for b in [args.block1, args.block2]271 if b is not None),272 mdir.rev,273 ' (was %s)' % ', '.join('%d' % m.rev for m in mdir.pair[1:])274 if len(mdir.pair) > 1 else '',275 ' (corrupted!)' if not mdir else '',276 ' -> {%#x, %#x}' % struct.unpack('<II', mdir.tail.data)277 if mdir.tail else ''))278 if args.all:279 mdir.dump_all(truncate=not args.no_truncate)280 elif args.log:281 mdir.dump_log(truncate=not args.no_truncate)282 else:283 mdir.dump_tags(truncate=not args.no_truncate)284 return 0 if mdir else 1285if __name__ == "__main__":286 import argparse287 import sys288 parser = argparse.ArgumentParser(289 description="Dump useful info about metadata pairs in littlefs.")290 parser.add_argument('disk',291 help="File representing the block device.")292 parser.add_argument('block_size', type=lambda x: int(x, 0),293 help="Size of a block in bytes.")294 parser.add_argument('block1', type=lambda x: int(x, 0),295 help="First block address for finding the metadata pair.")296 parser.add_argument('block2', nargs='?', type=lambda x: int(x, 0),297 help="Second block address for finding the metadata pair.")298 parser.add_argument('-l', '--log', action='store_true',299 help="Show tags in log.")300 parser.add_argument('-a', '--all', action='store_true',301 help="Show all tags in log, included tags in corrupted commits.")302 parser.add_argument('-T', '--no-truncate', action='store_true',303 help="Don't truncate large amounts of data.")...
readtree.py
Source:readtree.py
1#!/usr/bin/env python32import struct3import sys4import json5import io6import itertools as it7from readmdir import Tag, MetadataPair8def main(args):9 superblock = None10 gstate = b'\0\0\0\0\0\0\0\0\0\0\0\0'11 dirs = []12 mdirs = []13 corrupted = []14 cycle = False15 with open(args.disk, 'rb') as f:16 tail = (args.block1, args.block2)17 hard = False18 while True:19 for m in it.chain((m for d in dirs for m in d), mdirs):20 if set(m.blocks) == set(tail):21 # cycle detected22 cycle = m.blocks23 if cycle:24 break25 # load mdir26 data = []27 blocks = {}28 for block in tail:29 f.seek(block * args.block_size)30 data.append(f.read(args.block_size)31 .ljust(args.block_size, b'\xff'))32 blocks[id(data[-1])] = block33 mdir = MetadataPair(data)34 mdir.blocks = tuple(blocks[id(p.data)] for p in mdir.pair)35 # fetch some key metadata as a we scan36 try:37 mdir.tail = mdir[Tag('tail', 0, 0)]38 if mdir.tail.size != 8 or mdir.tail.data == 8*b'\xff':39 mdir.tail = None40 except KeyError:41 mdir.tail = None42 # have superblock?43 try:44 nsuperblock = mdir[45 Tag(0x7ff, 0x3ff, 0), Tag('superblock', 0, 0)]46 superblock = nsuperblock, mdir[Tag('inlinestruct', 0, 0)]47 except KeyError:48 pass49 # have gstate?50 try:51 ngstate = mdir[Tag('movestate', 0, 0)]52 gstate = bytes((a or 0) ^ (b or 0)53 for a,b in it.zip_longest(gstate, ngstate.data))54 except KeyError:55 pass56 # corrupted?57 if not mdir:58 corrupted.append(mdir)59 # add to directories60 mdirs.append(mdir)61 if mdir.tail is None or not mdir.tail.is_('hardtail'):62 dirs.append(mdirs)63 mdirs = []64 if mdir.tail is None:65 break66 tail = struct.unpack('<II', mdir.tail.data)67 hard = mdir.tail.is_('hardtail')68 # find paths69 dirtable = {}70 for dir in dirs:71 dirtable[frozenset(dir[0].blocks)] = dir72 pending = [("/", dirs[0])]73 while pending:74 path, dir = pending.pop(0)75 for mdir in dir:76 for tag in mdir.tags:77 if tag.is_('dir'):78 try:79 npath = tag.data.decode('utf8')80 dirstruct = mdir[Tag('dirstruct', tag.id, 0)]81 nblocks = struct.unpack('<II', dirstruct.data)82 nmdir = dirtable[frozenset(nblocks)]83 pending.append(((path + '/' + npath), nmdir))84 except KeyError:85 pass86 dir[0].path = path.replace('//', '/')87 # print littlefs + version info88 version = ('?', '?')89 if superblock:90 version = tuple(reversed(91 struct.unpack('<HH', superblock[1].data[0:4].ljust(4, b'\xff'))))92 print("%-47s%s" % ("littlefs v%s.%s" % version,93 "data (truncated, if it fits)"94 if not any([args.no_truncate, args.log, args.all]) else ""))95 # print gstate96 print("gstate 0x%s" % ''.join('%02x' % c for c in gstate))97 tag = Tag(struct.unpack('<I', gstate[0:4].ljust(4, b'\xff'))[0])98 blocks = struct.unpack('<II', gstate[4:4+8].ljust(8, b'\xff'))99 if tag.size or not tag.isvalid:100 print(" orphans >=%d" % max(tag.size, 1))101 if tag.type:102 print(" move dir {%#x, %#x} id %d" % (103 blocks[0], blocks[1], tag.id))104 # print mdir info105 for i, dir in enumerate(dirs):106 print("dir %s" % (json.dumps(dir[0].path)107 if hasattr(dir[0], 'path') else '(orphan)'))108 for j, mdir in enumerate(dir):109 print("mdir {%#x, %#x} rev %d (was %d)%s%s" % (110 mdir.blocks[0], mdir.blocks[1], mdir.rev, mdir.pair[1].rev,111 ' (corrupted!)' if not mdir else '',112 ' -> {%#x, %#x}' % struct.unpack('<II', mdir.tail.data)113 if mdir.tail else ''))114 f = io.StringIO()115 if args.log:116 mdir.dump_log(f, truncate=not args.no_truncate)117 elif args.all:118 mdir.dump_all(f, truncate=not args.no_truncate)119 else:120 mdir.dump_tags(f, truncate=not args.no_truncate)121 lines = list(filter(None, f.getvalue().split('\n')))122 for k, line in enumerate(lines):123 print("%s %s" % (124 ' ' if j == len(dir)-1 else125 'v' if k == len(lines)-1 else126 '|',127 line))128 errcode = 0129 for mdir in corrupted:130 errcode = errcode or 1131 print("*** corrupted mdir {%#x, %#x}! ***" % (132 mdir.blocks[0], mdir.blocks[1]))133 if cycle:134 errcode = errcode or 2135 print("*** cycle detected {%#x, %#x}! ***" % (136 cycle[0], cycle[1]))137 return errcode138if __name__ == "__main__":139 import argparse140 import sys141 parser = argparse.ArgumentParser(142 description="Dump semantic info about the metadata tree in littlefs")143 parser.add_argument('disk',144 help="File representing the block device.")145 parser.add_argument('block_size', type=lambda x: int(x, 0),146 help="Size of a block in bytes.")147 parser.add_argument('block1', nargs='?', default=0,148 type=lambda x: int(x, 0),149 help="Optional first block address for finding the superblock.")150 parser.add_argument('block2', nargs='?', default=1,151 type=lambda x: int(x, 0),152 help="Optional second block address for finding the superblock.")153 parser.add_argument('-l', '--log', action='store_true',154 help="Show tags in log.")155 parser.add_argument('-a', '--all', action='store_true',156 help="Show all tags in log, included tags in corrupted commits.")157 parser.add_argument('-T', '--no-truncate', action='store_true',158 help="Show the full contents of files/attrs/tags.")...
urltest.py
Source:urltest.py
1#2import re # regular expression3import requests4#url = 'http://www.baidu.com'5#url = 'https://search.jd.com/Search?keyword=shell&enc=utf-8&wq=shell&pvid=74ab31bb5135476389e063debe4458c4'6#url = 'http://search.yhd.com/c0-0-1004212/'7url = 'https://list.jd.com/list.html?cat=9987,653,655&ev=exbrand_18374&sort=sort_rank_asc&trans=1&JL=3_%E5%93%81%E7%89%8C_%E5%B0%8F%E7%B1%B3%EF%BC%88MI%EF%BC%89#J_crumbsBar'8html = requests.get(url).text9#pattern = '<img.*?src="(.*?)" />'10#pattern = '<img[\w ="/.-]+src="'11#pattern = '<img[\w ="/.-]+src="([\w\/.]+)" />'12#pattern = 'class="promo-words"'13#pattern = '<img alt="" src="([\w/.]+)">'14pattern = 'data-lazy-img="([\w/.]+)">'15pic_url = re.findall(pattern, html)16print '%d image url found' % len(pic_url)17i = 018for each in pic_url:19 print each20 pic = requests.get('http:' + each)21 fp = open('./mi/' + str(i) + '.jpg', 'wb')22 fp.write(pic.content)23 fp.close()...
douban.py
Source:douban.py
1#coding=utf-82import re3import requests4target = 'https://movie.douban.com/cinema/nowplaying/beijing/'5source = requests.get(target).text6pattern = u'data-title="([\w\u4e00-\u9fa5]+)".*?data-score="([\w.]+)"'7films = re.findall(pattern, source, re.S)8# high score on top9films = sorted(films, key = lambda x: x[1], reverse = True)10print '%d films found.' % len(films)11for film in films:12 name = repr(film[0]).replace('u\'', '\'')13 name = name.decode('unicode-escape')...
App.js
Source:App.js
1import "./App.css";2import axios from "axios";3import { useEffect, useState } from "react";4const URL = "http://localhost:3001";5function App() {6 const [message, setMessage] = useState("test");7 useEffect(() => {8 axios9 .get(URL)10 .then((response) => {11 console.log(response.data);12 setMessage(response.data.message);13 })14 .catch((error) => {15 setMessage(error);16 });17 }, []);18 return <p>{message}</p>;19}...
index.js
Source:index.js
1import React from "react";2import ReactDOM from "react-dom/client";3import "./index.css";4import App from "./App";5// import reportWebVitals from "./reportWebVitals";6const root = ReactDOM.createRoot(document.getElementById("root"));7root.render(8 <React.StrictMode>9 <App />10 </React.StrictMode>11);...
test.py
Source:test.py
...
__init__.py
Source:__init__.py
1undefined
Using AI Code Generation
1const { c } = require("fast-check-monorepo");2console.log(c());3const { d } = require("fast-check-monorepo");4console.log(d());5const { c } = require("fast-check-monorepo");6console.log(c());7const { d } = require("fast-check-monorepo");8console.log(d());
Using AI Code Generation
1const { c } = require("fast-check-monorepo");2const { a } = require("fast-check-monorepo");3const { b } = require("fast-check-monorepo");4const { d } = require("fast-check-monorepo");5const { e } = require("fast-check-monorepo");6const { f } = require("fast-check-monorepo");7const { g } = require("fast-check-monorepo");8const { h } = require("fast-check-monorepo");9const { i } = require("fast-check-monorepo");10const { j } = require("fast-check-monorepo");11const { k } = require("fast-check-monorepo");12const { l } = require("fast-check-monorepo");13const { m } = require("fast-check-monorepo");14const { n } = require("fast-check-monorepo");15const { o } = require("fast-check-monorepo");16const { p } = require("fast-check-monorepo");17const { q } = require("fast-check-monorepo");18const { r } = require("fast-check-monorepo");19const { s } = require("fast-check-monorepo");20const { t }
Using AI Code Generation
1const { c } = require('fast-check-monorepo');2console.log(c());3const { d } = require('fast-check-monorepo');4console.log(d());5const { e } = require('fast-check-monorepo');6console.log(e());7const { f } = require('fast-check-monorepo');8console.log(f());9const { g } = require('fast-check-monorepo');10console.log(g());11const { h } = require('fast-check-monorepo');12console.log(h());13const { i } = require('fast-check-monorepo');14console.log(i());15const { j } = require('fast-check-monorepo');16console.log(j());17const { k } = require('fast-check-monorepo');18console.log(k());19const { l } = require('fast-check-monorepo');20console.log(l());21const { m } = require('fast-check-monorepo');22console.log(m());23const { n } = require('fast-check-monorepo');24console.log(n());
Using AI Code Generation
1const fc = require('fast-check');2fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a), { verbose: true });3 after 1 tests and 1 shrinks (seed: 1578841551545)4 Got error: Error: Property failed after 1 tests (shrunk once)5 Error: Property failed after 1 tests (shrunk once)6 Error: Property failed after 1 tests (shrunk once)7 Error: Property failed after 1 tests (shrunk once)8 Error: Property failed after 1 tests (shrunk once)9 Error: Property failed after 1 tests (shrunk once)10 Error: Property failed after 1 tests (shrunk once)11 Error: Property failed after 1 tests (shrunk once)12 Error: Property failed after 1 tests (shrunk once)13 Error: Property failed after 1 tests (shrunk once)14 Error: Property failed after 1 tests (shrunk once)15 Error: Property failed after 1 tests (shrunk once)16 Error: Property failed after 1 tests (shrunk
Using AI Code Generation
1const c = require('fast-check-monorepo/c');2const fc = require('fast-check');3const arb = fc.tuple(fc.integer(), fc.string(), fc.boolean(), fc.double());4fc.assert(5 fc.property(arb, ([a, b, c, d]) => {6 return a + b + c + d === a + b + c + d;7 })8);
Using AI Code Generation
1const {c} = require("fast-check-monorepo");2const {property} = require("fast-check");3const {f} = require("./test2");4property("f(c) = c", c(), c(), (a, b) => {5 return f(a, b) === a;6});7This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
Using AI Code Generation
1const { c } = require('fast-check-monorepo');2c('test3', () => {3 expect(1).toBe(1);4});5const { fc } = require('fast-check-monorepo');6fc('test', () => {7 expect(1).toBe(1);8});9const { c } = require('fast-check-monorepo');10c('test2', () => {11 expect(1).toBe(1);12});13- `numRuns` (default to `100`): number of runs to perform14- `verbose` (default to `false`): whether to display logs or not15- `seed` (default to `Date.now()`): seed to use in order to reproduce a particular run16- `endOnFailure` (default to `false`): whether to stop the execution when a failure is detected17- `examples` (default to `[]`): examples to display in case of failure18- `examplesPath` (default to `undefined`): path to the file containing the examples to display in case of failure19- `examplesPathFromRoot` (default to `undefined`): path to the file containing the examples to display in case of failure (from the root of the project)20- `examplesPathFromProject` (default to `undefined`): path to the file containing the examples to display in case of failure (
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!