code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_constructor_failure(self): <NEW_LINE> <INDENT> repl = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.client.disconnect() <NEW_LINE> repl = Replicator(self.client) <NEW_LINE> self.fail('Above statement should raise a CloudantException') <NEW_LINE> <DEDENT> except CloudantException as err: <NEW_LINE> <INDENT> sel... | Test that constructing a Replicator will not work
without a valid client. | 625941d16e29344779a627b0 |
def __init__(self, pool, strategy): <NEW_LINE> <INDENT> self._pool = pool <NEW_LINE> self._strategy = strategy <NEW_LINE> self._job_queue = set() <NEW_LINE> self._currently_running = {} <NEW_LINE> self._leaked_valuerefs = set() <NEW_LINE> self._master_worker = None <NEW_LINE> self._statusreport_interval = 2 <NEW_LINE> ... | :param strategy: :class:`SchedulingStrategy`. | 625941d1fbf16365ca6f6365 |
def setUp(self): <NEW_LINE> <INDENT> os.mkdir(self._TEST_DIRNAME) <NEW_LINE> os.mkdir(self._TEST_DROPBOX_DIRPATH) | Creates a test directory and a test Dropbox directory within that | 625941d115fb5d323cde0caf |
def input_func(file,epoches,batch_size): <NEW_LINE> <INDENT> def decode_train_data(row): <NEW_LINE> <INDENT> data = tf.decode_csv(row,record_defaults=_CSV_COLUMN_DEFAULTS) <NEW_LINE> feature_dict = dict(zip(_CSV_COLUMNS,data)) <NEW_LINE> label = feature_dict.pop('income_bracket') <NEW_LINE> labels = tf.equal(label,">50... | tf.data读取数据,并处理数据格式,返回dataset迭代器
:return: | 625941d1e64d504609d749de |
def exchangemedium(self, xfer, source, dest1, dest2, **kwargs): <NEW_LINE> <INDENT> opcode = self.device.opcodes.EXCHANGE_MEDIUM <NEW_LINE> cmd = ExchangeMedium(opcode, xfer, source, dest1, dest2, **kwargs) <NEW_LINE> self.execute(cmd) <NEW_LINE> return cmd | Returns a ExchangeMedium Instance
:param xfer: medium transport element to use
:param source: source element
:param dest1: destination 1 element
:param dest2: destination 2 element
:param kwargs: inv1=0 invert/rotate the medium before loading
inv2=0 invert/rotate the medium before loading
:return: an Ex... | 625941d1fb3f5b602dac3832 |
def test_only_max(self): <NEW_LINE> <INDENT> self.assertEqual(1, solution(11, 12, 12)) | Only max is divisible | 625941d163f4b57ef00012b5 |
def simple_decoder(_, field): <NEW_LINE> <INDENT> return simple_field_decoders.get(field.type, None) | convert according to predefined rules | 625941d15f7d997b87174c37 |
def test_increase_order_sizes_valley_closest_order(worker, do_initial_allocation, issue_asset): <NEW_LINE> <INDENT> worker = do_initial_allocation(worker, 'valley') <NEW_LINE> increase_factor = max(1 + worker.increment, worker.min_increase_factor) <NEW_LINE> to_issue = worker.buy_orders[0]['base']['amount'] * (increase... | Should test proper calculation of closest order: order should not be less that min_increase_factor. | 625941d163f4b57ef00012b6 |
def setUp(self): <NEW_LINE> <INDENT> self.tmp_dir = TemporaryDirectory(prefix="innoconv-test-") <NEW_LINE> self.output_dir = join(self.tmp_dir.name, "innoconv_output") | Prepare temp dirs. | 625941d1379a373c97cface4 |
def swipe(self, start_ratioWidth, start_ratioHigh, end_ratioWidth, end_ratioHigh, duration=" "): <NEW_LINE> <INDENT> if start_ratioWidth < 1: <NEW_LINE> <INDENT> self.shell_return("input swipe %s %s %s %s %s" % ( str(start_ratioWidth * self.getScreenResolution()[0]), str(start_ratioHigh * self.getScreenResolution()[1])... | 发送滑动事件,Android 4.4以上可选duration(ms)
usage: swipe(0.9, 0.5, 0.1, 0.5) 左滑 | 625941d185dfad0860c3affa |
def post(self, key, values, serialization): <NEW_LINE> <INDENT> assert isinstance(key, str) <NEW_LINE> assert isinstance(serialization,str) <NEW_LINE> assert serialization in ['pickle', 'json', 'pyarrow'] <NEW_LINE> self._serialize(key, values, serialization) | Posts key,value to redis where its serilaized by the serialization param
Parameters:
-----------
key=str()
values=python object
serialization=str(), of which is 'pickle', 'json', 'pyarrow'
Returns:
--------
python object | 625941d19b70327d1c4e0f74 |
def __init__(self, name, salary, percent_completed=100): <NEW_LINE> <INDENT> super().__init__(name, salary) <NEW_LINE> self.__percent_completed = percent_completed | :param percent_completed: if the sales person completed the plan more than 100%, his bonus is doubled,
if more than 200% - tripled. | 625941d1090684286d50ee85 |
def main(): <NEW_LINE> <INDENT> test_continuous() <NEW_LINE> test_discrete() | Run some tests of axes classes. | 625941d11f037a2d8b94639c |
def get_user(self, **kwargs): <NEW_LINE> <INDENT> if 'uid' in kwargs: <NEW_LINE> <INDENT> key, key_type = kwargs.pop('uid'), 'user ID' <NEW_LINE> payload = {'localId' : [_auth_utils.validate_uid(key, required=True)]} <NEW_LINE> <DEDENT> elif 'email' in kwargs: <NEW_LINE> <INDENT> key, key_type = kwargs.pop('email'), 'e... | Gets the user data corresponding to the provided key. | 625941d1a934411ee3751832 |
@openstackcli.group() <NEW_LINE> @click.pass_context <NEW_LINE> def users(ctx): <NEW_LINE> <INDENT> resource = 'users' <NEW_LINE> ctx.obj = ControllerClient(resource) | Manages users. | 625941d123849d37ff7b322e |
def expand_list(label, items): <NEW_LINE> <INDENT> exp_items = [] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> if isinstance(item, str) and item.startswith("$"): <NEW_LINE> <INDENT> key = item[1:] <NEW_LINE> if key == 'toggle_panel': <NEW_LINE> <INDENT> exp_items += self.prepare_panel_menus() <NEW_LINE> <DEDENT> e... | :param label: menu title
:param items: menu items
:return: | 625941d14f6381625f114bda |
def model(self): <NEW_LINE> <INDENT> cell = rnn.BasicLSTMCell(self.hidden_dim) <NEW_LINE> outputs, states = tf.nn.dynamic_rnn(cell, self.x, dtype=tf.float32) <NEW_LINE> num_examples = tf.shape(self.x)[0] <NEW_LINE> tf_expand = tf.expand_dims(self.W_out, 0) <NEW_LINE> tf_tile = tf.tile(tf_expand, [num_examples, 1, 1]) <... | :param x: inputs of size [T, batch_size, input_size]
:param W: matrix of fully-connected output layer weights
:param b: vector of fully-connected output layer biases | 625941d18e71fb1e9831d947 |
def Nu_vertical_plate_Churchill(Pr, Gr): <NEW_LINE> <INDENT> Ra = Pr*Gr <NEW_LINE> term = (0.825 + (0.387*Ra**(1/6.)*(1.0 + (Pr/0.492)**(-0.5625))**(-8.0/27.0))) <NEW_LINE> return term*term | Calculates Nusselt number for natural convection around a vertical
plate according to the Churchill-Chu [1]_ correlation, also presented in
[2]_. Plate must be isothermal; an alternate expression exists for constant
heat flux.
.. math::
Nu_{L}=\left[0.825+\frac{0.387Ra_{L}^{1/6}}
{[1+(0.492/Pr)^{9/16}]^{8/27}}... | 625941d1b57a9660fec33a23 |
def split_line(line, sep = ','): <NEW_LINE> <INDENT> elements = line.split(sep) <NEW_LINE> for i in range(len(elements)): <NEW_LINE> <INDENT> elements[i] = elements[i].strip() <NEW_LINE> <DEDENT> return elements | (string, string) -> list:
Break a string into a list at some separator character(s). Resulting elements
are stripped of leading and trailing whitespace and then returned in a list
of strings. | 625941d15fcc89381b1e185e |
def get_tile_coords(self): <NEW_LINE> <INDENT> return [] | Returns all data tiles in this layer
:returns: All tiles with data
:rtype: sequence
This method should return a sequence listing the coordinates for
all tiles with data in this layer.
It is used when computing layer merges. Tile coordinates must
be returned as ``(tx, ty)`` pairs.
The base implementation returns an... | 625941d138b623060ff0af8c |
def testTruncatedMeanRaisesError(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> math_utils.TruncatedMean([], 0) | TruncatedMean should raise an error when passed an empty list. | 625941d13eb6a72ae02ec67e |
def cohen_kappa(*args, **kwargs): <NEW_LINE> <INDENT> return ConfusionMatrix2.from_ccw(*args, **kwargs).kappa() | Return Cohen's Kappa for a 2x2 contingency table
| 625941d16aa9bd52df036f43 |
def _on_(self): <NEW_LINE> <INDENT> raise NotImplementedError('TODO: must be implemented by assigning the correct logic on the relay_pin') | This is the method that does the actual turning on of the controller
by switching the relay pin to logic high.
*** Note: If needed, subclasses should override this method not self.turn_on() | 625941d163d6d428bbe4468e |
def pretest_log_setup(params): <NEW_LINE> <INDENT> libvirtd_conf_dict = eval(params.get("libvirtd_conf_dict", '{}')) <NEW_LINE> libvirtd_conf = libvirt.customize_libvirt_config(libvirtd_conf_dict) <NEW_LINE> return libvirtd_conf | Setup log before test
:param params: test params
:return: log conf object | 625941d130c21e258bdfa63c |
def __repr__(self): <NEW_LINE> <INDENT> return 'IapResourceRules<resource={}, rules={}>'.format( self.resource, self.rules) | String representation of this node.
Returns:
str: debug string | 625941d176e4537e8c351812 |
def getHcost(self, goalNode, heuristic='manhattan', preferredPath=None): <NEW_LINE> <INDENT> from shapely.geometry import LineString, Point <NEW_LINE> plusCost = 0 <NEW_LINE> if preferredPath is not None: <NEW_LINE> <INDENT> pline = LineString(preferredPath.coordsIdx.T) <NEW_LINE> point = Point(self.pos) <NEW_LINE> plu... | Method to obtain the heuristic component, :math:`h(n)`, that
estimates the cost (or length) of the shortest path from the current
node :math:`n` to the goal node.
It must be selected either ``manhattan`` or ``euclidean`` as the model
to estimate the length of the optimum path.
- **manhattan** is the sum of the ca... | 625941d1f548e778e58cd71d |
def addtag_withtag(self, newtag, tagOrId): <NEW_LINE> <INDENT> self.addtag(newtag, 'withtag', tagOrId) | Add tag NEWTAG to all items with TAGORID. | 625941d1ec188e330fd5a93c |
def add_device(self, device): <NEW_LINE> <INDENT> uid = self._get_id() <NEW_LINE> if uid is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> device.uid = uid <NEW_LINE> self._device_dict[uid] = device <NEW_LINE> return self._save() | Adds a device to the roster. Return 0 if success, None otherwise.
| 625941d145492302aab5e463 |
def marked_text(self,marker,input_text="",sep='\n'): <NEW_LINE> <INDENT> if not hasattr(self,'textdict'): <NEW_LINE> <INDENT> self.textdict = {} <NEW_LINE> <DEDENT> if marker in list(self.textdict.keys()): <NEW_LINE> <INDENT> idx = self.textdict[marker] <NEW_LINE> self.figurelist[idx]['print_string'] = ( self.figurelis... | Creates a named `marker` where we can place text. If `marker`
has been used, goes back and places text there. | 625941d12ae34c7f2600d2d0 |
def attributes(self): <NEW_LINE> <INDENT> self.queue.load() <NEW_LINE> return self.queue.attributes | 'QueueArn': 'ARN_STRING',
'ApproximateNumberOfMessages': '<int>',
'ApproximateNumberOfMessagesNotVisible': '<int>',
'ApproximateNumberOfMessagesDelayed': '<int>',
'CreatedTimestamp': 'epoch seconds',
'LastModifiedTimestamp': 'epoch seconds',
'VisibilityTimeout': '<int>',
'Maximum... | 625941d1de87d2750b85ff32 |
def to_dict(self): <NEW_LINE> <INDENT> return self._data | Convert credential to a dict, that can be used to reconstruct the
credential later. | 625941d16aa9bd52df036f44 |
@pytest.mark.usefixtures('authz_full_access') <NEW_LINE> def test_upload_batch_request(test_client): <NEW_LINE> <INDENT> request_payload = batch_request_payload(operation='upload') <NEW_LINE> response = test_client.post('/myorg/myrepo/objects/batch', json=request_payload) <NEW_LINE> assert 200 == response.status_code <... | Test basic batch API with a basic successful upload request
| 625941d13eb6a72ae02ec67f |
def set_row_heights(self): <NEW_LINE> <INDENT> if not self.height: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> y, pos, heights = 0, [], [] <NEW_LINE> for date, facts in self.days: <NEW_LINE> <INDENT> height = 0 <NEW_LINE> for fact in facts: <NEW_LINE> <INDENT> fact_height = self.fact_row.height(fact) <NEW_LINE> fact... | the row height is defined by following factors:
* how many facts are there in the day
* does the fact have description / tags
This func creates a list of row start positions to be able to
quickly determine what to display | 625941d10a50d4780f667032 |
def readProcessesDataFromCSVfile(fileName:str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(fileName, "r") as f: <NEW_LINE> <INDENT> processesList = [{key: int(value) if value.isdigit() else float(value) for key, value in row.items()} for row in csv.DictReader(f, skipinitialspace=True)] <NEW_LINE> <DEDENT> p... | Reads information about processes from CSV file. Returns a list where every single process is a dictionary. | 625941d1099cdd3c635f0dfa |
def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> def decision(prob): <NEW_LINE> <INDENT> return random.random() <= prob <NEW_LINE> <DEDENT> if not self.learning or decision(self.epsilon): <NEW_LINE> <INDENT> return random.choi... | The choose_action function is called when the agent is asked to choose
which action to take, based on the 'state' the smartcab is in. | 625941d1711fe17d82542509 |
def update_sysfs_path(self): <NEW_LINE> <INDENT> log_method_call(self, self.name, status=self.status) <NEW_LINE> if not self.exists: <NEW_LINE> <INDENT> raise errors.DeviceError("device has not been created", self.name) <NEW_LINE> <DEDENT> self.sysfs_path = '' | Update this device's sysfs path. | 625941d17b180e01f3dc499b |
def import_companies(data: CompaniesData): <NEW_LINE> <INDENT> companies_to_insert = [] <NEW_LINE> for piece in data: <NEW_LINE> <INDENT> company = Company(**piece) <NEW_LINE> companies_to_insert.append(company) <NEW_LINE> <DEDENT> Company.objects.bulk_create(companies_to_insert, ignore_conflicts=True) | Imports companies data into the database | 625941d163b5f9789fde7285 |
def is_input_vaild(born, today): <NEW_LINE> <INDENT> flag = True <NEW_LINE> if int(str(born[0]+str(born[1])+str(born[2]))) > int(str(today[0]+str(today[1])+str(today[2]))): <NEW_LINE> <INDENT> flag = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flag = True <NEW_LINE> <DEDENT> return flag | born: int[]
today: int[]
Just check if input date is earlier than today | 625941d1498bea3a759b9c4e |
def run(self): <NEW_LINE> <INDENT> self.dlg.show() <NEW_LINE> result = self.dlg.exec_() <NEW_LINE> if result: <NEW_LINE> <INDENT> return | Run method that performs all the real work | 625941d1cb5e8a47e48b7c48 |
def FindToolByIndex(self, pos): <NEW_LINE> <INDENT> if pos < 0 or pos >= len(self._items): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._items[pos] | Finds a tool for the given tool position in the :class:`AuiToolBar`.
:param integer `pos`: the tool position in the toolbar.
:returns: a pointer to a :class:`AuiToolBarItem` if a tool is found, or ``None`` otherwise. | 625941d1ac7a0e7691ed426a |
@decorators.check_perm <NEW_LINE> def manage_agent(request, cc_biz_id, action, ds_id, ip): <NEW_LINE> <INDENT> ds = Datasource.objects.get(cc_biz_id=cc_biz_id, id=ds_id) <NEW_LINE> res = { 'result': True, 'message': '', 'data': None, 'action': action, } <NEW_LINE> try: <NEW_LINE> <INDENT> if ds.status not in (DS_STATUS... | 新增/删除/重新下发agent
:param request:
:param cc_biz_id:
:param action: append、remove、refresh
:param ds_id:
:param ip:
:return: | 625941d1b7558d58953c50b2 |
@click.group() <NEW_LINE> def key(): <NEW_LINE> <INDENT> pass | Interact with Solo keys, see subcommands. | 625941d1d486a94d0b98e2e5 |
def getcpuload(self): <NEW_LINE> <INDENT> start = self.getcputime() <NEW_LINE> sleep(self.sleeptime) <NEW_LINE> stop = self.getcputime() <NEW_LINE> usage = [] <NEW_LINE> for cpu in start: <NEW_LINE> <INDENT> Total = stop[cpu]['total'] <NEW_LINE> PrevTotal = start[cpu]['total'] <NEW_LINE> Idle = stop[cpu]['idle'] <NEW_L... | CPU_Percentage=((Total-PrevTotal)-(Idle-PrevIdle))/(Total-PrevTotal) | 625941d1097d151d1a222ff8 |
def main(): <NEW_LINE> <INDENT> cli.perform_quiz_as_standalone_cli_app(calculator) | Start Brain Calculator game in CLI. | 625941d1d58c6744b4257dfe |
def window_cget(self, index, option): <NEW_LINE> <INDENT> if option[:1] != '-': <NEW_LINE> <INDENT> option = '-' + option <NEW_LINE> <DEDENT> if option[-1:] == '_': <NEW_LINE> <INDENT> option = option[:-1] <NEW_LINE> <DEDENT> return self.tk.call(self._w, 'window', 'cget', index, option) | Return the value of OPTION of an embedded window at INDEX. | 625941d121bff66bcd684af1 |
def test_grid_array_with_projection(self): <NEW_LINE> <INDENT> dataset = DAPHandler( "http://localhost:8001/?SimpleGrid.SimpleGrid[0]", self.app1).dataset <NEW_LINE> self.assertEqual(dataset.keys(), ["SimpleGrid"]) <NEW_LINE> self.assertNotIsInstance(dataset.SimpleGrid, GridType) <NEW_LINE> self.assertIsInstance(datase... | Test that a grid array can be properly pre sliced. | 625941d1a219f33f34628b08 |
def _strip_empty(sl): <NEW_LINE> <INDENT> return [z for z in sl if z] if sl else [] | strip empty strings from list I{sl}
@rtype: [str,...] | 625941d13346ee7daa2b2f0c |
def stash_image(self, image_id, image_data): <NEW_LINE> <INDENT> raise NotImplementedError('stash_image must be implemented') | Store image data in the backend manually
:param image_id: image identifier
:param image_data: string representing image data fixture
:return URI referencing newly-created backend object | 625941d1adb09d7d5db6c92e |
def __init__(self, dateTime='', comment='', advice='', contactDetail='', problemInfo='', Appointments=None, ErpPersons=None, TroubleTickets=None, status=None, *args, **kw_args): <NEW_LINE> <INDENT> self.dateTime = dateTime <NEW_LINE> self.comment = comment <NEW_LINE> self.advice = advice <NEW_LINE> self.contactDetail =... | Initialises a new 'CallBack' instance.
@param dateTime: (if callback already occured) Date and time when this call back occurred.
@param comment: Comments by customer during this call back.
@param advice: Advice already given to the customer during this call back.
@param contactDetail: Additional contact details th... | 625941d17d847024c06be45c |
def _create_python_proxy(self, scala_obj): <NEW_LINE> <INDENT> name_parts = scala_obj.getClass().getName().split('.') <NEW_LINE> try: <NEW_LINE> <INDENT> relevant_path = ".".join(name_parts[name_parts.index('sparktk')+1:]) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> relevant_path = "" <NEW_LINE> for... | Create a python object for the scala_obj
Convention is such that the python proxy object is available off the TkContext with the SAME
path that the object has in Scala, starting with sparktk.
Example:
org.trustedanalytics.sparktk.models.clustering.kmeans.KMeansModel
means a call to
tc.models.clustering.kmeans.KMea... | 625941d1956e5f7376d7100c |
def get_num(intent_request,key): <NEW_LINE> <INDENT> phone_num = response.get_slots(intent_request)['phoneNum'] <NEW_LINE> source = intent_request['invocationSource'] <NEW_LINE> if source == 'DialogCodeHook': <NEW_LINE> <INDENT> slots = response.get_slots(intent_request) <NEW_LINE> validation_result = validate_idnum(ph... | Performs dialog management and fulfillment for getting phone number.
Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action
in slot validation and re-prompting. | 625941d1cad5886f8bd27179 |
def is_sip_uploaded(sip, record=None): <NEW_LINE> <INDENT> if not sip.is_sealed(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if record is None: <NEW_LINE> <INDENT> record = get_record(sip.metadata.get('recid'), reset_cache=True) <NEW_LINE> <DEDENT> sip_version_id = sip.metadata.get('modification_date') <NEW_... | Check if a submission information package for a record has been uploaded. | 625941d1ec188e330fd5a93d |
def read_at24c32_byte(self, address): <NEW_LINE> <INDENT> self.set_current_at24c32_address(address) <NEW_LINE> return self._bus.read_byte(self._at24c32_addr) | ??? | 625941d167a9b606de4a8059 |
def valid_direction(self, direction): <NEW_LINE> <INDENT> if direction: <NEW_LINE> <INDENT> direction = direction.lower() <NEW_LINE> if direction in self.dirs.keys(): <NEW_LINE> <INDENT> return direction <NEW_LINE> <DEDENT> elif len(direction) == 1 and direction in self.dirs_short_to_long.keys(): <NEW_LINE> <INDENT> re... | This will return None if the direction is not valid.
If a single character is passed "n", then "north" is returned.
:param direction:
:return: | 625941d123e79379d52ee702 |
def candidate_skills(self, source_object: Dict) -> CandidateSkillYielder: <NEW_LINE> <INDENT> document = self.transform_func(source_object) <NEW_LINE> for cleaned_phrase, context, phrase_start in self.noun_phrases_matching_endings(document): <NEW_LINE> <INDENT> orig_context = self.detokenizer.detokenize([t[0] for t in ... | Generate candidate skills from the source object
Looks for all noun phrases with one of the configured endings.
Args:
source_object (dict) A single source object to extract skills from.
Yields: all candidate skills (algorithms.skill_extractors.base.CandidateSkill)
found in the job posting | 625941d1fff4ab517eb2f5dc |
def generate_additional_input(self): <NEW_LINE> <INDENT> self.set_description(self.model.description, 'body') <NEW_LINE> self.icon.set_text(( 'pending_icon', self.icon.get_text()[0] )) <NEW_LINE> for i in self.additional_input: <NEW_LINE> <INDENT> self.app.log.debug(i) <NEW_LINE> self.step_pile.contents.append((Padding... | Generates additional input fields, useful for doing it after
a previous step is run | 625941d13cc13d1c6d3c7519 |
def doStep(self, x, y, trace=False): <NEW_LINE> <INDENT> self._runinfo[1] += 1 <NEW_LINE> if trace: <NEW_LINE> <INDENT> import pdb;pdb.set_trace() <NEW_LINE> <DEDENT> if self._getValue(x, y) > 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> _all = list(self.gatherNum(x, y)) <NEW_LINE> if len(_all) != 1: <NEW_LINE> <I... | 单步录入 | 625941d1d7e4931a7ee9e0be |
def reverse_words(x): <NEW_LINE> <INDENT> sent = x <NEW_LINE> wds = [] <NEW_LINE> while sent: <NEW_LINE> <INDENT> word = '' <NEW_LINE> for i, val in enumerate(sent): <NEW_LINE> <INDENT> if val != ' ': <NEW_LINE> <INDENT> word+=val <NEW_LINE> if len(sent) == len(word): <NEW_LINE> <INDENT> sent='' <NEW_LINE> wds.append(w... | Given a sentence, return a sentence with the words reversed. | 625941d14e696a04525c95eb |
@app.route('/update_user_process', methods=['POST']) <NEW_LINE> def update_user_process(): <NEW_LINE> <INDENT> page = 'update_user_process' <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> user_id = request.form.get('user_id') <NEW_LINE> fname = request.form.get('fname') <NEW_LINE> lname = request.form.get('... | Update Existing User. | 625941d115baa723493c4116 |
def clientConnectionLost(self, connector, reason): <NEW_LINE> <INDENT> self.log.error("Connection lost. Reason: %s", str(reason)) <NEW_LINE> if self.config.reconnectOnConnectionLoss and self.connectionRetry: <NEW_LINE> <INDENT> self.log.info("Reconnecting after %d seconds ...", self.config.reconnectOnConnectionLossDela... | Connection lost
| 625941d14a966d76dd5511af |
def binary_cross_entropy_loss( y: NDArray[int], y_hat: NDArray[np.float64] ) -> NDArray[np.float64]: <NEW_LINE> <INDENT> return np.where(y == 1, -np.log(y_hat), -np.log(1 - y_hat)) | Binary CrossEntropy Loss is defined as:
loss = -[y * log(yhat) + (1 - y) * log(1 - yhat)]
When y = 1:
loss = -log(yhat)
When y = 0:
loss = -log(1 - yhat) | 625941d145492302aab5e464 |
def rgb_to_hues(rgb): <NEW_LINE> <INDENT> hsv = filter_rgb_to_hsv(rgb) <NEW_LINE> h = filter_hsv_to_h(hsv) <NEW_LINE> return h | Convert RGB NumPy array to 1-dimensional array of hue values (HSV H values in degrees).
Args:
rgb: RGB image as a NumPy array
Returns:
1-dimensional array of hue values in degrees | 625941d1d58c6744b4257dff |
def test_build_filepaths_from_filepaths(self): <NEW_LINE> <INDENT> in_fps = ['in1.txt','somewhere/in2.txt','in3.txt'] <NEW_LINE> actual = build_filepaths_from_filepaths(in_fps) <NEW_LINE> expected = ['in1.txt','in2.txt','in3.txt'] <NEW_LINE> self.assertEqual(actual,expected) <NEW_LINE> in_fps = ['in1.txt','somewhere/in... | build_filepaths_from_filepaths functions as expected
| 625941d1d99f1b3c44c6772d |
def myPow(x, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> negative = False if n > 0 else True <NEW_LINE> c = abs(n)-1 <NEW_LINE> total = x*x <NEW_LINE> while(c > 0): <NEW_LINE> <INDENT> if(c%2 == 0): <NEW_LINE> <INDENT> total *= total <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ... | :type x: float
:type n: int
:rtype: float | 625941d1de87d2750b85ff33 |
def __init__(self, element, ns_info): <NEW_LINE> <INDENT> super().__init__(ns_info) <NEW_LINE> self.element = element | Create an object of type PodLabelsElement
:param element: an element of type LabelExpr
:param ns_info: namespace set of type set[K8sNamespace] | 625941d14d74a7450ccd4363 |
def xml_pattern_to_str(et_pattern): <NEW_LINE> <INDENT> pattern_item_list = [] <NEW_LINE> for et_pattern_item in et_pattern: <NEW_LINE> <INDENT> pattern_item_str = '^{}'.format(et_pattern_item.attrib.get('lemma', '*')) <NEW_LINE> tags = et_pattern_item.attrib['tags'] <NEW_LINE> if tags != '': <NEW_LINE> <INDENT> patter... | Convert xml pattern item into pattern string. | 625941d17cff6e4e81117b25 |
def positionsPossibles(position_depart): <NEW_LINE> <INDENT> poss = [] <NEW_LINE> tmp = [] <NEW_LINE> poss.append(addMam(position_depart, [2,1])) <NEW_LINE> poss.append(addMam(position_depart, [1,2])) <NEW_LINE> poss.append(addMam(position_depart, [-1,2])) <NEW_LINE> poss.append(addMam(position_depart, [-2,1])) <NEW_LI... | Renvoie toutes les positions d'arrivée possibles | 625941d1925a0f43d254a018 |
def init_weight(shape, name='W', func=None, rng=None): <NEW_LINE> <INDENT> if rng is None: <NEW_LINE> <INDENT> rng = np.random <NEW_LINE> <DEDENT> value = np.asarray( rng.uniform( low=-np.sqrt(6. / (shape[0] + shape[1])), high=np.sqrt(6. / (shape[0] + shape[1])), size=shape), dtype=theano.config.floatX) <NEW_LINE> if f... | Initialize a theano weights variable
Attributes:
shape: (M, N) - shape of the matrix
name: Name to pass to theano.shared var constructor
func: Custom function to apply to the values
rng: numpy random state generator | 625941d1baa26c4b54cb12be |
def init_model(rnd_mean, rnd_std, input_cnt, output_cnt): <NEW_LINE> <INDENT> weight_arr = np.random.normal(loc=rnd_mean, scale=rnd_std, size=[input_cnt, output_cnt]) <NEW_LINE> bias_arr = np.zeros(shape=[output_cnt]) <NEW_LINE> return weight_arr, bias_arr | initiate model parameters
initiate weight, bias with hyperparameters
Parameters
------------
rnd_mean: float
rnd_std: float
input_cnt: int
output_cnt: int
Returns
--------
weigh_arr: np.ndarray
bias_arr: np.adarray | 625941d1e5267d203edcde3c |
def binario(n): <NEW_LINE> <INDENT> return bin(n)[2:] | Pasa el número dado a binario
:rtype : str
:param n: Un número
:return: El número en binario | 625941d1d10714528d5ffe84 |
def productsRegister(): <NEW_LINE> <INDENT> print("Digite as informações do seu produto") <NEW_LINE> continuar='1' <NEW_LINE> while continuar=='1': <NEW_LINE> <INDENT> name=input("Nome do produto: ") <NEW_LINE> price=input("Preço do produto: ") <NEW_LINE> description=input("Descrição do produto: ") <NEW_LINE> qu... | Esta função pede os dados da padaria para realizar o registro | 625941d130dc7b7665901b06 |
def _exc_info_to_string(self, err, test): <NEW_LINE> <INDENT> exctype, value, tb = err <NEW_LINE> if isinstance(value, test.failureException): <NEW_LINE> <INDENT> with self.__hide_traceback(): <NEW_LINE> <INDENT> return super()._exc_info_to_string(err, test) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return... | Convert the exception to a string.
We use unittest's conversion, but if the propagating exception
is a test failure, then suppress the traceback. If the
propagating exception is an error, or if tests are running in
verbose mode, we keep the traceback in the output. | 625941d191f36d47f21ac693 |
def list_attr(self, recursive=False): <NEW_LINE> <INDENT> if recursive: <NEW_LINE> <INDENT> raise DeprecationWarning("Symbol.list_attr with recursive=True has been deprecated. " "Please use attr_dict instead.") <NEW_LINE> <DEDENT> size = mx_uint() <NEW_LINE> pairs = ctypes.POINTER(ctypes.c_char_p)() <NEW_LINE> f_handle... | Gets all attributes from the symbol.
Example
-------
>>> data = mx.sym.Variable('data', attr={'mood': 'angry'})
>>> data.list_attr()
{'mood': 'angry'}
Returns
-------
ret : Dict of str to str
A dictionary mapping attribute keys to values. | 625941d1462c4b4f79d1d871 |
def cell(self, cell): <NEW_LINE> <INDENT> (c, r) = self._get_cell_indices(cell) <NEW_LINE> return self._table[r][c].string | Return the value of a given cell. | 625941d1cc0a2c11143dd031 |
def game_inventory(): <NEW_LINE> <INDENT> choice = False <NEW_LINE> while 'INVENTORY': <NEW_LINE> <INDENT> choice, p = formating.inventory(choice,p) <NEW_LINE> if choice == '1': <NEW_LINE> <INDENT> while 'use': <NEW_LINE> <INDENT> choice, p = formating.inventory_use(choice,p) <NEW_LINE> if choice in '123456789' and len... | Logic for Inventory | 625941d1f8510a7c17cf989c |
def quick_ion_col_function(coeff_ion, temp_min, passed_min_mass = False, zmax = 20., zmin = 0., zstep = 0.1, **cosmo): <NEW_LINE> <INDENT> z = numpy.arange(zmin, zmax, zstep) <NEW_LINE> w = ionization_from_collapse(z, coeff_ion, temp_min, passed_min_mass, **cosmo) <NEW_LINE> return scipy.interpolate.interp1d(z, w) | Return a function giving ionization_from_collapse as a function
of redshift (based on interpolation).
Calling the resulting function is much faster than evaluating
ionization_from_collapse. | 625941d13c8af77a43ae3941 |
@inlineCallbacks <NEW_LINE> def http_verify (ctx, uid, token) : <NEW_LINE> <INDENT> username, success_url = yield db.handle_verify(user_id, token) <NEW_LINE> success_url = utils.build_url(success_url, uid = user_id, username = username, ) <NEW_LINE> ctx.redirectTo(success_url) <NEW_LINE> returnValue( ("Accou... | Attempt to verify the given user with the given token. If it succeeds, the verification url should be invalidated,
and the account marked as verified.
Shows a message to the user, and possibly redirects them to the success_url defined for the verify action | 625941d1711fe17d8254250a |
def cleanup(self): <NEW_LINE> <INDENT> logger.info("Cleanup config for ID {}".format(self.app_name)) <NEW_LINE> if not self._config_file_exists(): <NEW_LINE> <INDENT> logger.info("Terraform plan not found, skipping cleanup") <NEW_LINE> self.status = "Skipped" <NEW_LINE> return <NEW_LINE> <DEDENT> self._remove_cloud_ini... | Remove the generated files under "files/output_configs/" | 625941d124f1403a92600d05 |
def __init__(self, key=None, val=None, asset_path=None, font_size=None, text_color=None, alignment=None, wrapping_shrink=None, wrapping_breakline=None, wrapping_minimum=None, wrapping_truncate=False, wrapping_truncate_string='…', right_to_left=False, vertical=False, is_hidden=False): <NEW_LINE> <INDENT> self._key = Non... | Text - a model defined in Swagger | 625941d14f88993c3716c206 |
def bandmath(images, expression, output_filename, out_type = ""): <NEW_LINE> <INDENT> command = ('%s ' '-il %s ' '-exp "%s" ' '-out "%s"' % ("otbcli_BandMath", " ".join(images), expression, output_filename)) <NEW_LINE> if out_type: <NEW_LINE> <INDENT> command += " " + out_type <NEW_LINE> <DEDENT> logger.info("command :... | This function applies otbcli_BandMath to image with the given expression
Keyword arguments:
image -- raster layer to process
expression -- expression to apply
output_filename -- output raster image
type -- type of the output image | 625941d1eab8aa0e5d26dcf8 |
def main(): <NEW_LINE> <INDENT> updater = Updater(telegram_key) <NEW_LINE> dp = updater.dispatcher <NEW_LINE> state_manager = GameStateManager('im-dreaming.md') <NEW_LINE> dp.add_handler(ConversationHandler( entry_points=[CommandHandler('start', state_manager.prompt_name)], states=state_manager, fallbacks=[], allow_ree... | Start the bot | 625941d14527f215b584c5f6 |
def add(self, req: InstallRequirement) -> None: <NEW_LINE> <INDENT> assert req.link <NEW_LINE> entry_path = self._entry_path(req.link) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(entry_path) as fp: <NEW_LINE> <INDENT> contents = fp.read() <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass... | Add an InstallRequirement to build tracking.
| 625941d18a349b6b435e8314 |
def _hash(self, string): <NEW_LINE> <INDENT> return sum([(ord(char) * self.x ** i) for i, char in enumerate(string)]) % self.p % self.m | Polynomial hash function
Used to generate more "random" hash values to preserve low collision probability
Calculated as the sum of the ASCII values of the characters times some prime number
exponentiated to the position of the character | 625941d13539df3088e2e4eb |
def test_utils_validate_url(self): <NEW_LINE> <INDENT> assert validate_url("http://test.com/nuget") <NEW_LINE> assert validate_url("https://test.com/nuget") <NEW_LINE> assert validate_url("http://test.com/nuget/") <NEW_LINE> assert validate_url("https://test.com/nuget") <NEW_LINE> assert validate_url("http://test.com")... | Test utils.validate_url | 625941d18e05c05ec3eea516 |
def __repr__(self): <NEW_LINE> <INDENT> return repr("Channel %d (%f)" % (self.get_channel(), self.get_freq())) | Overridden method. | 625941d1bf627c535bc1336f |
def read_csv(self, text_filepath = None, delim = ',', has_headers = True): <NEW_LINE> <INDENT> self.text_filepath = text_filepath <NEW_LINE> with open(self.text_filepath, 'r+') as f: <NEW_LINE> <INDENT> self.row_data = [] <NEW_LINE> if has_headers: <NEW_LINE> <INDENT> self.headers = next(f).replace('\n','').split(delim... | simple default reader of a delimited file. Does not read fixed-width | 625941d1be8e80087fb20de2 |
def get_direction(self, direction_id): <NEW_LINE> <INDENT> path = API_VER + 'directions/{}' <NEW_LINE> path = path.format(direction_id) <NEW_LINE> return self._api_call(path) | Get All routes that travel in the specified direction.
Parameters:
direction_id (int)
Identifier of direction of travel | 625941d1283ffb24f3c55aa0 |
@subscriber(TenderInitializeEvent, procurementMethodType="closeFrameworkAgreementSelectionUA") <NEW_LINE> def tender_init_handler(event): <NEW_LINE> <INDENT> tender = event.tender <NEW_LINE> default_status = type(tender).fields['status'].default <NEW_LINE> if tender.status != default_status: <NEW_LINE> <INDENT> raise E... | initialization handler for closeFrameworkAgreementSelectionUA tenders | 625941d16fece00bbac2d8df |
def __call__(self, val): <NEW_LINE> <INDENT> if val.type.strip_typedefs().code != gdb.TYPE_CODE_STRUCT: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> typename = val.type.name or val.type.tag or str(val.type) <NEW_LINE> match = re.match("^std::(__.*?)::", typename) <NEW_LINE> if match is not None and match.group(1... | Return the pretty printer for a val, if the type is supported. | 625941d15e10d32532c5f0c7 |
def add_missing_multiply(token_list): <NEW_LINE> <INDENT> for i in range(len(token_list)): <NEW_LINE> <INDENT> if type(token_list[i]) == list: <NEW_LINE> <INDENT> token_list[i] = add_missing_multiply(token_list[i]) <NEW_LINE> <DEDENT> <DEDENT> res = [] <NEW_LINE> for i in range(len(token_list) - 1): <NEW_LINE> <INDENT>... | pre-processing step, if there is any variable adjacent to a number, add a '*' | 625941d10383005118ecf782 |
@pytest.mark.django_db <NEW_LINE> def test_job_relaunch_permission_denied_response_other_user(get, post, inventory, project, alice, bob, survey_spec_factory): <NEW_LINE> <INDENT> jt = JobTemplate.objects.create( name='testjt', inventory=inventory, project=project, ask_credential_on_launch=True, ask_variables_on_launch=... | Asserts custom permission denied message corresponding to
awx/main/tests/functional/test_rbac_job.py::TestJobRelaunchAccess::test_other_user_prompts | 625941d1d486a94d0b98e2e6 |
def __init__(self, columns=_default_columns, headings=True, buffered=True, separator=" ", field_name_prefix="", unquoted=True, aligned=True, report_file=sys.stdout): <NEW_LINE> <INDENT> self.columns = columns <NEW_LINE> self.headings = headings <NEW_LINE> self.buffered = buffered <NEW_LINE> self.separator = separator <... | Initialise BoomReportOpts object.
Initialise a ``BoomReportOpts`` object to control output
of a ``BoomReport``.
:param columns: the number of columns to use for output.
:param headings: a boolean indicating whether to output
column headings for this report.
:param buffered: a boolean indicating wheth... | 625941d14428ac0f6e5ba993 |
def initialize(self, model, manager, methods, preprocessor, postprocessor, allow_patch_many, allow_method_override, validation_exceptions, exclude_queries, exclude_hybrids, include_columns, exclude_columns, results_per_page, max_results_per_page): <NEW_LINE> <INDENT> if allow_method_override and 'X-HTTP-Method-Override... | Init of the handler, derives arguments from api create_api_blueprint
:param model: The sqlalchemy model
:param manager: The tornado_restless Api Manager
:param methods: Allowed methods for this model
:param preprocessor: A dictionary of preprocessor functions
:param postprocessor: A dictionary of postprocessor functio... | 625941d130bbd722463cbf67 |
def _update_unknown_msg_array(self): <NEW_LINE> <INDENT> t = self.msg_array <NEW_LINE> self.unknown_msg_array = list(filter(lambda x: x.infotype_id == len(InfoType.known_infotype) - 1, t)) | 更新未识别消息 | 625941d1c432627299f04de7 |
def ws_44(self, ws): <NEW_LINE> <INDENT> secondary_counts = OrderedDict() <NEW_LINE> for gender_id, gender in self.male_female: <NEW_LINE> <INDENT> counts = Counter() <NEW_LINE> for media_type, model in tm_journalist_models.items(): <NEW_LINE> <INDENT> sheet_name = model.sheet_name() <NEW_LINE> region = sheet_name + '_... | Cols: Sex of reporter, Equality rights raised
Rows: Region | 625941d1fb3f5b602dac3834 |
def next_out(self): <NEW_LINE> <INDENT> assert False | Unsupported | 625941d15f7d997b87174c39 |
def update_instance_cdrom_active(context, instance_uuid, cdrom_active): <NEW_LINE> <INDENT> return IMPL.update_instance_cdrom_active( context, instance_uuid, cdrom_active) | Update the CDROM active info. | 625941d1a05bb46b383ec9c1 |
def move(self, move): <NEW_LINE> <INDENT> if not self.valid_move(move): <NEW_LINE> <INDENT> raise ValueError("Invalid move {0}".format(move)) <NEW_LINE> <DEDENT> self.board[move[0]] = 0 <NEW_LINE> self.board[move[1]] = 0 <NEW_LINE> self.board[move[2]] = 1 | Executes the given move on the board. A valid move must be a list with 3 2D coordinates in the form:
[(<coordinates of the jumping peg>, <coordinates of the jumped over peg>, <coordinates of the free space to jump to>].
If the move is invalid or not possible on the board this method will raise a ValueError.
:pa... | 625941d1ab23a570cc250323 |
def test_azone_cpu_usage(metrics_collection, appliance, provider): <NEW_LINE> <INDENT> generic_test_azone_rollup(appliance, provider, 'cpu_usage_rate_average') | Polarion:
assignee: nachandr
caseimportance: high
casecomponent: CandU
initialEstimate: 1/12h | 625941d1851cf427c661a6ae |
def absent(self, name, rdtype=None): <NEW_LINE> <INDENT> if isinstance(name, str): <NEW_LINE> <INDENT> name = dns.name.from_text(name, None) <NEW_LINE> <DEDENT> if rdtype is None: <NEW_LINE> <INDENT> self.find_rrset(self.answer, name, dns.rdataclass.NONE, dns.rdatatype.ANY, dns.rdatatype.NONE, None, True, True) <NEW_LI... | Require that an owner name (and optionally an rdata type) does
not exist as a prerequisite to the execution of the update. | 625941d1656771135c3eba10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.