code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def importAll(): <NEW_LINE> <INDENT> recipesCsv = openRecipes() <NEW_LINE> allRecipes = [] <NEW_LINE> with open(recipesCsv) as c: <NEW_LINE> <INDENT> readRecipe = csv.reader(c) <NEW_LINE> recipeRow = next(readRecipe) <NEW_LINE> count = 0 <NEW_LINE> for row in readRecipe: <NEW_LINE> <INDENT> allRecipes.append(row) <NEW_... | Import all the recipes. | 625941e707f4c71912b118e0 |
def floor_(self): <NEW_LINE> <INDENT> return self.no_params_func("floor_") | Performs the inplace floor of the input tensor.
Parameters
----------
Returns
-------
FloatTensor
Caller with values inplace | 625941e7be8e80087fb21098 |
def __init__( self, domain_whitelist=None, allow_utf8_user=False, allow_ip_domain=False, *args, **kwargs ): <NEW_LINE> <INDENT> self.domain_whitelist = domain_whitelist or [] <NEW_LINE> self.allow_utf8_user = allow_utf8_user <NEW_LINE> self.allow_ip_domain = allow_ip_domain <NEW_LINE> super().__init__(*args, **kwargs) | Initialize the EmailField.
Args:
domain_whitelist (list) - list of otherwise invalid domain
names which you'd like to support.
allow_utf8_user (bool) - if True, the user part of the email
address can contain UTF8 characters.
... | 625941e756b00c62f0f14ab8 |
def test_option_excluded_nodes(self): <NEW_LINE> <INDENT> mop = McOptionParser() <NEW_LINE> mop.configure_mop() <NEW_LINE> (options, args) = mop.parse_args(['service', 'start', '-n', 'foo[8-15]', '-x', 'foo[8-12]']) <NEW_LINE> self.assertTrue('foo[13-15]' in options.only_nodes) <NEW_LINE> self.assertFalse('foo[8... | Test usage of the excluded_nodes option | 625941e723e79379d52ee9ba |
def _testCmds( self, _shellEnv, testCmds, whichEnv ): <NEW_LINE> <INDENT> for cmd, pattern in testCmds: <NEW_LINE> <INDENT> dprint( "\nExecuting '%s' with %s environment" % (cmd, whichEnv)) <NEW_LINE> p = javashell.shellexecute(cmd) <NEW_LINE> line = FileUtil.wrap(p.getInputStream()).readlines()[0] <NEW_LINE> assert re... | test commands (key) and compare output to expected output (value).
this actually executes all the commands twice, testing the return
code by calling system(), and testing some of the output by calling
execute() | 625941e757b8e32f524838f9 |
def __ne__( self, other ): <NEW_LINE> <INDENT> return not self.__eq__(other) | Compare two ConfDict objects. The dictionaries are considered to
be different if the information stored is different.
:param other: another configuration to compare.
:type other: ConfMgr
:returns: comparison decision.
:rtype: bool
.. seealso:: :meth:`ConfDict.__eq__` | 625941e7656771135c3ebcd0 |
def add_and_commit(obj): <NEW_LINE> <INDENT> db.session.add(obj) <NEW_LINE> db.session.commit() <NEW_LINE> return obj | Add and commit an obj to the db
Returns obj | 625941e70c0af96317bb8643 |
def __init__(self): <NEW_LINE> <INDENT> self.Data = None <NEW_LINE> self.RequestId = None | :param Data: 业务数据
:type Data: :class:`tencentcloud.ssa.v20180608.models.AlertListData`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | 625941e7d6c5a102081444aa |
def to_obj(self): <NEW_LINE> <INDENT> entity_obj = self._binding_class() <NEW_LINE> for field in self.__class__._get_vars(): <NEW_LINE> <INDENT> val = getattr(self, field.attr_name) <NEW_LINE> if field.multiple: <NEW_LINE> <INDENT> if val: <NEW_LINE> <INDENT> val = [x.to_obj() for x in val] <NEW_LINE> <DEDENT> else: <N... | Convert to a GenerateDS binding object.
Subclasses can override this function.
Returns:
An instance of this Entity's ``_binding_class`` with properties
set from this Entity. | 625941e7d7e4931a7ee9e37b |
def get_portfolio_pnl_tsd(self): <NEW_LINE> <INDENT> return self._tsd_portfolio | get_portfolio_pnl_tsd - Gets P&L return statistics of portfolio as class to be queried
Returns
-------
TimeSeriesDesc | 625941e7f7d966606f6aa465 |
def train_classifier_lbph(self): <NEW_LINE> <INDENT> self._ids, self._faces = self._fileManager.get_ids_faces() <NEW_LINE> self._lbphClassifier.train(self._faces, self._ids) <NEW_LINE> self._lbphClassifier.write('FaceRecognizer/Dependencies/classifierLbph.yml') | Treinar o arquivo classifierLbph.yml | 625941e7d8ef3951e324399a |
def test_all_tests_interference(self): <NEW_LINE> <INDENT> all_tests = (getattr(self, name) for name in dir(self) if name.startswith('test_') and name != 'test_all_tests_interference') <NEW_LINE> for i in range(20): <NEW_LINE> <INDENT> tests = list(all_tests) <NEW_LINE> shuffle(tests) <NEW_LINE> print('='*20 + ' Random... | Repeat all tests by randomly mixing them and running them in different order
to make sure that they do not interfere with each other | 625941e7925a0f43d254a2d7 |
def __setitem__(self, key, message): <NEW_LINE> <INDENT> self._lookup(key) <NEW_LINE> self._toc[key] = self._append_message(message) <NEW_LINE> self._pending = True | Replace the keyed message; raise KeyError if it doesn't exist. | 625941e7009cb60464c6380a |
def test_excluded_apps(self): <NEW_LINE> <INDENT> self.assertFileNotFound('skip/skip_file.txt') | Can not find file in an app in STATICFILES_EXCLUDED_APPS. | 625941e756ac1b37e6264623 |
def get_image_uri(image,quiet=False): <NEW_LINE> <INDENT> image_uri = None <NEW_LINE> image = image.replace(' ','') <NEW_LINE> match = re.findall('^[A-Za-z0-9-]+[:]//',image) <NEW_LINE> if len(match) == 0: <NEW_LINE> <INDENT> if not quiet: <NEW_LINE> <INDENT> bot.warning("Could not detect any uri in %s" %image) <NEW_LI... | get_image_uri will parse a uri sent from Singularity to determine if it's
singularity (shub://) or docker (docker://)
:param image: the complete image uri (example: docker://ubuntu:latest | 625941e73617ad0b5ed68353 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure ... | Run administrative tasks. | 625941e7236d856c2ad44c3c |
def get_test_probs(cmd_args, ngrams_test, corpus_files, model): <NEW_LINE> <INDENT> sumprobs = {} <NEW_LINE> for lang in corpus_files: <NEW_LINE> <INDENT> sumprobs[lang] = 0.0 <NEW_LINE> <DEDENT> for ngram in ngrams_test: <NEW_LINE> <INDENT> for lang in corpus_files: <NEW_LINE> <INDENT> sumprobs[lang] += ngrams_test[ng... | Get sum of probabilities for ngrams of test data. | 625941e70fa83653e4657414 |
def handle(name, cfg, cloud, log, _args): <NEW_LINE> <INDENT> if 'chef' not in cfg: <NEW_LINE> <INDENT> log.debug(("Skipping module named %s," " no 'chef' key in configuration"), name) <NEW_LINE> return <NEW_LINE> <DEDENT> validate_cloudconfig_schema(cfg, schema) <NEW_LINE> chef_cfg = cfg['chef'] <NEW_LINE> chef_dirs =... | Handler method activated by cloud-init. | 625941e7a934411ee3751af1 |
def validate_event_inputs(event: dict, required_inputs: list, valid_values_per_input: dict) -> None: <NEW_LINE> <INDENT> for required_input in required_inputs: <NEW_LINE> <INDENT> if required_input not in event: <NEW_LINE> <INDENT> raise ValueError("{0} must be part of the event input passed in".format(required_input))... | Validates that the input provided to the Lambda is correct
:param event the event dictionary passed in as Lambda input
:param required_inputs a list of required attributes the event should have
:param valid_values_per_input a dictionary of required attribute to valid values | 625941e73346ee7daa2b31cb |
def daily404detail(date, limit=None, return_format=None): <NEW_LINE> <INDENT> uri = 'daily404detail' <NEW_LINE> if date: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> uri = '/'.join([uri, date.strftime("%Y-%m-%d")]) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> uri = '/'.join([uri, date]) <NEW_LINE> <DE... | Returns detail information of submitted 404 Error Page Information.
:param date: string or datetime.date() (required)
:param limit: string or int, limit for number of returned items | 625941e721a7993f00bc8154 |
def standard_figure(app, slideAR=1.6, height=1.0): <NEW_LINE> <INDENT> if app == 'fullslide': <NEW_LINE> <INDENT> fontsize = 20 <NEW_LINE> figsize = [fullwidth, fullwidth/slideAR*height] <NEW_LINE> fig = mplot.pyplot.figure(figsize=figsize, dpi=dpi) <NEW_LINE> <DEDENT> mplot.rcParams.update({'font.size': fontsize}) <NE... | Generate a figure of standard size for publishing.
implemented values for app (application) are:
'fullslide'
height is the fractional height of the figure relative to the "standard"
height. For slides the standard is the full height of a slide.
returns the figure object and default font size | 625941e7cdde0d52a9e53492 |
def test_validation_suite(self): <NEW_LINE> <INDENT> mars88 = Corewar.Benchmarking.MARS_88(maxcycles=1000) <NEW_LINE> w1 = self.parser.parse_file('warriors/88/simplified/Validate88.red') <NEW_LINE> w2 = self.parser.parse_file('warriors/88/simplified/Wait.red') <NEW_LINE> result = mars88.run((w1, w2), 1, 4000) <NEW_LINE... | Run validation program (Corewar.Benchmarking.MARS_88). | 625941e74a966d76dd551470 |
def addTwoNumbers(self, l1, l2): <NEW_LINE> <INDENT> carry = 0 <NEW_LINE> dummy = curr= ListNode(0) <NEW_LINE> while l1 or l2 or carry: <NEW_LINE> <INDENT> if l1: <NEW_LINE> <INDENT> carry += l1.val <NEW_LINE> l1 = l1.next <NEW_LINE> <DEDENT> if l2: <NEW_LINE> <INDENT> carry += l2.val <NEW_LINE> l2 = l2.next <NEW_LINE>... | :type l1: ListNode
:type l2: ListNode
:rtype: ListNode | 625941e799cbb53fe6793041 |
def __init__( self, db: Database, edge_table_name: str, node_table_name: str, node_id_column: str, poi_table_name: str, poi_id_column: str, output_table_name: str | None = None, output_schema: str | None = None, walking_mph: float = 2.5, max_minutes: float = 45, epsg: int = 26918, num_pois: int = 3, poi_match_threshold... | Capture user input | 625941e7e5267d203edce0f3 |
def a_star(self, neighbor_state): <NEW_LINE> <INDENT> cost = neighbor_state.cost_so_far <NEW_LINE> heuristic = self.heuristics[neighbor_state.position[0]][neighbor_state.position[1]] <NEW_LINE> return cost+heuristic | Calculates the A* value of an unexplored state
f(x) = g(x) + h(x)
h(x) = the cost to get from the neighbor node to the goal
g(x) = the cost to get from the current node to the neighbor node
NOTE:
function 'a_star' works under the assumption that the state has already
calculated the cost so far to calcul... | 625941e7d268445f265b52cb |
def __setitem__(self, addr, value): <NEW_LINE> <INDENT> if '.' in addr: <NEW_LINE> <INDENT> i = addr.index('.') <NEW_LINE> key = addr[:i] <NEW_LINE> tail = addr[i+1:] <NEW_LINE> getattr(self, key)[tail] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(self, addr, value) | Takes a string containing a dotted address and writes the given value to
that address. Creates structure as necessary to place the value at the
given address, but raises an AttributeError if doing so would overwrite
existing data (for example assigning "a.b.c" to "foo" when "a.b" is 3). | 625941e7956e5f7376d712c8 |
def test_persist_no_conf_failure(self): <NEW_LINE> <INDENT> asn_cmd = {'pid': 1337, 'retcode': 0, 'stderr': "sysctl: permission denied", 'stdout': ''} <NEW_LINE> mock_asn_cmd = MagicMock(return_value=asn_cmd) <NEW_LINE> cmd = "sysctl -w net.ipv4.ip_forward=1" <NEW_LINE> mock_cmd = MagicMock(return_value=cmd) <NEW_LINE>... | Tests adding of config file failure | 625941e7099cdd3c635f10b5 |
def aplicar_trimestre(self, boton): <NEW_LINE> <INDENT> anno = mx.DateTime.localtime().year <NEW_LINE> if self.wids['rd1t'].get_active(): <NEW_LINE> <INDENT> fini = mx.DateTime.DateTimeFrom(day = 1, month = 1, year = anno) <NEW_LINE> ffin = mx.DateTime.DateTimeFrom(day = 31, month = 3, year = anno) <NEW_LINE> <DEDENT> ... | Pone las fechas del trimestre seleccionado en los "entries". | 625941e7b5575c28eb68e460 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RPiDjangoSite.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are yo... | Run administrative tasks. | 625941e7596a897236089f17 |
def fadeTo(self, opacity=100, speed=500): <NEW_LINE> <INDENT> if self.loaded and self._player: <NEW_LINE> <INDENT> callback = 'onAnimate' <NEW_LINE> if self.name: <NEW_LINE> <INDENT> self._player.callFlash('fp_fadeTo', [self.name, opacity, speed, callback]) | @param opacity: specifies the end opacity of the animation (0 - 100).
@param speed: Integer; specifies the duration of the animation, in milliseconds.
Makes the plugin hidden in an animated manner by adjusting its opacity
from the initial opacity to the given opacity. | 625941e763d6d428bbe4494d |
def pullback(self, xbar_list): <NEW_LINE> <INDENT> import time <NEW_LINE> if len(self.dependentFunctionList) == 0: <NEW_LINE> <INDENT> raise Exception('You forgot to specify which variables are dependent!\n' ' e.g. with cg.dependentFunctionList = [F1,F2]') <NEW_LINE> <DEDENT> for f in self.fu... | Apply the pullback of the cotangent element,
e.g. for::
y = y(x)
compute::
ybar dy(x) = xbar dx | 625941e77b180e01f3dc4c51 |
def commandworker(self, json_data): <NEW_LINE> <INDENT> webhook_obj = Webhook(json_data) <NEW_LINE> room_id = json_data["data"]["roomId"] <NEW_LINE> message = self.spark_api.messages.get(webhook_obj.data.id) <NEW_LINE> person = self.spark_api.people.get(message.personId) <NEW_LINE> try: <NEW_LINE> <INDENT> commandline ... | Called by the bottle app when a command comes in. Glues together the behavior of SparkBot.
:param json_data: The blob of json that Spark POSTs to the webhook parsed into a dictionary | 625941e7e64d504609d74c9c |
def GetEndIndex(self): <NEW_LINE> <INDENT> return _itkImageFunctionPython.itkImageFunctionIUL2DF_GetEndIndex(self) | GetEndIndex(self) -> itkIndex2 | 625941e74e696a04525c98aa |
def merge_sort(list1): <NEW_LINE> <INDENT> leng = len(list1) <NEW_LINE> if leng < 2: <NEW_LINE> <INDENT> return list1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> split1 = list1[:(leng/2)] <NEW_LINE> split2 = list1[(leng/2):] <NEW_LINE> sorted1 = merge_sort(split1) <NEW_LINE> sorted2 = merge_sort(split2) <NEW_LINE> <D... | input: list1 - an unsorted list
output: sorted - a new sorted list that contains all the elements from list1
in ascending order | 625941e7b5575c28eb68e461 |
def bid(self): <NEW_LINE> <INDENT> return self.bookBid | Exposes the sides of a book.
:return: An instance of class Side with a list of bid offers. | 625941e77d43ff24873a3100 |
def onehot(indexes, N=None, ignore_index=None): <NEW_LINE> <INDENT> return_variable = False <NEW_LINE> if isinstance(indexes, Variable): <NEW_LINE> <INDENT> return_variable = True <NEW_LINE> indexes = indexes.data <NEW_LINE> <DEDENT> if N is None: <NEW_LINE> <INDENT> N = indexes.max() + 1 <NEW_LINE> <DEDENT> sz = list(... | Creates a one-representation of indexes with N possible entries
if N is not specified, it will suit the maximum index appearing.
indexes is a long-tensor of indexes
ignore_index will be zero in onehot representation | 625941e799fddb7c1c9de7eb |
def dataset2(): <NEW_LINE> <INDENT> dist = numpy.zeros(shape=(5, 5), dtype=numpy.float32) <NEW_LINE> dist[1, 0] = 38 <NEW_LINE> dist[2, 0:2] = (33, 6) <NEW_LINE> dist[3, 0:3] = (21, 10, 15) <NEW_LINE> dist[4, 0:4] = (2, 35, 29, 26) <NEW_LINE> return dist | output from R
1 2 3 4
2 38
3 33 6
4 21 10 15
5 2 35 29 26
single: 2 6 10 21
complete: 2 6 15 38
average: 2.00000 6.00000 12.50000 30.33333 | 625941e715baa723493c43d5 |
def import_dataStage02PhysiologySimulatedData_add(self, filename): <NEW_LINE> <INDENT> data = base_importData(); <NEW_LINE> data.read_csv(filename); <NEW_LINE> data.format_data(); <NEW_LINE> self.add_dataStage02PhysiologySimulatedData(data.data); <NEW_LINE> data.clear_data(); | table adds | 625941e72c8b7c6e89b35c1a |
def run(self, fetches, feed_dict=None, options=None, run_metadata=None): <NEW_LINE> <INDENT> self._run_call_count += 1 <NEW_LINE> run_start_resp = self.on_run_start( OnRunStartRequest(fetches, feed_dict, options, run_metadata, self._run_call_count)) <NEW_LINE> _check_type(run_start_resp, OnRunStartResponse) <NEW_LINE> ... | Wrapper around Session.run() that inserts tensor watch options.
Args:
fetches: Same as the fetches arg to regular Session.run()
feed_dict: Same as the feed_dict arg to regular Session.run()
options: Same as the options arg to regular Session.run()
run_metadata: Same as the run_metadata to regular Session.run()... | 625941e7be383301e01b58da |
def reflectionsubgroup(W, J): <NEW_LINE> <INDENT> gens = set(range(W.rank)) <NEW_LINE> if gens.issuperset(J): <NEW_LINE> <INDENT> P = CoxeterGroup(W.cartanmat[np.ix_(J, J)]) <NEW_LINE> P.embeddings.update({W : tuple(J)}) <NEW_LINE> return P <NEW_LINE> <DEDENT> reflsJ = [W.reflections[i] for i in J] <NEW_LINE> rootsJ = ... | Constructs an instance of CoxeterGroup as a subgroup. | 625941e7bde94217f3683249 |
def test_005_update_flag_clear(self): <NEW_LINE> <INDENT> filename = self.create_pkg(self.tmpdir, self.pkg_name, '1.0') <NEW_LINE> self.send_pkg(filename) <NEW_LINE> open(self.update_flag_path, 'a').close() <NEW_LINE> logpath = os.path.join(self.tmpdir, 'dom0-update-output.txt') <NEW_LINE> with open(logpath, 'w') as f_... | Check if 'updates pending' flag is creared | 625941e78c0ade5d55d3ee1b |
def get_personality_type(self): <NEW_LINE> <INDENT> return self.personality_type | Input: none
Output: str
Purpose: This getter function returns this object's personality type variable. | 625941e726068e7796caf142 |
def assertNotHasSchema(self, schema, *, msg=None, conn=None): <NEW_LINE> <INDENT> if msg is None: <NEW_LINE> <INDENT> msg = 'Schema %s exists' % schema <NEW_LINE> <DEDENT> assert not self._has_schema(schema, conn=conn), msg | Assert that the database does not have a particular schema. | 625941e794891a1f4081bf08 |
@orca.column('zones', 'generalized_cost_weighted_access_to_employment_hbw_am_drive_alone') <NEW_LINE> def generalized_cost_weighted_access_to_employment_hbw_am_drive_alone(zones, travel_data): <NEW_LINE> <INDENT> return abstract_weighted_access(travel_data.single_vehicle_to_work_travel_cost, zones.number_of_jobs) | Total employment in zone j divided by generalized cost from zone i to j,
The travel time used is for the home-based-work am trips by auto with
drive-alone. | 625941e74f6381625f114e98 |
def save(self): <NEW_LINE> <INDENT> if not self.config: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tablename = self.tablename <NEW_LINE> theset = self.theset <NEW_LINE> if not self.__status("dbupdate"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> nodes_dict = dict() <NEW_LINE> for node_id, node in theset.items()... | Save this hierarchy in s3_hierarchy | 625941e7498bea3a759b9f0b |
def toggle_private_network(self, id): <NEW_LINE> <INDENT> path = self._get_path("%s/toggle_private_network" % str(id)) <NEW_LINE> return self.post(path) | 默认内网开关
id: 路由器id | 625941e78e71fb1e9831dc04 |
def setup(self, spl_path: str, file_name: str, script_dir: str, link: bool = False, import_lang: bool = True): <NEW_LINE> <INDENT> self.spl_path = spl_path <NEW_LINE> self.file_name = file_name <NEW_LINE> self.script_dir = script_dir <NEW_LINE> self.link = link <NEW_LINE> self.import_lang = import_lang | Sets up the parameters of this lexer.
The <file_name> will be recorded in tokens and ast nodes, which is used for properly displaying
the error message, if any error occurs. This parameter does not contribute to the actual interpreting.
The <script_dir> is used to find the importing files, which is important to run t... | 625941e7851cf427c661a968 |
def CoCreateInstanceFromFactory(factory_ptr, iid_interface=pythoncom.IID_IDispatch, pUnkOuter=None): <NEW_LINE> <INDENT> print(factory_ptr.value) <NEW_LINE> print(pythoncom.IID_IClassFactory) <NEW_LINE> ClassFactory = pythoncom.ObjectFromAddress(factory_ptr.value, pythoncom.IID_IClassFactory) <NEW_LINE> i = ClassFactor... | Given a factory_ptr whose interface is IClassFactory, create the instance of clsid_class with the specified interface | 625941e74d74a7450ccd4621 |
def removeall(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.collection.remove() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print('selectall error', e) <NEW_LINE> return None | removeall 删除全部数据的方法
:return: | 625941e7d164cc61757831ac |
def get_chains(symbol,info=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> symbol = symbol.upper().strip() <NEW_LINE> <DEDENT> except AttributeError as message: <NEW_LINE> <INDENT> print(message) <NEW_LINE> return None <NEW_LINE> <DEDENT> url = urls.chains(symbol) <NEW_LINE> data = helper.request_get(url) <NEW_LINE... | Returns the chain information of an option.
:param symbol: The ticker of the stock.
:type symbol: str
:param info: Will filter the results to get a specific value.
:type info: Optional[str]
:returns: Returns a dictionary of key/value pairs for the option. If info parameter is provided, a list of strings is returne... | 625941e773bcbd0ca4b2c4d2 |
def __add__(self, days): <NEW_LINE> <INDENT> if not isinstance(days,int): <NEW_LINE> <INDENT> raise NormalDateException('__add__ parameter must be integer') <NEW_LINE> <DEDENT> cloned = self.clone() <NEW_LINE> cloned.add(days) <NEW_LINE> return cloned | add integer to BusinessDate and return a new, calculated value | 625941e7004d5f362079a78d |
@pexdoc.pcontracts.contract( wave=Waveform, indep_min="None|number", indep_max="None|number" ) <NEW_LINE> def average(wave, indep_min=None, indep_max=None): <NEW_LINE> <INDENT> ret = copy.copy(wave) <NEW_LINE> _bound_waveform(ret, indep_min, indep_max) <NEW_LINE> area = _running_area(ret._indep_vector, ret._dep_vector)... | Return the running average of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param indep_max: Independent vector stop point of computation
:type indep_max: in... | 625941e726068e7796caf143 |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941e7f548e778e58cd9dc |
def wordBreak_(self, s, wordDict): <NEW_LINE> <INDENT> ok = [True] <NEW_LINE> for i in range(1, len(s)+1): <NEW_LINE> <INDENT> ok += [any(ok[j] and s[j:i] in wordDict for j in range(i))] <NEW_LINE> <DEDENT> return ok[-1] | :type s: str
:type wordDict: List[str]
:rtype: bool | 625941e7377c676e91272604 |
def end_headers(self): <NEW_LINE> <INDENT> pass | Called at the end of the game headers. | 625941e750485f2cf553d1f8 |
def onSaveDiagramAs(self): <NEW_LINE> <INDENT> widget = self.currentWidget() <NEW_LINE> widgetType = widget.getType() <NEW_LINE> if widgetType not in [MainWindowTabWidgetBase.GeneratedDiagram, MainWindowTabWidgetBase.ProfileViewer]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if widgetType == MainWindowTabWidgetBase... | Saves the current tab diagram to a file | 625941e716aa5153ce3628d5 |
def load_ratings(self, filename): <NEW_LINE> <INDENT> dataset= pd.read_csv(filename) <NEW_LINE> self.userID = dataset['userId'].tolist() <NEW_LINE> self.movieID = dataset['movieId'].tolist() <NEW_LINE> self.ratings = dataset['rating'].tolist() | Load csv file into userId, movieId, ratings. | 625941e7bf627c535bc1362c |
def run_setup_que(self): <NEW_LINE> <INDENT> self._ques.set_active_que("setup") <NEW_LINE> if not self._claim_per_task: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._exec_active_que() | run all tasks in setup queue | 625941e73539df3088e2e7a8 |
def is_adverb(self, token): <NEW_LINE> <INDENT> return self._is_in(token, self.adverb_tags) | Check if a token represents an adverb.
Required parameters:
token -- a tokenized word (a pair (string, string)). | 625941e7956e5f7376d712c9 |
@image_comparison(['constrained_layout5.png'], tol=0.002) <NEW_LINE> def test_constrained_layout5(): <NEW_LINE> <INDENT> plt.rcParams['pcolormesh.snap'] = False <NEW_LINE> fig, axs = plt.subplots(2, 2, constrained_layout=True) <NEW_LINE> for ax in axs.flat: <NEW_LINE> <INDENT> pcm = example_pcolor(ax, fontsize=24) <NEW... | Test constrained_layout for a single colorbar with subplots,
colorbar bottom | 625941e7bde94217f368324a |
def get_client(): <NEW_LINE> <INDENT> client = AipNlp(baidu_nlp_parameters.APP_ID, baidu_nlp_parameters.API_KEY, baidu_nlp_parameters.SECRET_KEY) <NEW_LINE> client.setConnectionTimeoutInMillis(20000) <NEW_LINE> client.setSocketTimeoutInMillis(60000) <NEW_LINE> return client | 获取百度nlp client
:return: 百度nlp client | 625941e7adb09d7d5db6cbea |
def __login(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.brower.implicitly_wait(30) <NEW_LINE> self.brower.get(login_url) <NEW_LINE> user_input = self.brower.find_element_by_id('username') <NEW_LINE> user_input.clear() <NEW_LINE> if self.username is None: <NEW_LINE> <INDENT> print('[Error]: %s must not be N... | 登陆
:return: 0 :success -1 failure | 625941e7d6c5a102081444ab |
def translate(content, tk, sl, tl): <NEW_LINE> <INDENT> if len(content) > 4891: <NEW_LINE> <INDENT> print("翻译文本超过限制!") <NEW_LINE> return <NEW_LINE> <DEDENT> content = urllib.parse.quote(content) <NEW_LINE> url = "http://translate.google.cn/translate_a/single?client=t" "&sl=%s&tl=%s&hl=zh-CN&dt=at&dt=bd&dt=ex&d... | sl代表源语言,tl代表目标语言。 | 625941e744b2445a339324f0 |
def call(self, inputs, state): <NEW_LINE> <INDENT> input_size = inputs.get_shape()[-1] <NEW_LINE> if input_size.value is None: <NEW_LINE> <INDENT> raise ValueError("Could not infer input size from inputs.get_shape()[-1]") <NEW_LINE> <DEDENT> v, w = array_ops.split( value=self.kernel, num_or_size_splits=[2 * self.units,... | Run one step of CFN.
Args:
inputs: input Tensor, must be 2-D, `[batch, input_size]`.
state: state Tensor, must be 2-D, `[batch, state_size]`.
Returns:
A tuple containing:
- Output: A `2-D` tensor with shape `[batch_size, state_size]`.
- New state: A `2-D` tensor with shape `[batch_size, state_size]`.
Rais... | 625941e72eb69b55b151cd12 |
def if_else(condition, a, b): <NEW_LINE> <INDENT> if condition: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> return b | It's helper for lambda functions. | 625941e78c3a87329515881d |
def readcif(filename, **kwds): <NEW_LINE> <INDENT> a, b, c, alf, bet, gam = [[]]*6 <NEW_LINE> with open(filename, 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> if "length_a" in line: <NEW_LINE> <INDENT> a = numgrab(line) <NEW_LINE> <DEDENT> elif "length_b" in line: <NEW_LINE> <INDENT> b = numgrab(li... | Read a cif and parse structural parameters
:Parameters:
filename : str
filename address
:Returns:
atomLabels : str list
atomic labels
coords : numpy array
atomic coordinates
crystVec : list of numericals
unit cell parameters in a cif file | 625941e70a50d4780f6672f3 |
def onGotItem(self, item): <NEW_LINE> <INDENT> pass | Processes one L{Element} item and returns a L{defer.Deferred}
Overridden in derived classes | 625941e7f548e778e58cd9dd |
def __getattr__(self, name): <NEW_LINE> <INDENT> def default_method(*args, **kwargs): <NEW_LINE> <INDENT> LOGGER.debug('Call of unimplemented method detected. ' 'Method is {0}{1}{2}'.format(name, args, kwargs)) <NEW_LINE> <DEDENT> return default_method | Default method for all unimplemented functions. | 625941e723849d37ff7b34e9 |
def __call__(self, var): <NEW_LINE> <INDENT> if self._intp == 'fortran': <NEW_LINE> <INDENT> var = _convert_dtype(var, 'float32') <NEW_LINE> <DEDENT> return self._intp_func(var) | Interpolate data from cartesian (x-y) to polar (radius-theta) coordinate.
Parameter
---------
var: 2-d array, shape = (ny, nx)
Its shape should equal to `lon` and `lat`.
Return
------
Interpolating result, shape = (nradius, ntheta) | 625941e7cb5e8a47e48b7f01 |
def test_string_named_value_declaration_generation(self): <NEW_LINE> <INDENT> font_weight = FontWeight("Pooky") <NEW_LINE> self.assertEqual(font_weight.to_str(), '\tbold = Pooky;\n') | Tests the generation of a font weight declaration with
string parameters | 625941e7293b9510aa2c36ef |
def setEndOfDirectory(self, success = True): <NEW_LINE> <INDENT> xbmcplugin.setPluginCategory(self.pluginHandle, "") <NEW_LINE> xbmcplugin.addSortMethod(self.pluginHandle, xbmcplugin.SORT_METHOD_UNSORTED) <NEW_LINE> xbmcplugin.addSortMethod(self.pluginHandle, xbmcplugin.SORT_METHOD_VIDEO_RATING) <NEW_LINE> xbmcplugin.a... | mark the listing as completed, this is mandatory | 625941e75510c4643540f836 |
def post(self, request, format=None): <NEW_LINE> <INDENT> filename = int(time.time()) <NEW_LINE> s3c = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) <NEW_LINE> handle_txt = StringIO(request.data.get('keywords', '')) <NEW_LINE> txt_file = s3c.put_o... | Save all keywrods to xls | 625941e771ff763f4b549af0 |
def process_snapshots(paths, snapshot, sample_freq=100): <NEW_LINE> <INDENT> substate = snapshot[0:2] <NEW_LINE> clusters = generate_cluster_dictionary(substate) <NEW_LINE> hbdat = data_dir + snapshot + "_hb.dat" <NEW_LINE> msdat = data_dir + snapshot + "_ms.dat" <NEW_LINE> head3lst = data_dir + snapshot + "_head3.lst"... | Parameters
----------
paths : list
A list of tuples, each of which contains start and end residue corresponding to
a given snapshot
snapshot : string
Name of the snapshot, used as a prefix to all major input files | 625941e755399d3f05588b14 |
def create_GeneratorDelegate(self, delegate, *args, **kwargs): <NEW_LINE> <INDENT> base_cls = delegate.__class__ <NEW_LINE> class GeneratorDelegate(base_cls): <NEW_LINE> <INDENT> def __init__(self, delegate, *args, **kwargs): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(*args, **kwargs) <NEW_LINE> self._del... | Constructs a new GeneratorDelegate object.
*args and **kwargs are additional arguments for the
GeneratorDelegate's __init__ method. | 625941e73539df3088e2e7a9 |
def _request_global(self, api_url, params=dict()): <NEW_LINE> <INDENT> args = {'api_key': self.api_key} <NEW_LINE> for key, value in params.items(): <NEW_LINE> <INDENT> if key not in args: <NEW_LINE> <INDENT> args[key] = value <NEW_LINE> <DEDENT> <DEDENT> line = Consts.URL['base_global'].format( region = self.region, u... | (RiotAPI, Str, Dict()) -> Str (JSON Format)
Returns a JSON result based on the api_url inpited
and the aprams. Note that the if the _requests is invalid
a value of None will be returned instead. | 625941e74527f215b584c8b0 |
def kern(self, r): <NEW_LINE> <INDENT> w = 0 <NEW_LINE> if self.kernel == 'rectangular': <NEW_LINE> <INDENT> w = (r <= 1) / 2 <NEW_LINE> <DEDENT> if self.kernel == 'quartic': <NEW_LINE> <INDENT> w = (r <= 1) * (1 - r ** 2) ** 2 <NEW_LINE> w *= 15 / 16 <NEW_LINE> <DEDENT> if self.kernel == 'triangular': <NEW_LINE> <INDE... | INPUT:
r - kernel parameter
OUTPUT:
w - kernel output | 625941e7d164cc61757831ad |
def generate_pod_template_spec(self, pod_spec): <NEW_LINE> <INDENT> if not isinstance(pod_spec, k8s_client.V1PodSpec): <NEW_LINE> <INDENT> raise TypeError('pod_spec must be a V1PodSpec, but got %s' % type(pod_spec)) <NEW_LINE> <DEDENT> if not self.annotations: <NEW_LINE> <INDENT> self.annotations = {'sidecar.istio.io/i... | Generate a V1PodTemplateSpec initiazlied with correct metadata
and with the provided pod_spec
:param pod_spec: pod spec | 625941e7baa26c4b54cb1579 |
def read_bitcoin_config(dbdir): <NEW_LINE> <INDENT> from ConfigParser import SafeConfigParser <NEW_LINE> class FakeSecHead(object): <NEW_LINE> <INDENT> def __init__(self, fp): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> self.sechead = '[all]\n' <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> if self.sechead... | Read the latinio.conf file from dbdir, returns dictionary of settings | 625941e771ff763f4b549af1 |
def apply_to_fig_text(fig: mpl.figure.Figure, fn: Callable[[str], str]): <NEW_LINE> <INDENT> for text in fig.findobj(match=plt.Text): <NEW_LINE> <INDENT> text.set_text(fn(text.get_text())) | Applies `fn` to each `Text` object in `fig`. Use to prettify labels. | 625941e785dfad0860c3b2b9 |
def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(CognitiveServicesVisionProcessor, self).__init__(**kwargs) <NEW_LINE> self.type = '#Microsoft.VideoAnalyzer.CognitiveServicesVisionProcessor' <NEW_LINE> self.endpoint = kwargs['endpoint'] <NEW_LINE> self.image = kwargs.get('image', None) <NEW_LINE> self.sampling... | :keyword name: Required. Node name. Must be unique within the topology.
:paramtype name: str
:keyword inputs: Required. An array of upstream node references within the topology to be used
as inputs for this node.
:paramtype inputs: list[~azure.media.videoanalyzer.edge.models.NodeInput]
:keyword endpoint: Required. End... | 625941e7de87d2750b8601f5 |
def __stop_processing(self): <NEW_LINE> <INDENT> self.__plot_db.stop_processing() | This method stops plot processing thread by calling
plot_db.stop_processing method. | 625941e7dd821e528d63b603 |
def FileHeader(self): <NEW_LINE> <INDENT> dt = self.date_time <NEW_LINE> dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] <NEW_LINE> dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) <NEW_LINE> if self.flag_bits & 0x08: <NEW_LINE> <INDENT> CRC = compress_size = file_size = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE... | Return the per-file header as a string. | 625941e7656771135c3ebcd1 |
def CreateTableSymbols(self, drop): <NEW_LINE> <INDENT> c = self.db.cursor() <NEW_LINE> if drop: <NEW_LINE> <INDENT> c.execute('drop table if exists symbols') <NEW_LINE> <DEDENT> c.execute('create table symbols (symbol text primary key, name text, industry text, mcap real)') <NEW_LINE> c.close() | Create the symbols table, dropping any existing if asked | 625941e7ff9c53063f47c64f |
def getOption(self, p, name): <NEW_LINE> <INDENT> name = self.munge(name) <NEW_LINE> trace = False and not g.unitTesting <NEW_LINE> assert p, g.callers() <NEW_LINE> def dump(kind, p, val): <NEW_LINE> <INDENT> if trace: <NEW_LINE> <INDENT> g.pr('getOption: %7s %30s %-15r %s' % (kind, name, val, p.h)) <NEW_LINE> <DEDENT>... | Return the value of the named option at node p. | 625941e77b180e01f3dc4c52 |
def build_team_two(self): <NEW_LINE> <INDENT> team_name = input("What is the team name for second team? ") <NEW_LINE> self.team_two = Team(team_name) <NEW_LINE> numOfTeamMembers = int( input("How many members would you like on Team Two?\n")) <NEW_LINE> for i in range(numOfTeamMembers): <NEW_LINE> <INDENT> hero = self.c... | Prompt the user to build team_two | 625941e796565a6dacc8fb27 |
def test_gender(self): <NEW_LINE> <INDENT> pass | Test case for gender
Infer the likely gender of a name. # noqa: E501 | 625941e7ad47b63b2c50a3dc |
def test_save_City(self): <NEW_LINE> <INDENT> if My_storage == 'db': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.city.save() <NEW_LINE> self.assertNotEqual(self.city.created_at, self.city.updated_at) | test if the save works | 625941e757b8e32f524838fb |
def do_mov_in_mem_cell(self, pcb, mem_cell, cpu_regs, mem): <NEW_LINE> <INDENT> pass | Abstract method | 625941e77047854f462a1862 |
def init_logger(self, filename=None, debug=False): <NEW_LINE> <INDENT> fmt = "%(asctime)s %(levelname)-8s %(message)s" <NEW_LINE> debug = True <NEW_LINE> kwargs = { 'level' : logging.INFO, } <NEW_LINE> if debug: <NEW_LINE> <INDENT> kwargs['level'] = logging.DEBUG <NEW_LINE> <DEDENT> logging.basicConfig(format=fmt, date... | Define a logger | 625941e7442bda511e8be870 |
def test_utm_from_point(): <NEW_LINE> <INDENT> pts = ((-117, 32), (-117, -14), (-73, 38), (-23, -36), (41, 53), (52, -36)) <NEW_LINE> zones = ((11, False), (11, True), (18, False), (27, True), (37, False), (39, True)) <NEW_LINE> for pt, zone in zip(pts, zones): <NEW_LINE> <INDENT> utm = pfc.Utm.from_point(*pt) <NEW_LIN... | Tests that `Utm.from_point` accuractely calculates UTM zone/hemisphere.
| 625941e76e29344779a62a6e |
def uniquePathsWithObstacles(self, obstacleGrid): <NEW_LINE> <INDENT> assert len(obstacleGrid) > 0 and len(obstacleGrid[0]) > 0 <NEW_LINE> nrows = len(obstacleGrid) <NEW_LINE> ncols = len(obstacleGrid[0]) <NEW_LINE> paths = [[0]*ncols for _ in range(nrows)] <NEW_LINE> if obstacleGrid[0][0] == 1: <NEW_LINE> <INDENT> ret... | :type obstacleGrid: List[List[int]]
:rtype: int | 625941e7167d2b6e31218ff3 |
def df_to_conll(df, out_fn): <NEW_LINE> <INDENT> header = list(df.columns) <NEW_LINE> sents = [df[df.run_id == run_id] for run_id in sorted(set(df.run_id.values))] <NEW_LINE> with open(out_fn, 'w') as fout: <NEW_LINE> <INDENT> fout.write('\t'.join(header) + '\n') <NEW_LINE> fout.write('\n'.join([sent.to_csv(header = Fa... | Write a conll representation of this df to file
with column header and newlines between sentences. | 625941e7fb3f5b602dac3af6 |
@conv2d_winograd_nhwc.register(["mali"]) <NEW_LINE> def conv2d_winograd_nhwc_mali( data, weight, strides, padding, dilation, out_dtype, pre_computed=False ): <NEW_LINE> <INDENT> tile_size = _pick_tile_size(data, weight, layout="NHWC") <NEW_LINE> return _conv2d_winograd_nhwc_impl( data, weight, strides, padding, dilatio... | Conv2D Winograd in NHWC layout.
This is a clean version to be used by the auto-scheduler for mali. | 625941e73617ad0b5ed68354 |
def __init__(self, weight=1): <NEW_LINE> <INDENT> self.weight = weight | initialize loss module | 625941e7d8ef3951e324399b |
def create_snapshot(self, snapshot): <NEW_LINE> <INDENT> cmd = ['zfs', 'snapshot', "%s/%s@%s" % (self.zpool, snapshot['volume_name'], snapshot['name'])] <NEW_LINE> try: <NEW_LINE> <INDENT> self._execute(*cmd, run_as_root=True) <NEW_LINE> <DEDENT> except processutils.ProcessExecutionError as err: <NEW_LINE> <INDENT> LOG... | Creates a snapshot. | 625941e7d7e4931a7ee9e37d |
def lstrip_first_line(text): <NEW_LINE> <INDENT> if not text: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> if endswith_whitespace(text): <NEW_LINE> <INDENT> text += " " <NEW_LINE> <DEDENT> lines = text.splitlines() <NEW_LINE> lines[0] = lines[0].lstrip() <NEW_LINE> return "\n".join(lines) | lstrip only the first line of text | 625941e7f7d966606f6aa467 |
def _reconEngine(mmTheta_, vvSig_, iK): <NEW_LINE> <INDENT> global mmTh <NEW_LINE> mmTh = mmTheta_ <NEW_LINE> global iR <NEW_LINE> global iC <NEW_LINE> iR, iC = mmTh.size <NEW_LINE> solvers.options['show_progress'] = False <NEW_LINE> vvQ = matrix(float(iK), (2*iC,1)) <NEW_LINE> blas.gemv(mmTh, vvSig_, vvQ, alpha = -2.0... | This is the engine of the reconstruction.
Basis pursuit problem:
minimize ||A*x - y||_2^2 + k * ||x||_1
where:
1. A - Theta matrix
A = B * C:
B - observation matirx
C - dictionary matrix
2. y - observed signal
3. x - vector with coefficients we are looking ... | 625941e7bf627c535bc1362d |
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> sensors = [] <NEW_LINE> if int(hub.config.get('temperature', '1')): <NEW_LINE> <INDENT> hub.update_climate() <NEW_LINE> sensors.extend([ VerisureThermometer(value.id) for value in hub.climate_status.values() if hasattr(value, 'tempe... | Sets up the Verisure platform. | 625941e74a966d76dd551471 |
def __init__(self, dataModel, params): <NEW_LINE> <INDENT> self.model = DataModel(dataModel) <NEW_LINE> self.quadraticError = 0 <NEW_LINE> self.minK = params['minK'] <NEW_LINE> self.algorithm = params['algorithm'] <NEW_LINE> self.dec_points = params['gridPrecision'] <NEW_LINE> if self.algorithm == 'K-Means': <NEW_LINE>... | Constructor
Assign parameters depending on the selected algorithm
:param dataModel: The DataModel to be processed.
:param params: Object containing necessary parameters for each method. | 625941e756ac1b37e6264625 |
def create_field(size): <NEW_LINE> <INDENT> field = [] <NEW_LINE> n = 0 <NEW_LINE> while n < size: <NEW_LINE> <INDENT> r = [] <NEW_LINE> field.append(r) <NEW_LINE> i = 0 <NEW_LINE> while i < size: <NEW_LINE> <INDENT> field[n].append(' ') <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> n += 1 <NEW_LINE> <DEDENT> return show_field... | Creates field with a given size | 625941e7046cf37aa974d1a1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.