code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.m is None: <NEW_LINE> <INDENT> self.m = pr_msgs.msg.MassProperties() <NEW_LINE> <DEDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 81 <NEW_LINE> (_x.m.link, _x.m.mass, _x.m.cog_x, _x.m.cog_y, _x.m.c... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941c950812a4eaa59c3b3 |
def test_version(self): <NEW_LINE> <INDENT> mock = MagicMock(side_effect=[IOError('f'), 'A B C\n']) <NEW_LINE> with patch.dict(rsync.__salt__, {'cmd.run_stdout': mock}): <NEW_LINE> <INDENT> self.assertRaises(CommandExecutionError, rsync.version) <NEW_LINE> self.assertEqual(rsync.version(), 'C') | Test for return rsync version | 625941c966656f66f7cbc23b |
def B1Motion(self, event): <NEW_LINE> <INDENT> if self._flag is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self._flag.move(event.x, event.y) <NEW_LINE> if event.y < 50: <NEW_LINE> <INDENT> self.delete_object(self._flag) | 드래그액션.
클릭한 상태에서 움직일 때 플래그로 전달된 전하를 움직임.
메뉴바 높이까지 끌어올리면 삭제 | 625941c963f4b57ef00011ac |
def immune_stats(allStudents): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for x in range(len(allStudents)): <NEW_LINE> <INDENT> if allStudents[x].immune: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> <DEDENT> return i | gets the number of immune people in the population
allStudents: the list of students in the population
Return:
-------
i: number of people immune | 625941c9b7558d58953c4fa6 |
def test_add_two_numbers(): <NEW_LINE> <INDENT> def add_two_numbers(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> print() <NEW_LINE> print() | 思路:
时间复杂度: | 625941c9d6c5a102081440db |
def give_cards(self, hand, amount): <NEW_LINE> <INDENT> for i in range(amount): <NEW_LINE> <INDENT> hand.add_card(self.pop_card()) | Give the amount of cards from the deck to the player's hand. | 625941c950485f2cf553ce2a |
def CreateNewName(self, title, defName, invalidNames): <NEW_LINE> <INDENT> valid = false <NEW_LINE> dlgTxt = 'Name' <NEW_LINE> while not valid: <NEW_LINE> <INDENT> dlg = wxTextEntryDialog(self, dlgTxt, title, defName + str(len(invalidNames) + 1)) <NEW_LINE> if dlg.ShowModal() == wxID_OK: <NEW_LINE> <INDENT> name = dlg.... | Creates a new name different from names in a list | 625941c96fece00bbac2d7cf |
@oauth_remote_error_handler <NEW_LINE> def signup_handler(remote, *args, **kwargs): <NEW_LINE> <INDENT> remote_app_config = current_app.config['OAUTHCLIENT_REST_REMOTE_APPS'][ remote.name] <NEW_LINE> try: <NEW_LINE> <INDENT> form = create_csrf_disabled_registrationform(remote) <NEW_LINE> form = fill_form(form, request.... | Handle extra signup information.
:param remote: The remote application.
:returns: Redirect response or the template rendered. | 625941c930dc7b76659019f8 |
def __init__(self, program = CODEGUARD, options = None, outputs = None): <NEW_LINE> <INDENT> super(CodeGuard, self).__init__(program = program, options = options, outputs = outputs) | @copydoc actc.tools.AbstractBasicCmdTool.__init__ | 625941c966656f66f7cbc23c |
def reset(self, destination=None, testing=False): <NEW_LINE> <INDENT> self.planner.route_to(destination) <NEW_LINE> self.epsilon = math.exp(-self.alpha * self.t) <NEW_LINE> if testing: <NEW_LINE> <INDENT> self.epsilon = 0 <NEW_LINE> self.alpha = 0 <NEW_LINE> <DEDENT> self.t += 1 <NEW_LINE> return None | The reset function is called at the beginning of each trial.
'testing' is set to True if testing trials are being used
once training trials have completed. | 625941c932920d7e50b28260 |
def test_no_stop_heap(self): <NEW_LINE> <INDENT> thread_pool = spead2.ThreadPool(1) <NEW_LINE> sender = send.BytesStream(thread_pool) <NEW_LINE> ig = send.ItemGroup() <NEW_LINE> data = np.array([[6, 7, 8], [10, 11, 12000]], dtype=np.uint16) <NEW_LINE> ig.add_item(id=0x2345, name='name', description='description', shape... | A heap containing a stop is not passed to the ring | 625941c9be8e80087fb20cd5 |
def spearman(frame, features): <NEW_LINE> <INDENT> spr = pd.DataFrame() <NEW_LINE> spr['feature'] = features <NEW_LINE> spr['corr'] = [frame[f].corr(frame['SalePrice'], 'spearman') for f in features] <NEW_LINE> spr = spr.sort_values('corr') <NEW_LINE> plt.figure(figsize=(6, 0.2*len(features))) <NEW_LINE> sns.barplot(da... | :param frame:
:param features:
:return: | 625941c9d99f1b3c44c67620 |
def check_for_previous_progress(self, loc_info): <NEW_LINE> <INDENT> filename = loc_info['filename'] <NEW_LINE> try: <NEW_LINE> <INDENT> if self.done_progress["files"][filename] == 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False | Check previous progress key | 625941c96aa9bd52df036e35 |
def accept_union_battle_box(self, user_id, request): <NEW_LINE> <INDENT> timer = Timer(user_id) <NEW_LINE> req = union_battle_pb2.QueryUnionBattleBoxReq() <NEW_LINE> req.ParseFromString(request) <NEW_LINE> defer = DataBase().get_data(user_id) <NEW_LINE> defer.addCallback(self._calc_accept_union_battle_box, req, timer) ... | 领取联盟战大宝箱奖励 | 625941c9e1aae11d1e749d48 |
def get_modelled_vac_coverage( cluster: str = None, start_age: int = 0, end_age: int = 89, vaccine="pfizer", dose='dose_1' ): <NEW_LINE> <INDENT> msg = f"Starting age not one available from modelled vaccination coverage database: {start_age}" <NEW_LINE> assert start_age in VACC_COVERAGE_START_AGES, msg <NEW_LINE> msg =... | Returns the vaccination coverage per Vida's DHHS model
Args:
cluster (str, optional): The DHHS clusters as all caps with underscores. Defaults to None.
start_age (int, optional): Vida's start age brackets {0,5,12,16,20,30,40,50,60,70,80,85}. Defaults to 0.
end_age (int, optional): Vida's end age brackets {... | 625941c9ec188e330fd5a831 |
def add_timecons(master_list, app_t12 = False, modify_t12 = False): <NEW_LINE> <INDENT> new_master_list = [] <NEW_LINE> for chain in master_list: <NEW_LINE> <INDENT> new_chain = [] <NEW_LINE> for isotope in chain: <NEW_LINE> <INDENT> z = isotope[0] <NEW_LINE> a = isotope[1] <NEW_LINE> isomer = isotope[2] <NEW_LINE> iso... | Adds time constant to master list of all decay chains.
half-life = log(2)/time_const
--INPUT--
master_list: list of all decay chains (list)
t12: True = half-life will be calculated instead of time constants
modify_t12: True = half-lives will be modifed into strings with
nice unit, False = half-lives in seconds, also c... | 625941c9de87d2750b85fe23 |
def set_cartographic(cartographic): <NEW_LINE> <INDENT> coastlines = cartographic['coastlines'] <NEW_LINE> countries = cartographic['countries'] <NEW_LINE> rivers = cartographic['rivers'] <NEW_LINE> if coastlines: <NEW_LINE> <INDENT> plt.gca().coastlines() <NEW_LINE> <DEDENT> if countries: <NEW_LINE> <INDENT> countries... | Adds coastlines, country borders and rivers to the plot as desired.
Args:
* cartographic
dictionary containing Booleans for displaying coastlines, countries and
rivers. | 625941c97047854f462a149c |
@app.callback([Output('description', 'children'), Output('desc_button', 'style'), Output('desc_button', 'children')], [Input('desc_button', 'n_clicks')]) <NEW_LINE> def toggleDescription(click): <NEW_LINE> <INDENT> if not click: <NEW_LINE> <INDENT> click = 0 <NEW_LINE> <DEDENT> if click % 2 == 0: <NEW_LINE> <INDENT> de... | Toggle description on/off. | 625941c9eab8aa0e5d26dbe9 |
@pytest.fixture <NEW_LINE> def login(open_login_page, user, password): <NEW_LINE> <INDENT> open_login_page.set_username(user) <NEW_LINE> open_login_page.set_password(password) <NEW_LINE> open_login_page.login() | Logging in | 625941c9796e427e537b0657 |
def setOssSource(self, ossSource): <NEW_LINE> <INDENT> self.ossSource = ossSource | :param ossSource: (Optional) oss回源域名 | 625941c9a4f1c619b28b00cc |
def setUp(self): <NEW_LINE> <INDENT> super(TestAdding, self).setUp() <NEW_LINE> self.page = pywikibot.Page(self.site, 'foo') | Setup test. | 625941c991f36d47f21ac583 |
def main(): <NEW_LINE> <INDENT> config = Config(create_if_absent=True, debug=bool(os.getenv('DEBUG'))) <NEW_LINE> if config.debug: <NEW_LINE> <INDENT> print('DEBUG mode') <NEW_LINE> <DEDENT> browser = Browser(config) <NEW_LINE> browser.login() | log in navigate and reboot | 625941c9d486a94d0b98e1d7 |
def tearDown(self): <NEW_LINE> <INDENT> basetest.BaseTestCase.tearDown(self) | 清洁测试环境 | 625941c901c39578d7e74ecd |
def testNamesExpected(self): <NEW_LINE> <INDENT> self.assertEquals(set(self._diversePolicy.names()), self._fullNames) <NEW_LINE> self.assertEquals(set(self._diversePolicy.names(True)), self._topNames) <NEW_LINE> self.assertEquals(set(self._diversePolicy.names(False)), self._fullNames) | Test if `Policy::names(bool)` returns heirarchical names if and
only if they are requested. | 625941c97d43ff24873a2d32 |
def isMounted(self, mountpoint=None): <NEW_LINE> <INDENT> for line in self.getMountList(): <NEW_LINE> <INDENT> if not line or line == "": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> lineattrs=line.split(" ") <NEW_LINE> if lineattrs and len(lineattrs) > 1 and mountpoint and self.isMyMountpoint(lineattrs[1], mountpo... | returns True if this device is already mounted.
If mountpoint is also given, the mountpoint will be taken into account
otherwise the devicename
@param mountpoint: the mountpoint as DataObject
@return: True or False. True if device is already mounted otherwise False | 625941c9627d3e7fe0d68ee1 |
def main(): <NEW_LINE> <INDENT> yaml_dict = {} <NEW_LINE> file_list = [] <NEW_LINE> symlink_list = [] <NEW_LINE> logging.basicConfig(level=logging.INFO) <NEW_LINE> params = vars(parse_commandline()) <NEW_LINE> if params["tools"]: <NEW_LINE> <INDENT> tools_path = params["tools"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | Main function | 625941c9d18da76e23532567 |
def _normalize(self, node): <NEW_LINE> <INDENT> if node == self.root: <NEW_LINE> <INDENT> node.red = False <NEW_LINE> <DEDENT> elif node.parent.isblack: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif node.uncle and node.uncle.isred: <NEW_LINE> <INDENT> node.parent.red = False <NEW_LINE> node.uncle.red = False <NEW... | Fix Red-Black tree properties. | 625941c9d53ae8145f87a302 |
def t_string(self, input): <NEW_LINE> <INDENT> s = input[1:-1] <NEW_LINE> s = unescape_C(s) <NEW_LINE> self.rv.append(String(s)) | "([^"\\]+|\\.)*"|'([^'\\]+|\\.)*' | 625941c956b00c62f0f146ea |
def perform_create(self, serializer): <NEW_LINE> <INDENT> status_code = status.HTTP_201_CREATED <NEW_LINE> instance = serializer.save() <NEW_LINE> data = serializer.data <NEW_LINE> path = os.path.join(settings.MEDIA_ROOT, str(instance.doc)) <NEW_LINE> employees_list =[] <NEW_LINE> employees = models.Employee.objects.al... | post-save employee to employee table after upload empolyee.csv
:param serializer: save and get isntance
:return: message and status code | 625941c966673b3332b92122 |
def test_sort_range_4(self): <NEW_LINE> <INDENT> shuffled = [3, 2, 1, 0] <NEW_LINE> expected = [0, 1, 2, 3] <NEW_LINE> received = mergesort(shuffled) <NEW_LINE> self.assertEquals(expected, received) | Sort by MergeSort: list=[3, 2, 1, 0] returns [0, 1, 2, 3] | 625941c9f7d966606f6aa095 |
def upload_badge_to_gcs( badge: Badge, bucket_name: str, build: Build ) -> List[str]: <NEW_LINE> <INDENT> def upload(path: str) -> None: <NEW_LINE> <INDENT> bucket = gcs_client.get_bucket(bucket_name) <NEW_LINE> blob = bucket.blob(path) <NEW_LINE> blob.cache_control = "max-age=60, s-maxage=60" <NEW_LINE> blob.upload_fr... | バッジをGCSに保存する。
Parameters
----------
badge : Badge
バッジ。
bucket_name : str
バケット名。
build : Build
ビルドの情報。
Returns
-------
list of str
GCSに保存したバッジのURLを格納したリスト。 | 625941c9a219f33f346289fc |
def validateManifest(jobconf, confObj): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> console = Context.console <NEW_LINE> mnfst = None <NEW_LINE> global_let = confObj.get("let") <NEW_LINE> if "ARGS" in global_let and len(global_let["ARGS"]) == 1: <NEW_LINE> <INDENT> mnfst = Manifest(global_let["ARGS"][0]) <NEW_LINE> <DED... | Validates Manifest and prints to stdOut.
:param jobconf: generator.config.Job.Job
:param confObj: generator.config.Config.Config | 625941c923849d37ff7b3121 |
def send_to_honeycomb(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from clrenv import env <NEW_LINE> if env.get("honeycomb") is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> beeline.init( writekey=env.honeycomb.writekey, dataset="clr", service_name="clr", ) <NEW_LINE> honeycomb_data["duration_ms"] = int( 1000... | Attempts to log usage data to honeycomb.
Honeycomb logging is completely optional. If there are any failures
simply continue as normal. This includes if clrenv can not be loaded.
These metrics are sent to honeycomb as an event rather than a trace for two
reasons:
1) They don't really fit the web requests model.
2) Do... | 625941c956b00c62f0f146eb |
@asyncio.coroutine <NEW_LINE> def async_setup_scanner(hass, config, async_see, discovery_info=None): <NEW_LINE> <INDENT> devices = config[CONF_DEVICES] <NEW_LINE> qos = config[CONF_QOS] <NEW_LINE> dev_id_lookup = {} <NEW_LINE> @callback <NEW_LINE> def async_tracker_message_received(topic, payload, qos): <NEW_LINE> <IND... | Setup the MQTT tracker. | 625941c93c8af77a43ae3831 |
def validate_user(self): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print('EditController: validate_user()') <NEW_LINE> print(len(self.model.contact['user'].strip())) <NEW_LINE> <DEDENT> validation = True <NEW_LINE> if len(self.model.contact['user'].strip()) != int(self.model.settings['defaultUserLength']):... | validates user input 'user'
:return: boolean | 625941c94e696a04525c94dd |
def post_lunch(dow, channel): <NEW_LINE> <INDENT> if dow > 4: return <NEW_LINE> resp = '*Lunch of the Day (%s):*\n------------------------------------\n\n' % weekdays[dow] <NEW_LINE> for menu in menu_classes: <NEW_LINE> <INDENT> menu_obj = menu() <NEW_LINE> if dow != 4 and 'Avesta' in str(menu_obj): <NEW_LINE> <INDENT>... | Posts today's menu from all included restaurants | 625941c9379a373c97cfabd6 |
def get_env_vars(self): <NEW_LINE> <INDENT> env_vars = {} <NEW_LINE> for var in _interesting_env_vars: <NEW_LINE> <INDENT> env_vars[var] = os.getenv(var, None) <NEW_LINE> <DEDENT> if 'env_vars' in self.config and self.config['env_vars']: <NEW_LINE> <INDENT> for var in self.config['env_vars']: <NEW_LINE> <INDENT> env_va... | Return env vars defined at the main scope of the script. | 625941c957b8e32f5248352c |
def is_waiting_for_input(self): <NEW_LINE> <INDENT> return self.waiting_for and not isinstance(self.waiting_for, forking.SwitchOnValue) and not is_base_type(self.waiting_for) | could make one step further
:return: | 625941c938b623060ff0ae7f |
def remove_phrase_treeinput(self,tr,labels=None,stopwords=[]): <NEW_LINE> <INDENT> if not labels: <NEW_LINE> <INDENT> labels = ['ORGANIZATION','PERSON','LOCATION','DATE','TIME','MONEY','PERCENT','FACILITY','GPE'] <NEW_LINE> <DEDENT> labels.append('S') <NEW_LINE> return ' '.join([' '.join(tree_travel(e,stopwords)) if is... | :param tr: tree object
:param labels: list of label to extract phrase
:param stopwords: stopwords list
:return: | 625941c90a366e3fb873e8ab |
def cJSON_Print(item, indent): <NEW_LINE> <INDENT> return _iotkit.cJSON_Print(item, indent) | cJSON_Print(cJSON item, int indent) -> char *
Parameters:
item: cJSON *
indent: int | 625941c9596a897236089b53 |
def print_final(self, s='Final'): <NEW_LINE> <INDENT> log.hline('-') <NEW_LINE> log('%s reference Energy: %16.12f' %(s,self.compute_reference_energy()+self.ecore)) <NEW_LINE> log('%s correlation Energy: %16.12f' %(s,self.compute_correlation_energy())) <NEW_LINE> log.hline('=') <NEW_LINE> log('%s total Energy: ... | Print energies
**Optional arguments:**
s
A string. | 625941c9f548e778e58cd60f |
def grep(pattern, lines): <NEW_LINE> <INDENT> for line in lines: <NEW_LINE> <INDENT> if re.search(pattern, line): <NEW_LINE> <INDENT> yield line | Yield lines matching pattern.
>>> list(grep("a", ["cat", "dog", "mat", "cot"]))
['cat', 'mat']
The pattern is interpreted as a regular expression:
>>> list(grep("c.t", ["cat", "dog", "mat", "cot"]))
['cat', 'cot'] | 625941c9cad5886f8bd2706b |
def sliding_subset_check(sub, SUP, empty_set = None, tolerate_key_val = None): <NEW_LINE> <INDENT> depth_sub = dict_depth(sub) <NEW_LINE> depth_SUP = dict_depth(SUP) <NEW_LINE> if depth_sub and depth_SUP: <NEW_LINE> <INDENT> for depth_offset in range(depth_SUP - depth_sub, -1, -1): <NEW_LINE> <INDENT> if _DEBUG_LEVEL >... | for test, expect in [
( ({1: None, 4: None}, {2: [[{1: None, 4: None, 5:[]}], [], 1], 3:None}), True )
]:
assert sliding_subset_check(*test) == expect | 625941c938b623060ff0ae80 |
def pretty_print(data, indent=0, file=sys.stdout): <NEW_LINE> <INDENT> if isinstance(data, string_type): <NEW_LINE> <INDENT> _pprint_list(file, [data], indent) <NEW_LINE> <DEDENT> elif isinstance(data, list): <NEW_LINE> <INDENT> _pprint_list(file, data, indent) <NEW_LINE> <DEDENT> elif isinstance(data, dict): <NEW_LINE... | Pretty print a data structure. | 625941c99b70327d1c4e0e67 |
@subscriber(NewRequest) <NEW_LINE> def clean_db_session(event): <NEW_LINE> <INDENT> def clean_up(request): <NEW_LINE> <INDENT> request.session.remove() <NEW_LINE> <DEDENT> settings = event.request.registry.settings <NEW_LINE> db_session_cleanup = asbool(settings.get('db_session_cleanup', True)) <NEW_LINE> if db_session... | Clean up DB session when the request processing is finished
| 625941c97c178a314d6ef4f1 |
def plot_rolling_sharpe(returns, factor_returns=None, rolling_window=APPROX_BDAYS_PER_MONTH * 6, legend_loc='best', ax=None, **kwargs): <NEW_LINE> <INDENT> if ax is None: <NEW_LINE> <INDENT> ax = plt.gca() <NEW_LINE> <DEDENT> y_axis_formatter = FuncFormatter(utils.two_dec_places) <NEW_LINE> ax.yaxis.set_major_formatter... | Plots the rolling Sharpe ratio versus date.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
factor_returns : pd.Series, optional
Daily noncumulative returns of the benchmark factor for
which the benchmark r... | 625941c91f037a2d8b946290 |
def bas_completion_current_buffer_cb(data, completion_item, buffer, completion): <NEW_LINE> <INDENT> name = "%s.%s" % (weechat.buffer_get_string(buffer, "plugin"), weechat.buffer_get_string(buffer, "name")) <NEW_LINE> weechat.hook_completion_list_add(completion, name, 0, weechat.WEECHAT_LIST_POS_BEGINNING) <NEW_LINE> r... | Complete with current buffer name (plugin.name), for command '/autosetbuffer'. | 625941c93d592f4c4ed1d101 |
def estep__calc_r_NK(self, x_ND): <NEW_LINE> <INDENT> N = x_ND.shape[0] <NEW_LINE> r_NK = np.zeros((N, self.K)) <NEW_LINE> r_NK[:,0] = 1.0 <NEW_LINE> assert np.allclose(np.sum(r_NK, axis=1), 1.0) <NEW_LINE> return r_NK | Perform E-step to update assignment variables r controling q(z | r)
Returned value will optimize the EM loss function for r given fixed current GMM parameters
Args
----
x_ND : 2D array, shape (N, D)
Dataset of observed feature vectors
The n-th row x_ND[n] defines a length-D feature vector
Returns
-------
r_N... | 625941c976e4537e8c351704 |
def rotozoomSurfaceSizeXY(width, height, angle, zoomx, zoomy, dstwidth, dstheight): <NEW_LINE> <INDENT> return _funcs["rotozoomSurfaceSizeXY"]( width, height, angle, zoomx, zoomy, dstwidth, dstheight ) | Returns the output surface size of a :func:`rotozoomSurfaceXY` call.
This function outputs the calculated height and width by reference to the
``dstwidth`` and ``dstheight`` arguments, and does not return any value
itself.
Args:
width (int): The width (in pixels) of the source surface.
height (int): The heigh... | 625941c982261d6c526ab530 |
def get_selfenergy(self,energy,lead=0,delta=None,pristine=False): <NEW_LINE> <INDENT> if delta is None: delta = self.delta <NEW_LINE> if self.interpolated_selfenergy: <NEW_LINE> <INDENT> if lead==0: return np.matrix(self.selfgen[0](energy)) <NEW_LINE> if lead==1: return np.matrix(self.selfgen[1](energy)) <NEW_LINE> <D... | Return self energy of iesim lead | 625941c90a366e3fb873e8ac |
def init_env(project_info): <NEW_LINE> <INDENT> global env <NEW_LINE> env = os.environ.copy() <NEW_LINE> env["PATH"] = prepend_path(benchmark_dir, env["PATH"]) <NEW_LINE> if "env" in conf: <NEW_LINE> <INDENT> for key, val in conf["env"].items(): <NEW_LINE> <INDENT> if val.find('~') >= 0: <NEW_LINE> <INDENT> val = os.pa... | initialize env for commands with benchmark and project customizations | 625941c9b57a9660fec33916 |
def list_of_totient_numbers(upper_bound): <NEW_LINE> <INDENT> totient_numbers = {} <NEW_LINE> numbers = get_numbers(upper_bound) <NEW_LINE> for i in numbers: <NEW_LINE> <INDENT> totient_numbers[i] = 0 <NEW_LINE> for j in range(1, i + 1): <NEW_LINE> <INDENT> if gcd(j, i) == 1: <NEW_LINE> <INDENT> totient_numbers[i] += 1... | Loop through all numbers calculating the totient number to return a
dictionary of integers to the totient number
Only do factorials of primes to save time | 625941c95fdd1c0f98dc02c5 |
def rmsprop(x, dx, config=None): <NEW_LINE> <INDENT> if config is None: config = {} <NEW_LINE> config.setdefault('learning_rate', 1e-2) <NEW_LINE> config.setdefault('decay_rate', 0.99) <NEW_LINE> config.setdefault('epsilon', 1e-8) <NEW_LINE> config.setdefault('cache', np.zeros_like(x)) <NEW_LINE> next_x = None <NEW_LIN... | Uses the RMSProp update rule, which uses a moving average of squared gradient
values to set adaptive per-parameter learning rates.
config format:
- learning_rate: Scalar learning rate.
- decay_rate: Scalar between 0 and 1 giving the decay rate for the squared
gradient cache.
- epsilon: Small scalar used for smoothin... | 625941c90c0af96317bb827a |
def test_userStore(self): <NEW_LINE> <INDENT> ls = self.store.findUnique(LoginSystem) <NEW_LINE> substore = ls.accountByAddress(u'testuser', u'localhost').avatars.open() <NEW_LINE> d = substore.whenFullyUpgraded() <NEW_LINE> def fullyUpgraded(ignored): <NEW_LINE> <INDENT> web = substore.findUnique(WebSite) <NEW_LINE> s... | Test that WebSites in user stores upgrade without errors. | 625941c9f9cc0f698b14068e |
def set_args(self, ConfigPath, CustomVars, ExcludedBundles): <NEW_LINE> <INDENT> self.kwargs["ConfigPath"] = self.ConfigPath = ConfigPath <NEW_LINE> self.kwargs["CustomVars"] = self.CustomVars = CustomVars <NEW_LINE> self.kwargs["ExcludedBundles"] = self.ExcludedBundles = ExcludedBundles | :param ConfigPath:
:type ConfigPath: str | 625941c915baa723493c4007 |
def grid_2d_slim_from( grid_2d_native: np.ndarray, mask: np.ndarray, sub_size: int ) -> np.ndarray: <NEW_LINE> <INDENT> grid_1d_slim_y = array_2d_util.array_2d_slim_from( array_2d_native=grid_2d_native[:, :, 0], mask_2d=mask, sub_size=sub_size ) <NEW_LINE> grid_1d_slim_x = array_2d_util.array_2d_slim_from( array_2d_nat... | For a native 2D grid and mask of shape [total_y_pixels, total_x_pixels, 2], map the values of all unmasked
pixels to a slimmed grid of shape [total_unmasked_pixels, 2].
The pixel coordinate origin is at the top left corner of the native grid and goes right-wards and downwards, such
that for an grid of shape (3,3) wher... | 625941c95166f23b2e1a51ec |
def GetLevel(self): <NEW_LINE> <INDENT> return _itkIntensityWindowingImageFilterPython.itkIntensityWindowingImageFilterIF2IUC2_GetLevel(self) | GetLevel(self) -> float | 625941c963d6d428bbe44582 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SubComputeViewModelIEnumerablePaginatedViewModel): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941c9566aa707497f45fc |
def get_type(self): <NEW_LINE> <INDENT> return _moduleconnectorwrapper.PreferredSplitSize_get_type(self) | get_type(PreferredSplitSize self) -> XeThru::PreferredSplitSize::SizeType
The value reflects the last specified type, e.g.
if calling set_duration(15 * 60) this function returns DurationType.
Returns
-------
the type of the preferred size.
See also: SizeType | 625941c9b5575c28eb68e092 |
def hash_entity(self, path, level="card"): <NEW_LINE> <INDENT> if level == "card" and os.path.splitext(path)[1] == ".jpg": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> img_phash = ih.phash(Image.open(path)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("pb de hashage sur la carte {0}".format(path)) <NEW_LINE> i... | Méthode récursive qui applique un perceptual hash sur une entité:
directory, folder ou card | 625941c9596a897236089b54 |
def random_ray(dataset_file, output_data_dir="", axis="z", ray_prefix="Ray", return_ray=False): <NEW_LINE> <INDENT> if isinstance(dataset_file, str): <NEW_LINE> <INDENT> ds = yt.load(dataset_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ds = dataset_file <NEW_LINE> <DEDENT> width = ds.parameters['BoxSize'] <NEW_L... | Generate a ray with a random start and end point. | 625941c95e10d32532c5efb9 |
def __init__(self, parent, width, height): <NEW_LINE> <INDENT> Frame.__init__(self, parent) <NEW_LINE> self.parent = parent <NEW_LINE> self.width = width <NEW_LINE> self.height = height <NEW_LINE> center_window(self) <NEW_LINE> self.parent.title("Evolution Simulator") <NEW_LINE> self.pack(fill=BOTH, expand=1) <NEW_LINE... | Initializes the application
Args:
parent: An object for the parent of the application
width: An integer for the width of the application
height: An integer for the height of the application | 625941c96fece00bbac2d7d0 |
@parallel <NEW_LINE> @roles('frontends') <NEW_LINE> def upload_firmware(firmware): <NEW_LINE> <INDENT> operations.put(firmware, '~/A8') | Upload the firmware to the frontends A8 shared directory | 625941c9fbf16365ca6f6256 |
@pytest.mark.parametrize('pattern', [ 'aa.py', '_a.py', 'a1.py', 'a10.py', 'a10a10a.py' ]) <NEW_LINE> def test_taskfile_regex(pattern): <NEW_LINE> <INDENT> assert loadlimit.importhook.taskfile_regex.match(pattern) | Regex matches as expected | 625941c926238365f5f0ef00 |
def model_summary(self): <NEW_LINE> <INDENT> print(self.model.summary()) | Print summary of currently loaded model
| 625941c9a17c0f6771cbe0e3 |
def vectorizer_to_dataframe(vectorizer, document_term_mat): <NEW_LINE> <INDENT> dfv = pd.DataFrame(document_term_mat.todense(), columns=vectorizer.get_feature_names()) <NEW_LINE> return dfv | Given a sklearn vectorizer return a dataframe with
documents on rows, words on columns, weights as values.
Input - fitted vectorizer
document_term_mat, from vectorizer.fit_transform(docs)
Output - pandas dataframe | 625941c9c4546d3d9de72ac6 |
def indent_selection(self, cursor): <NEW_LINE> <INDENT> doc = self.editor.document() <NEW_LINE> cursor.beginEditBlock() <NEW_LINE> nb_lines = len(cursor.selection().toPlainText().splitlines()) <NEW_LINE> c = self.editor.textCursor() <NEW_LINE> if c.atBlockStart() and c.position() == c.selectionEnd(): <NEW_LINE> <INDENT... | Indent selected text
:param cursor: QTextCursor | 625941c9711fe17d82542400 |
def not_none(param): <NEW_LINE> <INDENT> if param is None: <NEW_LINE> <INDENT> raise ValueError('{} is None'.format(get_name_from_param(param))) | Fails if the input parameter is None | 625941c9f548e778e58cd610 |
def generate_log(lst1, lst2): <NEW_LINE> <INDENT> line_numbers1, list1 = compress(lst1) <NEW_LINE> line_numbers2, list2 = compress(lst2) <NEW_LINE> t = LCS(list1, list2) <NEW_LINE> i = j = 0 <NEW_LINE> log = [] <NEW_LINE> while i < len(list1) and j < len(list2): <NEW_LINE> <INDENT> if t[i][j] == t[i + 1][j]: <NEW_LINE>... | generate log that can be used for rollback from lst2 to lst1 | 625941c9b830903b967e999e |
def inventory_csv(request): <NEW_LINE> <INDENT> response = http.HttpResponse(content_type='text/csv') <NEW_LINE> response['Content-Disposition'] = 'attachment; filename="inventory.csv"' <NEW_LINE> writer = csv.writer(response) <NEW_LINE> max_pairs = inventory_models.Shoe.objects.annotate( db_models.Count('shoeattribute... | Restore backup from May 1, <year> to snapshot.perfectarch.ca
Comment out auditlog tracking
Load this view
To get the total in-stock and total cost, run the following in shell:
from inventory import models
shoes=models.Shoe.objects.prefetch_related('shoeattributes_set')
cost = 0
quantity_total = 0
for shoe in shoes:... | 625941c976d4e153a657ebc3 |
@check_reservation_permissions <NEW_LINE> def cancel_occurrence(request, reservation_id, template_name='schedule/cancel_occurrence.html', *args, **kwargs): <NEW_LINE> <INDENT> extra_context = kwargs.get('extra_context', None) or {} <NEW_LINE> reservation, occurrence = get_occurrence(reservation_id, *args, **kwargs) <NE... | This view is used to cancel an occurrence. If it is called with a POST it
will cancel the view. If it is called with a GET it will ask for
conformation to cancel. | 625941c997e22403b379d02c |
def eval_rational(self, tol): <NEW_LINE> <INDENT> if not self.is_real: <NEW_LINE> <INDENT> raise NotImplementedError("eval_rational() only works for real polynomials so far") <NEW_LINE> <DEDENT> func = lambdify(self.poly.gen, self.expr) <NEW_LINE> interval = self._get_interval() <NEW_LINE> a = Rational(str(interval.a))... | Returns a Rational approximation to ``self`` with the tolerance ``tol``.
This method uses bisection, which is very robust and it will always
converge. The returned Rational instance will be at most 'tol' from the
exact root.
The following example first obtains Rational approximation to 1e-7
accuracy for all roots of ... | 625941c976d4e153a657ebc4 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, RatePlanChargeData): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941c99f2886367277a921 |
def set_dataset(self, dataset): <NEW_LINE> <INDENT> self.__dataset = dataset | Set the dataset for the training. | 625941c9d268445f265b4f01 |
def reset(option_name: str) -> None: <NEW_LINE> <INDENT> set_(option_name, _global_settings._options[option_name].default) | Set an option to its default value given to :func:`add_option`. | 625941c94527f215b584c4ea |
def search(self, name): <NEW_LINE> <INDENT> url = self.__CreateSearchUrl__(name) <NEW_LINE> page = self.__DownloadSearchPage__(url) <NEW_LINE> results = self.__GetSearchResults__(page) <NEW_LINE> results_xml = ElementTree_fromstring(results) <NEW_LINE> rv = [] <NEW_LINE> for result in results_xml.findall("entity"): <NE... | returns an array where each entry is a hit in the results:
[ {title: "Gladiator",
id: "98",
year: "2000",
url: "http://api.themoviedb.org/2.1/Movie.getInfo/$INFO[language]/xml/57983e31fb435df4df77afb854740ea9/98"}
{...},
... | 625941c901c39578d7e74ece |
def _Dynamic_SendPresence(self, request, response): <NEW_LINE> <INDENT> from_jid = self._GetFrom(request.from_jid()) <NEW_LINE> log_message = [] <NEW_LINE> log_message.append('Sending an XMPP Presence:') <NEW_LINE> log_message.append(' From:') <NEW_LINE> log_message.append(' ' + from_jid) <NEW_LINE> log_messag... | Implementation of XmppService::SendPresence.
Args:
request: An XmppSendPresenceRequest.
response: An XmppSendPresenceResponse . | 625941c9f8510a7c17cf978f |
def click_add_button(self): <NEW_LINE> <INDENT> self.b.find_element(*self.add_btn).click() | 点击新增设备按钮 | 625941c9283ffb24f3c55995 |
def comma_separated_values(values): <NEW_LINE> <INDENT> string_values = [str(value) for value in values] <NEW_LINE> string = ",".join(string_values) <NEW_LINE> return string | For requests that require multiple values for one parameter | 625941c915baa723493c4008 |
def _debug(obj): <NEW_LINE> <INDENT> pass | For debug purpose | 625941c9462c4b4f79d1d764 |
def sizeof_fmt(num: float) -> str: <NEW_LINE> <INDENT> for unit in ("B", "K", "M", "G", "T", "P", "E", "Z"): <NEW_LINE> <INDENT> if num < 1024.0: <NEW_LINE> <INDENT> if num < 100: <NEW_LINE> <INDENT> return f"{num:3.1f}{unit}" <NEW_LINE> <DEDENT> return f"{num:3.0f}{unit}" <NEW_LINE> <DEDENT> num /= 1024.0 <NEW_LINE> <... | Retrieve size of a byte number in human-readable format.
Args:
num: Filesize in bytes.
Returns:
Filesize in human-readable format. | 625941c98e05c05ec3eea407 |
def __init__(self, name, direction, description = ''): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> d = direction.lower() <NEW_LINE> if d != 'in' and d != 'out': <NEW_LINE> <INDENT> raise ModelError("Invalid direction '{0}' in event port '{1}'".format(direction, name)) <NEW_LINE> <DEDENT> self.direction = direction ... | Constructor.
See instance variable documentation for more details on parameters. | 625941c950485f2cf553ce2d |
def multigaussian(x, mean, stddev): <NEW_LINE> <INDENT> tmp = -0.5 * ((x-mean)/stddev)**2 <NEW_LINE> return np.exp(tmp) / (np.sqrt(2.*np.pi) * stddev) | Returns value of uncorrelated Gaussians at given scalar point.
x: scalar
mean: vector
stddev: vector | 625941c97b25080760e394ed |
def updatecolumnorder(self, logical, old, new): <NEW_LINE> <INDENT> moved_col = self.Properties['col_order'][old] <NEW_LINE> moved_width = self.Properties['col_widths'][old] <NEW_LINE> del self.Properties['col_order'][old] <NEW_LINE> del self.Properties['col_widths'][old] <NEW_LINE> self.Properties['col_order'].insert(... | slot for sectionMoved(int,int,int) | 625941c9d486a94d0b98e1d8 |
def print_dict(data, indent_level=0): <NEW_LINE> <INDENT> indent = ' ' * indent_level <NEW_LINE> def _format_key(k): <NEW_LINE> <INDENT> return '{}{}{: <40}{}'.format( indent, '\x1b[36m', k + ':', '\x1b[0m' ) <NEW_LINE> <DEDENT> for k, v in sorted(data.items()): <NEW_LINE> <INDENT> if not isinstance(v, dict): <NEW_LIN... | Pretty-print a dict full of key-value metadata pairs | 625941c907f4c71912b11515 |
@register_ibs_method <NEW_LINE> @accessor_decors.setter <NEW_LINE> @register_api('/api/part/metadata/', methods=['PUT']) <NEW_LINE> def set_part_metadata(ibs, part_rowid_list, metadata_dict_list): <NEW_LINE> <INDENT> id_iter = ((part_rowid,) for part_rowid in part_rowid_list) <NEW_LINE> metadata_str_list = [] <NEW_LINE... | Sets the part's metadata using a metadata dictionary
RESTful:
Method: PUT
URL: /api/part/metadata/
CommandLine:
python -m ibeis.control.manual_part_funcs --test-set_part_metadata
Example:
>>> # ENABLE_DOCTEST
>>> from ibeis.control.manual_part_funcs import * # NOQA
>>> import ibeis
>>... | 625941c9ec188e330fd5a834 |
def insert_text_at_selection_bound(self, text: str) -> None: <NEW_LINE> <INDENT> start = self.textCursor().selectionStart() <NEW_LINE> end = self.textCursor().selectionEnd() <NEW_LINE> self.textCursor().clearSelection() <NEW_LINE> cursor = self.textCursor() <NEW_LINE> cursor.setPosition(end) <NEW_LINE> self.setTextCurs... | Inserts given text at the beginning and at the end of the current selection | 625941c94e4d5625662d446c |
@persistent <NEW_LINE> def print_updated_objects(scene): <NEW_LINE> <INDENT> for im_ob in scene.objects: <NEW_LINE> <INDENT> if im_ob.is_updated: <NEW_LINE> <INDENT> if (im_ob.name in ["Image DV","Image AP","Image ML"]): <NEW_LINE> <INDENT> (ind, N, delta, orientation, image_files, locs) = getIndex(im_ob) <NEW_LINE> lo... | Called when that the scene is updated. It look for the updated images and
load the image corresponding to it's actual location. | 625941c901c39578d7e74ecf |
def test_run(base_url, axe): <NEW_LINE> <INDENT> violations = axe.run() <NEW_LINE> assert violations == test_data | Assert that run method returns results. | 625941c9d18da76e23532569 |
def draw_tail(self, context): <NEW_LINE> <INDENT> context.cairo.line_to(0, 0) | Default tail drawer: draw line to the last handle. | 625941c992d797404e30421d |
def person_one(name, age, *, city, study='high'): <NEW_LINE> <INDENT> print(name, age, city, study) | 命名关键字参数: 对 * 后的参数进行检查, 只接收 city 关键字 | 625941c9ff9c53063f47c287 |
def deleteItem(self, itemid, userid=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__session = Session() <NEW_LINE> item = self.__getItemFromLotNumber(itemid) <NEW_LINE> uid = item.offered.uid <NEW_LINE> itemsowned = len(item.offered.owneditems)-1 <NEW_LINE> if userid: <NEW_LINE> <INDENT> user = self.__getUse... | Method to delete an item by ID from the DB.
Args:
itemid - Lot number of the item to delete.
[optional] userid - If provided, will only let the calling user ID delete their own items.
Exceptions:
DoesNotExist - Will be raised if item is not found in the DB.
UserNotRegistered - Raised if passed use... | 625941c9dc8b845886cb55c8 |
def remove(self, fact): <NEW_LINE> <INDENT> if not isinstance(fact, lib_objects.Fact): <NEW_LINE> <INDENT> message = _("You need to pass a ``hamster_lib.objects.Fact`` instance") <NEW_LINE> raise TypeError(message) <NEW_LINE> <DEDENT> self._interface.Remove(fact.pk) | Remove a Fact.
For details see the corresponding method in ``hamster_lib.storage``. | 625941c929b78933be1e5740 |
def get_openness_choices(self): <NEW_LINE> <INDENT> return ( (Group.OPEN, _('Can join when they want')), (Group.MODERATED, _('Users ask permission')), (Group.CLOSED, _('Moderator adds users')) ) | gives answers to question
"How can users join this group?" | 625941c966673b3332b92124 |
def laplacian(self, pos): <NEW_LINE> <INDENT> ao_lapls = np.zeros((self.num_aos,), dtype=float) <NEW_LINE> for iao in range(self.num_aos): <NEW_LINE> <INDENT> ao_lapls[iao] = self.aos[iao].laplacian(pos) <NEW_LINE> <DEDENT> return ao_lapls | Evaluate the laplacian of all atomic orbitals in the LCAO at a given position.
| 625941c9925a0f43d2549f0a |
def _get_entry(entries, name): <NEW_LINE> <INDENT> for entry in entries: <NEW_LINE> <INDENT> if entry["name"] == name: <NEW_LINE> <INDENT> entry = entry.copy() <NEW_LINE> entry["name"] = prefix + entry["name"] <NEW_LINE> return entry | Finds the entry with the requested name, prepends the
prefix (to get its full path), and returns it.
If no entry has that name, returns None. | 625941c9a8370b7717052933 |
def _concatenate_punctuations(self, chunks): <NEW_LINE> <INDENT> result = [] <NEW_LINE> tmp_bucket = [] <NEW_LINE> chunks = chunks[::-1] <NEW_LINE> for chunk in chunks: <NEW_LINE> <INDENT> if chunk.pos == u'PUNCT': <NEW_LINE> <INDENT> tmp_bucket.append(chunk) <NEW_LINE> continue <NEW_LINE> <DEDENT> if tmp_bucket: <NEW_... | Concatenates chunks backword if they are punctuation marks.
Args:
chunks: The list of word chunks.
Returns:
The processed word chunks. | 625941c9f7d966606f6aa097 |
def files(url, root_file, retries=3, verbose=1, chunk_size=1024): <NEW_LINE> <INDENT> for i in range(retries): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = requests.get(url, stream=True) <NEW_LINE> content_type = r.headers.get('Content-Length') <NEW_LINE> total_size = None if content_type is None else int(content_t... | Request url and download to root_file.
Args:
url: str, request url.
root_file: str, downloaded and saved file name.
retries: retry counts.
verbose: Verbosity mode, 0 (silent), 1 (verbose)
chunk_size: the number of bytes it should read into memory.
Return:
root_file: str, downloaded and saved fi... | 625941c944b2445a3393212a |
def decode(self, data): <NEW_LINE> <INDENT> uncrypted = [] <NEW_LINE> chunk = self.chunk <NEW_LINE> reversed_key = self.reversed_key <NEW_LINE> for i in range(0, len(data), chunk): <NEW_LINE> <INDENT> temp = list(np.dot(reversed_key, data[i:i + chunk])) <NEW_LINE> uncrypted.append(temp) <NEW_LINE> <DEDENT> uncrypted = ... | Decode function | 625941c9c4546d3d9de72ac7 |
def compile_values(options): <NEW_LINE> <INDENT> key_to_values = dict() <NEW_LINE> for option in options: <NEW_LINE> <INDENT> option_key = option['title'] <NEW_LINE> compiled_values = list() <NEW_LINE> if 'values' in option: <NEW_LINE> <INDENT> option_values = option['values'] <NEW_LINE> for option_value in option_valu... | Bake completions from the provided YAML options.
Considers stuff like hints and values. | 625941c9d53ae8145f87a305 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.