id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
8
768k
001a18006a334a96d515
def maxabs(a, axis=None): maxa = a.max(axis=axis) mina = a.min(axis=axis) p = abs(maxa) > abs(mina) # bool, or indices where +ve values win n = abs(mina) > abs(maxa) # bool, or indices where -ve values win if axis == None: if p: return maxa else: return mina shape = list(a.shape)...
001a58cac7d67dfeb319
def get_row_map(self): return self.row_map
001a5f305d90bbc26ee8
def _modify_position(self, fill_event): exchange = 'TestExchange' if fill_event.symbol in self.positions: if (self.positions[fill_event.symbol].volume < fill_event.volume) and ( self.positions[fill_event.symbol].side != fill_event.side): fill_even...
001a7b790450a419fdaa
def parse_metadata(entry): # Stream in first 164 KB of each file to parse metadata. data = requests.get(entry['media_content'][0]['url'], stream=True) asset = StringIO(data.raw.read(167936)) # Parse video metadata with PyAV (ffmpeg wrapper). container = av.open(asset) stream = next(s for s in container.st...
001a7ee387de398ab645
def densify(geometries, spatial_ref, max_segment_length, length_unit, geodesic=False, gis=None): if gis is None: gis = arcgis.env.active_gis return gis._tools.geometry.densify( geometries, spatial_ref, max_seg...
001ab2573ca8763293c4
def is_resolved(self) -> bool: return self.state == Vote.APPROVED or self.state == Vote.DENIED
001abfba7444da627064
def initialize(): ConfluenceLogger.logger = logging.getLogger("confluence")
001ad4d105ae455ae722
def log_event(time, message): lock.acquire() with open(args.out_folder + "/" + args.out, 'a') as fl: fl.write('execution time: {} s'.format(time) + "\n") fl.write(message + "\n") fl.write('-'*17 + "\n") lock.release()
001ae476293f82396c4b
def _apply_weight(self): for key in self.global_weights: self.global_weights[key] = np.round(self.global_weight * self.local_weights[key], self.precision)
001af7f2844df9ad67c6
def students(self): return Student.objects.filter(courses_taken=self)
001b01b49fedda82e005
def reload_config(self): assert os.path.exists(self.configpath),"No file can be found at location {}".format(self.configpath) try: with open(self.configpath) as f: config = yaml.full_load(f) self.config = config except Exception: print("Th...
001b34244a06d8682ee5
def search (self, query): data = urllib.request.urlopen(self._get_url(query)).read() return json.loads(data)
001b4d3c0840672fe446
def evaluate(): step = optimizer.iterations.numpy() if "best_accuracy" not in evaluate.__dict__: evaluate.best_accuracy = 0 if step % FLAGS.ev_every != 0: return evaluate.best_accuracy aggregator = tf.keras.metrics.SparseCategoricalAccuracy() for example in ds_test: points, labels = example["point...
001b522fa1959edadd21
def getBackdropHorizontalOffset(self): return _osgText.Text_getBackdropHorizontalOffset(self)
001b613dbe5cc46e42ae
def intersect(self, other: Cuboid) -> Cuboid | None: x_overlap = self._range_intersect( Range(self.bounds.x_min, self.bounds.x_max), Range(other.bounds.x_min, other.bounds.x_max), ) y_overlap = self._range_intersect( Range(self.bounds.y_min, self.bounds.y_max)...
001b8dfb9a7e34432843
def generate_password(size=8, char=string.ascii_uppercase+string.ascii_lowercase+string.digits): gen_pass = ''.join(random.choice(char) for _ in range(size)) return gen_pass
001b9abcac339e17f21d
def pascal_triangle(n): triangle = [] for num in range(n): row = [] for val in range(num + 1): if val == 0 or val == num: row.append(1) continue row.append(triangle[num - 1][val - 1] + triangle[num - 1][val]) triangle.append(row) ...
001bad714f90a912f7c8
def translate(self): expressions = [] varnames = set() funcnames = set() for part in self.parts: if isinstance(part, str): expressions.append(ex_literal(part)) else: e, v, f = part.translate() expressions.extend(e) ...
001bb918ac2ccbe98ab1
def gaussian_pdf(self, x, mu, Sigma, detSigma, invSigma): n = np.size(x) return (1./(detSigma*(2*np.pi)**(0.5*n)))* \ np.exp(-0.5*np.dot((x-mu),np.dot(invSigma,(x-mu))))
001bbae6085d0a1c9f5d
def import_action_second(self, request, *args, **kwargs): if not self.has_import_permission(request): raise PermissionDenied context = self.get_import_context_data() form_type = self.get_import_form() form_kwargs = self.get_form_kwargs(form_type, *args, **kwargs) ...
001bc1dcc4533e11ffa8
def iipdisabledmipdisabled(self) : try : return self._iipdisabledmipdisabled except Exception as e: raise e
001c033ee76b879ce7c8
def delete_index_files(self): self.clear_cache() db_path = self.db.local_db_path() if exists(db_path): remove(db_path)
001c25bd8daf02fcc9d5
def analyse(self): # get the amount of days between the start and end date (not including the weekend) diff_days = np.busday_count(self.period_begin.strftime("%Y-%m-%d"), self.period_end.strftime("%Y-%m-%d"), weekmask=[1, 1, 1, 1, 1...
001c5696024a3642e1ff
def get_plot_axis(**kwargs): from matplotlib import gridspec import matplotlib.pyplot as plt fig = plt.figure(**kwargs) gs = gridspec.GridSpec(5, 1) ax0 = plt.subplot(gs[:-2, :]) ax1 = plt.subplot(gs[3, :], sharex=ax0) gs.update(hspace=0.1) plt.setp(ax0.get_xticklabels(), visible=Fal...
001c6325c9aa06b560cc
async def help(self): if self.GameStage == 0: await self.Channel.send("Everyone will recieve a random article from wikipedia in their DMs. You can do 3 things: \n\t - Accept the article given to you by replying `-ready`;\n\t - Reject the article and ask for a new one by replying `-new`;\n\t - Submit your own arti...
001c6544549da4867762
def download_fasttext_models(self): model_url = self._build_fasttext_url() if not self.interactive: if not self.silent: print( f"CLTK message: Going to download file '{model_url}' to '{self.model_fp} ..." ) # pragma: no cover g...
001c7912fffc4628b2e3
def getResourceLocation(): return core.Kernel.getResourceLocation() + 'scg'
001c83e2d79639ea87e2
def authenticate(): return Response('Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
001c85da9ae75d72c6be
def test_cant_get_short_url_details(self): response = self.client.get("/api/short_url/{}/".format(self.short_url_2.id)) self.assertEqual(response.status_code, 404)
001c9efdb6d145dc4d04
def largest_anagram(filename): reader = open(filename, "r") lines = reader.readlines() largest = "" count = 0 for line in lines: # Removes newline character from line if "\n" in line: line = line.replace("\n", "") temp = count_anagrams(line) if temp > count: count = temp...
001cb616d2c7f2ede24b
def _set_value(self, value): self.bind_value(value)
001cbd3b80d600294eeb
def __len__(self): # type: () -> int return len(self.__dict__)
001cc8bea8c0c279364c
def generate_repeating_fixtures(self,line,form,form_list,fixtures,pk_num,pk_num_list,primary_key_counter): num_repeats_all = 1; num_repeats_list = []; current_repeat_list = []; counter = 0; #populates current_repeat_list with 1s, amount equal to length of form_list - 1 current_repeat_list = [1] * len(form_list...
001cde68cfb653a85541
def print_actions(self): for (a,b) in self.actions: print("Player%d played %s" % (a+1, b), end=", ") print("")
001cf13de6db4cbc0aad
def performActionDiffDbRepo ( argObject, includeSchemas, includeObjectTypes) : global g_primaryOraPassword validateSettings( argObject ) if argObject.repo_url1.startswith( 'file:///' ) : # file protocol needs no credentials? svnHelper.g_needCredentials= False else: promptAndSetSvnPasswor (argObject.svn_user...
001d0531dc85d35922a6
def BayesianOptOnCV(self): skf = StratifiedKFold(n_splits=5) train = self.train y = self.y param_hyperopt= { 'learning_rate': hp.loguniform('learning_rate', np.log(0.001), np.log(1)), 'max_depth': scope.int(hp.qun...
001d464ab69bf0b91366
def fetchall(self): try: return tuple(self) except TypeError: raise ProgrammingError("attempting to use unexecuted cursor")
001d46eb6734984b20f8
def get_big_joker_value(card_deck: List[int]) -> int: big_j = 0 for value in card_deck: if value > big_j: big_j = value return big_j
001d7f7cba9314dcd46f
def addAtTail(self, val: int) -> None: cur_node = self._head if not cur_node: self.addAtHead(val) else: while True: if not cur_node.next_node: node = Node(val) cur_node.next_node = node self._leng...
001dba4c5752c05a9b07
def read_data(self): print("--- Reading in data ---") # read networkx graph from edge list self._read_nx_graph() # readin list of node ids for each subgraph & their labels self._read_subgraph() # check if the dataset is multilabel (e.g. HPO-NEURO) self._init_label...
001dbad49c3508ef75ae
def Array(node, inputs, outputs): outputs[0].data = N.arange(5, dtype='d')
001dd2bd651aefd1bd63
def standalone_page_title(self, request, fragment, **kwargs): return _('Theming Administration')
001de212c315ac4a7d74
def ensure_folder_exists(folder_path): if not os.path.exists(folder_path): os.mkdir(folder_path) return folder_path
001de490a9fddd1eb1ec
def available_actions(self): moves = self.adjacent_moves() moves.append(actions.ListCommands()) moves.append(actions.ViewInventory()) moves.append(actions.Look()) moves.append(actions.View()) moves.append(actions.Equip()) moves.append(actions.Take()) ...
001deb1a21fdc76de8cd
def ss_to_index(ss): if ss=='H': return 0 if ss=='E': return 1 if ss=='C': return 2 assert 0
001e2549f6f9063df316
def supports_relationship_batch(self): return 'supports_relationship_batch' in profile.SUPPORTS
001e4ff68852f86a673f
def reset(self): self.log.info("Reset all events") for ev in list(self._events): try: ev.close() except: pass self._events = set()
001e9b7facd1bc347a67
def griddata(self): # Input Variables # get extrema values. # make coordinate arrays. # make the initial grid # cdef np.ndarray[double, ndim=1] xi = np.linspace(ranges[0]-offset, ranges[1]+offset, points) # cdef np.ndarray[double, ndim=1] yi = np.linspace(ranges[2]-offset, ranges[3]+offset, po...
001ebb0b38f522a8577f
def test_message_timestamp(self): schema = Message("bar", {}) self.assertEqual( schema.coerce({"type": "bar", "timestamp": 0.33}), {"type": "bar", "timestamp": 0.33})
001ef28ab39d529c92d4
def _time_to_file(self,time): if(time >= 0): if(time >= self.total_time_steps): raise Exception("Time indexing is out of range") file_index = next(x[0] for x in enumerate(self.time_steps_before[1:]) if time < x[1]) time_slice = ti...
001ef7691d5e98551c78
def _createModuleObj(self): ModuleSCECCVMH.__init__(self)
001ef9bd912fb454e5d6
def discard_missing(self): removed = [] for rmol in self[::-1]: if rmol.GetNumConformers() == 0: rmindex = self.index(rmol) print( f"Discarding a molecule (id {rmindex}) due to the lack of conformers. " ) sel...
001f05d6c107c4d4e0d6
def filter(self): return self.filters[self.filters_lb.GetSelections()[0]][0]
001f2c3b389b80b8bba6
def actual_words(self) -> Dict[str, DictionaryEntryType]: return { k: v for k, v in self.words.items() if k not in [self.sil_code, self.oov_code, "<eps>"] and len(v) }
001f2f329dd00f6ff5b3
def clean(self, stall_time=None): self.driver.clean(stall_time)
001f3b39b0fb846adb3b
def extract_zip(zipfile): with zipfile as thezip: for zipinfo in thezip.infolist(): with thezip.open(zipinfo) as thefile: if not zipinfo.filename.startswith('.') and not zipinfo.filename.startswith('__MACOSX') and not zipinfo.is_dir(): yield thefile
001f4125690f2a61dbed
def slope_from_origin(self): rise = Point().y - self.y run = Point().x - self.x m = rise / run return m
001f71417ee57b4ed522
def execute(self, collection, begin_time, end_time, coord_list, srid): col_name = collection collection = models.Collection.objects.get(identifier=collection) eo_objects = collection.eo_objects.filter( begin_time__lte=end_time, end_time__gte=begin_time ) coordinates...
001f7411b6590e6915f2
def evaluate_Q_d(self, q): Q_d = np.zeros(self.rows_C_q) for joint in self.MBD_system.joints: Q_d_joint_vector = joint.evaluate_Q_d(q) if joint.joint_type in joint._supported_types: rows = sum(C_q_i_dim_i[0] for C_q_i_dim_i in GlobalVariables.C_q_i_dim[0:join...
001f961fdd2580c1dfee
def testSignurlGetWithJSONKey(self): expected = sigs.TEST_SIGN_URL_GET_WITH_JSON_KEY json_contents = pkgutil.get_data('gslib', 'tests/test_data/test.json').decode() key, client_email = gslib.commands.signurl._ReadJSONKeystore(json_contents) duration = timedelta(sec...
001f9b4a6eaa00043ef6
def __get_class_bound_columns(cls) -> list: data_fields = Py2SQL.__get_data_fields(cls) base_ref_columns = [Py2SQL.__get_base_class_table_reference_name( b) for b in cls.__bases__ if b != object] # prevent undesired recursion attr_columns = [Py2SQL.__get_class_column_name( ...
001fa36ada3fc82f4b82
def buy_shopping_item(sender, **kwargs): instance = kwargs.get('instance') shopping_lists = instance.shoppinglist_set.values() for shopping_list in shopping_lists: # update item price fin each shopping list accordingly id = shopping_list.get('id') list_instance = ShoppingList.objects...
001fa57f5529890a74f8
def lookup(tickers, list_items, stats = 'sd1l1c1dr1q'): # Tag information from # https://ilmusaham.wordpress.com/tag/stock-yahoo-data/ # 0 s: symbol # 1 d1: last trade date # 2 l1: last trade # 3 c: change # 4 d: dividend/share # 5 r1: dividend pay date # 6 q: ex-dividend date...
001fa7392b48b7e8ef83
def setResult(result):
001fabf8f785ad17d151
def clone_gameState_new_nobles_in_play( old_game_state: GameState, new_nobles_in_play: NoblesInPlay, ) -> GameState: ret = old_game_state.copy() ret.set_nobles_in_play(new_nobles_in_play) return ret
001fb71b28930b537ddb
def merge_and_count_inv((lst1, count1), (lst2, count2)): i = 0 j = 0 count = 0 output = [] while i < len(lst1) and j < len(lst2): if lst1[i] < lst2[j]: output.append(lst1[i]) i += 1 else: output.append(lst2[j]) j += 1 count += len(lst1[i:]) return (output + lst1[i:] + lst2[j:], count + count...
001fd00959ea8b57d3cb
def set_thread_limit(self, limit): limit = int(limit) if limit <= 0 or limit > 50000: print( 'Warning: Invalid thread number limit {}!' 'Please make sure the thread limit is within the range of (1, 50,000)!'.format(limit) ) print('The ...
001fdb6f4c1e9e8ec1a0
def test_get_pattern(self): pass
00200cfa4676f5765d94
def _anchored_predecessors(self, n): # loop on all incoming edges for t in self.predecessors(n): # if predecessor is anchored # stop looking for (necessarily earlier) predecessors if t.is_anchored: yield t continue ...
00201a3b55ea9946b999
def run(self): self.get_data()
002047e225132c3e444c
def walker_plot(samples, nwalkers, limit, truth, ID): s = samples.reshape(nwalkers, -1, 3) s = s[:,:limit, :] fig = P.figure(figsize=(8,12)) ax1 = P.subplot(3,1,1) ax2 = P.subplot(3,1,2) ax3 = P.subplot(3,1,3) ax1.plot(s[:,:,0].T, 'k') ax1.axhline(truth[0], color='r') ax2.plot(s[:,:,...
002065d6d91466a9030e
def max_num_in_list2(a_list): return max(a_list)
00207743d11fa3afc4cd
def top_three(input_list): # TODO: implement this function return sorted(input_list, reverse=True)[:3]
002080e68ce283f895b1
def update(now): for host in hosts: host.update(see) track_point_in_utc_time(hass, update, now + interval) return True
0020962b72248a0a9c13
def issuer_type(self) -> str: return self.__issuer_type
0020a591e26fb8991dd6
def main(do_train, do_predict, model_str, kw_dict): if model_str is None: model = build_model(kw_dict) kw_dict['modelname'] = make_model_name(kw_dict) else: model = load_model(model_str) kw_dict['modelname'] = make_model_name(model_str) if not os.path.exists(kw_dict['modeldir...
0020ad62a30f0c713845
def exec_and_time(self, query, query_options=None, impalad=0): client = self.create_client_for_nth_impalad(impalad) if query_options is not None: client.set_configuration(query_options) start_time = int(round(time.time() * 1000)) client.execute(query) end_time = int(round(time.time() * 1000)) ...
0020d56ba0af87319c00
def x(self, dt, models): data = {} db = dbio.connect(models.dbname) cur = db.cursor() for s in self.statevar: sql = "select ensemble,st_x(geom),st_y(geom),val from (select ensemble,(ST_PixelAsCentroids(rast)).* from {0}.{1} where fdate=date '{2}-{3}-{4}') foo group by ensembl...
00211e19172c09584fc8
def if_up(interface): cmd = ["ip", "link", "show", "dev", interface] return "state UP" in subprocess.check_output(cmd)
00212d3cda763964981e
def remove_from_group(self, group_id: str) -> None: self.client.remove_record_from_group(group_id=group_id, record_id=self.id)
002186a39dae193838cf
def float_transform(self, *args): for column in args: self.train[column] = self.train[column].apply(lambda x:float(x)) self.test[column] = self.test[column].apply(lambda x:float(x))
00218b27395772e8ab34
def cancel(self): self._logger.debug("--- CANCEL ---") self._shutdown = True self._stop()
0021e5fc078a7840b5ff
def set_driver(self, device): connect = self._ip_search_(device=device) IP = connect[0] port = connect[1] driver = A11713C.a11713c(IP=IP, port=port) return driver
0021e653b4da642030a5
def start_new_game(self): url = "{base_url}/games".format(base_url=self.base_url) response = requests.post(url=url) if response.status_code != httplib.CREATED: raise errors.GameClientException(response.text) body = response.json() game_dict = body["game_state"] ...
0022359d4eab5c7ce511
def close(self): self.device.close()
002238e548c997a98e52
def reportMatch(winner, loser): # Connect to the DB and get a cursor to execute statements connection = connect() cursor = get_cursor(connection) # Insert the results of the match into the table cursor.execute("INSERT INTO matches (winner_id, loser_id) VALUES (%s,%s)",(winner,loser)) c...
002248b9a76447e82ebf
async def create_new_order(message): order_details = message.content.split(",") # order_details.append(randint(MIN, MAX)) await create_order_line_items(message.author.name, order_details)
002291a5f8db4ad1600c
def instantiate_from_string(string, **init_kwargs): class_ = string_to_object(string) return class_(**init_kwargs)
0022a0841814f150274e
def crossover_operator(state1, state2, incompatabilities): new_list = [] slots1 = state1.get_slots() slots2 = state2.get_slots() for i in range(len(slots1)): if i % 2 == 0: new_list.append(slots1[i]) else: new_list.append(slots2[i]) new_state = State(incomp...
0022c56997b6fe01c60c
def _AddOutputLayer(self, prev_layer, out_dims, out_func, num_classes): # Reduce dimensionality appropriate to the output dimensions. batch_in = shapes.tensor_dim(prev_layer, dim=0) height_in = shapes.tensor_dim(prev_layer, dim=1) width_in = shapes.tensor_dim(prev_layer, dim=2) depth_in = shapes.ten...
0022cc35e75a3e60974e
def shortest_hops(gr, s):
0022cf65d90dcbf4d8b4
def chat(request): return render_to_response('chatapp1/chat.html', {}, RequestContext(request))
0022f6bb6e932c6a0983
def predict_species(penguin: Penguin): species = classifier.predict(penguin.to_df()) return species[0]
00230f13edbc71f8d91a
def dist_by_rating(self): return ratings_distribution
002346a99c59a7c475f8
def get_parsing_fn(t: Type[T]) -> Callable[[Any], T]: if t in _parsing_fns: logger.debug(f"The type {t} has a dedicated parsing function.") return _parsing_fns[t] elif t is Any: logger.debug(f"parsing an Any type: {t}") return no_op # TODO: Do we want to support parsing a D...
00234f958ab951b18467
def lasagna_wmt_zh_en_big(args): args.dropout = getattr(args, "dropout", 0.2) args.attention_dropout = getattr(args, "attention_dropout", 0.2) args.weight_dropout = getattr(args, "weight_dropout", 0.2) lasagna_wmt_en_de_big(args)
0023688caddcac4b06cf
def absolute_co(ob, co=None): co, proxy, prox = get_proxy_co(ob, co, return_proxy=True) m = np.array(ob.matrix_world, dtype=np.float32) mat = m[:3, :3].T # rotates backwards without T loc = m[:3, 3] return co @ mat + loc, proxy, prox
00237319bf412d4cebb3
def va_set_route(self, address=None, next_hop=None, commit=False): try: configured = ipaddress.IPv4Interface(address) gw = ipaddress.IPv4Address(next_hop) except (AddressValueError, NetmaskValueError): raise else: network = configured.with_p...
002378d31c32280ab63a
def _get_node(self, node_id, current): if current.id == node_id: return current for conn in current.child_connections(): self._nodes[conn.node.id] = conn.node node = self._get_node(node_id, conn.node) if node: return node return N...
0023882c0abf48451589
def forward(self, test_data, train_data):