id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
8
768k
00927f27b11065717e60
def handleInvalidUsage(error): response = jsonify(error.to_dict()) response.status_code = error.status_code return response
009287f4c9daaff47b1b
def product_type(self): err, buf = self.lib.GetDevProductType(*RetStr(default_buf_size)) return buf
0092a72be0439871489d
def handle_dump(self, params): print("Clients:", self.server.clients) for client in self.server.clients.values(): print(" ", client) for channel in client.channels.values(): print(" ", channel.name) print("Channels:", self.server.channels) for ...
0092b39f324122fd3150
def queue_len(self): return len(self.queue)
0092bce32f6bf413d1de
def pbs_submit(command, name='', template=''): if not template: template = """#!/bin/bash #PBS -S /bin/bash #PBS -m ae """ if not name: name = command template = '\n'.join([template, ' '.join(["#PBS -N", name]), "cd $PBS_O_WORKDIR", '']) # Open pbs session pbs_command = subprocess...
0092cb33da32a4eb592e
def getPacmanMatrix(state): width, height = state.data.layout.width, state.data.layout.height matrix = np.zeros((height, width), dtype=np.int8) for agentState in state.data.agentStates: if agentState.isPacman: pos = agentState.configuration.getPosition() ...
00930244fa01ff9e635f
def setParameters(): par = os.path.join(Vars.sys_path, 'Parameters.txt') Vars.parameters = {} if not os.path.exists(par): print("\n" + Vars.instructions_All["greetings"]) Vars.lang = chooseLanguage() Vars.availableBooks = list(Vars.listNumber[Vars.lang]) Vars.instructions = readSystemFile(Vars.lang) timeZo...
009330189b255f5d6feb
def generate_tf_idf(dictionary, text, stopwords, reader=UnicodeReader(), stemmer=Stemmer()): words = [w.stem for w in map(stemmer, reader(text))] term_count = collections.defaultdict(int) for w in words: term_count[w] += 1 dict_out = {} for w, cnt in term_count.iteritems(): if w in dictionary: dict_...
009345755044b904ded5
def indexView(request): context={}; template_name='video/index.html' return render(request,template_name,context)
009369adad7270e842ac
def init_parameters(self): for m in self.modules(): if m.__class__ in [nn.Conv2d, nn.Conv3d, nn.ConvTranspose2d, nn.ConvTranspose3d]: init.xavier_normal_(m.weight.data) if m.bias is not None: init.normal_(m.bias.data) elif m.__class__ i...
00937d6c474cbf6a8c03
def calculate_FK(): # Compute individual transforms between adjacent links # T(i-1)_i = Rx(alpha(i-1)) * Dx(alpha(i-1)) * Rz(q(i)) * Dz(d(i)) T0_1 = TF_(dh['alpha0'], dh['a0'], dh['d1'], dh['q1']) T1_2 = TF_(dh['alpha1'], dh['a1'], dh['d2'], dh['q2']) ...
0093807a8fe1be2eb916
def normalise_around_zero(src_array, bsl_end=15000): out_array = src_array.copy() bsl = np.mean(out_array[:bsl_end]) out_array -= bsl out_array /= out_array.max() return out_array
0093bd50e2604b3bd49b
def _get_new_vertices(self): for vertex_id, vertex in enumerate( self._graph_state.get_vertices() ): if ( len(self._neighbor_positions.get(vertex_id, [])) == self._vertex_degrees[vertex_id] ): yield vertex.with_position...
0093c9bd8027d84a3828
def product(list): prod = 1 for i in list: prod = prod * i return prod
0093db519736e41a471e
def _make_tonnetz_matrix(): pi = np.pi chroma = np.arange(12) # Define each row of the transform matrix fifth_x = r_fifth*(np.sin((7*pi/6) * chroma)) fifth_y = r_fifth*(np.cos((7*pi/6) * chroma)) minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chroma)) minor_third_y = r_minor_thirds*(np.cos...
0093e64f7710470e76f4
def last(element): return element[-1]
0093e91305d118aaa182
def get_tag_version(nrml_node): version, tag = re.search(r'(nrml/[\d\.]+)\}(\w+)', nrml_node.tag).groups() return tag, version
0093f8c5126467ccc3e8
def origin_group_name(self) -> pulumi.Output[str]: return pulumi.get(self, "origin_group_name")
0094044f366c2dfb0554
def preprocess(): # Load the data random.seed(77) X,y = make_classification(n_samples=500, n_features=30, n_informative=8, n_redundant=2, n_repeated=0, n_classes=3, n_clusters_per_class=2, weights=None, flip_y=0.01, class_sep=1.0, hypercube=True,...
0094086fddb73aa0adfd
def run_scrape(self): self._open_browser() self._expand_players() self._get_players() self._get_injuries() self.browser.close()
00940dd53419012d20b8
def tokenizeComplexArr(val): last = None if val is None: return for item in val.split(): if not item: continue if last is None: last = item else: yield "%s %s"%(last, item) last = None if last: yield last
00942d4308aaecedbc37
def load_sql(sql_file, dbname): some_options = "-X -q -1 -v ON_ERROR_STOP=0 --pset pager=off" run_cmd("/usr/bin/psql {0} -d {1} -f {2}".format(some_options, dbname, sql_file))
0094373d1dd981db2f74
def get_id(col9): return col9.split(";")[0].replace("ID=", "")
009446d546809766410a
def get_timestamp(self): return self._timestamp
0094490a005108bed880
def verificar_maiorias(self): self.maiorias = {} for j in self.jogadores.values(): for naipe in j.mesa.keys(): quant = len(j.mesa[naipe]) if quant: # Aplica especial dados = {"naipe":naipe, "...
00948e7356bf0e7d07a2
def get_output_names(onnx_filepath: str) -> List[str]: return [output.name for output in get_external_outputs(onnx_filepath)]
0094a6ea232cac46d40c
def get_path(arr, node: int) -> str: n = len(arr) for subarr in arr: if len(subarr) != n: return "The adjacency matrix is incorrect!" node = int(node) if node < 2 or node > n: return "The node is incorrect!" arr_v = get_markers(arr, n) if arr_v[node - 1] == 999: ...
0094ad2f3d3bc3026d2c
def test_run_empty_tests(self): self.r.run_given_tests([], "", "")
0094c3dd482dec633ba5
def state(self) -> Union[None, str, int, float]: return self.entity.state
0094e2ea5e66256b54b3
def check(self, number): return number in self.items
0094efdfc6dc8592d114
def plot_hitstogram_graph(data_values, title, number_of_keys, max_val, file_in): #bins = max(data_values) #pylab.hist(data_values, facecolor='blue') pylab.hist(data_values, facecolor='green', alpha=0.6) pylab.grid(True) pylab.title(title+"_histogram") pylab.xlabel('number in cluster'...
0094f5f809d8629696ee
def fluxToMag(flux): return -2.5 * np.log10(flux)
009515f9cec78ad0eec6
def GetItemList(html, url, item_title, type_title): episode_list = html.xpath('//table[@class="listing"]/tr/td') item_title_decode = Common.StringCode(string=item_title, code='decode') item_title_regex = Regex(r'[^a-zA-Z0-9 \n\.]').sub('', item_title_decode) # if no shows, then none have been added ye...
00952e3a469b3e537ec7
def makeGeoTransform(self): geotransform = (self.xMin, self.xRes, 0.0, self.yMax, 0.0, -self.yRes) return geotransform
009547b1e1021f8a54cc
def transformation_synthesis(inputFile, fs, tfreq, tmag, freqScaling = np.array([0, 2.0, 1, .3]), timeScaling = np.array([0, .0, .671, .671, 1.978, 1.978+1.0])): # size of fft used in synthesis Ns = 512 # hop size (has to be 1/4 of Ns) H = 128 # frequency scaling of the sinusoidal tracks ytfreq = ...
00957d1eac52592f82ba
def diag_construct(a: Numeric): # pragma: no cover if B.rank(a) == 0: raise ValueError("Input must have at least rank 1.") # The one-dimensional case is better handled by `diag`. if B.rank(a) == 1: return B.diag(a) identity_matrix = B.eye(B.dtype(a), B.shape(a)[-1]) # Deal with th...
00957d48358387de834d
def get_device(serial: str, credential: str, device_type: str) -> Optional[DysonDevice]: if device_type == DEVICE_TYPE_360_EYE: return Dyson360Eye(serial, credential) if device_type == DEVICE_TYPE_360_HEURIST: return Dyson360Heurist(serial, credential) if device_type in [ DEVICE_TYPE...
0095a5b2fbdb2e4d724b
def generate_grid(batch_size, input_depth, input_height, input_width, dtype, cuda): grid = np.meshgrid( range(input_depth), range(input_height), range(input_width), indexing='ij' ) grid = np.stack(grid, axis=-1) grid = grid.reshape(-1, 3) grid = np.expand_dims(grid, 0) grid = np.tile(gr...
0095a95a5bfd24b58e1d
def binomial_coefficients_list(n): n = as_int(n) d = [1] * (n + 1) a = 1 for k in range(1, n//2 + 1): a = (a * (n - k + 1))//k d[k] = d[n - k] = a return d
0095ab7ff4f0576d42f6
def get_timezone_offset_hours_from_date(self, year, month, day, hour=6, minute=0, seconds=0): import pytz local_time = pytz.timezone(self.timezone).localize(datetime(year, month, day, hour, minute, seconds)) return (datetime.utcoffset(local_time).days * 86400 + datetime.utcoffset(local_time).sec...
0095b32f7be1284b35ef
def _set_enable(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/relay-agent', de...
0095cf45815714f2714f
def scale_features(self): df = stats.scale_features(self, metadata_string=self.metadata_string, prefix=self.prefix) return DataFrame(df, metadata_string=self.metadata_string, prefix=self.prefix)
0095cf5319095aae9e2f
def create_one_hot(eles): one_hot = {} for i, l in enumerate(eles): bits = [0]*len(eles); #Every element in the string/list is assigned 0 bits[i] = 1; #Only one bit is set to "ON" one_hot[l] = bits #Actual assignment is made return one_hot
0095d5ce54ac9bde7001
def get_organization(self): return self.org
0095f1e94d8b8caf9381
def get_protein_atomtypes(input_parm): # protein atomtypes proteic_atomtypes = [] for resid in input_parm.residues: for atom in resid.atoms: if atom.atomic_number in [6, 14, 16, 18]: # C, N , O and S if atom.name != 'C' and atom.type.isupper() and atom.type not in proteic...
0096069a7bdadcaa79b2
def reformat_code(code): py_ast = ast.parse(code).body[0] reformatted_code = astor.to_source(py_ast).strip() return reformatted_code
009607c405703d35bc68
def __start_task(self, taskresult): task = taskresult['task'] self.log.info("Starting task {id} - {name}".format(**task)) # notify that we are processing this task self.server_io.set_task_start_time(taskresult["id"]) token = self.server_io.request_token_for_container( ...
00961168e649560b142f
def vectorisation(): v = TfidfVectorizer(stop_words=stop_words, min_df=min_df, max_df=max_df) vectorised_df = pd.DataFrame( v.fit_transform(get_joined_skills()["skills_and_occup_descr"]).toarray(), columns=v.get_feature_names(), ) tfidf_values = pd.concat([get_joined_skills(), vectorised...
0096174ac22a0850e078
def plot_raw(self): plt.scatter(self.X, self.Y, label="Training Data", color="grey") # plots all the data points # axis labels / title plt.title("Working Experience vs Salary") plt.xlabel("Working Experience (Years)") plt.ylabel("Salary ($)") plt.legend() # displa...
00962909b0b88ce375ee
async def on_fetch(self, request, data: dict): if data.get("type") != "picklenode": return await self.conn.sendto( data["id"], "on_replicate", { "type":"picklenode", "value":base64.b64encode(pickle.dumps(self.stored)).decod...
0096424389b42c0ad1de
def load_snapshots(snapshots): snapshots = deepcopy(snapshots) version = snapshots.get(VERSION) if version is None: snapshot_list = snapshots.get(SNAPSHOTS, []) for snapshot_data in snapshot_list: snapshot_data[TIME_WORKED] = snapshot_data.get(TIME_WORKED, 0) snapshots[SN...
009647e9dc5b484a710f
def _start(self): self._sender = StreamitSender(self._data_queue, self._experiment_name, self._host) try: self._sender.start() self._is_started = True except Exception: print("Fail to start streamit client.")
00964d2be5de064398a8
def Tokenizer(text): #test "if reader is alpha:"; faster, slower than text[p].isalpha()? def alpha(p): i = 1 try: while CHAR_MAP.get(text[p+i]) is alpha: i += 1 except IndexError: pass return CM.GET_CONTEXT_OR_DEFAULT(text[p:p+i]), p+i def numeric(p): if text[p] == "0": try: num_type =...
0096528417ef055070ad
def store_secret(): def wrapped(key, value): sm = boto3.client("secretsmanager", region_name="us-west-1") sm.create_secret(Name=key, SecretString=value) return wrapped
00965e16693e2698aa33
def pc_output_buffers_full_var(self, *args): return _iio_swig.fmcomms_source_sptr_pc_output_buffers_full_var(self, *args)
0096669b605aa52300e2
def eval_safe(self, two_electron_func): def wrapper(k1, k2, k3, k4, *args, **kwargs): k = k1 + k2 - (k3 + k4) k = self.parameters.to_first_brillouin_zone(k) if np.linalg.norm(k) < constants.SMALL_NUMBER: return two_electron_func(k1, k2, k3, k4, *args, **kwargs...
009675ee9b6953e3823b
def UpdateStudent(self): firstName = self.firstNameText.text() lastName = self.lastNameText.text() msgdict = {'cmd':'UpdateStudent', 'data':{'ID':self.selectedID, 'values':{'first_name':firstName, 'last_n...
00967adfe241ac0480e7
def require(self, *requirements): needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
0096c6f5310d9b965589
def callback(widget, event): t = tvtk.Transform() bw.get_transform(t) bw.prop3d.user_transform = t
0096ca9ccbdc8f4715be
def get_report_in_dict(self): report = dict() properties_to_return=['reported_by', 'event', 'reported_time', 'examined', 'examined_by', 'examined_time', 'decision'] for prop in properties_to_return: report[prop] = self.__getattribute__(prop) report['reported...
0096dfe3fdd84527d09a
def coerceValue(cls, val): try: if not hasattr(cls, 'quantifier'): cls.quantifier = decimal.Decimal("0."+(cls.precision-1)*"0"+"1") return decimal.Decimal(val).quantize(cls.quantifier) except Exception as e: raise exceptions.DecimalValueError(val)
0096ee9d3f3eb232053a
def replaceTag(query, aInfo): string = query for tag in aInfo: string = string.replace('<' + tag + '>', str(aInfo[tag])) string = string.replace("<br>", '\n') return string
0096fd5e1c2d0d84b4d2
def player_bets(truecount, total_cards_dealt): if total_cards_dealt == 0: current_hand_bet = bet_per_round print("As this is the first round of the shoe, there is no available statistical information to use to place bets.") print("I will therefore bet {}".format(current_hand_bet)) e...
009719b9f862bc64c187
def camel_to_snake_case(name: str) -> str: return CAMEL_CASE_PATTERN.sub("_", name).upper()
009747071d8c91c658a3
def show(self): sleep(2) print("***** SCOREBOARD *****") print("*** HAND OUTCOMES ***") if self.player_wins == 1: print(f"{gambler.name} has won {self.player_wins} hand.") else: print(f"{gambler.name} has won {self.player_wins} hands.") if self.ho...
0097513cedb0d6dd6061
def run_experiment(self, opName): outdir = 'results/OPT/{}'.format(opName) # get results directory outfile = 'GA_{}_{}_{}_results.csv'.format(self.p, self.ma, self.mu) fname = get_abspath(outfile, outdir) # get output filename # delete existing results file, if it already exists ...
00978ab2ccb41cce0d7e
def suffixes(self): name = self.name if name.endswith('.'): return [] name = name.lstrip('.') return ['.' + suffix for suffix in name.split('.')[1:]]
00978b5934f81736cd5f
def categ_encoding(self, df: pd.DataFrame): logging.info("Category encoding") df_copy = df.copy() df_copy = pd.get_dummies(df_copy) return df_copy
0097b620fa92d13aeec6
def predict(self): t_t = self.t_t k = self.k H = self.H sys = self.sys M = self.M eta = self.eta r_m = self.r_m y_pred_full = [] pred_error = [] for t in range(1, t_t): X = [] for j in range(k): sc...
0097b8fd2ad3e10dd1ff
def url_check(domain, link): if 'href' in link.attrs: newurl = link.attrs['href'] elif 'src' in link.attrs: newurl = link.attrs['src'] else: return None # resolve relative URLs if newurl.startswith('/'): newurl = urljoin(domain, newurl) # ignore any URL that d...
0097e169e5f63a4bd1cf
def getPortsDetails(port_id): logger.debug('Start.') code, res = rest_requests.get(ports_url + "/" + port_id) if code != requests.codes.ok: logger.error((code, res)) return None return res["port"]
0097e6a0c6d7ce736878
def get_max_cnt_violation(self): max_vio = 0.0 for bound_expr in self._nonlin_cnt_exprs: cnt_vio = self._compute_cnt_violation(bound_expr) cnt_max_vio = np.amax(cnt_vio) max_vio = np.maximum(max_vio, cnt_max_vio) return max_vio
0098042c6fc80d1e93b3
def is_parent(self, some_process): if some_process.pid == self.monitor.parent_proc.pid: return True else: return False
009816439720048fe5f5
def set_default_quality_profile(self, language, qualityProfile):
009817c6938f44b995a2
def __layoutNodeTipOver(node, xPos, yPos, xOffset, yOffset): # No children? Then this is very easy to position... if(len(node._treeChildren) == 0): node.setNewCoords((xPos, yPos)) return node.getSize()[1] + yOffset # Has children, doh! Layout children first, then position parent else...
009820bf42f9d7a8dfc5
def promptForSave(self, info, cancel=True): if self.saveObject.dirty: code = confirm(info.ui.control, self.savePromptMessage, title="Save now?", cancel=cancel) if code == CANCEL: return False elif code == YES: ...
00983bc887ef9f1368a9
def generate(self): print("generate") with open(self.file, "r") as file: lines = file.readlines() self.gridsize = lines[0].split() self.startposition = lines[1].split() for sprite in lines[2]: if sprite != " " and sprite != "\n": ...
00983c5eb7adca5d1a87
def get_context(cls): return g
009852d90c908680ec13
def is_ngff( # noqa: PLR0911 path: Path, min_version: Version = MIN_NGFF_VERSION, max_version: Version = MAX_NGFF_VERSION, ) -> bool: path = Path(path) store = zarr.SQLiteStore(path) if path.is_file() and is_sqlite3(path) else path try: zarr_group = zarr.open(store, mode="r") except...
00985db51bd652adf9b3
def get(self): self.post()
00985dfd53995d28861b
def QueryState(self): return self.state
00985fef4249beac8c05
def get_num_infected(self) -> int: return self.__num_infected
00986a4c787bce9eac75
def overhead(): return 1.3
009871add3ed3b941589
def year(): conn = sqlite3.connect('./refugee_data.sqlite') # conn.row_factory = dict_factory cur = conn.cursor() rows = cur.execute("SELECT DISTINCT year FROM refugee_data WHERE Origin NOT IN ('Various/Unknown') ORDER BY year") year_list = [] for row in rows: year_list.append(row[0]) ...
0098787b8a9dd67fff5d
def tensor_dim(self): return self.dim() - self.nested_dim()
00988971a4c86aceec51
def rating_info(self): zeros, ones, twos, threes, fours, fives = 0, 0, 0, 0, 0, 0 count = 0 rating_sum = 0 for track in self.tracks.keys(): rating = self.tracks[track].rating if rating == 20: ones += 1 elif rating == 40: ...
0098ac14cdd00efd289f
def test_image_field_of_view_tall(self): fov_wanted = [15.0, 29.05191311] * astropy.units.deg ref_val = astropy.coordinates.SkyCoord( ra=0 * astropy.units.deg, dec=0 * astropy.units.deg, frame="icrs" ) wcs = kbmod.analysis.wcs_utils.construct_wcs_tangent_projection( ...
0098f6a204d6eaf07cf5
def style(self, style): self._style = style
0099080a6d34ba91ca9b
def setUp(self): self.client = Client() call_command('flush', verbosity=2, interactive=False) self._pre_setup()
0099371acbfbfd69ab0e
def object_update(self, obj): object = self.gameobjects[obj['objid']]
00993ca43decf26ad74c
def _snapshot_db(cls, identifier): # pragma: no cover cls._db_snapshots[identifier] = cls._get_dump()
009958ce182cf6a97994
def __pencil(self): if self.action == "pencil": self.change_action("no") else: self.change_action("pencil")
009968445ce141bedc89
def greet_users(names): for name in names: msg = "Hello, " + name.title() + "!" print(msg)
00997e87f24c3eca11f7
def has_forgon_this_turn(self) -> bool: return assert_set(self._has_forgon_this_turn)
009984e0cc3569c50237
def set_cell(self, row, col, obj): if isinstance(obj, JavaObject): obj = obj.jobject javabridge.call( self.jobject, "setCell", "(IILjava/lang/Object;)V", row, col, obj)
00999b52235b193601f1
def decompress(path): store = zarr.ZipStore(path, mode='r') root = zarr.group(store=store) return decompress_zarr(root)
00999bc9f346d6007cff
def _parse_packet(self, packet): logging.debug("Received packet:\n%s" % packet) contents = packet.split(" ") if len(contents) < 8: logging.error("Received incomplete packet.") raise ParseError("Packet too short.") point1 = (int(contents[1]), int(contents[2])) ...
0099b2aac4ce2019a4ca
def load_synthetic(): path = os.path.join(EXAMPLE_DIRECTORY, 'synthetic.tif') data = sl.load(path) return data
0099c9614490f58d67ac
def saveit(self): data = self.settings() print(data) try: with open('mutespeak.json', 'w') as fp: json.dump(data,fp) except IOError: print('Could not save settings')
009a1096a8659a2c207c
def text(self, text, enter=True): if enter: text += '\n' self.keyevent(text)