id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
8
768k
ff924a685e45e30fb042
def md5(fname): hash_md5 = hashlib.md5() with open(fname, 'rb') as f: for chunk in iter(lambda: f.read(4096), b''): hash_md5.update(chunk) return hash_md5.hexdigest()
ff929ec060f1f082cb21
def get_records(): # Download if doesn't exist # There are 3 files for each record # *.atr is one of them paths = glob('/path/to/MITDB/dataset/*.atr') # Get rid of the extension, [:-4] to remove '.atr' paths = [path[:-4] for path in paths] paths.sort() return paths
ff930223ca2356d76956
def RunTrainingSteps(self, config_string, num_steps=10): config = defaults.default_config_with_updates(config_string) FLAGS.max_npe = num_steps * config.batch_size FLAGS.logdir = tf.test.get_temp_dir() FLAGS.config = config_string run.main(None)
ff93044830baa55f383e
def file_format(self, file_format): self._file_format = file_format
ff9306b17d27ed913111
def gen_card(): rank = '23456789TJQKA' suits = [] for i in rank: for j in 'CDHS': suits.append(i+j) return suits
ff931887b4510c41ac05
def saveSelectedDataToCsvFile(self, filename): data_list = [] headers = [] paths = [] print 'Fields in file:' for item in self.selectedItems(): if isinstance(item.h5node, h5py.Dataset): # Avoid the spurious 0-th entry in MOOSE table dat...
ff9344824ae88a208678
def RunSolutionLoop(self): while self.KeepAdvancingSolutionLoop(): self.time = self._GetSolver().AdvanceInTime(self.time) ini_time = time.time() self.InitializeSolutionStep() self.initialize_step_time += time.time() - ini_time self._GetSolver().Predict...
ff938cb4ccf3681fbc05
def map_cyclic_coords(self, x): return (x + self.mid) % self.dim - self.mid
ff93a23b52147be80265
def test_retrieve_ingredients_assigned_to_recipes(self): ing1 = Ingredient.objects.create(user=self.user, name='Apples') ing2 = Ingredient.objects.create(user=self.user, name='Turkey') recipe = Recipe.objects.create( title='Apple crumble', time_minutes=6, ...
ff93db1f0e4451110097
def split_data(cls, data, ratio, seed): np.random.seed(seed) n_train = int(len(data["input_ids"]) * ratio) idx = np.arange(len(data["input_ids"])) np.random.shuffle(idx) train_idx = idx[:n_train] val_idx = idx[n_train:] train_data = {k: np.array(data[k])[train_idx] for k in data.keys()} ...
ff93f5a2fe1f5fd6a8ae
def expand_sent(tagged_tokens,en_lists): full_tags = [(tag or None) for _, tag in tagged_tokens] simp_tags = [((tag and tag[0]) or None) for _, tag in tagged_tokens] for i, (t, tag) in enumerate(tagged_tokens): if tag and tag.startswith('v') and (not tag[2] == 'p'): use_pronoun = ('n' n...
ff940ed5b18a22dcf409
def test_get_next_word_03_empty_line(self): # Arrange line = "\n" # Act result = get_next_word(0, line) # Assert self.assertEqual(END_OF_LINE, result)
ff944aa51901af5cf4f1
def compute_smooth_flux(self): self.observed_smooth_flux = {} for b in self.bands: self.observed_smooth_flux[b] = self.mass * ( (1 - self.stochastic_mass_fraction) * observed_cts_per_sec(self.smooth_flux[b], self.distance, self.zpt[b]))
ff9462bc2bdc2c42e9e5
def generate_test_data(preconfirm=False): if settings.DJANGO_ENV == settings.PRODUCTION: print("This cannot be run in production! Aborting.") return if not preconfirm and not confirm_run(): return management.call_command("flush", interactive=False) course_info = [ # (nam...
ff9471a8bce310d4b220
def new_game(cls, user, start_time): values = [i for i in range(52)] shuffle(values) fliped = [False for i in range(0, 52)] game = Game(user=user, start_time=start_time, game_over=False, gameboard_values=values, ...
ff94884aa9b5675bf885
def compose_resource_path( self, namespace: str, name: str = None, api_version: str = None, suffix: str = None, ) -> str: api_version = api_version or self.api_version version_header = "apis" if re.match(r"v[0-9]+", api_version): version_he...
ff94a45d0dd2c4d36f3c
async def calendar_task(client, system): await client.wait_until_ready() while not client.is_closed() and system.time_manager is not None: logger.debug("Checking the calendar for reminders.") reminders = system.time_manager.clock_pass() for date, reminder_embed, channel_name, tag_name in...
ff94c2db20c17ce1a376
def least_cost_path(self, graph, start, dest, cost): # est_min_cost[v] is our estimate of the lowest cost # from vertex start to vertex v est_min_cost = {} # parents[v] is the parent of v in our current # shorest path from start to v parents = {} # todo is the s...
ff94dfd0cd7b056312f5
def create_gaussian_files(self) -> None: # prepare directory for gaussian files cleanup_directory_files(self.directory, types=["com"]) os.makedirs(self.directory, exist_ok=True) # resources configuration n_processors = 1 #max(1, min(config['slurm']['max_processors'], ...
ff951ec3a95bf5f628b5
def test_if_true(self): prog = ['if', 1, 42, 0] result = eval_prog(prog) self.assertEqual(result, 42)
ff955028662ebc65a4c9
def load_profiles(self,filename,valid_split=0.2): with open(filename, 'rb') as f: myattrs = pd.read_pickle(f) for key in myattrs: setattr(self, key, myattrs[key]) # processing self.test_profiles = np.array(self.test_profiles) test_...
ff95657004e35f54488f
def rates(self): self.r_ik = { "pp": self.n_p ** 2 * self.lmbda_values["pp"] / (2 * self.rho), "33": self.n_He3 ** 2 * self.lmbda_values["33"] / (2 * self.rho), "34": self.n_He * self.n_He3 * self.lmbda_values["34"] / self.rho, "e7": self.n_Be7 * self.n_e * self.l...
ff956f938fd669283699
def __ne__(self,other) : return not(self == other)
ff957a6b4bedb51bd333
async def test_gain_all_single(self, client: aiokatcp.Client, sensor_proxy_client) -> None: await self._configure_subarray(client, SUBARRAY_PRODUCT) await client.request("gain-all", "gpucbf_antenna_channelised_voltage", "1+2j") # TODO: this doesn't check that it goes to the correct nodes ...
ff95bab58766af4c5f89
def num_samples(self): return len(self._samples)
ff95bb4939af5b7f450a
def is_git_template(self): return "git" in self.template_path or "https" in self.template_path
ff95be4982ae22f3bcd7
def set_geo(self, api): geo = api.geo(self.host)['geo'] self.country = geo['country'] self.region = geo['region'] self.city = geo['city']
ff95f45a1bde951c8d16
def rasterizeSingle(info, vector, progress): try: if info.isFirstBlock(): projection = info.getProjection() veclayer = vector.layer if not vector.matchingProj(projection): veclayer = vector.reproject(projection) ...
ff960baba9e4a30abd48
def pyfunc(x, y, t): for i in range(t): x, y = y, x return x, y
ff961fce91afe5955f00
async def embeds(self, ctx, search=100): await self.do_removal(ctx, search, lambda e: len(e.embeds))
ff9635af1ff17bb771bc
def filter_sig_OTUs(genomes, sig_file, sig_cutoff): #open file to be parsed and toss first line f = open(sig_file, 'U') if f.closed: "KO's not opened" return genomes f.readline() #for each line in file write KO, direction, weight otus = set() for line in f: line = li...
ff9682e608cc7dd309da
def store_pubkey(username, home_dir, pubkey): dir_ssh = os.path.join(home_dir, '.ssh') if not os.path.exists(dir_ssh): os.makedirs(dir_ssh, mode=0o700) auth_key_path = os.path.join(dir_ssh, 'authorized_keys') pubkey = '{0}\n'.format(pubkey.strip()) with open(auth_key_path, 'wb') as fd: ...
ff968b7ea5714590dd98
def add_asset(self, asset: Asset, ownership_type: AssetOwnershipType, amount: int) -> None: assert isinstance(asset, Asset) assert isinstance(ownership_type, AssetOwnershipType) key = dsha256(asset.name + ownership_type.value).encode('utf-8') try: prev_value = int.from_byte...
ff96a83db6ae34831ffc
def set_phone(self, data): self.phone = data
ff96b4650ab11949016a
def user_data(): stocklist = request.form.getlist('stocklist') gender = request.form.get('gender') agegroup = request.form.get('agegroup') income = request.form.get('income') amounttoinvest = request.form.get('amounttoinvest') riskexpectation = request.form.get('riskexpectation') re...
ff96bf142b4bfe8b1d7b
def verify(self, request: CaptchaRequest): if not request: raise Exception("Invalid request") valid_captcha = self.captcha_repository.check(request.id_form, request.captcha) self.captcha_repository.update_form(request.id_form) return True if valid_captcha else False
ff96d8a3b806dd88b012
def _create_schema_for_validation(cls, context) -> typing.Union[PathAwareSchema, Schema]: raise NotImplementedError()
ff972929117435d51c0a
def show_point_cloud(self): import open3d as open3d rgbd = open3d.geometry.RGBDImage.create_from_color_and_depth(open3d.geometry.Image(self.img), open3d.geometry.Image(self.dep_raw)) # it looses the colors with the create func...
ff975a807c894eaabbba
def download_file_by_path(server_path, path_to_store_file, control_sock, session_id, server_ip, progressbar, queue, group=''): file_to_download_to = open(path_to_store_file, 'wb') attemps_counter = 0 data_sock = passive_connect(control_sock, server_ip) data_sock.settimeo...
ff97ced3099375f67cdd
def is_in_operation(self): return self.get_operation() is not None
ff97d654a18037843f08
def Main(): build_targets = frozenset([ 'download', 'dpkg', 'dpkg-source', 'msi', 'osc', 'pkg', 'rpm', 'source', 'srpm']) argument_parser = argparse.ArgumentParser(description=( 'Downloads and builds the latest versions of projects.')) argument_parser.add_argument( 'build_target', choice...
ff97e91ea57b2811024c
def dumps(self, obj: D) -> bytes:
ff97edda785a31134d66
def create_widget(self, interactive=True): # XXX: Clean up this horrible mess widget = self.adaptor.create(self.project.context, interactive) self.project.set_new_widget_name(widget) self.setup_widget(widget) self.adaptor.post_create(self.project.context, widget, interactive) ...
ff97f5a4fe0fd43c9fd4
def close(self): self._conn.close()
ff9815be90505dc8529c
def randomString(): length = random.randrange(4, 10) letters = string.ascii_lowercase + string.digits return ''.join(random.choice(letters) for i in range(length))
ff9830518acdd7c3b429
def set_attribute(self, name, value=None): self.__attributes[name] = value return self.__attributes
ff986472817a7dcbebc4
def logistic_regression(self, penalty='l2'): models = [] for X, y in self._training_data(): model = LogisticRegression(solver='liblinear', penalty=penalty, random_state=self.seed) model.fit(X, y) ...
ff98686a0377f8fd757f
def release_group(): rebulk = Rebulk() expected_group = build_expected_function('expected_group') rebulk.functional(expected_group, name='release_group', tags=['expected'], validator=seps_surround, conflict_solver=lambda match, other: other, ...
ff986c9509f66302bb6e
def remove_punctuation(self, text): return text.translate(str.maketrans('', '', string.punctuation))
ff987765aee922834eb6
def re_ranking(q_g_dist, q_q_dist, g_g_dist, k1=20, k2=6, lambda_value=0.3): # Don't care about it. original_dist = np.concatenate([np.concatenate([q_q_dist, q_g_dist], axis=1), np.concatenate([q_g_dist.T, g_g_dist], axis=1)], axis=0) original_dist = 2. - 2 * original_dis...
ff9886b0f51f8db90c6d
def plot_undulation_spectrum(ax,sn,**kwargs): mesh = data[sn]['data']['mesh'] surf = mesh.mean(axis=0) #! somewhat amazing that the following is necessary, but it is surf = (surf - np.tile(surf.reshape(len(surf),-1).mean(axis=1), (surf.shape[1],surf.shape[2],1)).transpose(2,0,1)) vecs = data[sn]['data']['vecs'] ...
ff98950267d6fcc62b5c
def updateUserOverdue(user): days_since_joined = (timezone.now() - user.date_joined).days checkups = user.study_participation.checkup_set.all().order_by("daysUntil") appointmentsAttended = Appointment.objects.all().filter(patient=user).filter(noshow=False).order_by('appointment_start') # get number of att...
ff98a1603ff0ea9e7b98
def test_sum_all_positive(): os.chdir(".") from preparatory_assignment import list_sum # given numbers = [1,2,3,4] expected_result = 10 # Execute result = list_sum(numbers) # Compare print(result == expected_result) assert result == expected_result
ff98a582a0981b77da6c
def get_parameter_data(self, index): value_str = create_string_buffer(256) value = c_void_p() value_len = c_uint() self._call_fmod( "FMOD_DSP_GetParameterData", index, byref(value), byref(value_len), value_str, len(v...
ff98ad0ef1ba2dd86d2e
def show_all_experiments(): return Experiment.list(WS)
ff98e8109e0586e7cd7d
def accumulation_2d_neighborhood( point_cloud, bin_size=1 ): xmin, xmax = np.min(point_cloud["x"]), np.max(point_cloud["x"]) ymin, ymax = np.min(point_cloud["y"]), np.max(point_cloud["y"]) xbins = np.arange(xmin, xmax + bin_size + BIN_BUF, bin_size) point_cloud["xbin"] = pd.cut(point_cloud.x, xb...
ff98ff65bb50cb9fb543
def meshgrid(x, y, normalized_coordinates=False, requires_grad=False): xs = torch.linspace(0, int(x - 1), int(x), device=get_session_value('device'), dtype=Dtype.float, requires_grad=requires_grad) ys = torch.linspace(0, int(y - 1), int(y), device=get_session_value('device'), dtype=Dtype.float, requires_grad=re...
ff991b2dafdea82890c8
def test_filter_by_product(self): cv = self.F.CaseVersionFactory.create(name="Case 1") self.F.CaseVersionFactory.create(name="Case 2") res = self.get(params={"filter-product": cv.case.product.id}) self.assertInList(res, "Case 1") self.assertNotInList(res, "Case 2")
ff9939c60b11b613f7e4
def _convertToDict(self): if self.isEmpty: self.raiseAnError(ValueError, f'DataObject named "{self.name}" is empty!') self.raiseAWarning('DataObject._convertToDict can be a slow operation and should be avoided where possible!') # container for all necessary information dataDict = {} # supporti...
ff995b0da82bf3261feb
def save_pickle(file_path, data): with open(file_path + '.pkl', 'wb') as f: pickle.dump(data, f)
ff99879d9935caf862c7
def flatten_json(nested_json): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 ...
ff998afb21872b8f0c3a
def count(amount, maxcoin=0): if maxcoin == Ncoins - 1: return 1 res = 0 for i in range(maxcoin, Ncoins): amount_left = amount - coins[i] if amount_left == 0: res += 1 if amount_left > 0: res += count(amount_left, i) return res
ff999f8c7ea77156b2d6
def testAddTag(self): sample = self.session.create_sample() sample.add_tag("test") self.assertEqual(sample.tags, ["test"], "Can add a tag to a sample.") json_str = sample.to_json() doc = json.loads(json_str) self.assertEqual(doc['meta']['tags'], ["test"], ...
ff99b5b47b0c59af2170
def is_box_in_box(corners1, corners2): min_x = min(map(lambda x: x[0], corners2)) max_x = max(map(lambda x: x[0], corners2)) min_y = min(map(lambda x: x[1], corners2)) max_y = max(map(lambda x: x[1], corners2)) width = max_x - min_x height = max_y - min_y for p in corners1: if p[0] >...
ff99beb0ff46a46824e2
def transaction(personInfo, idNum): #get current date, and input, store in temp file date = (time.strftime("%y.%m.%d")) trans = raw_input('\n\tW)ithdraw or D)eposit: ') amount = raw_input('\tAmount: ') for log in personInfo: accInfo = log.split(':') name = accInfo[1] temp = open('temp.db', 'a') temp.w...
ff99d81c489c3bb8f566
def reconstruct(self): res = 0 N = 1 def modular_inverse(a, b): """ Computes the modular inverse x = a^(-1) mod b with Euclid's extended algorithm. The coefficient are computed and stored in a list in ascending order of moduli. The list is then tu...
ff99e1c9bcd474671e10
def UTC(self): # timezone.utc pass
ff99e5c33fc9caecaaee
def create( self, resource_group_name, # type: str account_name, # type: str share_subscription_name, # type: str invitation_id, # type: str source_share_location, # type: str **kwargs # type: Any ): # type: (...) -> "models.ShareSubscription" ...
ff9a0e10a51dd32a6363
def measure(self): return abs(SpiAdc.measure(self) - Sound.CAL)
ff9a157ccd62c3668792
def bilinear_sampler(self, img, batch_grids): if self.inverse: input_shape = tf.shape(img) # [B, B', H, W, C] H_x, W_x = input_shape[2], input_shape[3] else: input_shape = tf.shape(img) # [B, H, W, C] H_x, W_x = input_shape[1], input_shape[2] x =...
ff9a1cb48e415061dff8
def analyze_something(): pass
ff9a6817ef1a1239a831
def _update_mapping_type(self): self._last_sent_value = -1 self._mapping_type = SLIDER self._smoother.stop_smoothing() if self._parameter_to_map_to is not None: param = self._parameter_to_map_to if self._is_fine_tuning: self._mapping_type = INC_DEC...
ff9a7af51aa029907a94
def login_error(request): messages = get_messages(request) return render_to_response( 'scs/error.html', {'version': version, 'messages': messages}, RequestContext(request) )
ff9a7c30a73029d22378
def dhcpsapi_DhcpEnumClasses(jitter): ret_ad, args = jitter.func_args_stdcall(["ServerIpAddress", "ReservedMustBeZero", "ResumeHandle", "PreferredMaximum", "ClassInfoArray", "nRead", "nTotal"]) raise RuntimeError('API not implemented') jitter.func_ret_stdcall(ret_ad, ret_value)
ff9aab904a25936fe683
def quit(bus_name, binary): if running_dbus(bus_name): remote = dbus.SessionBus().get_object(bus_name, '/MainApplication') remote.quit() sleep(0.5) if running_dbus(bus_name): raise Exception("Couldn't properly quit %s" % bus_name) return True if running_binary...
ff9acdff8e58ecb05f4a
def get_data_loaders(args, tokenizer): personachat = get_dataset(tokenizer, args.dataset_path, args.dataset_cache) print("Build inputs and labels") datasets = {"train": defaultdict(list), "valid": defaultdict(list)} for dataset_name, dataset in personachat.items(): num_candidates = len(dataset[...
ff9ad9ed2f6dd96cb03f
def add_report_item(self, severity, engine_name, data): self._persistor.add_report_item(severity, engine_name, data)
ff9ae2ead9ad0a4894e8
def check_and_run(func: Union[str, Callable], *args, **kwargs) -> Any: if isinstance(func, str): func = get_global_func(func) return func(*args, **kwargs) # type: ignore
ff9b0bb6711289526af7
def disable(self): self.__logger.info('Output turned off.') self.__pwm.turn_off()
ff9b27cadeb2ebd9600b
def compound(r): return np.expm1(np.log1p(r).sum())
ff9b4b1587a5bcc910bf
def color_threshold(img): yellow = select_yellow(img) white = select_white(img) combined_binary = np.zeros_like(yellow) combined_binary[(yellow >= 1) | (white >= 1)] = 1 return combined_binary
ff9b6bccb3eeff89f0c0
def init_vehicle_patch(vehicle, index): length, width = vehicle.get_data(('length', 'width')) return (plt.Rectangle(xy=(-150, -150), width=length, height=width, fc=vehicle_color(index), zorder=100+2*index), plt.Rectangle(xy=(-150, -150), width=length/5, height=width, ...
ff9b9d8e237408c71ade
def feeding_season(self): for landscape in self.map.values(): landscape.feed_all_herbivores() landscape.feed_all_carnivores()
ff9ba38c81e2f71960c0
def _at_goal(self, new_state): (n, m) = new_state.shape return new_state[int(n / 2), int(m / 2)] == 1
ff9ba463ee4e67b38a00
def vmd_out(self,filename): with open(filename,'w') as f: positions = self.get_pos_arr(force=True) formatstring = "{color} {x} {y} {z}\n" for ind,row in enumerate(positions): f.write(formatstring.format(x=row[0], y=row[1], z=0, color=self.cells...
ff9bffb24fc8ea01ce5a
def calculate_kstest(long_short_signal_returns): #TODO: Implement function ticker_groups = long_short_signal_returns.groupby('ticker') return_ks_values = pd.Series() retrn_p_values = pd.Series() all_returns = long_short_signal_returns['signal_return'] normal_args = [np.mean(all_returns), np...
ff9c00c80dedd58a2963
def bigram(string): char, time, lis_char = "", 0, dict() for i in xrange(len(string) - 1): key = string[i] + string[i + 1] lis_char[key] = lis_char.get(key, 0) + 1 if lis_char[key] > time: time, char = lis_char[key], key print char , "\n", time
ff9c1724f80cb8201ade
def remove_status_widgets(self): for w in self.get_status_widgets(): self.remove_status_widget(w)
ff9c382611ca4335ced5
def _update_weights(weights, y_example, x_example, learning_rate): return weights + learning_rate * y_example * x_example
ff9c3900844a765a7b8f
def get_health(self): if self._process is not None: try: status = self._process.status() return {'exists': True, 'status': status} except psutil.NoSuchProcess: pass return {'exists': False, 'status': None}
ff9c557bcecd376f66fb
def initialize_agents(): # Staff for ward in range(parameters.number_of_wards): for role, total_number in parameters.initial_regular_staff.items(): for i in range(total_number): hire_staff(ward=ward + 1, role=role, hour=0) # Patients for i in range(int(roun...
ff9c66efafc2e6099840
def getPrimaryKeys(self, tableName): table = self.getTable(tableName) return table.primary_key.keys()
ff9c7103620ead34cf4f
def getQuarter(side, point): # Checks on which side of the bottom-left to top-right diagonal the point # is. posDiag = (point[1] - point[0] > 0) # Checks on which side of the top-left to bottom-right diagonal the point # is. negDiag = (point[0] + point[1] - side < 0) if posDiag: if...
ff9c764f4df134d037fb
def getVarName(grid): return str(Util.cleanTypeName(GridUtil.getParamType(grid).getComponent(0).getName()))
ff9cd5c775a43ddfe85f
def create_indexes(self, model): return NotImplementedError()
ff9cf0830750165aae94
def sort_count(arr): max_element = int(max(arr)) min_element = int(min(arr)) range_of_elements = max_element - min_element + 1 # Create a count array to store count of individual # elements and initialize count array as 0 count_arr = [0 for _ in range(range_of_elements)] output_arr = [0 for ...
ff9cfc193b5d005598fc
def screen_detail_substitute(self, origin_id, substitute_id): (origin_designation, origin_grade, substitute_designation, substitute_grade, \ url, stores, \ substitute_exist) = self.db.show_product_detail(origin_id, substitute_id)[0] print("Produit d'origine :\n {}".format(orig...
ff9d06c9dcf7043857fa
def get_data(self): with open(os.path.join('data_file.csv'), 'r') as fin: reader = csv.reader(fin) data = list(filter(None,reader)) return data
ff9d0cf3925d6deb7bb5
def setUp(self): self.o0 = State()
ff9d10109d7e8006055c
def active_thread_priority(self): return _transmit_nodes_swig.howto_bfweight2_cc_sptr_active_thread_priority(self)