code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def shortest_path(source, target): <NEW_LINE> <INDENT> explored = ExploredSet() <NEW_LINE> target_movies = people[target]["movies"] <NEW_LINE> node = Node(source, None, None) <NEW_LINE> frontier = QueueFrontier() <NEW_LINE> while True: <NEW_LINE> <INDENT> for movie in people[node.state]["movies"]: <NEW_LINE> <INDENT> i...
Returns the shortest list of (movie_id, person_id) pairs that connect the source to the target. If no possible path, returns None.
625941d4091ae3566866714c
def averageOfLevels(self, root): <NEW_LINE> <INDENT> myQuary = [] <NEW_LINE> myQuary.append(root) <NEW_LINE> result=[] <NEW_LINE> def searchchild(notelist): <NEW_LINE> <INDENT> list=[] <NEW_LINE> if notelist.left != None: <NEW_LINE> <INDENT> list.append(notelist.left) <NEW_LINE> <DEDENT> if notelist.right != None: <NEW...
:type root: TreeNode :rtype: List[float]
625941d45fcc89381b1e18b0
def set_description(self, room_description): <NEW_LINE> <INDENT> self.description = room_description
Sets the description of the room. Inputs: room_description, a textual description of the room
625941d4f548e778e58cd76e
def sub_lookups(self, script, old_key, old_val, new_key, new_val): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(script, list): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if (len(script) == 2 and isinstance(script[0], str) and isinstance(script[1], str) and script[0] == old_key and script[1] == old_val):...
Substitute lookup key/value names throughout a script. Given a script, recursively substitute ``[old_key, old_val]`` lookups with [new_key, new_val] lookups everywhere. NOTE: This method, in its current form, will modify the input script object! :param script: The parsed YAML script. :type script: dict or :class:`ru...
625941d4dd821e528d63b398
def make_text_entry(self, root): <NEW_LINE> <INDENT> text_fields = [] <NEW_LINE> for field in self.fields: <NEW_LINE> <INDENT> row = Frame(root) <NEW_LINE> lab = Label(row, width=12, text=field, anchor='w') <NEW_LINE> ent = Entry(row, width=50) <NEW_LINE> row.pack(side=TOP, fill=X, padx=5, pady=5) <NEW_LINE> lab.pack(s...
loops over Fields, creating label and text box for each. Returns a list allowing them to be accessed
625941d4cad5886f8bd271c9
def test_solution(self): <NEW_LINE> <INDENT> post = Post.objects.create( title='asd', preview='fsd', content='esd', author=self.root, ) <NEW_LINE> comment = Comment.objects.create( post=post, author=self.root, content='asdfg', ) <NEW_LINE> with self.assertRaises(NotQuestionError): <NEW_LINE> <INDENT> post.set_solution(...
Test question sulution
625941d4ab23a570cc250373
def exportCyExpression(obj, attributes, filename = '-'): <NEW_LINE> <INDENT> if filename == '-': <NEW_LINE> <INDENT> arq = sys.stdout <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arq = open(filename, 'w') <NEW_LINE> arq.write('GENE') <NEW_LINE> <DEDENT> for name in attributes: <NEW_LINE> <INDENT> arq.write('\t'+name) ...
Exports expression to Cytoscape expression data format @param obj: network @param filename: .pvals file
625941d4a17c0f6771cbe240
def send(self, data): <NEW_LINE> <INDENT> self.socket.sendall(bytes(data + "&", "utf-8"))
send data to server
625941d44428ac0f6e5ba9e3
def readConfiguration(): <NEW_LINE> <INDENT> configPath = '%s/configuration.json' % settings.BOOKI_ROOT <NEW_LINE> try: <NEW_LINE> <INDENT> f = open(configPath, 'r') <NEW_LINE> data = f.read() <NEW_LINE> f.close() <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise ConfigurationError("Can't read file %s." % c...
Reads configuration file and returns content as a dictionary. @rtype: C{dict} @return: Returns dictionary with all the values
625941d423849d37ff7b327e
def jacobian(theta, mu, lmbda): <NEW_LINE> <INDENT> return f ** 3 * sinh(lmbda) * sin(mu) * (sinh(lmbda) ** 2 + sin(mu) ** 2)
Compute sqrt(det(G_ij)), where G_ij is the covariant metric tensor for the transformation from prolate-spheroid coordinates to rectangular cartesian
625941d4dc8b845886cb5726
def __repr__ (self): <NEW_LINE> <INDENT> return '<{0:s}: ({1:d}, {2:s})>'.format(self.__class__.__name__, self.__i, repr(self.__ime))
Dohvati repr(self).
625941d4379a373c97cfad35
def Box(self, x, y, w, h): <NEW_LINE> <INDENT> pts = [[x - w/2, y - h/2], [x + w/2, y - h/2], [x + w/2, y + h/2], [x - w/2, y + h/2], [x - w/2, y - h/2]] <NEW_LINE> self.Polyline(pts)
! Draw a rectangular box, centred at (x,y), with given width and height @param x: the x co-ordinate of the box's centre @param y: the y co-ordinate of the box's centre @param w: the width of the box @param h: the height of the box
625941d47d43ff24873a2e90
def read_metadata(self, handler): <NEW_LINE> <INDENT> self.metadata = handler.read_metadata(self.cname)
retrieve the metadata for this columns
625941d49c8ee82313fbb965
def __sub__(self, *args): <NEW_LINE> <INDENT> return _itkVariableLengthVectorPython.itkVariableLengthVectorF___sub__(self, *args)
__sub__(self, float s) -> itkVariableLengthVectorF
625941d491f36d47f21ac6e4
@lru_cache() <NEW_LINE> def find_project_root(srcs: Iterable[str]) -> Path: <NEW_LINE> <INDENT> if not srcs: <NEW_LINE> <INDENT> return Path("/").resolve() <NEW_LINE> <DEDENT> path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs] <NEW_LINE> src_parents = [list(path.parents) + ([path] if path.is_dir() else []) f...
Return a directory containing .git, or robotidy.toml. That directory will be a common parent of all files and directories passed in `srcs`. If no directory in the tree contains a marker that would specify it's the project root, the root of the file system is returned.
625941d499cbb53fe6792dd6
def __str__(self) -> str: <NEW_LINE> <INDENT> string = "%s\n%s\n%s\n%s\nScore: %0.3F Solved: %s" % ( str([mol.smiles for mol in self.mols]), str([mol.transform for mol in self.mols]), str([mol.parent.smiles if mol.parent else "-" for mol in self.mols]), str(self.in_stock_list), self.score, self.is_solved, ) <NEW_LINE> ...
A string representation of the state (for print(state))
625941d4187af65679ca530f
def add_user_zonefile_url(user_zonefile, url): <NEW_LINE> <INDENT> from .zonefile import url_to_uri_record <NEW_LINE> assert is_user_zonefile(user_zonefile) <NEW_LINE> assert re.match(OP_URI_TARGET_PATTERN, url) <NEW_LINE> user_zonefile.setdefault('uri', []) <NEW_LINE> for urirec in user_zonefile['uri']: <NEW_LINE> <IN...
Add a url to a zonefile Return the new zonefile on success Return None on error or on duplicate URL
625941d494891a1f4081bc9a
def repeat_result(ret): <NEW_LINE> <INDENT> return np.concatenate((ret, ret), axis=1)
复制第一周结果接在第一周结果之后,在首列之前加入shop_id列
625941d47d847024c06be4ae
def balance_data_oversampling_smote_borderline2(self): <NEW_LINE> <INDENT> x = self.X <NEW_LINE> y = self.y <NEW_LINE> y.shape = (len(self.y)) <NEW_LINE> verbose = True <NEW_LINE> sm = SMOTE(kind = 'borderline2', verbose = verbose) <NEW_LINE> svmx, svmy = sm.fit_transform(x, y) <NEW_LINE> self.X = svmx <NEW_LINE> self....
Balance data using SMOTE bordeline 2.
625941d42ae34c7f2600d321
def argumentDefinition(self): <NEW_LINE> <INDENT> return self.__argument_definition
@rtype: ArgumentDefinition
625941d416aa5153ce362668
def update_geo_chrono(self): <NEW_LINE> <INDENT> pass
geos = Geospaceold.objects.all() for geo in geos: record = {'uuid': geo.uuid, 'project_uuid': geo.project_uuid, 'source_id': 'ArchaeoML doc', 'item_type': 'subjects', 'feature_id': geo.fid, 'meta_type': geo.meta_type, 'ftype': geo.f...
625941d4f9cc0f698b1407ea
def test_download_using_import_export_generic_view(self): <NEW_LINE> <INDENT> response = self.client.get('/abc_import_export/?format=yaml') <NEW_LINE> content = ( b'- id: 1\n name: me\n- id: 2\n name: you\n' b'- id: 3\n name: him\n- id: 4\n name: her\n' ) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_...
Download a file using generic view.
625941d423849d37ff7b327f
def push(self, item): <NEW_LINE> <INDENT> new_max = item <NEW_LINE> if (not self.is_empty()) and (self.get_max() > item): <NEW_LINE> <INDENT> new_max = self.get_max() <NEW_LINE> <DEDENT> super(MaxStack2, self).push((item, new_max)) <NEW_LINE> return
push/put new object into the stack
625941d4f8510a7c17cf98ec
@permission_required(['czn', ]) <NEW_LINE> def employer_save(request, employer_id): <NEW_LINE> <INDENT> current_profile = get_object_or_404(UserProfile, user=request.user) <NEW_LINE> if request.POST: <NEW_LINE> <INDENT> employer = get_object_or_404(Employer, id=employer_id) <NEW_LINE> formset = FormEmployerNew(request....
:param request: :param employer_id: :return:
625941d4d6c5a1020814423c
def main(): <NEW_LINE> <INDENT> cmd_args = parse_args() <NEW_LINE> setup_logging(cmd_args) <NEW_LINE> logger.info("Starting up.") <NEW_LINE> try: <NEW_LINE> <INDENT> dispatcher = Dispatcher(cmd_args.config_file, publish_port=cmd_args.pub_port, publish_nameservers=cmd_args.pub_nameservers) <NEW_LINE> <DEDENT> except Exc...
Start and run the dispatcher.
625941d467a9b606de4a80a9
def PgTime(hour, minute, second): <NEW_LINE> <INDENT> return Time(hour, minute, second)
Construct an object holding a time value. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.time`
625941d4a934411ee3751884
def match(self,instr): <NEW_LINE> <INDENT> return self._match(instr)
Indica si aquesta instància s'identifica amb l'opcode contingut a instr :param instr: :class:`bitVector.Word` que denota una instrucció :return: Retorna True ssi aquesta instància pot executar la instrucció instr.
625941d429b78933be1e589a
def download_to_cache(meta, config): <NEW_LINE> <INDENT> print('Source cache directory is: %s' % config.src_cache) <NEW_LINE> if not isdir(config.src_cache): <NEW_LINE> <INDENT> os.makedirs(config.src_cache) <NEW_LINE> <DEDENT> fn = meta['fn'] if 'fn' in meta else basename(meta['url']) <NEW_LINE> path = join(config.src...
Download a source to the local cache.
625941d43617ad0b5ed680e6
def calc_crc_byte_array(st, start_crc=0xFFFF): <NEW_LINE> <INDENT> for ch in st: <NEW_LINE> <INDENT> start_crc = (start_crc >> 8) ^ CRC_TABLE[(start_crc ^ ch) & 0xFF] <NEW_LINE> <DEDENT> crcb = bytearray(2) <NEW_LINE> crcb[1] = int(start_crc / 256) <NEW_LINE> crcb[0] = start_crc % 256 <NEW_LINE> return crcb
Given a byte array and starting CRC, Calc a final CRC-16
625941d4adb09d7d5db6c97f
def __init__(self): <NEW_LINE> <INDENT> raise NotImplementedError('DebianPackager is a static class')
Dummy init method, DebianPackager is static
625941d4ad47b63b2c50a170
def getFormattedResult(self, specs=None): <NEW_LINE> <INDENT> result = self.getResult() <NEW_LINE> service = self.getService() <NEW_LINE> try: <NEW_LINE> <INDENT> result = float(result) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> belowmin = False <NEW_LINE> abovemax = False <NEW_LI...
Formatted result: 1. If the result is not floatable, return it without being formatted 2. If the analysis specs has hidemin or hidemax enabled and the result is out of range, render result as '<min' or '>max' 3. If the result is floatable, render it to the correct precision specs param is optional. A dictionary as f...
625941d4046cf37aa974cf37
def test_select_merge_components_random_raisesError(self): <NEW_LINE> <INDENT> MT = MergeTracker(3) <NEW_LINE> MSelector = MergePairSelector() <NEW_LINE> MT.excludeList = set([0]) <NEW_LINE> MT._synchronize_and_verify() <NEW_LINE> for trial in range(10): <NEW_LINE> <INDENT> kA, kB = MSelector.select_merge_components(No...
Verify that when comp 0 is excluded with K=3 we cannot provide comp 0 as kA, [error is raised] AND in free choice, we only choose kA=1, kB=2
625941d4e5267d203edcde8b
def is_interpolator(f) : <NEW_LINE> <INDENT> return type(f) == FunctionType and hasattr(f, "is_interpolator") and f.is_interpolator
checks if f is an interpolator function.
625941d407d97122c4178a7e
def setUp(self): <NEW_LINE> <INDENT> self.app = Flask(__name__) <NEW_LINE> setup_db(self.app) <NEW_LINE> self.client = app.test_client
Executed before each test. Define test variables and initialize app.
625941d47d43ff24873a2e91
def get_markdown_instance(inline=False, js_support=False): <NEW_LINE> <INDENT> zdsext = ZdsExtension({"inline": inline, "emoticons": smileys, "js_support": js_support}) <NEW_LINE> md = markdown.Markdown(extensions=(zdsext,), safe_mode = 'escape', inline = inline, enable_attributes = False, tab_length = 4, output_format...
Provide a pre-configured markdown parser. :param bool inline: If `True`, configure parser to parse only inline content. :return: A ZMarkdown parser.
625941d43539df3088e2e53b
def __ne__(self, other): <NEW_LINE> <INDENT> return self.job_id != other.job_id
job handles are equal if they point at the same job id
625941d45fcc89381b1e18b1
def get_stat_from_dynamics(singlecdt, tmin=None, tmax=None): <NEW_LINE> <INDENT> times = singlecdt.time <NEW_LINE> autocorr = singlecdt.autocorr <NEW_LINE> cts = singlecdt.count_two <NEW_LINE> indexlow, indexup = 0, None <NEW_LINE> if tmin is not None: <NEW_LINE> <INDENT> while indexlow < len(times) and times[indexlow]...
Computes stationary autocorrelation vector from autocorr matrix. This function uses the autocorrelation matrix, that stores two-point autocorrelation functions between the various acquisition time-points, to compute the autocorrelation function in case of stationary hypothesis. Computation is fast but result is mostly...
625941d46aa9bd52df036f95
def serialize_iso8601_date(dt): <NEW_LINE> <INDENT> if isinstance(dt, datetime.datetime): <NEW_LINE> <INDENT> return dt.replace(hour=0, minute=0, second=0).isoformat() <NEW_LINE> <DEDENT> if isinstance(dt, datetime.date): <NEW_LINE> <INDENT> return pytz.utc.localize(datetime.datetime.combine( dt, datetime.time(0, 0, 0)...
From a localized datetime.datetime object, it returns the section that contains the date together with the timezone. :param dt: datetime.datetime object. :return: Date and TimeZone in ISO8601 format.
625941d4283ffb24f3c55af0
def __load_hidapi(): <NEW_LINE> <INDENT> global __hidapi <NEW_LINE> global __libpath <NEW_LINE> if __hidapi is None: <NEW_LINE> <INDENT> __libpath = find_library('hidapi-hidraw') <NEW_LINE> if __libpath is None: <NEW_LINE> <INDENT> raise RuntimeError('Could not find the hidapi shared library.') <NEW_LINE> <DEDENT> __hi...
Load the hidapi library. For internal use only.
625941d4fff4ab517eb2f62d
def __forward(self): <NEW_LINE> <INDENT> self.nn1.forward(self.points) <NEW_LINE> self.nn2.forward(self.nn1.out) <NEW_LINE> self.nn3.forward(self.nn2.out)
前向传播
625941d40a50d4780f667084
def main(): <NEW_LINE> <INDENT> ficentree1 = "dicoVillesDBpedia.csv" <NEW_LINE> ficentree2 = "abstractvillescadbpedia.csv" <NEW_LINE> ficresultat = "compareOcCat.csv" <NEW_LINE> dicoVilles = litDico(ficentree1) <NEW_LINE> with open(ficentree2, newline='', encoding='utf-8') as csvfile: <NEW_LINE> <INDENT> spamreader = c...
Le programme principal.
625941d43c8af77a43ae3992
def __init__(self): <NEW_LINE> <INDENT> self.filters = []
Creates an instance of the FilterArticles class
625941d47cff6e4e81117b76
def create_data(self, user): <NEW_LINE> <INDENT> k = str(random.random()) <NEW_LINE> f = tempfile.NamedTemporaryFile(delete=False) <NEW_LINE> self._data_map[k] = {'type': 'default', 'state': None, 'data': f.name, 'user': user} <NEW_LINE> return k
Creates data locations for job output This allows jobs to place data in a location that makes sense for it. Motivating Examples: If the job is running on a GPU then the results may be held in GPU RAM for further processing, if run on a Hadoop cluster than it would be on HDFS, and if run on an external service it wou...
625941d45510c4643540f5d2
def validate_file(self, dir_entry: os.DirEntry) -> bool: <NEW_LINE> <INDENT> from .log import Log <NEW_LINE> if dir_entry.is_symlink(): <NEW_LINE> <INDENT> Log.vv('{name}: It is the symbolic link. Skipping.'.format(name=dir_entry.name)) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not dir_entry.is_file(): <NEW_LINE> ...
Validates given DirEntry. Returns False if entry should be completely ignored, or True if we want to keep it for further processing. Ignore all zero length files. There are usually there for a purpose like .dummy etc, so there can be tons of it with the same name even, so by default, ignore them completely. Also ignor...
625941d473bcbd0ca4b2c267
def findNumbers(self, nums): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for i in nums: <NEW_LINE> <INDENT> a=str(i) <NEW_LINE> b=[j for j in a] <NEW_LINE> l=len(b) <NEW_LINE> if l % 2 == 0: <NEW_LINE> <INDENT> count+=1 <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return count
:type nums: List[int] :rtype: int
625941d4dd821e528d63b399
def getTimes(self): <NEW_LINE> <INDENT> return copy.copy(self.times)
Get all timing data Returns: list. A list of pairs (time, phrase), ordered by time:: time (int): start time of a lyric in hundredths of a second phrase (int): index of a phrase in the list returned by self.getPhrases()
625941d46fece00bbac2d931
def conduct(definition): <NEW_LINE> <INDENT> identities = [uuid.uuid4() for i in range(definition.executions)] <NEW_LINE> analysts = get_analysts(definition) <NEW_LINE> for execution in identities: <NEW_LINE> <INDENT> technique = get_technique(definition) <NEW_LINE> try: <NEW_LINE> <INDENT> technique.allocate() <NEW_LI...
Conduct a live digital forensic experiment. Arguments: definition -- the experiment definition.
625941d4627d3e7fe0d69042
def title_score(title, sentence): <NEW_LINE> <INDENT> title = [x for x in title if x not in STOPWORDS] <NEW_LINE> count = 0.0 <NEW_LINE> for word in sentence: <NEW_LINE> <INDENT> if word not in STOPWORDS and word in title: <NEW_LINE> <INDENT> count += 1.0 <NEW_LINE> <DEDENT> <DEDENT> if len(title) == 0: <NEW_LINE> <IND...
Score the title based on occurrence of words in the sentence.
625941d4be7bc26dc91cd7ef
def variogram(image, axis): <NEW_LINE> <INDENT> if isinstance(image, Image): <NEW_LINE> <INDENT> image = image.asArray() <NEW_LINE> <DEDENT> n = image.shape[axis] <NEW_LINE> variogram = {} <NEW_LINE> categories = np.unique(image) <NEW_LINE> volume = 1 <NEW_LINE> for i in range(0, image.ndim): <NEW_LINE> <INDENT> volume...
Returns dictionary of indicator variogram values in x direction at all pixels for all categories
625941d4d53ae8145f87a45f
def countBits(self, num): <NEW_LINE> <INDENT> out = [0] <NEW_LINE> for i in range(1, num+1): <NEW_LINE> <INDENT> out.append((i&1) + out[i>>1]) <NEW_LINE> <DEDENT> return out
:type num: int :rtype: List[int]
625941d44a966d76dd551201
def show_files(conn, *args, **kwargs) -> List[str]: <NEW_LINE> <INDENT> raise NotImplementedError
Lists the targets with all of the applied tags.
625941d4e64d504609d74a31
def mds_deactivate(self, who, **kwargs): <NEW_LINE> <INDENT> return self.put('mds/deactivate?who={0}' .format(who), **kwargs)
deactivate mds cluster :param who: :param kwargs: :return:
625941d4187af65679ca5310
def removeDup(head): <NEW_LINE> <INDENT> if head is None or head.next is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> outer_cur = head.next <NEW_LINE> inner_cur = None <NEW_LINE> inner_pre = None <NEW_LINE> while outer_cur is not None: <NEW_LINE> <INDENT> inner_cur = outer_cur.next <NEW_LINE> inner_pre = outer_...
方法功能:对带头结点的无序单链表删除重复的结点 输入参数:head: 链表头结点
625941d4d18da76e235326c8
@configure_aws_region() <NEW_LINE> @convert_errors() <NEW_LINE> def describe_image(image_id, region=None): <NEW_LINE> <INDENT> imagebuilder = ImageBuilder(image_id=image_id) <NEW_LINE> try: <NEW_LINE> <INDENT> return _image_to_describe_image_response(imagebuilder) <NEW_LINE> <DEDENT> except NonExistingImageError: <NEW_...
Get detailed information about an existing image. :param image_id: Id of the image :type image_id: str :param region: AWS Region that the operation corresponds to. :type region: str :rtype: DescribeImageResponseContent
625941d426068e7796caeed2
def bitOfByte( bit, byte ): <NEW_LINE> <INDENT> if bit < 0 or bit > 7: <NEW_LINE> <INDENT> print('Your bit of', bit, 'is out of range (0-7)') <NEW_LINE> print('returning 0') <NEW_LINE> return 0 <NEW_LINE> <DEDENT> return ((byte >> bit) & 0x01)
returns a 0 or 1: the value of the 'bit' of 'byte'
625941d4c4546d3d9de72c26
def isPalindrome(self, head): <NEW_LINE> <INDENT> array = [] <NEW_LINE> while head is not None: <NEW_LINE> <INDENT> array.append(head.val) <NEW_LINE> head = head.next <NEW_LINE> <DEDENT> for i, j in zip(range(len(array)), range(len(array) - 1, -1, -1)): <NEW_LINE> <INDENT> if array[i] != array[j]: <NEW_LINE> <INDENT> r...
:type head: ListNode :rtype: bool
625941d438b623060ff0afdf
def undo(self) -> None: <NEW_LINE> <INDENT> self._node.setTransformation(self._old_transformation)
Undoes the rotation, rotating the node back.
625941d40fa83653e46571ac
def test_fetch_data_1(): <NEW_LINE> <INDENT> mushroom = fetch_data('mushroom') <NEW_LINE> assert not mushroom.empty <NEW_LINE> assert not mushroom.isnull().values.any()
Test fetch_data can fetch data from GitHub.
625941d46fece00bbac2d932
def normalize(df): <NEW_LINE> <INDENT> result = (df - df.min()) / (df.max() - df.min()) <NEW_LINE> return result
Takes a dataframe and normlizes features to be in range [0, 1]. Parameters ---------- df: A pandas.DataFrame Returns ------- A pandas.DataFrame
625941d40a366e3fb873ea0c
def inverse_transform(self, data): <NEW_LINE> <INDENT> return (tf.maximum(tf.sqrt(self.var)*self.sc_factor, 1e-2)) * data + self.mu
Undoes the transformation performed by this scaler. Arguments: data (np.array): A numpy array containing the points to be transformed. Returns: (np.array) The transformed dataset.
625941d460cbc95b062c6735
def insert(self, doc_number, notice): <NEW_LINE> <INDENT> model = Notice(document_number=doc_number, fr_url=notice['fr_url'], publication_date=notice['publication_date'], notice=notice) <NEW_LINE> if 'effective_on' in notice: <NEW_LINE> <INDENT> model.effective_on = notice['effective_on'] <NEW_LINE> <DEDENT> model.save...
Store a single notice
625941d4796e427e537b07b8
def is_up_to_date(self): <NEW_LINE> <INDENT> installed = self.get_installed_version() <NEW_LINE> if installed: <NEW_LINE> <INDENT> if installed['version'] > self.version: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif installed['version'] == self.version: <NEW_LINE> <INDENT> return self.branches[installed['br...
Renvoie : True si l'application est à jour, False sinon
625941d4097d151d1a22304a
def click_create_cpe_bundle_button(self): <NEW_LINE> <INDENT> self.click_element(self.create_cpe_bundle_button_locator)
Implementing click create cpe bundle button functionality :return:
625941d4293b9510aa2c3486
def num_lines(input_file, skip = 0): <NEW_LINE> <INDENT> with open(input_file, 'r') as f: <NEW_LINE> <INDENT> lines = f.read() <NEW_LINE> num = lines.count('\n') <NEW_LINE> <DEDENT> num = num - skip <NEW_LINE> return(num)
Count the number of lines in a file TODO: add tests for this one
625941d4287bf620b61d3c54
def get_infall_by_count(self, target_count, step, min_mass=1e10, max_mass=1e16, tolerance=0.01, min_count = None, max_count=None): <NEW_LINE> <INDENT> print("{:.2e} -> {:.2e}".format(min_mass, max_mass)) <NEW_LINE> if min_count is None: <NEW_LINE> <INDENT> min_count = self.get_count_by_infall(min_mass, step) <NEW_LINE>...
Binary search to match by expected count
625941d466656f66f7cbc39d
def testModifiedSetFlag( self ): <NEW_LINE> <INDENT> game = minesweeper.Game() <NEW_LINE> game.Flag( 4, 6 ) <NEW_LINE> self.assertEqual( True, game.IsModified() )
Modified flag has to set automatically when flag a cell.
625941d466656f66f7cbc39e
def register_blueprint(self, blueprint: Blueprint, **options) -> None: <NEW_LINE> <INDENT> def deferred(state): <NEW_LINE> <INDENT> url_prefix = (state.url_prefix or u"") + (options.get('url_prefix', blueprint.url_prefix) or u"") <NEW_LINE> if 'url_prefix' in options: <NEW_LINE> <INDENT> del options['url_prefix'] <NEW_...
Registers a blueprint onto this blueprint just like how you might register a blueprint on the Flask app with 'app.register_blueprint'. This is what enables chaining a series of NestableBlueprints together to form independent views. Args: blueprint: Either a regular Blueprint or NestableBlueprint to chain onto the...
625941d48a43f66fc4b54255
def where_not_in(self, key = None, values = None): <NEW_LINE> <INDENT> return self._where_in(key, values, True)
* Where_not_in * * Generates a WHERE field NOT IN ('item', 'item') SQL query joined * with AND if appropriate * * @param string The field to search * @param array The values searched on * @return object
625941d421bff66bcd684b43
def __exit__(self, _type, value, traceback): <NEW_LINE> <INDENT> if traceback is not None: <NEW_LINE> <INDENT> logging.error('Exiting with statement with exception %s' % traceback) <NEW_LINE> <DEDENT> self.cleanup()
Exit a with statement
625941d496565a6dacc8f8bc
def generate(user): <NEW_LINE> <INDENT> jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER <NEW_LINE> jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER <NEW_LINE> payload = jwt_payload_handler(user) <NEW_LINE> token = jwt_encode_handler(payload) <NEW_LINE> return token
签发jwt token
625941d4d58c6744b4257e50
def _get_samples(key, rate): <NEW_LINE> <INDENT> int_rate = int(rate) <NEW_LINE> if int_rate == rate: <NEW_LINE> <INDENT> return int_rate <NEW_LINE> <DEDENT> decimal_part = rate - int_rate <NEW_LINE> return int_rate + int(random.Random(key).random() < decimal_part)
Maps a sampling rate into an integer sample count deterministically. Args: key: Key to use for hashing function. rate: Sample rate. Returns: sample_count. If `rate` is an integer, the function returns `rate`. For the decimal part we sample a random number from [0, 1) and add one if sampled] float is bel...
625941d4dc8b845886cb5727
def enforce_git_config(self): <NEW_LINE> <INDENT> git_config = os.path.join(self.gitdir, 'config') <NEW_LINE> conf = hubblestack.utils.configparser.GitConfigParser() <NEW_LINE> if not conf.read(git_config): <NEW_LINE> <INDENT> log.error('Failed to read from git config file %s', git_config) <NEW_LINE> <DEDENT> else: <NE...
For the config options which need to be maintained in the git config, ensure that the git config file is configured as desired.
625941d4004d5f362079a524
def test_set_note_of_task(self): <NEW_LINE> <INDENT> args = [ 'TestTask', '-n', 'This is a note for the task.' ] <NEW_LINE> parsed = cli.parse_arguments(args) <NEW_LINE> self.assertEqual(parsed.note, 'This is a note for the task.')
A task can have a note: -n "some notes to the task ...".
625941d4091ae3566866714e
def prep_msg(self, msg): <NEW_LINE> <INDENT> self.msg_image = self.font.render(msg,True,self.text_color,self.button_color) <NEW_LINE> self.msg_image_rect = self.msg_image.get_rect() <NEW_LINE> self.msg_image_rect.center = self.rect.center
将prep_msg渲染为图像,并使其在按钮上居中
625941d485dfad0860c3b04d
def length(self): <NEW_LINE> <INDENT> cur = self._head <NEW_LINE> count = 0 <NEW_LINE> while cur != None: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> cur = cur.next <NEW_LINE> <DEDENT> return count
返回链表长度 :return:
625941d491f36d47f21ac6e5
def update_report(): <NEW_LINE> <INDENT> print("Updating reports...") <NEW_LINE> qs = urlencode({'agent': USER_AGENT}) <NEW_LINE> url = server + "/updateReports?{}".format(qs) <NEW_LINE> for _ in WebSocket(url): <NEW_LINE> <INDENT> pass
Tell wstest to update reports.
625941d4dd821e528d63b39a
def fieldlist(self): <NEW_LINE> <INDENT> result = self.field() <NEW_LINE> while self.lookaheadIsInSet(first['fieldsep']): <NEW_LINE> <INDENT> self.fieldsep() <NEW_LINE> if self.lookaheadIsInSet(first['field']): <NEW_LINE> <INDENT> result = ( self.field() and result ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return...
fieldlist ::= field (fieldsep field)* (fieldsep)?
625941d4851cf427c661a6ff
def __init__(self, length_str, dim): <NEW_LINE> <INDENT> self.dim = dim <NEW_LINE> if length_str.endswith("%"): <NEW_LINE> <INDENT> self.relunits = True <NEW_LINE> self.rellength = 0.01 * float(length_str[:-1]) <NEW_LINE> self.length = None <NEW_LINE> <DEDENT> elif length_str.endswith("px"): <NEW_LINE> <INDENT> self.re...
Builds a Length object. Args: length_str: a string of the form '<float>%' or '<int>px' describing a relative or absolute length, respectively dim: the dimension to measure length along
625941d4a17c0f6771cbe242
def serve_pil_image(pil_img): <NEW_LINE> <INDENT> img_io = StringIO.StringIO() <NEW_LINE> pil_img.save(img_io, pil_img.format) <NEW_LINE> img_io.seek(0) <NEW_LINE> mimetype = ''.join(['image/', pil_img.format.lower()]) <NEW_LINE> return send_file(img_io, mimetype=mimetype)
Serve a image from a PIL object :param pil_img: image tp serve
625941d40c0af96317bb83da
def test_init(self): <NEW_LINE> <INDENT> parent_node_id = '0xdeadbeef' <NEW_LINE> r = RoutingTable(parent_node_id) <NEW_LINE> self.assertEqual(1, len(r._buckets)) <NEW_LINE> self.assertEqual(parent_node_id, r._parent_node_id)
Ensures an object is created as expected.
625941d4d7e4931a7ee9e10f
def _load_from_stream(self): <NEW_LINE> <INDENT> self.__load_from_memory_flag = True <NEW_LINE> self.__line_terminator = self._keywords.get( constants.KEYWORD_LINE_TERMINATOR, self.__line_terminator) <NEW_LINE> separator = DEFAULT_SHEET_SEPARATOR_FORMATTER % self.__line_terminator <NEW_LINE> if self.__multiple_sheets: ...
Load content from memory :params stream file_content: the actual file content in memory :returns: a book
625941d41f037a2d8b9463ef
def setUp(self): <NEW_LINE> <INDENT> self.new_user = User("Sarah","Tuitoek","sjtoek13@gmail.com","tui","mkambez")
set up method to run before each test cases
625941d49f2886367277aa7e
def ToString(self): <NEW_LINE> <INDENT> pass
ToString(self: ListViewGroup) -> str Returns: A string that represents the current object.
625941d494891a1f4081bc9b
def test_doc(self): <NEW_LINE> <INDENT> self.assertEqual(doctest.testmod(vcard)[0], 0) <NEW_LINE> self.assertEqual(doctest.testmod(vcard_definitions)[0], 0) <NEW_LINE> self.assertEqual(doctest.testmod(vcard_errors)[0], 0) <NEW_LINE> self.assertEqual(doctest.testmod(vcard_utils)[0], 0) <NEW_LINE> self.assertEqual(doctes...
Run DocTests
625941d48da39b475bd65167
def release_job_res(self, node_dict): <NEW_LINE> <INDENT> self.release_network_load(node_dict['network'], node_dict['network']) <NEW_LINE> cpu = self.release_cpus(node_dict['num_cpu']) <NEW_LINE> gpu = self.release_gpus(node_dict['num_gpu']) <NEW_LINE> self.free_mem = self.free_mem + node_dict['mem'] <NEW_LINE> return ...
input is node_dict from placement {'id':xx, 'num_gpu':xxx, 'num_cpu': xxx, 'network': xxxx, 'tasks': [w2, ps2]}
625941d45e10d32532c5f118
def test_enemy_between_snake_wall_up(self): <NEW_LINE> <INDENT> data = TestGameData() <NEW_LINE> data.set_self([(1, 3), (1, 4), (1, 5), (1, 6), (1, 7)]) <NEW_LINE> data.add_enemy([(0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9)]) <NEW_LINE> response = requests.post(TEST_INSTANCE, json=data.data) <NEW_LINE> self.assertE...
should tunnel them into wall and not cut them off
625941d450812a4eaa59c512
def no_focus_process(self, process_id): <NEW_LINE> <INDENT> import random <NEW_LINE> save = random.randrange(2, 100000000000000) <NEW_LINE> sql = 'update process_info set save = "%s" WHERE process_id = "%s"' <NEW_LINE> try: <NEW_LINE> <INDENT> self.db.execute(sql % (save, process_id)) <NEW_LINE> return "执行成功" <NEW_LINE...
取消关注进程
625941d4d268445f265b5060
def process_message(self) -> None: <NEW_LINE> <INDENT> message = b''.join(self.rbuffer) <NEW_LINE> self.rbuffer = [] <NEW_LINE> try: <NEW_LINE> <INDENT> data = sublime.decode_value(message.decode('utf8')) <NEW_LINE> <DEDENT> except (NameError, ValueError): <NEW_LINE> <INDENT> data = json.loads(message.replace(b'\t', b'...
Called when a full line has been read from the socket
625941d44f88993c3716c258
def update(self, force=False): <NEW_LINE> <INDENT> log.info("Updating to version %s" % DB_VERSION) <NEW_LINE> with warnings.catch_warnings(): <NEW_LINE> <INDENT> table_names = self.db.get_bind().table_names() <NEW_LINE> tables_to_inquiry = ["master_workflowstate", "master_workflow", "workflow"] <NEW_LINE> if set(tables...
Fixes malfunction past migrations and clean the database
625941d4e76e3b2f99f3a9fb
def preprocessData(self, dataFilePath, mode): <NEW_LINE> <INDENT> turn1s = [] <NEW_LINE> turn2s = [] <NEW_LINE> turn3s = [] <NEW_LINE> labels = [] <NEW_LINE> with io.open(dataFilePath, encoding="utf8") as finput: <NEW_LINE> <INDENT> finput.readline() <NEW_LINE> for line in finput: <NEW_LINE> <INDENT> repeatedChars = ['...
Load data from a file, process and return indices, conversations and labels in separate lists Input: dataFilePath : Path to train/test file to be processed mode : "train" mode returns labels. "test" mode doesn't return labels. Output: indices : Unique conversation ID list conversations : List of 3 turn ...
625941d4d99f1b3c44c6777e
def parse_data(block): <NEW_LINE> <INDENT> rval = { 'Total' : None, 'Electronic' : None, 'Translational' : None, 'Rotational' : None, 'Vibrational' : None } <NEW_LINE> for line in block.splitlines(): <NEW_LINE> <INDENT> if re.match(r'^\s*Total', line): <NEW_LINE> <INDENT> key = 'Total' <NEW_LINE> <DEDENT> elif re.match...
Parse the line(s) to get the data.
625941d4d6c5a1020814423e
def _validate_with_jsonschema(instance, proposal): <NEW_LINE> <INDENT> jsonschema.validate(instance.to_dict(), instance.SCHEMA) <NEW_LINE> return proposal['value']
Validate that contents satisfy a jsonschema. This is meant to be used with traitlets' @validate decorator.
625941d4a8370b7717052a91
def test_backlink_text(self): <NEW_LINE> <INDENT> self.assertMarkdownRenders( 'paragraph[^1]\n\n[^1]: A Footnote', '<p>paragraph<sup id="fnref:1"><a class="footnote-ref" href="#fn:1">1</a></sup></p>\n' '<div class="footnote">\n' '<hr />\n' '<ol>\n' '<li id="fn:1">\n' '<p>A Footnote&#160;<a class="footnote-backref" href...
Test backlink configuration.
625941d430dc7b7665901b57
def load_command_extension(command, path): <NEW_LINE> <INDENT> extension = extension_name(path) <NEW_LINE> if not extension: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> cmd_package = '{0}.{1}.cmd'.format(__name__, extension) <NEW_LINE> python_name = command.replace('-', '_') <NEW_LINE> module_name = '{0}.{1}'.f...
Loads a command extension from the path passed as argument. Args: command (str): name of the command path (str): base path of the command extension Returns: A valid module object if the command is found or None
625941d44d74a7450ccd43b5
def parse_osu_output(job_id: str, path: Path = Path.cwd()) -> float: <NEW_LINE> <INDENT> elapsed_time = 0 <NEW_LINE> out_file = path / f"slurm-{job_id}.out" <NEW_LINE> try: <NEW_LINE> <INDENT> with open(out_file, "r") as file: <NEW_LINE> <INDENT> lines = file.readlines() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT...
Performs the parsing of the file slurm-{job_id}.out by returning the sums of the elapsed time multiplied by the size of the messages. Args: out_file (str): The job slurm output file path to parse. path (Path): The path where to look for the slurm output. Defaults to the current working directory. Retu...
625941d49f2886367277aa7f
def make_text(chains): <NEW_LINE> <INDENT> keys_list = list(chains.keys()) <NEW_LINE> key = random.choice(keys_list) <NEW_LINE> words = list(key) <NEW_LINE> value = random.choice(chains[key]) <NEW_LINE> words.append(value) <NEW_LINE> key = (key[1], value) <NEW_LINE> while True: <NEW_LINE> <INDENT> if key in chains: <N...
Return text from chains.
625941d45f7d997b87174c8b
def merge_faces_from_selected_objects_RH(refobj=None): <NEW_LINE> <INDENT> faces = [] <NEW_LINE> doc=FreeCAD.ActiveDocument <NEW_LINE> docG = FreeCADGui.ActiveDocument <NEW_LINE> sel=FreeCADGui.Selection.getSelection() <NEW_LINE> if len (sel): <NEW_LINE> <INDENT> for o in sel: <NEW_LINE> <INDENT> for f in o.Shape.Faces...
merging Faces of selected shapes
625941d43c8af77a43ae3993
def check(self, output): <NEW_LINE> <INDENT> new_items = self.process_feed() <NEW_LINE> if self.failed: <NEW_LINE> <INDENT> self.display_next_check() <NEW_LINE> return None <NEW_LINE> <DEDENT> if new_items: <NEW_LINE> <INDENT> logger.info('Found %d new item(s)' % len(new_items)) <NEW_LINE> if not self.initial_check: <N...
Update this feed with new items and timestamps.
625941d4711fe17d8254255b
def _find_check (query, mk_warning): <NEW_LINE> <INDENT> rename = query() <NEW_LINE> if rename is not None: <NEW_LINE> <INDENT> yield mk_warning(rename)
Run a `db` query to get a warning as a single rename. query: function to call which returns a `(frm, to)` rename to use in creating a warning mk_warning: function to call with the rename from `query` if not None; should return a `util.Warn` instance Returns an iterator of `util.Warn` instances from...
625941d450812a4eaa59c513
def get_status(self): <NEW_LINE> <INDENT> return self._status_code
Returns the status code for our response.
625941d4009cb60464c635a3