code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def prob_win(a, b): <NEW_LINE> <INDENT> magnitude_score_differential = 400 <NEW_LINE> return 1 / (1 + (10 ** ((b - a) / magnitude_score_differential)))
Calculates the chance player A will beat player B, given their respective ELOs. A differential in ELOs of 400 corresponds to a 10-times differential in expected win probabilities.
625941cf283ffb24f3c55a4a
def getpads(self,items): <NEW_LINE> <INDENT> items = items[0] <NEW_LINE> p = [] <NEW_LINE> for i in items: <NEW_LINE> <INDENT> p.extend(list(i.Pads())) <NEW_LINE> <DEDENT> return p
Elements [MODULES] Get pads of each module in MODULES.
625941cf30dc7b7665901aaf
def test_get_card(self): <NEW_LINE> <INDENT> self.assertEqual(self.card.get_card(), (5, '♥'))
get_card() returns correct tuple
625941cf63f4b57ef0001262
def run(self): <NEW_LINE> <INDENT> self.started = False <NEW_LINE> self.console("Database started") <NEW_LINE> self.conn = sqlite3.connect(self.file) <NEW_LINE> self.c = self.conn.cursor() <NEW_LINE> self.started = True <NEW_LINE> while True: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> while self.hasqueued('control'...
Database main thread
625941cfbe7bc26dc91cd748
def populate(self, iterable): <NEW_LINE> <INDENT> self.deck += [card for card in iterable]
Put a whole bunch of cards into the deck.
625941cfbde94217f3682f3a
def _kill_process(self, box_config): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger.info(f'kill: {box_config.process_name} {{') <NEW_LINE> self.logger.info(f'target process pid={box_config.pid}') <NEW_LINE> if box_config.pid and psutil.pid_exists(box_config.pid): <NEW_LINE> <INDENT> p = psutil.Process(box_con...
method is called to kill a running process
625941cf236d856c2ad44924
def polar_kmeans(df): <NEW_LINE> <INDENT> xs_idxs = df.iloc[1].map(lambda x: str(x) == 'x') <NEW_LINE> xs = df[xs_idxs.index[xs_idxs]][2:].values.tolist() <NEW_LINE> xs = [float(x) for x_list in xs for x in x_list] <NEW_LINE> ys_idxs = df.iloc[1].map(lambda x: str(x) == 'y') <NEW_LINE> ys = df[...
K-Means clustering of whisker traces on polar coordinate system. Attempt to resolve fundamental K-Means assumption violations.
625941cfbf627c535bc13318
def slurp_distinct( self, table, cols=[]): <NEW_LINE> <INDENT> self._get_conn() <NEW_LINE> rows = None <NEW_LINE> columns = '' <NEW_LINE> for col in cols: <NEW_LINE> <INDENT> columns += col + ',' <NEW_LINE> columns = chop (columns) <NEW_LINE> <DEDENT> if columns == '': columns = '*' <NEW_LINE> query = 'SELECT distinct ...
Slurp some table columns into list of dicts, without dups
625941cf0a50d4780f666fdc
@csrf_exempt <NEW_LINE> def snippet_detail(request, pk): <NEW_LINE> <INDENT> snippet='' <NEW_LINE> try: <NEW_LINE> <INDENT> if re.search('snippets1',request.path)!=None: <NEW_LINE> <INDENT> snippet = Snippet.objects.get(pk=pk) <NEW_LINE> <DEDENT> <DEDENT> except Snippet.DoesNotExist: <NEW_LINE> <INDENT> return HttpResp...
Retrieve, update or delete a code snippet.
625941cfe8904600ed9f2076
def main(): <NEW_LINE> <INDENT> description="Program to clone git repo using the twobit.oebuild.Repo object." <NEW_LINE> parser = ArgumentParser(prog=__file__, description=description) <NEW_LINE> parser.add_argument("-n", "--name", default="repo_clone_test", help="name of Repo object") <NEW_LINE> parser.add_argument("-...
Test case to exercise the fetch method from the Repo object.
625941cf090684286d50ee2f
def __init__(self, batch_size=None, dtype=np.float32, name=None, task='classification', est_configs=None, n_classes=None, keep_in_mem=False, data_save_dir=None, model_save_dir=None, metrics=None, keep_test_result=False, seed=None, distribute=False, verbose_dis=False, dis_level=1, num_workers=None): <NEW_LINE> <INDENT> ...
The final classification layer. The estimator(s) of this layer commonly is/are estimator(s) with low bias. :param batch_size: :param dtype: :param name: :param est_configs: :param n_classes: :param keep_in_mem: :param data_save_dir: :param model_save_dir: :param metrics: :param keep_test_result: :param seed: :param di...
625941cf73bcbd0ca4b2c1bf
def OnDownLeft(self, *args): <NEW_LINE> <INDENT> self.car.MoveBackwardLeft( self.SpeedValue )
Procesa el evento de retroceder izquierda - DownLeft.
625941cf26068e7796caee29
def _construct_mapping( loader: BaseConstructor, node: MappingNode, deep: bool = False, ) -> Dict[Any, Any]: <NEW_LINE> <INDENT> if not isinstance(node, MappingNode): <NEW_LINE> <INDENT> raise ConstructorError( None, None, f"expected a mapping node, but found {node.id}", node.start_mark, ) <NEW_LINE> <DEDENT> if isinst...
A helper function for handling :meth:`~yaml.BaseConstructor.construct_mapping` methods.
625941cfeab8aa0e5d26dca1
def HTTPGet(self, **kwargs): <NEW_LINE> <INDENT> global global_HmcHeaders <NEW_LINE> url = global_HmcHeaders.url <NEW_LINE> if any(kwargs): <NEW_LINE> <INDENT> if not "url" in kwargs: <NEW_LINE> <INDENT> l_kwargs = list(kwargs.keys()) <NEW_LINE> url = global_HmcHeaders.url+"/"+kwargs[l_kwargs[0]] <NEW_LINE> <DEDENT> el...
This function performs the HTTP get request
625941cff548e778e58cd6c7
def testElectionSearch(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
Test ElectionSearch
625941cfd164cc6175782e97
def calculate_compensated_uvb(self): <NEW_LINE> <INDENT> uvb = self._read_2bytes_as_ushort_lsbfirst(self.VEML6075_UVB_DATA) <NEW_LINE> uvcomp1 = self._read_2bytes_as_ushort_lsbfirst(self.VEML6075_UVCOMP1_DATA) <NEW_LINE> uvcomp2 = self._read_2bytes_as_ushort_lsbfirst(self.VEML6075_UVCOMP2_DATA) <NEW_LINE> uVBcalc = uvb...
Calculates Compensated UVB.
625941cf82261d6c526ab5e9
def test_set_value_proposals(self): <NEW_LINE> <INDENT> self._propose('sawtooth.config.vote.proposals', EMPTY_CANDIDATES) <NEW_LINE> self._expect_get('sawtooth.config.authorization_type', 'None') <NEW_LINE> self._expect_get('sawtooth.config.vote.authorized_keys', '') <NEW_LINE> self._expect_invalid_transaction()
Tests setting the value of sawtooth.config.vote.proposals, which is only an internally set structure.
625941cfd4950a0f3b08c498
def read_response(self, delegate): <NEW_LINE> <INDENT> return self._read_message(delegate)
Read a single RPC response. Typical client-mode usage is to write a request using `write_headers`, `write`, and `finish`, and then call ``read_response``. :arg delegate: a `.RPCMessageDelegate` Returns a `.Future` that resolves to None after the full response has been read.
625941cf57b8e32f524835e4
def setLoop(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "b", x) <NEW_LINE> self._loop = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> for i, obj in enumerate(self._base_players): <NEW_LINE> <INDENT> if wrap(x,i): obj.setLoop(1) <NEW_LINE> else: obj.setLoop(0)
Replace the `loop` attribute. :Args: x: bool {True, False} new `loop` attribute.
625941cf287bf620b61d3bad
def get_localized_names(self): <NEW_LINE> <INDENT> day_names_items = babel.dates.get_day_names(locale=self.locale).items() <NEW_LINE> month_names_items = babel.dates.get_month_names(locale=self.locale).items() <NEW_LINE> return { "days": [day_name for _, day_name in sorted(day_names_items)], "months": [month_name for _...
Gets months and days names in the locale given to the constructor. Returns ------- dict{str: list[str]} A dict with the keys "days" and "months" containing lists of respectively 7 and 12 strings.
625941cf3539df3088e2e494
def main(): <NEW_LINE> <INDENT> currentpath = os.path.dirname(__file__) <NEW_LINE> outfile = "search_qcow_trial.json" <NEW_LINE> is_log = True <NEW_LINE> files, q_dirs, q_files, qfi_files = parse_dirs(currentpath, is_log=is_log) <NEW_LINE> try: <NEW_LINE> <INDENT> if q_files == 0: <NEW_LINE> <INDENT> raise MyError("The...
main function insert qcow files info to json outfile
625941cf627d3e7fe0d68f99
@contextmanager <NEW_LINE> def session_scope(session): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yield session <NEW_LINE> session.commit() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> session.rollback() <NEW_LINE> raise
Provide a transactional scope around a series of operations.
625941cf91f36d47f21ac63d
def get_depart_time(self): <NEW_LINE> <INDENT> flight_time = self.exp_dist(**self.kwargs) <NEW_LINE> return flight_time
Returns a time (in hours) for length of time from infection to boarding flight for some infected individual. This is selected according to instances chosen exposure-to-boarding distribution
625941cf091ae356686670a7
def notesToInterval(n1, n2=None): <NEW_LINE> <INDENT> if n2 is None: <NEW_LINE> <INDENT> if hasattr(n1, 'pitch'): <NEW_LINE> <INDENT> from music21 import note <NEW_LINE> n2 = note.Note() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from music21 import pitch <NEW_LINE> n2 = pitch.Pitch() <NEW_LINE> <DEDENT> <DEDENT> gI...
Given two :class:`~music21.note.Note` objects, returns an :class:`~music21.interval.Interval` object. The same functionality is available by calling the Interval class with two Notes as arguments. Works equally well with :class:`~music21.pitch.Pitch` objects. N.B.: MOVE TO PRIVATE USE. Use: inverval.Interval(noteSt...
625941cfb545ff76a8913f5f
def getCmdargs(): <NEW_LINE> <INDENT> p = argparse.ArgumentParser() <NEW_LINE> p.add_argument("-i", "--infile", help=("Input Raster file. Neighbours will " + "be written back to this file. This file should have a Raster" + "Attribute Table")) <NEW_LINE> p.add_argument("-t", "--tilesize", default=DFLT_TILESIZE, help="Si...
Get the command line arguments.
625941cf7cff6e4e81117acf
def loss(self, X, y=None, reg=0.0): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> N, D = X.shape <NEW_LINE> scores = None <NEW_LINE> h1=X.dot(W1)+b1 <NEW_LINE> h2=np.maximum(0,h1) <NEW_LINE> scores=h2.dot(W2)+b2 <NEW_LINE> if y is N...
Compute the loss and gradients for a two layer fully connected neural network. Inputs: - X: Input data of shape (N, D). Each X[i] is a training sample. - y: Vector of training labels. y[i] is the label for X[i], and each y[i] is an integer in the range 0 <= y[i] < C. This parameter is optional; if it is not passed...
625941cfdc8b845886cb567f
def snapshots(self, droplet): <NEW_LINE> <INDENT> return self.getHttp('droplets/{:s}/snapshots'.format(droplet))
Retrieves the snapshots that have been created for a Droplet
625941cfb830903b967e9a54
def _data_and_metadata(self, always_both=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> b64_data = b2a_base64(self.data).decode('ascii') <NEW_LINE> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> raise FileNotFoundError( "No such file or directory: '%s'" % (self.data)) from e <NEW_LINE> <DEDENT> md = {} <NEW_...
shortcut for returning metadata with shape information, if defined
625941cfa934411ee37517dd
def __init__(self, coordinator): <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> Camera.__init__(self) <NEW_LINE> self.radar_object = coordinator.ec_data <NEW_LINE> self._attr_name = f"{coordinator.config_entry.title} Radar" <NEW_LINE> self._attr_unique_id = f"{coordinator.config_entry.unique_id}-radar" <N...
Initialize the camera.
625941cfad47b63b2c50a0c9
def stitch_four(size, x, z, out_path, in_path): <NEW_LINE> <INDENT> nw_path = in_path + '/%i,%i.png' % (x, z) <NEW_LINE> sw_path = in_path + '/%i,%i.png' % (x, z+1) <NEW_LINE> ne_path = in_path + '/%i,%i.png' % (x+1, z) <NEW_LINE> se_path = in_path + '/%i,%i.png' % (x+1, z+1) <NEW_LINE> out = Image.new('RGBA', (2*size,...
x,z are tile coords of the nw small tile size is the width of a small tile
625941cf236d856c2ad44925
def set_authorization_key(self, authorization_key): <NEW_LINE> <INDENT> self.__authorization_key = authorization_key
Set authorization key :param authorization_key: The authorization_key to be set. :type authorization_key: str
625941cf377c676e912722f2
def getNextServer(self): <NEW_LINE> <INDENT> self.currentServer = self.currentServer % len(self.servers) <NEW_LINE> host, port = self.servers[self.currentServer] <NEW_LINE> self.currentServer += 1 <NEW_LINE> if port is None: <NEW_LINE> <INDENT> port = self.defaultPort <NEW_LINE> <DEDENT> return (host, port)
Return the next server, as a (host, port) tuple, to use for this network.
625941cff7d966606f6aa14e
def update_displayed_information(self): <NEW_LINE> <INDENT> for key,val in self.summaries.items(): <NEW_LINE> <INDENT> val.source.update() <NEW_LINE> <DEDENT> for g in self.visible_graphs.values(): <NEW_LINE> <INDENT> g.update_displayed_graph_data() <NEW_LINE> <DEDENT> for s in self.available_summaries.values(): <NEW_L...
Update all the graphs that are being displayed
625941cf30dc7b7665901ab0
def path_get(self, project_file=None): <NEW_LINE> <INDENT> root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', ) ) <NEW_LINE> if project_file: <NEW_LINE> <INDENT> return os.path.join(root, project_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return root
Get the absolute path to a file. Used for testing the API. :param project_file: File whose path to return. Default: None. :returns: path to the specified file, or path to project root.
625941cfac7a0e7691ed4215
def _reservoir_step_conceptor(self, previous_state, input_n): <NEW_LINE> <INDENT> previous_state = tf.reshape(previous_state, [1, self._reservoir_size]) <NEW_LINE> input_n = tf.reshape(input_n, [1, self._input_size]) <NEW_LINE> bias = tf.reshape(self.bias, [1, self._reservoir_size]) <NEW_LINE> state = tf.matmul(previou...
Reservoir step :param previous_state: previous state in the reservoir :type previous_state: tensor :param input_n: time-series step to calculate the actual state :type input_n: tensor :return: actual state :rtype: tensor
625941cfdd821e528d63b2f2
def to_json(self, target=None): <NEW_LINE> <INDENT> return json_dump(self.to_dict(), target)
Serialize the object as JSON. Args: target (str or file-like): A file or filepath to serialize the object to. If `None`, return the JSON as a string. Returns: None or str
625941cfd486a94d0b98e28f
def send_warning_email(warning_stats, email_recipients=cfg.warning_email_recipients): <NEW_LINE> <INDENT> if not type(email_recipients) is list: <NEW_LINE> <INDENT> raise Exception("Email recipients must be in a list") <NEW_LINE> <DEDENT> email = EmailMessage() <NEW_LINE> email_text = '\n'.join(warning_stats[0]) <NEW_L...
This function sends an email with critical information. It is triggered based on trigger_warning_email.
625941cfa79ad161976cc28f
def select_as_multiple(self, keys, where=None, selector=None, columns=None, start=None, stop=None, iterator=False, chunksize=None, auto_close=False, **kwargs): <NEW_LINE> <INDENT> where = _ensure_term(where, scope_level=1) <NEW_LINE> if isinstance(keys, (list, tuple)) and len(keys) == 1: <NEW_LINE> <INDENT> keys = keys...
Retrieve pandas objects from multiple tables Parameters ---------- keys : a list of the tables selector : the table to apply the where criteria (defaults to keys[0] if not supplied) columns : the columns I want back start : integer (defaults to None), row number to start selection stop : integer (defaults to None...
625941cfcad5886f8bd27123
def resetSeed(swarm, seed): <NEW_LINE> <INDENT> return makeGET("{0}/reset_package_generator?seed={1}".format(swarm, seed))
Resets the RNG seed Args: swarm: Swarm ID seed: New RNG seed Returns: Server response
625941cf0c0af96317bb8332
def __call__(self, equation): <NEW_LINE> <INDENT> if self.operand is None: <NEW_LINE> <INDENT> return self.operator(equation) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.operator(equation, self.operand)
Applies the operation to an equation.
625941cf5e10d32532c5f071
def _reporting_worker(endpoint, ml_service_name, project_number, version_reporting_id, reporting_interval_sec): <NEW_LINE> <INDENT> service_control_client = _ServiceControlClient(endpoint, ml_service_name, project_number) <NEW_LINE> previous_time_sec = datetime.datetime.now() <NEW_LINE> while not _stop_requested: <NEW_...
Periodically reports metrics to ServiceControl until stop is requested.
625941cfa17c0f6771cbe19a
def printListFromTailToHead(self, listNode): <NEW_LINE> <INDENT> if not listNode: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> list_num = [] <NEW_LINE> global list_num <NEW_LINE> if listNode == None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> list_num = self.printListFromTailToHead(listNode.next) <NEW_LINE> li...
通过递归实现先打印最后一个 :param listNode: :return:
625941cfa05bb46b383ec96b
def with_superuser_rights(fn): <NEW_LINE> <INDENT> def __to_superuser_only(request, *args, **kwds): <NEW_LINE> <INDENT> if not Firewall.allowed(request, True): <NEW_LINE> <INDENT> return Firewall.show(request, True) <NEW_LINE> <DEDENT> if not request.user.is_authenticated() or not request.user.is_superuser: <NEW_LINE> ...
Check user have passed firewall, authenticated and marked as superuser
625941cfe5267d203edcdde7
def to_factor(self): <NEW_LINE> <INDENT> return DiscreteFactor(self.variables, self.cardinality, self.values)
Returns an equivalent factor with the same variables, cardinality, values as that of the cpd Examples -------- >>> from pgmpy.factors.discrete import TabularCPD >>> cpd = TabularCPD('grade', 3, [[0.1, 0.1], ... [0.1, 0.1], ... [0.8, 0.8]], ... ...
625941cfd53ae8145f87a3b9
@app.route("/<variable_name>", methods=['GET', 'POST']) <NEW_LINE> def get_nearest_bansefi(variable_name = "fecha"): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> request_dic = request.form.to_dict() <NEW_LINE> values_dic = request_dic['values'] <NEW_LINE> to_parse= values_dic[:values_dic.rfind(v...
List or create notes.
625941cf7047854f462a1553
def nativeKey(self): <NEW_LINE> <INDENT> return QString()
QString QSharedMemory.nativeKey()
625941cf3317a56b86939da1
def heading_change(s_left,s_right,wheel_base = 4): <NEW_LINE> <INDENT> return np.arctan2((s_right-s_left)/2, wheel_base/2)
The heading change of the robot, i.e. delta_theta. Args: s_left: the distance traveled by the left wheel. s_right: the distance traveled by the right wheel. wheel_base: wheel base of the robot. Returns: The heading change in radians.
625941cfd486a94d0b98e290
def find_package_for(filename, pathonly=False): <NEW_LINE> <INDENT> packages = {} <NEW_LINE> if filename.startswith('/var/lib/dpkg/info/'): <NEW_LINE> <INDENT> dpkg_info = re.compile('/var/lib/dpkg/info/(.+)\.[^.]+') <NEW_LINE> m = dpkg_info.match(filename) <NEW_LINE> packages[m.group(1)] = '' <NEW_LINE> return (filena...
Find the package(s) containing this file.
625941cf8e7ae83300e4b117
def get_tuples(self): <NEW_LINE> <INDENT> df = self.get_dataframe() <NEW_LINE> df = df.where((pd.notnull(df)), None) <NEW_LINE> data_list = [] <NEW_LINE> for _, row in df.iterrows(): <NEW_LINE> <INDENT> sample_dict = row.to_dict() <NEW_LINE> sample_dict = {k.lower().replace('-', '_'): v for k, v in sample_dict.items()}...
Returns a list of Sample data types. Returns: List[Sample]
625941cf45492302aab5e40e
def _turn_ends(self) -> bool: <NEW_LINE> <INDENT> if self.get_current_player() == self.game.scoreboard.columns[-1]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Checks if the turn/round ends. If the current player is the last one to play the turn, turn ends. Returns: bool: True if turn ends, else False
625941cfb5575c28eb68e14b
def test_treestyle(self): <NEW_LINE> <INDENT> self.assertEqual(self.project.get_treestyle(), 'nongnu')
test treestyle detection
625941cf8c0ade5d55d3eb05
def query_contains_field(self, query, field_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.get_value_from_query(query, field_name) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
For the specified field name, does the query contain it? Used know whether we need to parse a compound query. .. versionadded: 0.1.0 Support for parsing values embedded in compound db queries
625941cf3eb6a72ae02ec628
def judgeSquareSum(self, c): <NEW_LINE> <INDENT> j = int(sqrt(c)) <NEW_LINE> i = 0 <NEW_LINE> while i <= j: <NEW_LINE> <INDENT> temp = i ** 2 + j ** 2 <NEW_LINE> if temp > c: <NEW_LINE> <INDENT> j -= 1 <NEW_LINE> <DEDENT> elif temp < c: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Tru...
:type c: int :rtype: bool
625941cfcc40096d61595a9a
def can_win(cards, target): <NEW_LINE> <INDENT> for i in set(target): <NEW_LINE> <INDENT> tCount = target.count(i) <NEW_LINE> cCount = sum(1 for j in cards if i in j) <NEW_LINE> if tCount > cCount: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Only can win if there are enough cards for target's needs
625941cf460517430c3942ce
def miner_status(self, bot, update, groups): <NEW_LINE> <INDENT> query = update.callback_query <NEW_LINE> api_id = groups[0] <NEW_LINE> chat_id = query.message.chat_id <NEW_LINE> bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING) <NEW_LINE> try: <NEW_LINE> <INDENT> api = API.get(id=api_id) <NEW_LINE> data ...
Query Miner status and return it properly formatted.
625941cf5fc7496912cc3ac8
def _raw(self, msg): <NEW_LINE> <INDENT> if type(msg) == unicode: <NEW_LINE> <INDENT> msg = msg.encode('gbk') <NEW_LINE> <DEDENT> cmd = c_char_p(msg) <NEW_LINE> size = wintypes.DWORD(len(msg)) <NEW_LINE> tmp = byref(wintypes.DWORD()) <NEW_LINE> self.WriteUsb(self.device, cmd, size, tmp)
Print any of the commands above, or clear text
625941cf3eb6a72ae02ec629
def wait_tasklist(self, task_id_list, block=True): <NEW_LINE> <INDENT> ret_dict = {} <NEW_LINE> running_tasks = list(task_id_list) <NEW_LINE> for task_id in task_id_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process = self.task_map[task_id][0] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.except...
Check the status of a list of tasks. If ``block`` is ``True``, return a dictionary of return values when *all* tasks have completed. If ``block`` is ``False``, return a dictionary containing entries for each *completed* task. Note that the dictionary may be empty. Raise :class:`KeyError` exception if ``task_id`` no...
625941cf15fb5d323cde0c5a
def __init__(self, text=None, pollster_label=None, value=None): <NEW_LINE> <INDENT> self.swagger_types = { 'text': 'str', 'pollster_label': 'str', 'value': 'float' } <NEW_LINE> self.attribute_map = { 'text': 'text', 'pollster_label': 'pollster_label', 'value': 'value' } <NEW_LINE> self._text = text <NEW_LINE> self._pol...
PollQuestionResponses - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941cfd53ae8145f87a3ba
def test_get(self, category_manager, stored_category): <NEW_LINE> <INDENT> result = category_manager.Get(stored_category.pk) <NEW_LINE> result = helpers.dbus_to_hamster_category(result) <NEW_LINE> assert result.pk == stored_category.pk <NEW_LINE> assert result.name == stored_category.name
Make sure a matching category is returned.
625941cf091ae356686670a8
def tag_processor(view_func): <NEW_LINE> <INDENT> def _check_tag_query(request, *args, **kwargs): <NEW_LINE> <INDENT> if "addtag" in request.GET: <NEW_LINE> <INDENT> return HttpResponseRedirect("/news/tags/?addtag=" + request.GET["addtag"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return view_func(r...
Decorator for views has tag handling
625941cffff4ab517eb2f586
def runVotingClassifier(inputs, outputs, lstClassifiers, votingMethod): <NEW_LINE> <INDENT> estimatorsLst = [] <NEW_LINE> for i in range(len(lstClassifiers)): <NEW_LINE> <INDENT> estimatorsLst.append((str(i), lstClassifiers[i])) <NEW_LINE> <DEDENT> voting = VotingClassifier(estimators=estimatorsLst, voting=votingMethod...
This function takes a list of classifiers and applies voting classifier to them according to voting method which can either be 'soft' or 'hard'
625941cf6fb2d068a760f1e8
def run(self): <NEW_LINE> <INDENT> results = { "_temp": {}, } <NEW_LINE> processing_list = mmpi.processing.plugins <NEW_LINE> if processing_list: <NEW_LINE> <INDENT> processing_list.sort(key=lambda module: module.order) <NEW_LINE> for module in processing_list: <NEW_LINE> <INDENT> key, result = self.process(module, res...
Run all processing modules and all signatures. @return: processing results.
625941cf7d847024c06be406
def test_all(self): <NEW_LINE> <INDENT> entries = PeeweeDBRel.select() <NEW_LINE> entry = list(entries.dicts()) <NEW_LINE> first = entry[0] <NEW_LINE> first['relaters'] = [1, 2, 3] <NEW_LINE> second = entry[1] <NEW_LINE> second['relaters'] = [] <NEW_LINE> result = self.rel.all(entries) <NEW_LINE> self.assertEquals(firs...
We want all the entries
625941cf66656f66f7cbc2f6
def existing_url(module): <NEW_LINE> <INDENT> url_base = "/axapi/v3/scaleout/cluster/{cluster_id}/cluster-devices/minimum-nodes" <NEW_LINE> f_dict = {} <NEW_LINE> f_dict["cluster_id"] = module.params["cluster_id"] <NEW_LINE> return url_base.format(**f_dict)
Return the URL for an existing resource
625941cf66656f66f7cbc2f5
def diag(x, offset=0, padding_value=0, name=None): <NEW_LINE> <INDENT> if in_dygraph_mode(): <NEW_LINE> <INDENT> return _C_ops.diag_v2(x, "offset", offset, "padding_value", padding_value) <NEW_LINE> <DEDENT> check_type(x, 'x', (Variable), 'diag_v2') <NEW_LINE> check_dtype(x.dtype, 'x', ['float32', 'float64', 'int32', '...
If ``x`` is a vector (1-D tensor), a 2-D square tensor with the elements of ``x`` as the diagonal is returned. If ``x`` is a matrix (2-D tensor), a 1-D tensor with the diagonal elements of ``x`` is returned. The argument ``offset`` controls the diagonal offset: If ``offset`` = 0, it is the main diagonal. If ``offse...
625941cfa8ecb033257d3217
def get_queryset(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> campaign = Campaign.objects.get(id=self.request.session['campaign']) <NEW_LINE> qs = MageNPC.objects.filter(campaign=campaign) <NEW_LINE> return self._sort_queryset(qs) <NEW_LINE> <DEDENT> except Campaign.DoesNotExist: <NEW_LINE> <INDENT> return None
Return only the currently activated campaign's MageNPC objects or None.
625941cf2eb69b55b151c9fa
def example(n: int, list: List[AStruct]) -> None: <NEW_LINE> <INDENT> pass
:param n: a number, used as a size :param list: a list of structs
625941cfa05bb46b383ec96c
def __init__(self, name, start_url): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.start_url = start_url <NEW_LINE> self.domain = '{uri.scheme}://{uri.netloc}'.format(uri=urlparse(self.start_url))
初始化 :param name:将要被保存为pdf的文件名称 :param start_url:爬虫入口URL
625941cf6aa9bd52df036eef
def test_repr(self): <NEW_LINE> <INDENT> a_repr = '(%(x)s, %(y)s, %(z)s)' % {'x':self.p1.x(), 'y':self.p1.y(), 'z':self.p1.z()} <NEW_LINE> self.assertEqual(a_repr, repr(self.p1))
Test repr
625941cf97e22403b379d0e4
def after_delete(self, id:str)->None: <NEW_LINE> <INDENT> pass
Perform some action after deletion ## Param * id - the complete id prefix:id * doc - the deleted document ## rAfterDeleteException
625941cfbd1bec0571d9077a
def connection_lost(self, exc): <NEW_LINE> <INDENT> self.__log.log_callinfo() <NEW_LINE> self.transport = None <NEW_LINE> super(HM_DatTrc_SMLPacket, self).connection_lost(exc)
@brief Forgets transport. @param exc Exception if connection was terminated by error else None.
625941cff548e778e58cd6c8
def test_error_kind_equals(f2003_create): <NEW_LINE> <INDENT> reader = get_reader("(KIND some_kind") <NEW_LINE> ast = Kind_Selector(reader) <NEW_LINE> assert not ast
Test that None is returned if the '=' after 'kind' is not there.
625941cf379a373c97cfac8f
def test2(self): <NEW_LINE> <INDENT> a = [1, 2, 3, 4] <NEW_LINE> b = (x**2 for x in a) <NEW_LINE> c = (x + 1 for x in b) <NEW_LINE> self.assertEqual([2, 5, 10, 17], list(c))
Generators can be composed together! Chaining generators like this executes very quickly in Python. When you’re looking for a way to compose functionality that’s operating on a large stream of input, generator expressions are the best tool for the job.
625941cfbde94217f3682f3b
def generate(self): <NEW_LINE> <INDENT> cache = Cache(True, False) <NEW_LINE> srcs = self.resources.headers + self.resources.s_sources + self.resources.c_sources + self.resources.cpp_sources + self.resources.objects + self.libraries <NEW_LINE> ctx = { 'name': self.project_name, 'project_file...
Generate the .uvproj file
625941cfad47b63b2c50a0ca
def error(message, *args): <NEW_LINE> <INDENT> raise MDParserException(message % args)
Raise a MDParserException with a given message.
625941cf4f6381625f114b85
@pytest.mark.django_db <NEW_LINE> def test_quiz_list_view(teacher_api_client, coursera_course_id): <NEW_LINE> <INDENT> response = teacher_api_client.get( reverse("coursera-api:quiz-list", kwargs={"course_id": coursera_course_id}) ) <NEW_LINE> keys = [ "id", "base_id", "version", "name", "type", "update_timestamp", "pas...
Test that the quiz list view can be accessed and returns a non-empty list of quizzes with the appropriate data. Test that for every quiz, only a single version appears in the response. The following data must be present: - id - base_id - version - name - type - update_timestamp - passing_fraction - graded
625941cf7047854f462a1554
def __init__(self, weight, order, bias): <NEW_LINE> <INDENT> super(MyLinear, self).__init__() <NEW_LINE> self.weight = nn.Parameter(weight) <NEW_LINE> self.bias = nn.Parameter(bias) <NEW_LINE> self.order = order
v konstruktore inicializujeme premenne, ktore neskor pouzijeme pouzivame self lebo budeme je pouyivat mimo funkcie ale stale v triede
625941cf4f6381625f114b86
def has_field(self, group, field): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return field in self[group] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False
Check if a field is in a group. Parameters ---------- group: str Name of the group. field: str Name of the field. Returns ------- boolean ``True`` if the group contains the field, otherwise ``False``. Examples -------- Check if the field named ``topographic__elevation`` is contained in a group. >>> from...
625941cf91af0d3eaac9bb64
@login_required(login_url="/qishi/home/") <NEW_LINE> def delete_post(request, post_id): <NEW_LINE> <INDENT> post = get_object_or_404(Post, id=post_id) <NEW_LINE> topic = post.topic <NEW_LINE> if not (request.user.is_staff or request.user.id == post.posted_by.id): <NEW_LINE> <INDENT> return HttpResponse('no right to del...
Delete a post with 'post_id'. If the post is the mainpost of a topic, replace the post message by a "delete" message.
625941cf711fe17d825424b6
def _expandDataframe(self): <NEW_LINE> <INDENT> self.vax_ts["est_bedarf_biontech_zweit_kumulativ"] = 0 <NEW_LINE> self.vax_ts["est_bedarf_biontech_zweit_rest"] = 0 <NEW_LINE> self.vax_ts["est_bedarf_moderna_zweit_kumulativ"] = 0 <NEW_LINE> self.vax_ts["est_bedarf_moderna_zweit_rest"] = 0 <NEW_LINE> self.vax_ts["est_bed...
add new columns to dataframe for predicitons
625941cf2ae34c7f2600d27c
def __init__(self, keyword, course_id, response): <NEW_LINE> <INDENT> self.keyword = keyword <NEW_LINE> self.course_id = course_id <NEW_LINE> self.response = response
Creates a new Response-record connected to course_id.
625941cfd10714528d5ffe2f
def FeedBlob(name, arr, device_option=None): <NEW_LINE> <INDENT> if type(arr) is caffe2_pb2.TensorProto: <NEW_LINE> <INDENT> arr = utils.Caffe2TensorToNumpyArray(arr) <NEW_LINE> <DEDENT> if type(arr) is np.ndarray and arr.dtype.kind == 'S': <NEW_LINE> <INDENT> arr = arr.astype(np.object) <NEW_LINE> <DEDENT> if device_o...
Feeds a blob into the workspace. Inputs: name: the name of the blob. arr: either a TensorProto object or a numpy array object to be fed into the workspace. device_option (optional): the device option to feed the data with. Returns: True or False, stating whether the feed is successful.
625941cf4527f215b584c5a1
def getCategory(categoryObj): <NEW_LINE> <INDENT> category = categoryDal.getCategory(categoryObj) <NEW_LINE> return category
Gets all details of the given category :param categoryObj:Holds the id of the string.Contains the following field, id :type categoryObj: object :return category: return the category
625941cfbe8e80087fb20d8d
def test_save_wea(): <NEW_LINE> <INDENT> path = './tests/fixtures/epw/chicago.epw' <NEW_LINE> epw = EPW(path) <NEW_LINE> wea_path = './tests/fixtures/wea/chicago_epw.wea' <NEW_LINE> epw.to_wea(wea_path) <NEW_LINE> assert os.path.isfile(wea_path) <NEW_LINE> assert os.stat(wea_path).st_size > 1 <NEW_LINE> with open(wea_p...
Test save wea_rel.
625941cfbe7bc26dc91cd74a
def set_object(self,Point,Object): <NEW_LINE> <INDENT> self.room[Point.x][Point.y]=Object
sets an object at the specific Point in the Current Room
625941cf73bcbd0ca4b2c1c1
def resolve(self,wavelengths,resolution,resolve_method='resample',upscaling=False,**kwargs): <NEW_LINE> <INDENT> self.resolver = getattr(self,resolve_method) <NEW_LINE> self.resolve_method = resolve_method <NEW_LINE> newwl = np.copy(wavelengths) <NEW_LINE> newrs = np.copy(resolution) <NEW_LINE> oldwl,oldfl = self.data ...
This method calls a spectrum method, saving and returning the result. The saved data is prepared for the :meth:`resolve_and_integrate` function before being returned. The method also prevents over-resolution sampling. The resolution provided (`resolution` keyword) are used to request a resampled resolution. However, t...
625941cfeab8aa0e5d26dca3
def generate(self, required_options=None): <NEW_LINE> <INDENT> self.required_options = required_options <NEW_LINE> if self.msfvenomCommand == '' and self.custom_shellcode == '': <NEW_LINE> <INDENT> self.menu() <NEW_LINE> <DEDENT> if self.custom_shellcode != '': <NEW_LINE> <INDENT> print(helpers.color("\n [*] Using pre-...
Based on the options set by menu() or SetPayload() either returns the custom shellcode string or calls msfvenom and returns the result. Returns the shellcode string for this object.
625941cff548e778e58cd6c9
def mouse_click(self,x,y,button=None,double_click=False): <NEW_LINE> <INDENT> if not self._connect(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._send_comand(G.SENSOR_CONTROL.MOUSE_CMD+":"+"%5s"%x+"%5s"%y)
This will move the mouse the specified (X,Y) coordinate and click
625941cf82261d6c526ab5eb
def ipynb2md(ipynb_file): <NEW_LINE> <INDENT> md_file = ipynb_file.with_suffix('.md') <NEW_LINE> content = f'# {ipynb_file.stem}\n' <NEW_LINE> with open(ipynb_file, encoding='utf-8') as f1: <NEW_LINE> <INDENT> with open(md_file, 'w', encoding='utf-8') as f2: <NEW_LINE> <INDENT> cells = json.loads(f1.read())['cells'] <N...
转换ipynb文件为markdown文件
625941cfdc8b845886cb5680
def get_id( self ): <NEW_LINE> <INDENT> return self._id
Returns the employee's id :return: str
625941cf01c39578d7e74f86
def loglike(self, params): <NEW_LINE> <INDENT> return np.sum(self.loglikeobs(params))
Loglikelihood of Generic Zero Inflated model Parameters ---------- params : array-like The parameters of the model. Returns ------- loglike : float The log-likelihood function of the model evaluated at `params`. See notes. Notes -------- .. math:: \ln L=\sum_{y_{i}=0}\ln(w_{i}+(1-w_{i})*P_{main\_model})+...
625941cfa219f33f34628ab5
def db_to_df(table_name:str, db_conn): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sql = f"SELECT * FROM {table_name}" <NEW_LINE> dataframe = pd.read_sql(sql, db_conn) <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> print(str(exception)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> db_conn.c...
build a pandas dataframe from a mySQL table
625941cf50485f2cf553cee5
def __create_password(): <NEW_LINE> <INDENT> salt = b64encode(API.__generate_string(32)) <NEW_LINE> password = b64encode(API.__generate_string(64)) <NEW_LINE> return b64encode(sha1(password + salt).digest())
Create a password for the user.
625941cf004d5f362079a47e
def GetParams(self): <NEW_LINE> <INDENT> input_name = "input" <NEW_LINE> input_dims = [10, 24, 24, 20] <NEW_LINE> output_name = "output" <NEW_LINE> g = ops.Graph() <NEW_LINE> with g.as_default(): <NEW_LINE> <INDENT> x = array_ops.placeholder( dtype=dtypes.float32, shape=input_dims, name=input_name) <NEW_LINE> for weigh...
Tests for scale & elementwise layers in TF-TRT.
625941cf91f36d47f21ac63f
def decompressGameData(): <NEW_LINE> <INDENT> games = glob.glob('*.7z') <NEW_LINE> for game in games: <NEW_LINE> <INDENT> print('Decompressing: ' + game) <NEW_LINE> os.system( '7z x ' + game + ' -y > nul')
Decompress the 7z files used as data storage
625941cf1d351010ab855c67
def pre_process_message_related_subtasks( client_message: Message, client_public_key: bytes ) -> None: <NEW_LINE> <INDENT> subtask_ids_list = [] <NEW_LINE> if isinstance(client_message, ForcePayment): <NEW_LINE> <INDENT> for subtask_result_accepted in client_message.subtask_results_accepted_list: <NEW_LINE> <INDENT> su...
Function gets subtask_id (or more subtask id's if message is ForcePayment) from client message, starts transaction, checks if state is active and subtask is timed out (in database query, if it is subtask is locked). If so, file status is verified (check additional conditions in verify_file_status) and subtask's state i...
625941cf8e71fb1e9831d8f4
def _get_upper_state_constraints(self, xmax): <NEW_LINE> <INDENT> AX = sparse.kron(sparse.eye((self.h + 1) * self.n), [1, 0]) <NEW_LINE> upper = numpy.ones((self.h + 1) * self.n)*xmax[0] <NEW_LINE> constraint = [AX*self.x - self.v_slack <= upper] <NEW_LINE> return constraint
Returns the upper constraints for the states. Includes the slack variable for velocity limitation. Called on initialization.
625941cf5fdd1c0f98dc037f
def load_protocols(self, folder, overwrite=False): <NEW_LINE> <INDENT> if overwrite: <NEW_LINE> <INDENT> logging.debug('Protocol list will be overriden') <NEW_LINE> self.protocols = {} <NEW_LINE> self.goalsets = {} <NEW_LINE> <DEDENT> logging.debug('Searching folder {} for protocols, goal sets'.format(folder)) <NEW_LIN...
tpo.load_protocols(folder)
625941cf8c3a873295158506
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(Path, self).__init__(*args, **kwds) <NEW_LINE> if self.target_x is None: <NEW_LINE> <INDENT> self.target_x = [] <NEW_LINE> <DEDENT> if self.target_y is None: <NEW_LINE> <INDENT> self.target_y = [] <NEW_LINE> <DEDENT> if se...
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: target_x,target_y,target_st :para...
625941cf4f88993c3716c1b2
def SetOutsideValue(self, *args): <NEW_LINE> <INDENT> return _itkRobustAutomaticThresholdImageFilterPython.itkRobustAutomaticThresholdImageFilterIUC3IUC3IUL3_SetOutsideValue(self, *args)
SetOutsideValue(self, unsigned long _arg)
625941cfcdde0d52a9e5317f