code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def check_center(bbox): <NEW_LINE> <INDENT> meta = POLICY <NEW_LINE> S, B = meta['side'], meta['num'] <NEW_LINE> w, h = 10, 10 <NEW_LINE> cellx = 1. * w / S <NEW_LINE> celly = 1. * h / S <NEW_LINE> centerx = .5 * (bbox.x1 + bbox.x2) <NEW_LINE> centery = .5 * (bbox.y1 + bbox.y2) <NEW_LINE> cx = centerx / cellx <NEW_LINE... | Takes a chunk of parsed annotations
returns value for placeholders of net's
input & loss layer correspond to this chunk
:param box: box.x1, box.y1, box.x2, box.y2 | 625941d292d797404e30433c |
def print_list(self, fields: typing.Union[str, typing.Iterable] = "owner__login", **config) -> None: <NEW_LINE> <INDENT> if isinstance(fields, str): <NEW_LINE> <INDENT> print("".join(map(lambda i: "{}\n".format(i.get(fields)), self.__items))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for item in self.__items: <NEW_... | generate the list of output returned by GitHub
:param fields: list | string, see get_fields()
:param config:
:return: | 625941d2adb09d7d5db6c941 |
def js_response(content): <NEW_LINE> <INDENT> return JSResponse(content) | Kept for backward compatibility.
Users might as well use JSResponse directly. | 625941d294891a1f4081bc5b |
def choose_product(self): <NEW_LINE> <INDENT> self._choose_catalog_element_("Products", *AdminPageLocators.CATALOG_ELEMENTS) | public method to choose Product | 625941d299fddb7c1c9de542 |
def add_client(self, client): <NEW_LINE> <INDENT> self._clients.append(client) | Function to add a client to the client repository.
:param client: object, contains the client object to be appended to the repository. | 625941d24d74a7450ccd4375 |
def download_link(object_to_download: str, download_filename: str, download_link_text: str) -> str: <NEW_LINE> <INDENT> if isinstance(object_to_download, pd.DataFrame): <NEW_LINE> <INDENT> object_to_download = object_to_download.to_csv(index=False) <NEW_LINE> <DEDENT> b64 = base64.b64encode(object_to_download.encode())... | Generates a link to download the given object_to_download.
object_to_download (str, pd.DataFrame): The object to be downloaded.
download_filename (str): filename and extension of file. e.g. mydata.csv, some_txt_output.txt
download_link_text (str): Text to display for download link.
Examples:
download_link(YOUR_DF, '... | 625941d2d99f1b3c44c6773e |
def dir_names(self, connId='default'): <NEW_LINE> <INDENT> files_list = [] <NEW_LINE> thisConn = self.__getConnection(connId) <NEW_LINE> try: <NEW_LINE> <INDENT> files_list = thisConn.nlst() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> files_list = [] <NEW_LINE> <DEDENT> return files_list | Returns list of files (and/or directories) of current directory.
Parameters:
- connId(optional) - connection identifier. By default equals 'default' | 625941d2dc8b845886cb56e7 |
def get_by_name(self, domain_id, name, tenant=policy_constants.POLICY_INFRA_TENANT): <NEW_LINE> <INDENT> return super(NsxPolicyGroupApi, self).get_by_name(name, domain_id, tenant=tenant) | Return first group matched by name of this domain | 625941d25166f23b2e1a530b |
def delete_dataset(self, wdmpath, dsn, ): <NEW_LINE> <INDENT> if self.verbose: print('deleting dsn {}'.format(dsn)) <NEW_LINE> wdmfp = self.openfiles[wdmpath] <NEW_LINE> retcode = self.wddsdl(wdmfp, int(dsn)) <NEW_LINE> self.retcode_check(retcode, function = 'wddsdl') | Deletes a data series. | 625941d23c8af77a43ae3953 |
def cleanMe(filename): <NEW_LINE> <INDENT> cleanedpath = path+r'\cleaned' <NEW_LINE> print (cleanedpath) <NEW_LINE> if not os.path.exists(cleanedpath): <NEW_LINE> <INDENT> os.makedirs(cleanedpath) <NEW_LINE> <DEDENT> response = open(path+'\\'+filename, 'r') <NEW_LINE> html_doc = response.read() <NEW_LINE> soup = Beauti... | Strip many tag from the .html file
:param filename: filename.html
:return: return a clean .html file | 625941d2ec188e330fd5a94f |
def format_message_internal(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output["id"] = self.get_message_id() <NEW_LINE> output["match"] = self.is_match() <NEW_LINE> output["filename"] = self.get_filename() <NEW_LINE> output["tags"] = list(self.get_tags()) <NEW_LINE> headers = {} <NEW_LINE> for h in ["Subject", "F... | Create an internal representation of the message parts,
which can easily be output to json, text, or another output
format. The argument match tells whether this matched a
query. | 625941d2d53ae8145f87a420 |
def chipsec_ucode_id(toolns, tool, prd, ptd, erc): <NEW_LINE> <INDENT> info('Executing ' + toolns + ' variation of tool: ' + tool) <NEW_LINE> cmd = ['python', '-i', '-m', 'chipsec_util', 'ucode', 'id'] <NEW_LINE> return spawn_process(cmd, ptd, erc, toolns) | Call chipsec_util ucode id | 625941d276d4e153a657ece3 |
def resample_data(df): <NEW_LINE> <INDENT> sample_period = resample_slider.value <NEW_LINE> time_resolution = int(sample_period * 60) <NEW_LINE> time_start = df['DateTime'].iloc[0] <NEW_LINE> time_end = df['DateTime'].iloc[-1] <NEW_LINE> df = df.resample('{}min'.format(time_resolution), on='DateTime').mean() <NEW_LINE>... | Takes in a dataframe and a sample period (in minutes).
Returns a dataframe resampled to the specified sample period. | 625941d230dc7b7665901b17 |
def lookup(self, module_name): <NEW_LINE> <INDENT> for search_path in self._paths: <NEW_LINE> <INDENT> module_path = os.path.join(search_path, module_name) <NEW_LINE> new_module_name, module_file = self._lookup(module_path, module_name) <NEW_LINE> if module_file: <NEW_LINE> <INDENT> return new_module_name, module_file ... | Searches for a file providing given module.
Returns the normalized module id and path of the file. | 625941d285dfad0860c3b00d |
def get_several_playlists_data(UserSettings, playlist_ids: list) -> tuple: <NEW_LINE> <INDENT> output = tuple( UserSettings.spotify.playlist(playlist.playlist_id, fields="name, images, external_urls, id") for playlist in playlist_ids) <NEW_LINE> return output | Возвращает сырые данные плейлиста для HTML отображения | 625941d2d8ef3951e32436ef |
def __init__(self, hostname, port, username, password, authentication_db): <NEW_LINE> <INDENT> self.hostname = hostname <NEW_LINE> self.port = port <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.authentication_db = authentication_db <NEW_LINE> c = self.mmo_connect() <NEW_LINE> s... | Constructor for the pymmmo class. Provide details for conection to the Mongogo cluster.
:param hostname:
:param port:
:param username:
:param password:
:param authentication_db:
:return: | 625941d2c432627299f04df8 |
def GetNumCompileUnits(self) -> int: <NEW_LINE> <INDENT> return _lldb.SBModule_GetNumCompileUnits(self) | GetNumCompileUnits(SBModule self) -> uint32_t | 625941d25510c4643540f594 |
def load_ans(self, ansi_path, wide_mode = False): <NEW_LINE> <INDENT> with open(ansi_path, "rb") as f: <NEW_LINE> <INDENT> ansi_data = f.read() <NEW_LINE> <DEDENT> self.parse_ans(ansi_data, wide_mode) <NEW_LINE> self.is_dirty = False | Loads and parses and ansi file. Documentation of parse_ans applies.
wide_mode makes it so the parser doesn't insert line breaks at 80 characters. | 625941d22ae34c7f2600d2e3 |
def IntesectionSize(collection1,collection2): <NEW_LINE> <INDENT> if len(collection1) > len(collection2): <NEW_LINE> <INDENT> small = collection2 <NEW_LINE> big = collection1 <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> small = collection1 <NEW_LINE> big = collection2 <NEW_LINE> <DEDENT> ans = 0 <NEW_LINE> for comm i... | counts the amount of elements in the intersection of two collections
:param collection1: first collection
:param collection2: second collection
:return: the amount of elements in the intersection of thetwo collections | 625941d2d53ae8145f87a421 |
def __move_in_y_axis(self, tpp_camera: TPPCamera): <NEW_LINE> <INDENT> camera_yaw_deg = base.camera.getH() <NEW_LINE> camera_yaw_rad = math.radians(camera_yaw_deg) <NEW_LINE> camera_yaw_quarter = rotation.get_angle_quarter(camera_yaw_deg) <NEW_LINE> delta_x_m = delta_y_m = 0.0 <NEW_LINE> if camera_yaw_quarter == 1 or 2... | Y-axis movement handling. | 625941d25fc7496912cc3b30 |
def delete(self, request): <NEW_LINE> <INDENT> del request.session['user'] <NEW_LINE> return Response({"status": True, "message": "成功", "data": {}}) | 用户退出登录 | 625941d210dbd63aa1bd2d56 |
def update_theta_beta_a(data, lr, theta, beta): <NEW_LINE> <INDENT> user_id = data['user_id'] <NEW_LINE> question_id = data['question_id'] <NEW_LINE> is_correct = data['is_correct'] <NEW_LINE> dl_dbeta = np.zeros(len(beta[0])) <NEW_LINE> def beta_helper_inner(c, theta, beta): <NEW_LINE> <INDENT> top = np.exp(theta - be... | Update theta and beta using gradient descent.
You are using alternating gradient descent. Your update should look:
for i in iterations ...
theta <- new_theta
beta <- new_beta
You may optionally replace the function arguments to receive a matrix.
:param data: A dictionary {user_id: list, question_id: list, is... | 625941d21b99ca400220ac63 |
def test_inc_dec_get_counter(self): <NEW_LINE> <INDENT> rse_id = get_rse('MOCK').id <NEW_LINE> rse_update(once=True) <NEW_LINE> rse_counter.del_counter(rse_id=rse_id) <NEW_LINE> rse_counter.add_counter(rse_id=rse_id) <NEW_LINE> cnt = rse_counter.get_counter(rse_id=rse_id) <NEW_LINE> del cnt['updated_at'] <NEW_LINE> ass... | RSE COUNTER (CORE): Increase, decrease and get counter | 625941d2f8510a7c17cf98ae |
def _new_conn(self): <NEW_LINE> <INDENT> extra_kw = {} <NEW_LINE> if self.source_address: <NEW_LINE> <INDENT> extra_kw["source_address"] = self.source_address <NEW_LINE> <DEDENT> if self.socket_options: <NEW_LINE> <INDENT> extra_kw["socket_options"] = self.socket_options <NEW_LINE> <DEDENT> address = self.forward_addre... | Establish a socket connection and set nodelay settings on it.
:return: New socket connection. | 625941d230bbd722463cbf78 |
def test_parser_with_unknown_driver(parser): <NEW_LINE> <INDENT> with pytest.raises(SystemExit): <NEW_LINE> <INDENT> parser.parse_args([url, '--driver', 'azure', 'destination']) | The parser will exit if the driver is unknown. | 625941d27cff6e4e81117b38 |
def test_rotate(self): <NEW_LINE> <INDENT> self.assertEqual(len(os.listdir(self.basepath)), 3) <NEW_LINE> weekdirname = backup.get_copy_week(os.listdir(self.basepath)[0]) <NEW_LINE> weekdirpath = os.path.join(self.basepath, weekdirname) <NEW_LINE> prev_inodes = len(list(find_inodes(self.basepath))) <NEW_LINE> ret = sub... | Tests rotate command | 625941d2004d5f362079a4e5 |
def detect_pages(self, coll, rec, upload_key, total_size): <NEW_LINE> <INDENT> key = self.cdxj_key.format(coll=coll, rec=rec) <NEW_LINE> pages = [] <NEW_LINE> count = 0 <NEW_LINE> total_cdx = self.redis.zcard(key) <NEW_LINE> incr = int((total_size * 0.25) / total_cdx) <NEW_LINE> count = 0 <NEW_LINE> for member, score i... | Find pages in recording.
:param str coll: collection ID
:param str rec: recording ID
:returns: pages
:rtype: list | 625941d2a17c0f6771cbe202 |
def test_HA_low(self): <NEW_LINE> <INDENT> outcome = self.ntwrk.feed_forward([0,0]) <NEW_LINE> self.assertEqual(outcome, [0,0]) | Tests some scenarios in which both outputs would be low (0) | 625941d230bbd722463cbf79 |
def aoi_fixed(surface_tilt, surface_azimuth, apparent_zenith, azimuth): <NEW_LINE> <INDENT> aoi = pvlib.irradiance.aoi(surface_tilt, surface_azimuth, apparent_zenith, azimuth) <NEW_LINE> return surface_tilt, surface_azimuth, aoi | Calculate AOI for fixed system, bundle return with tilt, azimuth for
consistency with similar tracker function.
Parameters
----------
surface_tilt : float
surface_azimuth : float
apparent_zenith : pd.Series
Solar apparent zenith
azimuth : pd.Series
Solar azimuth
Returns
-------
surface_tilt : pd.Series, surfa... | 625941d26fb2d068a760f251 |
def click_handler(self, x, y): <NEW_LINE> <INDENT> self.clicked = True <NEW_LINE> self.replace_img(x, y) <NEW_LINE> self.count +=1 | Handles the clicks on beers, adds one to the number of clicks
each time it is clicked
Calls the replace_img function to change the image of beers
once it is clicked
:param x:
:param y:
:return: | 625941d24428ac0f6e5ba9a5 |
def setConvergenciaMeridianos(self,ConvergenciaMeridianos): <NEW_LINE> <INDENT> if ConvergenciaMeridianos==None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> float(ConvergenciaMeridianos) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception(e) <NEW_LINE> <DEDENT> fin... | !
@brief: Método para asignar la convergencia de meridianos del punto.
@param ConvergenciaMeridianos float|int|str: Valor de la Convergencia de meridianos. | 625941d2be7bc26dc91cd7b0 |
def read_magic_number(path: str) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(path) as f: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> num = float(line) <NEW_LINE> return 1 <= num < 3 <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("it must be a number") | This function reads the first line of the file.
If first line is a number returns true if number
in an interval [1, 3)* and false otherwise.
Raises ValueError if first line not number.
Args:
path: path to working file
Returns:
bool: True if line is number from 1 to 3, False otherwise | 625941d291af0d3eaac9bbcc |
def getVerticalAdvance(self): <NEW_LINE> <INDENT> return _osgText.Glyph_getVerticalAdvance(self) | getVerticalAdvance(Glyph self) -> float | 625941d2c4546d3d9de72be7 |
def list_server_group(self, feed_id): <NEW_LINE> <INDENT> server_groups = self.list_resource( feed_id=feed_id, resource_type_id='Domain Server Group', cls=ServerGroup, list_children=True, include_data=True ) <NEW_LINE> return server_groups | Returns list of middleware domain's server groups.
Args:
feed_id: Feed id of the resource (optional) | 625941d2566aa707497f4719 |
def copy_stlport_libs(src_dir, dst_dir, triple, abi): <NEW_LINE> <INDENT> src_libdir = get_src_libdir(src_dir, abi) <NEW_LINE> dst_libdir = get_dest_libdir(dst_dir, triple, abi) <NEW_LINE> if not os.path.exists(dst_libdir): <NEW_LINE> <INDENT> os.makedirs(dst_libdir) <NEW_LINE> <DEDENT> shutil.copy2(os.path.join(src_li... | Copy the stlport libraries to the toolchain. | 625941d27d847024c06be46f |
def read_pad(bindings, key=None): <NEW_LINE> <INDENT> joysticks = init_joysticks() <NEW_LINE> vkeys = 0 <NEW_LINE> mouse_b = None <NEW_LINE> for binding in bindings: <NEW_LINE> <INDENT> if not binding: <NEW_LINE> <INDENT> pressed = 0 <NEW_LINE> <DEDENT> elif binding[0] == 'key': <NEW_LINE> <INDENT> key = key or G.key.g... | Read a single pad (list of bindings).
bindings -- a list of bindings returned from
key -- output of pygame.key.get_pressed() | 625941d26fece00bbac2d8f2 |
def is_polynome(function): <NEW_LINE> <INDENT> if function.as_poly(x): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Проверяем, не полином ли наша функция | 625941d2c432627299f04df9 |
def load_training_file(file): <NEW_LINE> <INDENT> with open(file) as f: <NEW_LINE> <INDENT> text = f.read() <NEW_LINE> return text | Load file and return text as string | 625941d297e22403b379d14c |
def t350190_x7(): <NEW_LINE> <INDENT> assert t350190_x1() <NEW_LINE> assert GetCurrentStateElapsedFrames() > 1 <NEW_LINE> if not GetEventStatus(1156) and not GetEventStatus(1157): <NEW_LINE> <INDENT> if GetDistanceToPlayer() < 10: <NEW_LINE> <INDENT> call = t350190_x15() <NEW_LINE> if call.Done(): <NEW_LINE> <INDENT> p... | State 0,9 | 625941d2a79ad161976cc2f8 |
def get_pref(self, option): <NEW_LINE> <INDENT> return self._pref['General'][option] | Return the current setting for `option` from General section | 625941d2656771135c3eba22 |
def fit(self, x, dc=None): <NEW_LINE> <INDENT> if self.distance_matrix is not None: <NEW_LINE> <INDENT> distance_matrix = self.distance_matrix <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> distance_matrix = np.array(self.dist_func(x, x)) <NEW_LINE> <DEDENT> num_points = distance_matrix.shape[0] <NEW_LINE> assert not (d... | Cluster the data.
Args:
x : data
dc : local density threshold, call select_dc if dc is None
Returns:
local density vector, min_distance vector, nearest neighbor vector | 625941d2be7bc26dc91cd7b1 |
def readDatabase(self, file): <NEW_LINE> <INDENT> import csv <NEW_LINE> if not file: return False, 1 <NEW_LINE> if not os.path.isfile(file): return False, 1 <NEW_LINE> reader = csv.reader(open(file,mode='r+')) <NEW_LINE> if not reader: return False, 2 <NEW_LINE> table = [[e for e in r] for r in reader] <NEW_LINE> if le... | Read data from file: error messages: 1= no file found, 2= file found but corrupt, 3= file found but no data
| 625941d2fff4ab517eb2f5ef |
def test_calculate_frame_scores_spare(self): <NEW_LINE> <INDENT> game_state = [ {'ball_1_score': 0, 'ball_2_score': 1}, {'ball_1_score': 5, 'ball_2_score': 5, 'is_spare': True}, {'ball_1_score': 3, 'ball_2_score': 4}, ] <NEW_LINE> for i in range(len(game_state)-1): <NEW_LINE> <INDENT> game_state[i] = self.b.link_frames... | It should calculate up to three frame scores when at least one is a spare. | 625941d2851cf427c661a6c0 |
def undemand_Comp1(S): <NEW_LINE> <INDENT> if (_U_Comp1.getref(S) == 1): <NEW_LINE> <INDENT> _maint_Comp1__U_Comp1_remove(S) <NEW_LINE> _maint_Comp1_TS__U_Comp1_remove(S) <NEW_LINE> _U_Comp1.remove(S) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _U_Comp1.decref(S) | {(S, S) : S in _U_Comp1, (S, _) in _M} | 625941d2b5575c28eb68e1b3 |
def reverse_association(gene2go): <NEW_LINE> <INDENT> go2gene = defaultdict(set) <NEW_LINE> for gene, go_set in gene2go.items(): <NEW_LINE> <INDENT> for go in go_set: <NEW_LINE> <INDENT> go2gene[go].add(gene) <NEW_LINE> <DEDENT> <DEDENT> return go2gene | For given dictionary of genes mapped to set of GO
terms, creates mapping of GO terms to gene IDs.
gene2go: mapping of gene IDs to GO terms
return: mapping of GO terms to gene IDs | 625941d2a05bb46b383ec9d3 |
def merge_count_inversion_dec(lst): <NEW_LINE> <INDENT> if len(lst) <= 1: <NEW_LINE> <INDENT> return lst, 0 <NEW_LINE> <DEDENT> middle = int(len(lst) / 2) <NEW_LINE> left, a = merge_count_inversion_dec(lst[:middle]) <NEW_LINE> right, b = merge_count_inversion_dec(lst[middle:]) <NEW_LINE> result, c = merge_count_split_i... | @pre: a list of integers
@post: a list sorted in descending order, and the number of inversions in the list
This function sorts a list of integers in descending order using merge sort, and counts the number of inversions | 625941d266673b3332b92244 |
def enum_value(self, tree: "Tree") -> "SchemaNode": <NEW_LINE> <INDENT> return SchemaNode( type="enum_value", value=lark_to_enum_value_node(tree) ) | Creates and returns a SchemaNode instance of type "enum_value" with an
EnumValueNode instance as value (extracted from the parsing of the tree
instance).
:param tree: the Tree to parse in order to extract the proper node
:type tree: Tree
:return: a SchemaNode instance of type "enum_value" with an
EnumValueNode instance... | 625941d2090684286d50ee99 |
def __init__(self,filein): <NEW_LINE> <INDENT> self.atom_names = [] <NEW_LINE> self.filename = filein <NEW_LINE> genhandle = open(filein,'r') <NEW_LINE> genfile = genhandle.readlines() <NEW_LINE> while parse(genfile[-1].replace('\n','')) == []: <NEW_LINE> <INDENT> del(genfile[-1]) <NEW_LINE> <DEDENT> genhandle.close() ... | cree l'objet genFile et initialise les attributs:
atom_names: ['atom1', 'atom2', ... , 'atomN']
n_atoms: nombre d'atomes
geometry: [ [1, 'atom1', x1, y1, z1] , ... , [N, 'atomN', xN, yN, zN] ]
lattice: [[Ox, Oy, Oz], [v1x, v1y, v1z], [v2x, v2y, v2z], [v3x, v3y, v3z]] | 625941d28e7ae83300e4b17f |
def pid_exists(pid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.kill(pid, 0) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False | Return True if a given PID exists.
:param pid: Process ID number. | 625941d2a05bb46b383ec9d4 |
def stop(self): <NEW_LINE> <INDENT> self.pwm_controller.stop() | Stops the PWM signal
Use set_value(0) for intermediate "off", and stop() to free up processor | 625941d28e71fb1e9831d95b |
def LoadConfig(self): <NEW_LINE> <INDENT> LOG.info("\n======================== Loading Config Files ======================== Version: {}\n".format(__version__)) <NEW_LINE> for _l_key, l_module in self.m_modules_api.items(): <NEW_LINE> <INDENT> l_module.LoadConfig() <NEW_LINE> <DEDENT> for l_module in self.m_modules_api... | Load in the entire configuration for PyHouse.
This will fill in pyhouse_obj for all defined features of PyHouse. | 625941d28c3a87329515856e |
@operation <NEW_LINE> def packages( packages=None, present=True, latest=False, update=False, upgrade=False, state=None, host=None, ): <NEW_LINE> <INDENT> if update: <NEW_LINE> <INDENT> yield _update(state=state, host=host) <NEW_LINE> <DEDENT> if upgrade: <NEW_LINE> <INDENT> yield _upgrade(state=state, host=host) <NEW_L... | Add/remove/update brew packages.
+ packages: list of packages to ensure
+ present: whether the packages should be installed
+ latest: whether to upgrade packages without a specified version
+ update: run ``brew update`` before installing packages
+ upgrade: run ``brew upgrade`` before installing packages
Versions:
... | 625941d263f4b57ef00012c9 |
def fml_cost(self, fml, candidate): <NEW_LINE> <INDENT> alpha = 1e-20 <NEW_LINE> for i in fml: <NEW_LINE> <INDENT> if (not self.candidate_has(candidate, i)) and (i not in self.graph_model.parameters.obs_ass): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> parents = fml[:-1] <NEW_LINE> kid = fml... | compute the cost of fml based on the candidate and obs
if not all the values in the fml is assigned, return 0 | 625941d230c21e258bdfa650 |
def do_index(self, arg=None): <NEW_LINE> <INDENT> self.application.index_all(arg) | Index | 625941d2b57a9660fec33a38 |
def rotate(self, nums, k): <NEW_LINE> <INDENT> k = k % len(nums) <NEW_LINE> nums[:k] = nums[len(nums)-k:] <NEW_LINE> nums[k:] = nums[:len(nums) - k] <NEW_LINE> print(nums) | :type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead. | 625941d266656f66f7cbc35e |
def correct_imu(r,p,h,t,dt=0,n=8,decorr=False): <NEW_LINE> <INDENT> h = unwrap(h) <NEW_LINE> dh,tdh = derivative(h,t) <NEW_LINE> if decorr: d2h,td2h = derivative(dh,tdh) <NEW_LINE> dh = interp(t,tdh,dh) <NEW_LINE> if decorr: d2h = interp(t,td2h,d2h) <NEW_LINE> f = sinc_filter(2*n+1,3) <NEW_LINE> tf = convolve(t,f,'vali... | correct_imu(r,p,h,t,dt=0,n=8,decorr=False)
r,p,h,t: roll, pitch, heading, time
dt: difference between t and when r,p,h was actually sampled
sample time = t - dt
n: number of filter taps = 2*n+1
decorr: if true, remove components of r and p that correlate with 1st and 2nd derivatives of h
Returns: r,p,h, dh | 625941d263d6d428bbe446a2 |
def df_resid(self): <NEW_LINE> <INDENT> return self.N - self.order - 1 | Residual degrees of freedom from last fit. | 625941d299cbb53fe6792d99 |
def replace_all(self, string, replace): <NEW_LINE> <INDENT> for i, j in replace.iteritems(): <NEW_LINE> <INDENT> string = string.replace(i, j) <NEW_LINE> <DEDENT> return string | This function will take a dictionary as an input and replaces the values with its keys in the
strings.
:param string: -> The string which should be used to replace characters.
:param replace: -> A dictionary which contains the words to be replaces with their keys
:return: | 625941d263f4b57ef00012ca |
def inverse_3by3_int(M): <NEW_LINE> <INDENT> if len(M.shape) > 1: <NEW_LINE> <INDENT> M = M.flatten() <NEW_LINE> <DEDENT> determinant = 0 <NEW_LINE> adj_M = np.zeros((9,), 'int') <NEW_LINE> adj_M[0] = (M[4] * M[8] - M[7] * M[5]) <NEW_LINE> adj_M[1] = -(M[1] * M[8] - M[7] * M[2]) <NEW_LINE> adj_M[2] = (M[1] * M[5] - M[4... | C style inverse of a flattened 3 by 3 matrix.
Returns the adjoint matrix and the determinant, s.t.
.. math::
M^{-1} = \frac{1}{\det(M)} \cdot \text{adj}(M).
For integer matrices, this then returns exact results by avoiding
to apply the division.
:param M: The matrix to find inverse to.
:type M: :py:class:`num... | 625941d2b830903b967e9abd |
def process_data_conll(data_path): <NEW_LINE> <INDENT> df = pd.read_csv(data_path, encoding="latin-1", sep="\t") <NEW_LINE> sentences = [] <NEW_LINE> sent_tags = [] <NEW_LINE> tmp_snt = [] <NEW_LINE> tmp_tag = [] <NEW_LINE> df = df.fillna("-1") <NEW_LINE> for wrd, tg in df.values: <NEW_LINE> <INDENT> if wrd=="-1" and t... | To read CONLL type data
Args:
data_path ([str]): File name
Returns:
Sentences, Sentence_wise_tags, Encoding Tags | 625941d25166f23b2e1a530c |
def get_incorrect_offset(self): <NEW_LINE> <INDENT> if not self.is_incorrect_offset(): <NEW_LINE> <INDENT> raise AttributeError("tag 'incorrect_offset' not set") <NEW_LINE> <DEDENT> return self._value | The specified offset was incorrect. See the value for the correct
offset. This error may occur when a previous request was received and
processed successfully but the client did not receive the response, e.g.
due to a network error.
Only call this if :meth:`is_incorrect_offset` is true.
:rtype: UploadSessionOffsetErr... | 625941d2cdde0d52a9e531e7 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.phonebook = ["Bob Brown", "Cat Cyan", "Oren Ochre"] | Construct main app | 625941d23539df3088e2e4fe |
def forward(self, src, tgt, lengths, dec_state=None): <NEW_LINE> <INDENT> enc_final, memory_bank = self.encoder(src, lengths) <NEW_LINE> enc_state = self.decoder.init_decoder_state(src, memory_bank, enc_final) <NEW_LINE> assert tgt.size(0) % self.pair_size == 0 <NEW_LINE> if tgt.size(0) > self.pair_size: <NE... | Forward propagate a `src` and `tgt` pair for training.
Possible initialized with a beginning decoder state.
Args:
src (:obj:`Tensor`):
a source sequence passed to encoder.
typically for inputs this will be a padded :obj:`LongTensor`
of size `[len x batch x features]`. however, may be an
... | 625941d25fcc89381b1e1873 |
def split_img(img, block_size=32): <NEW_LINE> <INDENT> m,n = img.shape <NEW_LINE> nb_bloc32_x = m//block_size <NEW_LINE> nb_bloc32_y = n//block_size <NEW_LINE> nb_bloc32 = nb_bloc32_x * nb_bloc32_y <NEW_LINE> list_bloc_out = np.zeros((nb_bloc32, block_size, block_size)) <NEW_LINE> no_bloc = 0 <NEW_LINE> for i in range(... | Return a list of blocks of size block_size x block_size | 625941d207f4c71912b11636 |
def test_create_invalid_request(self): <NEW_LINE> <INDENT> admin_user = mocks.create_user('adminuser@test.com') <NEW_LINE> other_user = mocks.create_user('otheruser@test.com') <NEW_LINE> inst_test = mocks.create_institution() <NEW_LINE> admin_user.institutions_admin = [inst_test.key] <NEW_LINE> inst_test.admin = admin_... | Test create invalid request. | 625941d23317a56b86939e09 |
def start_daris_client_command(): <NEW_LINE> <INDENT> basename = os.path.basename(__file__) <NEW_LINE> return ['java', '-Ddc.prefix=' + basename, '-jar', get_daris_client_jar_path()] | Creates the command string for executing the daris-client.jar
| 625941d2a219f33f34628b1b |
def __init__(self, k, q, base_ring, prefix, diagrams, category=None): <NEW_LINE> <INDENT> DiagramAlgebra.__init__(self, k, q, base_ring, prefix, diagrams, category) <NEW_LINE> amb = self.ambient() <NEW_LINE> self.module_morphism(self.lift, codomain=amb, category=self.category()).register_as_coercion() | Initialize ``self`` by adding a coercion to the ambient space.
EXAMPLES::
sage: R.<x> = QQ[]
sage: BA = BrauerAlgebra(2, x, R)
sage: BA.ambient().has_coerce_map_from(BA)
True | 625941d2d268445f265b5021 |
def getLayers(include=False, exclude=False): <NEW_LINE> <INDENT> docLayers = list(filter(lambda x: not rs.IsLayerReference(x),rs.LayerNames())) <NEW_LINE> layerSplit = [d.split("::") for d in docLayers] <NEW_LINE> returnList = [] <NEW_LINE> nestWarning = 0 <NEW_LINE> includePattern = re.compile(r"______________") <NEW_... | Help on function getLayers in module getLayerList:
getLayers(include, exclude)
Get list of layers that begin with regex L/d.
Parameters:
include = List of layers to linclude that do not begin with
regex L/d
exclude = List of layers to exclude from children ... | 625941d2dc8b845886cb56e8 |
def check_required_modules(required_modules, verbose=True): <NEW_LINE> <INDENT> import imp <NEW_LINE> not_installed_modules = [] <NEW_LINE> for module_name in required_modules: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> imp.find_module(module_name) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> try: <NEW... | Function checks for Python modules which should be "importable"
before test suite can be used.
@return returns True if all modules are installed already | 625941d263b5f9789fde7299 |
def get_items(self): <NEW_LINE> <INDENT> return self.__items | ゲームを取得
:return: ゲーム
:rtype: list[Game] | 625941d2fb3f5b602dac3847 |
def __body_for_body_func(self, line): <NEW_LINE> <INDENT> action = self.__in_body_dict.get(self.__token_info) <NEW_LINE> if action is not None: <NEW_LINE> <INDENT> action(line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__write_obj.write(line) | Required:
line -- line to parse
Returns:
nothing
Logic:
Used when parsing the body. | 625941d2be383301e01b5637 |
def tril(m, k=0): <NEW_LINE> <INDENT> m = asanyarray(m) <NEW_LINE> out = multiply(tri(m.shape[0], m.shape[1], k=k, dtype=int),m) <NEW_LINE> return out | Lower triangle of an array.
Return a copy of an array with elements above the `k`-th diagonal zeroed.
Parameters
----------
m : array_like, shape (M, N)
Input array.
k : int, optional
Diagonal above which to zero elements. `k = 0` (the default) is the
main diagonal, `k < 0` is below it and `k > 0` is abo... | 625941d224f1403a92600d18 |
def powerDown(self, powerup, interface=None): <NEW_LINE> <INDENT> if interface is None: <NEW_LINE> <INDENT> for interface, priority in powerup._getPowerupInterfaces(): <NEW_LINE> <INDENT> self.powerDown(powerup, interface) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for cable in self.store.query(_PowerupConn... | Remove a powerup.
If no interface is specified, and the type of the object being
installed has a "powerupInterfaces" attribute (containing
either a sequence of interfaces, or a sequence of (interface,
priority) tuples), the target will be powered down with this
object on those interfaces.
If this object has a "__getP... | 625941d223849d37ff7b3242 |
def test_auto_delay_inside_job(self): <NEW_LINE> <INDENT> job_ = self.env["test.queue.job"].delay_me(1, kwarg=2) <NEW_LINE> self.assertTrue(job_.perform(), (1, 2)) | when a delayed job is processed, it must not delay itself | 625941d282261d6c526ab654 |
def list_by_resource_group( self, resource_group_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2019-08-... | Gets all route filters in a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either RouteFilterListResult or the result of cls(respons... | 625941d255399d3f05588868 |
def quest_1_6(): <NEW_LINE> <INDENT> output_str = "" <NEW_LINE> i = 0 <NEW_LINE> test_str = input("Please enter in a string.\n>>\t") <NEW_LINE> while i < len(test_str): <NEW_LINE> <INDENT> char_ctr = 1 <NEW_LINE> i_shift = 0 <NEW_LINE> while test_str[i] == test_str[i + i_shift]: <NEW_LINE> <INDENT> char_ctr += 1 <NEW_L... | Question 1.6: String Compression
Implement a method to perform basic string compression using the counts of
repeated characters. For example, the string aabcccccaaa would become
a2b1c5a3. If the "compressed" string would not become smaller than the
original string, your method should return the original string. You ca... | 625941d2507cdc57c6306e90 |
def make_config(self, instance_relative=False): <NEW_LINE> <INDENT> root_path = self.root_path <NEW_LINE> if instance_relative: <NEW_LINE> <INDENT> root_path = self.instance_path <NEW_LINE> <DEDENT> defaults = dict(self.default_config) <NEW_LINE> defaults["ENV"] = get_env() <NEW_LINE> defaults["DEBUG"] = get_debug_flag... | Used to create the config attribute by the Flask constructor.
The `instance_relative` parameter is passed in from the constructor
of Flask (there named `instance_relative_config`) and indicates if
the config should be relative to the instance path or the root path
of the application.
Flask 构造函数调用, 用于创建 config 属性. 传入 `... | 625941d230c21e258bdfa651 |
def get_summary_statistic(sequences, function): <NEW_LINE> <INDENT> return [function(s) for s in sequences] | Computes a summary statistic (e.g. entropy, complexity, or turbulence) for each sequence in a collection, returning the results as a list. | 625941d2ec188e330fd5a950 |
def setStr(self, d): <NEW_LINE> <INDENT> fn = list(d.keys())[0] <NEW_LINE> repl = d[fn] <NEW_LINE> for k, v in repl.items(): <NEW_LINE> <INDENT> execute_in_path(self.path, subs(k, v, fn)) | usage setKey(constant/coalCloudProperties,{str:val} | 625941d22ae34c7f2600d2e4 |
def convert_to_datetime(line): <NEW_LINE> <INDENT> return datetime.strptime(line.split()[1], '%Y-%m-%dT%H:%M:%S') | TODO 1:
Given a log line extract its timestamp and convert it to a datetime object.
For example calling the function with:
INFO 2014-07-03T23:27:51 supybot Shutdown complete.
returns:
datetime(2014, 7, 3, 23, 27, 51) | 625941d23c8af77a43ae3954 |
def flush_end(self): <NEW_LINE> <INDENT> self._sync_response() | Wait for the child process to finish flushing output. | 625941d296565a6dacc8f87e |
def expose_inputs(self): <NEW_LINE> <INDENT> return {} | The inputs of a BlackBox should specified by returning a dictionary of string keys to TendrilsSpecifictation.
{"input":self.mymodule["in_0001"]} | 625941d2460517430c394336 |
def get_initial_charges(self): <NEW_LINE> <INDENT> if 'charges' in self.arrays: <NEW_LINE> <INDENT> return self.arrays['charges'].copy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.zeros(len(self)) | Get array of initial charges. | 625941d2236d856c2ad4498f |
def to_struct(self): <NEW_LINE> <INDENT> return {"_class": "Researcher", "street": self.street, "locality": self.locality, "city": self.city, "country": self.county, "state": self.state, "country": self.country, "postal": self.postal, "phone": self.phone, "name": self.name, "address": self.addr, "email": self.email} | Convert the data held in this object to a structure (eg,
struct) that represents all the data elements.
This method is used to recursively convert the object into a
self-documenting form that can easily be used for various
purposes, including diffs and queries.
These structures may be primitive Python types (string,
... | 625941d2711fe17d8254251d |
def diffMarkupPairs(content1, content2): <NEW_LINE> <INDENT> pairResult = {"byAttributeValuePair": None, "byValue": None} <NEW_LINE> content1 = jsonStopCharRe.sub("", content1) <NEW_LINE> content2 = jsonStopCharRe.sub("", content2) <NEW_LINE> if not ((not content1) and (not content2)): <NEW_LINE> <INDENT> pairResult["b... | Compare two markup (XML) files by their common attribute-value pairs and common values.
Args:
content1: Extracted attribute-value pairs
content2: Extracted values
Returns:
Result object with properties: byAttributeValuePair and byValue (both of the same structure as the output from diffContentPairAsFiles) | 625941d221bff66bcd684b05 |
def play(players): <NEW_LINE> <INDENT> deck = generateDeck() <NEW_LINE> currentPlayer = players[list(players.keys())[0]] <NEW_LINE> for _ in range(len(players) * 2): <NEW_LINE> <INDENT> deal(currentPlayer, deck) <NEW_LINE> currentPlayer = getNextPlayer(currentPlayer, players) <NEW_LINE> <DEDENT> printHands(players) <NE... | Core mechanics to handle playing
@param players: All players to play with | 625941d2187af65679ca52d3 |
def get_fxn(self, resource): <NEW_LINE> <INDENT> _key_name = self.key_name or '' <NEW_LINE> fxn = self._fxn <NEW_LINE> authenticate = self.authenticate or resource.requires_authentication() <NEW_LINE> def wrapped_fxn(self, **kwargs): <NEW_LINE> <INDENT> account = None <NEW_LINE> if authenticate and resource.get_auth():... | Wraps the fxn to pull out a key if there is one
:param resource: Resource class that will be calling this controller -> link to model
:return: | 625941d2a219f33f34628b1c |
def parserTime(fromTime): <NEW_LINE> <INDENT> fromTime=fromTime.split(":") <NEW_LINE> return fromTime | function parser fromTime to standard datetime format | 625941d27b180e01f3dc49af |
def test_find_credential(self): <NEW_LINE> <INDENT> self.new_credential.add_credentials() <NEW_LINE> other_credential = Credentials("Fortnite", "Jojo", "password123") <NEW_LINE> other_credential.add_credentials() <NEW_LINE> retrieved_credential = Credential.find_credentials("Fortnite") <NEW_LINE> self.assertEqual(retri... | test whether credential can be found by platform | 625941d2091ae35668667110 |
def tf_idf(tf, df, collection, document_id): <NEW_LINE> <INDENT> N = len(collection) <NEW_LINE> return tf * log10(N / df) | - ptf = tf
- pdf = log10(N / df)
- n = 1 | 625941d2ac7a0e7691ed427d |
def __get_plain_address(link, base_dir): <NEW_LINE> <INDENT> modified_link = link <NEW_LINE> if link.startswith(base_dir): <NEW_LINE> <INDENT> modified_link = link.lstrip(base_dir) <NEW_LINE> <DEDENT> return modified_link | If a link starts with base address, remove the base address and return the link. | 625941d2bf627c535bc13382 |
def to_dict(input, symbol=';'): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for i in input.split(symbol): <NEW_LINE> <INDENT> d[i.split('=', 1)[0]] = i.split('=', 1)[1] <NEW_LINE> <DEDENT> return d | input like "name=mohanson;age=21" | 625941d27c178a314d6ef615 |
def generateParenthesis(self, n): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return ["()"] <NEW_LINE> <DEDENT> result_set = set() <NEW_LINE> for item3 in self.generateParenthesis(n-1): <NEW_LINE> <INDENT> result3 = "(" + item3 + ")" <NEW_LINE> result_set.add(result3) <NEW_LINE> <DEDENT> for i in range(1, n): <N... | :type n: int
:rtype: List[str] | 625941d27047854f462a15bc |
def wrap_view(self, view): <NEW_LINE> <INDENT> def wrapper(request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> callback = getattr(self, view) <NEW_LINE> response = callback(request, *args, **kwargs) <NEW_LINE> return response <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return self... | Wraps views to return custom error codes instead of generic 500's | 625941d223e79379d52ee717 |
def testPriority(self): <NEW_LINE> <INDENT> my_brain = TestBrain._emptyBrain() <NEW_LINE> hn_module = 'HN' <NEW_LINE> hn = filter(lambda m: m.__name__ == hn_module, my_brain.modules)[0] <NEW_LINE> with patch.object(hn, 'handle') as mocked_handle: <NEW_LINE> <INDENT> my_brain.query(["hacker news"]) <NEW_LINE> self.asser... | Does Brain correctly send query to higher-priority module? | 625941d2d99f1b3c44c67740 |
def fx_adjusted_boxplot_Rule(series_id, series_data): <NEW_LINE> <INDENT> v_df = pd.DataFrame({}) <NEW_LINE> v_df_outliers_final = pd.DataFrame({}) <NEW_LINE> v_df['id'] = series_id <NEW_LINE> v_df['data'] = series_data <NEW_LINE> q1 = np.percentile(v_df['data'], 25) <NEW_LINE> q3 = np.percentile(v_df['data'], 75) <NEW... | value should be in +- range of -->(y > q3 + 1.5 * iqr) or (y < q1 - 1.5 * iqr
Usage :
df_outliers= fx_boxplot_Rule(df['myid'],df['series1'])
df_outliers
For presense of outliers --less sensitive than 3 sigma but more sensitive to MAD test
No depenedence of median and mean
better for moderately asymmetric distribution... | 625941d25166f23b2e1a530d |
def find_suitable_period(): <NEW_LINE> <INDENT> highest_acceptable_factor = int(math.sqrt(SIZE)) <NEW_LINE> starting_point = len(VALID_CHARS) > 14 and len(VALID_CHARS) / 2 or 13 <NEW_LINE> for p in range(starting_point, 7, -1) + range(highest_acceptable_factor, starting_point + 1, -1) + [6, 5, 4, ... | Automatically find a suitable period to use.
Factors are best, because they will have 1 left over when
dividing SIZE+1.
This only needs to be run once, on import. | 625941d2ec188e330fd5a951 |
def save_keys_dict(keyslist, outfile): <NEW_LINE> <INDENT> if outfile is None: <NEW_LINE> <INDENT> homepath = os.path.expanduser('~') <NEW_LINE> outfile = os.path.join(homepath, 'Desktop/keys.txt') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> outfile = os.path.abspath(outfile) <NEW_LINE> <DEDENT> with open(outfile, 'w... | 保存密码字典
Args:
keyslist: 密码列表
outfile: 要保存的密码字典文件 | 625941d230dc7b7665901b19 |
def _parse_line(self, regex, line): <NEW_LINE> <INDENT> info = regex.match(line) <NEW_LINE> if info is None: <NEW_LINE> <INDENT> print ("EXceptionLine: %s"%line) <NEW_LINE> raise LogParserError('Failed parsing Slow Query line: %s' % line[:30]) <NEW_LINE> <DEDENT> return info.groups() | Parses a log line using given regular expression
regex[in] a SRE_Match-object
line[in] a string
This function takes a log line and matches the regular expresion given
with the regex argument. It returns the result of
re.MatchObject.groups(), which is a tuple.
Raises LogParserError on errors.
Returns a tuple. | 625941d256b00c62f0f1480e |
def loss_iou(self, outputs, targets, indices, num_boxes): <NEW_LINE> <INDENT> assert 'pred_iou' in outputs <NEW_LINE> assert 'pred_boxes' in outputs <NEW_LINE> bs = outputs['pred_boxes'].shape[0] <NEW_LINE> pred_boxes = outputs['pred_boxes'] <NEW_LINE> preds_iou = outputs['pred_iou'] <NEW_LINE> tgt_iou = [] <NEW_LINE> ... | tIoU loss for the completeness head.
Args:
outputs (dict): Dict of RTD outputs.
targets (list): A list of size batch_size. Each element is a dict composed of:
'labels': Labels of groundtruth instances (0: action).
'boxes': Relative temporal ratio of groundtruth instances.
'video_id': ID... | 625941d2287bf620b61d3c17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.