id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
8
768k
ffb6d322407017058d98
def __init__(self): # Crear un socket TCP/IP self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
ffb6eb5f27b436f9d02d
def _find_file(filename): return pyrewall.find_file(filename=filename, paths=TEST_SEARCH_PATH, extensions=TEST_SEARCH_EXT)
ffb72b566852f332aedf
def merge_dicts(*args): iter_ = iter(args) mergedict_ = six.next(iter_).copy() for dict_ in iter_: mergedict_.update(dict_) return mergedict_
ffb733267b19ac42c353
def count_columns(self): return len(self.columns)
ffb75a10b87a0acbc5df
def test_IOError(self): self.P.read_struct(datafile("Ni.stru")) self.assertRaises(IOError, self.P.save_struct, 1, "nodir183160/"+self.strufile)
ffb771bf37cd3932342c
def get_time(self, server_list): sock_list = [] # connect to all time servers for server in server_list: self.logger.debug("Opening socket to time server: %s", server) try: sock = socket.socket(self.family, socket.SOCK_DGRAM) self.logger.de...
ffb7816ed0b739952d65
def findRelationship(self, tableName): cursor = MySQL() names = self.findAllForeignKeyTables(tableName) finalList = [] if len(names) > 1: for i in range(0, len(names), 2): List = [] cursor.do("select " + names[i][1] + " from " + names[i][ ...
ffb7932e771de972e6af
def display_win(self) -> None: print("YOU WIN!")
ffb79a703f64957a48ba
def get_wind_speed(speed): if speed < 10: wind_speed = ARROWS_UNICODE['RIGHTWARDS ARROW'] elif speed < 20: wind_speed = ARROWS_UNICODE['RIGHTWARDS PAIRED ARROWS'] else: wind_speed = ARROWS_UNICODE['THREE RIGHTWARDS ARROWS'] wind_speed += string_to_fullwidth(str(speed), 2) + 'mph'...
ffb7b4914d4881ae14dc
def unique_slug(item,slug_source,slug_field): if not getattr(item, slug_field): # if it's already got a slug, do nothing. from django.template.defaultfilters import slugify slug = slugify(getattr(item,slug_source)) itemModel = item.__class__ # the following gets all existing slug values ...
ffb7bebe6992e5e50f03
def test_recurrent_actor_critic_base(self): class Base(ActorCriticBase): def forward(self, ob, state_in=None): if isinstance(ob, PackedSequence): ob = ob.data logits = np.random.rand(ob.shape[0], 2) if state_...
ffb7e5a4a2220e703091
def _err(self, msg=None): return mudsling.errors.CommandInvalid(cmdline=self.raw, msg=msg)
ffb808ddb60dcafbd743
def test_f_score(): y_true = [1, 1, 2, 2, 3, 4, 5] y_pred = [1, 2, 2, 2, 3, 4, 5] desired_output = 2*(1.0/3)*0.5/((1.0/3)+0.5) assert_almost_equal(clustering.paired_f_score(y_true, y_pred), desired_output) y_true = [1, 1, 1, 4, 5, 5, 0, 4] y_pred = [1, 1, 1, 1, 5, 5, 6, ...
ffb86d8fcc3aaeaf4cc3
def run_continuously(interval=5): cease_continuous_run = threading.Event() class ScheduleThread(threading.Thread): @classmethod def run(cls): while not cease_continuous_run.is_set(): schedule.run_pending() time.sleep(interval) continuous_thread =...
ffb885a2b0deedb30bfd
def random_colors(N, bright=True): brightness = 1.0 if bright else 0.7 hsv = [(i / N, 1, brightness) for i in range(N)] colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv)) random.shuffle(colors) return colors
ffb89cc89e3d27b179bb
def bringAllToFront(self): for window in self.windows: window.showNormal()
ffb8ab80c3d831de1a9a
def homepage(): return render_template('home/index.html', title='welcome')
ffb8c8ccdbc87c8d1865
def test_get_suggested_paths(self): query_string = [('limit', 789), ('offset', 789)] response = self.client.open( '/api/v1/user/{userId}/suggestedPaths'.format(userId=789), method='GET', query_string=query_string) self.assert200(respons...
ffb8d6b2a9354e1260fd
def test_do_select_all(test_dao): DUT = dtmTestMethod(test_dao) _tree = DUT.do_select_all(parent_id=1) assert isinstance(_tree, Tree) assert isinstance(_tree.get_node(1).data, RAMSTKTestMethod)
ffb8e76d0e9b297a8427
def length(node): if node is None: return 0 if node is not None: count_len = length(node._next) count_len = count_len + 1 return count_len
ffb8ed819a21e52cf417
def check_bool_is_false(val: Any) -> bool: if not val and isinstance(val, bool): return True raise ValueError(f'Value should be "False"; got {val}')
ffb8f04b26fc00e48b61
def minimum_distance(a, b, p): a = np.array(a) b = np.array(b) p = np.array(p) t = np.dot( p - a, b - a ) / np.linalg.norm( a - b )**2 t = np.clip( t, 0, 1 ) proj = a + t * ( b - a ) return np.linalg.norm(p-proj)
ffb93fbb03a2955146a0
def _take_screenshot(self): screenshot_name = self._get_next_screenshot_name() screenshot_file_name = self._get_screenshot_session_file_name(screenshot_name) get_buffer_manager().get_color_buffer().image_data.save(screenshot_file_name) self._screenshots.append(screenshot_name)
ffb95143e32535c2bb0c
def init_embedding(n_vectors, dim): entity_embeddings = nn.Embedding(n_vectors, dim) entity_embeddings.weight = nn.Parameter(nn.init.xavier_uniform_(torch.empty(size=(n_vectors, dim))), requires_grad=True) return entity_embeddings
ffb9720644c194c35fb4
def forward(self, data: np.ndarray) -> np.ndarray: return data.flatten()
ffb972bbb49d4b8dfb49
def set_state_sizes( self, state_sizes ): self.state_sizes = state_sizes
ffb983f329acf375084a
def _log_like(self, th): #compute positive normalized basis th_zs = th[0:self._K*self._Nz] zs = th_zs.reshape((self._K, self._Nz)) logBs = (zs[:,0] + zs[:,1:].T).T Bs_unnorm = self._cell_vol * np.exp(logBs) row_sums = Bs_unnorm.sum(axis=1) Bs = Bs_unnorm / row_sums[:...
ffb9abb1c62990876481
def main(): unittest.main(verbosity=2)
ffb9be7f4a171275e927
def radius_server_secret(self) -> Optional[str]: return pulumi.get(self, "radius_server_secret")
ffb9f3980d0310d2594a
def get_queryset(self): return (AuthToken.objects .filter(user=self.request.user) .order_by('-created'))
ffba0a430f6aaaa3cf35
def _rectOverlapROIs(top, bottom, pos): # the position of the top rect coordinates give bottom top right = (0,0) tr = (pos[0]+top[0],pos[1]) tl = pos br = (pos[0]+top[0],pos[1]+top[1]) bl = (pos[0],pos[1]+top[1]) # do an overlap test to weed out corner cases and errors def inBounds(a, b): ...
ffba2162ff5f31f10007
def _clean(self, response): try: if self.command_object: # might not have found it yet response = self.command_object.clean_response(response) return response.decode("utf-8").split("\r\n") # first element of list should now be the command, but we'll let the caller filter that except UnicodeDecodeEr...
ffba4234534896359668
def split_data(data, n_parts): part_length = len(data) // n_parts + 1 return [data[i:i + part_length] for i in range(0, len(data), part_length)]
ffba43a2266a8b9623ca
def find_clusters(location_ids, location_vectors, tol, strict=False): location_vectors = np.asarray(location_vectors) location_ids = np.asarray(location_ids) if location_vectors.ndim == 1: location_vectors = location_vectors[:, np.newaxis] adj = _adj_list(location_vectors, tol) # adj = list of...
ffba4777accff82092a1
def iter_dicts(self): self._set_headers() for row in self: result = {} for key, value in zip(self._headers, row): # note since we're reading this in from a csv file # value is going to be a string or unicode string, we # quite simpl...
ffba4bced16516014dee
def bright(self) -> bool: return bool(0 if self.dim else 1)
ffba6e586dfd5fad6ced
def iterate_nested_dict_keys(dictionary): if isinstance(dictionary, dict): current_level_keys = [] for key in dictionary.keys(): current_level_keys.append(key) yield key for key in current_level_keys: value = dictionary[key] for ret in iterate_...
ffba70c377d8061a5ce6
def __init__(self): self.__sum = XorGate(2) self.__carry = AndGate(2) super().__init__(2, 2) self.setShow(HalfAdderShow())
ffbaf489fda54f71b1e8
def iipfailedmipusedrate(self) : try : return self._iipfailedmipusedrate except Exception as e: raise e
ffbafb2a2e32085da785
def predict(self, msg): prediction = choice([True, True]) output_msg = Message(True, msg.timestamp) if prediction: self.get_output_stream( MockPredictGripOperator.success_stream_name).send(output_msg) else: self.get_output_stream( M...
ffbb0c270b6d3300a613
def _get_selected_timestamp(ref_timestamp, timestamp_options): ref_date = _get_datetime(ref_timestamp) time_dist = [(ref_date - _get_datetime(_timestamp)).total_seconds() \ for _timestamp in timestamp_options] possible_idx = [i for i, _ in enumerate(time_dist) if time_dist[i] > 0] ...
ffbb0c3268500d83d2ac
def get(self): return self._wrapped_type(self._impl.get())
ffbb3bac7b79994b911e
def test_viz_valid(launch, app): app.return_value.get_template_url.return_value = "http://127.0.0.1:8080/index.html" app.return_value.start.return_value = True launch.return_value = True runner = CliRunner() result = runner.invoke(viz, [cog_path]) app.assert_called_once() assert not result...
ffbb3c451bd333888d2d
def readArgs(): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('outputName', metavar='output_name', action='store', default=os.path.dirname(os.path.abspath(__file__)) + "/result.txt", help='the name for the summary...
ffbb8bcf8700048064e5
def data_prep(): df = pd.read_excel("city_mean_zacaut_geo_with_nafa_clean.xlsx") out = pd.DataFrame(columns=["idxCol","תשעה", "תשעז" ,"תשעח", "תשעד", "תשעו","average", "city", "Nafa", "geo_y", "geo_x"]) for idx, row in df.iterrows(): out.loc[idx] = row.fillna(row["average"]) df = pd.re...
ffbb99ad96d0b9ba2289
def fix_kait_header(pathname,outpathname=None): try: hdu = pf.open(pathname) except IOError: # probably a zcatted image hdu = get_zipped_fitsfile(pathname) base,ext = os.path.splitext( pathname.strip('.Z') ) if outpathname == None: outpathname = base + '.fixed' + ext ...
ffbba78415cf81959f4e
def __init__( self, unique_id, model, pos, hardship, regime_legitimacy, risk_aversion, threshold, vision, ): super().__init__(unique_id, model) self.breed = "citizen" self.pos = pos self.hardship = hardship ...
ffbbaeaff1f5292f73bc
async def project(request): try: user, repo = REPOSITORIES[request.match_info["name"]] except KeyError: raise aiohttp.web.HTTPNotFound() url = _endpoint("repos", user, repo, "releases") async with _create_session(request) as session: async with session.get(url) as api_resp: ...
ffbbb36b8461fae3d81a
def test_validate_get_data_values(self, get_url): response = requests.get(url=get_url) data = response.json() assert response.status_code == 200 assert isinstance(data, list) if data: for item in data: assert item.get("username", "") ...
ffbbbde8703d7b45035e
def main(): for path, _, files in os.walk('DOFSTA/manufacturer'): for file in files: # Skip hidden files if file[0] == '.': continue cal = SBE43Calibration() cal.read_cal(os.path.join(path, file)) cal.write_cal_info(os.path.join(pa...
ffbbce3027deb516f738
def load_label(self, label, **kwargs): labels = self._load_labels(label, **kwargs) if label in labels: return labels[label] elif not label.endswith(('-lh', '-rh')): return labels[label + '-lh'] + labels[label + '-rh'] else: raise ValueError("Label %r c...
ffbbe033a4bce68cb614
def _test_replacement(self, replacement, clazz=replace.Replacement, offset=0): self.assertIsInstance(replacement, clazz) self.assertEqual(replacement.old, str(offset * 2 + 1)) if not callable(replacement.new): self.assertEqual(replacement.new, str(offset * 2...
ffbbfb11c0c0ff3a289e
def classification_feature(df, key, width=0.417, threshold=0.5, nominal=False, drop_key=True): classification_list = np.array([]) k = 0 while True: for i in range(k, len(df)): if df[key][df.index[i]] >= threshold: begin = i break begin = i ...
ffbc0a9ed15396dced26
def __str__(self) -> str: res = "" res += "\tNode ID: " + get_id(self) + "\n" res += "\tleft_child:\t" + get_id(self.left_child) + "\n" res += "\tright_child:\t" + get_id(self.right_child) + "\n" return res
ffbc0c9d5ed0bb6f00ef
def __init_parameters__(self, params):
ffbc23db31291daab2d7
def generate_kgrid(grid=[5, 5, 5]): t = [] for i in range(grid[0]): for j in range(grid[1]): for k in range(grid[2]): t.append( [ float(i) / (float(grid[0])), float(j) / (float(grid[1])), ...
ffbc35caf45fe99ceba1
def private(self) -> bool: return self._private
ffbc5db93fcca3a1cd1d
def _try_refresh(self): try: cm = self._get_cm() # If we're too slow it may have expired. # In this case act like for an acquire if not cm or self._is_lock_expired(cm): return self._try_lock_cm(cm) elif not self._is_cm_mine(cm): ...
ffbc6f9166bb1266d051
def from_cell(self, input, output): raise NotImplementedError()
ffbc7c4de1212e0d2356
def set_test_case(self, tc_name): url = self.etsy_url + '/set_test_id?test_id=' + tc_name try: r = requests.get(url) except requests.exceptions.RequestException as e: raise EtsyEmulatorRequestError(str(e)) if r.status_code != 200: error = 'Cannot se...
ffbc9a909ad5cf153f5c
def test_sign_in_fail_view(self): self.client.logout() # non existing user credentials resp = self.client.post(reverse('signin'), {'username': 'someusername', 'password': 'Password'}) self.assertEqual(resp.status_code, 401) self.assertEqual(resp.context['error'], 'Given username ...
ffbcae8e5677ce96c96e
def wait_until(action, description=None, exception_class=AssertionError, patience=30): __tracebackhide__ = True start = time_monotonic() cause = [] if not description: description = action.__doc__ or action.__name__ message = [] while time_monotonic() < (start + patience): try: ...
ffbcbad8d7c24ac9d0ff
def delete_trade(conn, sequence): sql = 'DELETE FROM public_trades WHERE sequence=?' cur = conn.cursor() cur.execute(sql, (sequence,)) conn.commit()
ffbcd492f3df95ec365f
def entropy(self, alpha): alpha = tf.cast(alpha, dtype=tf.float32) if len(get_dims(alpha)) == 1: K = get_dims(alpha)[0] a = tf.reduce_sum(alpha) return tf.lbeta(alpha) + \ (a - K) * tf.digamma(a) - \ tf.reduce_sum((alpha-1) * tf.d...
ffbcd8d2659dd748ee94
def setup_blueprints(app_): bps = { auth: -1, index: -1, users: "/users", heartbeats: "/users", durations: "/users", summaries: "/users", leaders: "/leaders", } for bpr, suffix in bps.items(): url_prefix = f'/api/v1{suffix or ""}' if ...
ffbce5a935c2e39e1e64
def is_unique_plain(string): # We'll loop through all the chars for i in range(len(string)): current_char = string[i] # Getting the current char # Searching for the current char in the rest of the string. If we find # it, the char is not unique if string.find(current_char, i + ...
ffbd0175783a1d62e233
def build_corpus(self): #assemble dataframe of reports self.df_data = join_montage_files(self.data_dir, self.NAME_UNID_REPORTS, self.NAME_TEXT_REPORTS) # build dataframe with all the report text #get list of stop words en_stop = give_stop_words() # preprocess report text, get list with length (# reports) a...
ffbd0e323e6e11cfba6b
def update_with_info(self, userinfo): self.nickname = userinfo["nickname"] self.sex = str(userinfo["sex"]) self.city = str(userinfo["city"]) self.headimgurl = str(userinfo["headimgurl"]) self.country = str(userinfo["country"]) if userinfo.get("subscribe") == 1: ...
ffbd6644f2d1220bdbab
def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]): app = inliner.document.settings.env.app #app.info('user link %r' % text) try: base = app.config.github_project_url if not base: raise AttributeError if not base.endswith('/'): ...
ffbd686bbe2dcbe979e8
def add_secondary_field(self, **kwargs): self.secondaryFields.append(Field(**kwargs))
ffbd708c36aa2ef3f4b5
def move_figure(f, x, y): backend = matplotlib.get_backend() if backend == 'TkAgg': f.canvas.manager.window.wm_geometry("+%d+%d" % (x, y)) elif backend == 'WXAgg': f.canvas.manager.window.SetPosition((x, y)) else: # This works for QT and GTK # You can also use window.setG...
ffbd8ed13ce0b2b31b6a
def _check_Xy(self, X, y): X, y = np.array(X, dtype=np.float64), np.array(y, dtype=np.int64) assert X.shape[0] == y.shape[0] and len( y.shape) == 1, "Accepcted input dimesions: X ~ [m, d], y ~ [m, ]" return X, y
ffbd92d6ed3feb679171
def _optimized(self): #get len of ordinary signals in a record olens, _ = self._signal_lens() #determine if the len is unique optimized = len(set(olens)) == 1 #remove annotation calibration and offset if annotations if optimized and self.annotated: an...
ffbd983e7ecca9d135db
def add_attribute(self, cell, *args): if cell not in self._attrs: raise AttributeError, 'cell is not packed into the TreeMap' if len(args) % 2 != 0: raise AttributeError, 'args must be in sets of 2' attrs = {} i = 0 while i < len(args): k,v = a...
ffbdb77df4b34b4252b0
def create_Chemplate_from_sources(sources, overrides=None, values=None): #make local copies, so there are no accidental changes to the original when we override verbose = False temp=CP.Chemplate(DoD={}) if verbose: print("\nSOURCES:",sources,"\nOVER:",overrides,"\nVALt:",type(values)) if values is N...
ffbdf0b804005b333398
def getSessionID(self): self.count = self.count+1 return 'cmd-%s-%d'%(self.name,self.count)
ffbe00800c7b37fe8592
def recognize(self, true_img, true_lbl): n_samples = true_img.shape[0] n_lables = true_lbl.shape[1] vis = true_img # visible layer gets the image data lbl = np.ones(true_lbl.shape)/10. # start the net by telling you know nothing about labels # Fix the image data ...
ffbe078b8cb4472ab410
def list_search_indexes(self): raise NotImplementedError
ffbe0af042012ecfdefa
def get_product_by_keyword(keyword=None): with database.make_connection() as connection: if keyword is None: cursor = list(r.table('reference_features')\ .pluck('product')\ .distinct()\ .run(connection)) else: ...
ffbe0c7ea66b43c30238
def write_hab_task(task): import requests import json auth = get_started('auth.cfg') url = 'https://habitica.com/api/v3/tasks/user/' # hab = json.dumps(task) r = requests.post(headers=auth, url=url, data=task) return r
ffbe472af4d0c48f7dc2
async def remove_duplicates(): async with aiosqlite.connect("main.sqlite") as conn: await conn.execute("DELETE FROM prefixes WHERE rowid NOT IN(SELECT min(rowid) FROM prefixes GROUP BY id);") await conn.commit()
ffbe6a6fac62cebd9f7b
def aspect_ratio(axes): width = axes.get_position().width * axes.figure.get_figwidth() height = axes.get_position().height * axes.figure.get_figheight() xmin, xmax = axes.get_xlim() ymin, ymax = axes.get_ylim() return height / width / (ymax - ymin) * (xmax - xmin)
ffbe9f780ca17e72b7c6
def are_concurrent(*planes): planes = list(uniq(planes)) for i in planes: if not isinstance(i, Plane): raise ValueError('All objects should be Planes but got %s' % i.func) if len(planes) < 2: return False planes = list(planes) first = plane...
ffbea6471fa713334e70
def _validate(self, errors): pass
ffbea9504363b60b7981
def get_files(path, png_list): temp_list = [] with os.scandir(path) as scanner: for file_path in scanner: if file_path.is_dir(): get_files(file_path.path, png_list) elif file_path.name.endswith(".png"): temp_list.append(file_path.name) png_list...
ffbeaad86d6c9f911b1c
def is_403_forbidden(self, response): self.assertEqual(response.status_code, 403)
ffbeb25dd6fecd22ec60
def version() -> str: return BIDFX_API_INFO.version
ffbebd5d7b18187b503b
def onChannelsList(self, channels):
ffbebe7ebb156d547b9e
def __init__(self, view, model): self.view = view self.model = model
ffbec890c5312bbdfb8f
def get_data(year, mon): for ccd in range(0, 10): ifile = data_dir + m_list[mon-1] + str(year) + '/ccd' + str(ccd) data = mcf.read_data_file(ifile) xdata = [] sum1 = 0 sum2 = 0 line = '' for ent in data: atemp = re.split('\s+', ent) ...
ffbeee7fb2e5d525b0a9
def _parse_file(cls, filename: str) -> Res: self = cls() self.filename = filename with zopen(filename, "r") as file: self.source = file.read() return self._parse_txt()
ffbf03c6535aa810b299
def get_unit_type(self) -> str: return "Cavalry"
ffbf21a584211471ce92
def update_policy(module, array): changed = True if not module.check_mode: changed = changed_rule = changed_enable = False if module.params['policy'] == 'nfs': try: current_enabled = list(array.get_policies_nfs(names=[module.params['name']]).items)[0].enabled ...
ffbf26c74f97ce701ba1
def is_sellable(self): if self.field_source == 3 or self.shape_rating <= 5 or self.color_rating <= 5: return False return True
ffbf3b83ab6b72eb6b9b
def load_module_from_file(module_name, module_path): if sys.version_info[0] == 3 and sys.version_info[1] >= 5: # Python 3, 3.5 or less import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) ...
ffbf614d7705441efa42
def draw_grid(self): coordinates = [[-290, 270], [-310, -310]] for i in range(2): line = turtle.Turtle() line.hideturtle() line.color('white') if not i: line.right(90) for _ in range(30 - i): line.penup(...
ffbf801123a798eb33fd
def detect(gray, frame): # detected faces in image or video faces = face_cascade.detectMultiScale(gray, 1.3, 5) # go through each face in givin image and grab position info for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) # grab roi(r...
ffbf863d3fd8bda66091
def do_sensing_plot(self,line): import matplotlib.pyplot as plt cols = line.split() if len(cols)==0: return id_input = int(cols[0]) #print("id_input = %i" %(id_input)) titles = ['VISCNT','LOGO','LIGHT','SOUND','A_X','A_Y','A_Z'] keys = dm.nodes.keys()...
ffbfcb824909c417a378
def __len__(self) -> int: # do a DFS to count the number of leaf nodes count = 0 stack = [self._data] while stack: node = stack.pop() if isinstance(node, NestedDict): node = node._data if isinstance(node, Mapping): stac...
ffbfe875aa179dd0648b
def test_bad_rel_path(self): Configuration.reset() with self.assertRaises(IOError): c = Configuration('_non_existent_.yaml')