code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def toy_fn_1(arg1, arg2): <NEW_LINE> <INDENT> sess = tf.Session() <NEW_LINE> node1 = tf.pow(arg1, 3) <NEW_LINE> node2 = tf.multiply(tf.pow(arg2, 2), 4) <NEW_LINE> node3 = tf.multiply(arg1, 10) <NEW_LINE> addNode = tf.subtract(tf.add(node1, node2), node3) <NEW_LINE> return sess.run(addNode) | Given two tensors of arbitrary (but same) rank and size, build a computation
graph for the following function, which should be computed element-wise:
arg1^3 + 4*arg2^2 - 10*arg1
Args:
arg1(tf.Tensor): A tensor of arbitrary rank
arg2(tf.Tensor): A tensor of the same rank as arg1
Returns:
(tf.Tensor): the r... | 625941cb01c39578d7e74f17 |
def ship_loader(floader, lresolver, macro_db, ext_name): <NEW_LINE> <INDENT> macro_db.set_macro_parser( lambda *args: macro_parser(*args, lresolver=lresolver) ) <NEW_LINE> macro_db.set_component_parser(component_parser) <NEW_LINE> units_root_xml = get_path_in_ext('assets/units', ext_name) <NEW_LINE> for ship_size in ['... | Loads ship game macro files and returns ship data.
This function will set the macro_db's macro parser and component parser.
Arguments:
floader: FileLoader to use.
lresolver: LanguageResolver used to resolve ship names.
macro_db: MacroDB used to load macros.
ext_name: extension to load ships from. Use None for the base... | 625941cbcc40096d61595a2c |
def pyflake_issue(): <NEW_LINE> <INDENT> a = sys | A function with an unused variable. | 625941cb507cdc57c6306db6 |
def khop_adj(g, k): <NEW_LINE> <INDENT> assert g.is_homogeneous, 'only homogeneous graph is supported' <NEW_LINE> adj_k = g.adj(scipy_fmt=g.formats()['created'][0]) ** k <NEW_LINE> return F.tensor(adj_k.todense().astype(np.float32)) | Return the matrix of :math:`A^k` where :math:`A` is the adjacency matrix of the graph
:math:`g`, where rows represent source nodes and columns represent destination nodes.
The returned matrix is a 32-bit float dense matrix on CPU.
The graph must be homogeneous.
Parameters
----------
g : DGLGraph
The input graph.... | 625941cb07f4c71912b1155d |
def clean_email(self): <NEW_LINE> <INDENT> existing = User.objects.filter(email__iexact=self.cleaned_data['email']) <NEW_LINE> if existing.exists(): <NEW_LINE> <INDENT> raise forms.ValidationError(_("This email address is already in use. Please enter a different email " "address!")) <NEW_LINE> <DEDENT> else: <NEW_LINE>... | Make sure the email isn't taken yet. | 625941cbaad79263cf390b1c |
def linear_ode(self): <NEW_LINE> <INDENT> is_linear = True <NEW_LINE> if self._Jacobian is None: <NEW_LINE> <INDENT> self.get_jacobian_eqn() <NEW_LINE> <DEDENT> a = self._Jacobian.atoms() <NEW_LINE> for s in self._stateDict.values(): <NEW_LINE> <INDENT> if s in a: <NEW_LINE> <INDENT> is_linear = False <NEW_LINE> <DEDEN... | To check whether the input ode is linear
Returns
-------
bool
True if it is linear, False otherwise | 625941cb21bff66bcd684a2f |
def delete_volume(module, array): <NEW_LINE> <INDENT> if not module.check_mode: <NEW_LINE> <INDENT> array.destroy_volume(module.params['name']) <NEW_LINE> if module.params['eradicate'] == 'true': <NEW_LINE> <INDENT> array.eradicate_volume(module.params['name']) <NEW_LINE> <DEDENT> <DEDENT> module.exit_json(changed=True... | Delete Volume | 625941cb1b99ca400220ab8d |
def init_robots(node_map): <NEW_LINE> <INDENT> robots = [] <NEW_LINE> for robot_start in node_map.robots: <NEW_LINE> <INDENT> if robot_start in node_map.nodes: <NEW_LINE> <INDENT> print('{} initialized'.format(robot_start)) <NEW_LINE> came_from, cost_so_far = a_star(node_map, robot_start, node_map.rendezvous) <NEW_LINE... | <<<<<<< HEAD
=======
>>>>>>> 4ea83ae2feac247d47021c295b6599daf8dacc5d
| 625941cb5fcc89381b1e179a |
def InDisabled(self): <NEW_LINE> <INDENT> d0 = None <NEW_LINE> d1 = None <NEW_LINE> if not hasattr(self, 'timer'): <NEW_LINE> <INDENT> self.timer = wpilib.Timer() <NEW_LINE> self.timer.Start() <NEW_LINE> <DEDENT> if self.timer is not None: <NEW_LINE> <INDENT> tm = self.timer.Get() <NEW_LINE> n = random.randint(0,9999) ... | Easter egg: Call in disabled mode when there is new data from the DS | 625941cb283ffb24f3c559dd |
def transform(self, node, results): <NEW_LINE> <INDENT> if self.skip: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> imp = results['imp'] <NEW_LINE> if node.type == syms.import_from: <NEW_LINE> <INDENT> while not hasattr(imp, 'value'): <NEW_LINE> <INDENT> imp = imp.children[0] <NEW_LINE> <DEDENT> if self.probably_a_loc... | Copied from FixImport.transform(), but with this line added in
any modules that had implicit relative imports changed:
from __future__ import absolute_import" | 625941cbbaa26c4b54cb11fb |
@pytest.fixture <NEW_LINE> def results(): <NEW_LINE> <INDENT> spider = wsp_spider.WorldScientificSpider() <NEW_LINE> records = list(spider.parse( fake_response_from_file('world_scientific/sample_ws_record.xml') )) <NEW_LINE> assert records <NEW_LINE> return records | Return results generator from the WSP spider. | 625941cbd99f1b3c44c6766a |
def reindent(self, text): <NEW_LINE> <INDENT> lines = text.split('\n') <NEW_LINE> new_lines = [] <NEW_LINE> credit = 0 <NEW_LINE> k = 0 <NEW_LINE> for raw_line in lines: <NEW_LINE> <INDENT> line = raw_line.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if TemplateParser.re_block.match(... | Reindents a string of unindented python code. | 625941cbfbf16365ca6f62a0 |
def map(self, function, kind): <NEW_LINE> <INDENT> return self.apply(MapTransformation(function, kind)) | Applies a function to the ``data`` element of events of ``kind`` in
the selection.
>>> html = HTML('<html><head><title>Some Title</title></head>'
... '<body>Some <em>body</em> text.</body></html>',
... encoding='utf-8')
>>> print(html | Transformer('head/title').map(unicode.upper, TEXT))
<htm... | 625941cb63b5f9789fde71c1 |
def has_perm(self, perm, obj=None): <NEW_LINE> <INDENT> return self.is_active and self.is_superuser | Returns True if the user is superadmin and is active | 625941cbd164cc6175782e29 |
def main(): <NEW_LINE> <INDENT> LayoutDemo().mainloop() | Instantiate and pop up the window. | 625941cb0a366e3fb873e8f6 |
def WriteRecent(tweet): <NEW_LINE> <INDENT> recentpath = path.realpath(path.join(os.getcwd(), path.dirname(__file__))) <NEW_LINE> with open(path.join(recentpath, 'RECENT.txt'), 'r') as f: <NEW_LINE> <INDENT> recent = f.readlines() <NEW_LINE> <DEDENT> if len(recent) >= 5: <NEW_LINE> <INDENT> recent = [''] + recent[:-1] ... | Write the most recent tweet to a file, keeping the 5 most recent tweets.
Adds tweet to front of file and pops the oldest recent tweet off the file. | 625941cb94891a1f4081bb85 |
def _check_list_(blist): <NEW_LINE> <INDENT> if len(blist) == 0: <NEW_LINE> <INDENT> raise EmptyList('list of biclusters is empty') | Checks if any of the expected or found bicluster lists are empty.
Args:
* blist: List of biclusters. | 625941cb99fddb7c1c9de46d |
def record_init_stats(self): <NEW_LINE> <INDENT> num_sites = len(self.hc.points_to_compute()) <NEW_LINE> realizations = models.LtRealization.objects.filter( hazard_calculation=self.hc.id) <NEW_LINE> num_rlzs = realizations.count() <NEW_LINE> [job_stats] = models.JobStats.objects.filter(oq_job=self.job.id) <NEW_LINE> jo... | Record some basic job stats, including the number of sites,
realizations (end branches), and total number of tasks for the job.
This should be run between the `pre-execute` and `execute` phases, once
the job has been fully initialized. | 625941cb091ae3566866703a |
def MotionMTF(self, psfArray=[], psfSpatial=[], startpoint=0, tint=0.005): <NEW_LINE> <INDENT> if (len(psfArray)==0 or len(psfSpatial)==0) and (len(self.amplitudes)==0): <NEW_LINE> <INDENT> self.displayWarning('MotionMTF() requires the two PSF arguments or populated amplitude data.') <NEW_LINE> <DEDENT> elif (len(psfAr... | docstring | 625941cb0fa83653e4657097 |
def tableRowParser(): <NEW_LINE> <INDENT> def formatBloc(t): <NEW_LINE> <INDENT> rows = [] <NEW_LINE> units = {} <NEW_LINE> names = [] <NEW_LINE> for row in t : <NEW_LINE> <INDENT> rows.append(ParseResults([ row.header, array(tuple(row.value)) ])) <NEW_LINE> names.append(row.header) <NEW_LINE> if row.unit : units[row.h... | Define a pattern matching a table described in row following the schema :
Name_1 (unit) value_11 value_12 ... value_1n
Name_2 (unit) value_21 value_22 ... value_2n
... ... ... ... ... ...
Units are optional.
Name can contains spaces if theyt are followed by an u... | 625941cb6e29344779a626ee |
def interpreter(self): <NEW_LINE> <INDENT> return self.mediator.interpreter() | return a reference to the mediator's current CmdInterp object
**INPUTS**
*none*
**OUTPUTS**
*none* | 625941cb4527f215b584c533 |
def ReadRemarks(user_id): <NEW_LINE> <INDENT> start_time = memcache.get(_MakeLastGetKey(user_id)) <NEW_LINE> LogLastGet(user_id) <NEW_LINE> remarks = [] <NEW_LINE> query = Remark.query(Remark.timestamp >= start_time).order(Remark.timestamp) <NEW_LINE> for remark in query.fetch(): <NEW_LINE> <INDENT> remarks.append((rem... | Get all remarks since the given user's last read. | 625941cc3346ee7daa2b2e47 |
def dbx_uri(path): <NEW_LINE> <INDENT> return "dbx:/%s" % normpath(path) | Convert some path into dbx://path. | 625941ccad47b63b2c50a05b |
def dictparse(csvfilename, keyfield, separator, quote, quotestrategy): <NEW_LINE> <INDENT> table = {} <NEW_LINE> with open(csvfilename, "rt") as csvfile: <NEW_LINE> <INDENT> csvreader = csv.DictReader(csvfile, skipinitialspace =True, delimiter=separator, quotechar=quote, quoting=quotestrategy) <NEW_LINE> for row in csv... | Reads csv file named csvfilename, parses its contents and return the data as a dictionary of dictionaries. | 625941ccf8510a7c17cf97d9 |
def id_nodes(g): <NEW_LINE> <INDENT> return [n for n in g if 'contraction' in g.node[n]] | -> list of identified nodes in g | 625941ccc432627299f04d22 |
def start_data_processing(): <NEW_LINE> <INDENT> parent = os.fork() <NEW_LINE> if parent > 0: <NEW_LINE> <INDENT> track['mode'] = "LOG" <NEW_LINE> if_config_vars['projectName'] += '-log' <NEW_LINE> logger.debug(str(os.getpid()) + ' is running the log agent') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> track['mode'] =... | get traces from the last <samplingInterval> minutes | 625941cccb5e8a47e48b7b87 |
def test_one_partition_is_never_processed_when_periodicity_is_negative(self): <NEW_LINE> <INDENT> computer = ComputerForTest(self.software_root, self.instance_root, 1, 1) <NEW_LINE> with httmock.HTTMock(computer.request_handler): <NEW_LINE> <INDENT> timestamp = str(int(time.time())) <NEW_LINE> instance = computer.insta... | Checks that a partition is not processed when
its periodicity is negative
1. We setup one instance and set periodicity at -1
2. We mock the install method from slapos.grid.slapgrid.Partition
3. We launch slapgrid once so that .timestamp file is created and check that install method is
indeed called (through mocked_meth... | 625941cc4e4d5625662d44b4 |
def reply(self, event: EventCommandReceived) -> Optional[EventCommandToSend]: <NEW_LINE> <INDENT> variants: Dict[CallbackType, Callable[[EventCommandReceived], EventCommandToSend]] = { CallbackType.GREETING: self.form_category_list, CallbackType.CATEGORY: self.form_product_list, CallbackType.PRODUCT: self.form_product_... | Основной метод класса, формирует словарь-ответ на базе типа и параметров запроса в формате ECR. | 625941cccad5886f8bd270b5 |
def lengthOfLastWord(self, s): <NEW_LINE> <INDENT> s = s.split() <NEW_LINE> if s: <NEW_LINE> <INDENT> return len(s[-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 | :type s: str
:rtype: int | 625941ccfff4ab517eb2f518 |
def __new__(cls, base=u'', encoding=None, errors='strict'): <NEW_LINE> <INDENT> if encoding is None and isinstance(base, str): <NEW_LINE> <INDENT> encoding = 'utf8' <NEW_LINE> warnings.warn( "Convert string '{0}' in template to unicode.".format(base), RuntimeWarning, stacklevel=3) <NEW_LINE> <DEDENT> return jinja2_Mark... | Add encoding for base of type str. | 625941cc3cc13d1c6d3c7456 |
def _populate_languages(self, termbase): <NEW_LINE> <INDENT> locales = self._view.get_termbase_locales() <NEW_LINE> for locale in locales: <NEW_LINE> <INDENT> termbase.add_language(locale) | Adds the languages that have been chosen in the UI to the newly
created termbase.
:param termbase: termbase to be populated
:type termbase: mdl.Termbase
:rtype: None | 625941cc5f7d997b87174b74 |
def addAccount(self,title,description,account,password,secret,tagIds): <NEW_LINE> <INDENT> conn = self.getConnection() <NEW_LINE> pwdDao = PwdDao(conn) <NEW_LINE> master = config.getRootPwd() <NEW_LINE> ePassword = util.encrypt(master, password.decode("utf-8")) <NEW_LINE> eSecret = util.encrypt(master,secret) if secret... | add a user input account to database
@param title: account title
@param description: account description
@param account: account name/username, emailaddr, ....
@param password: password
@param secret: the secret text from user
@param tagIds: a list of related tagIds | 625941cc10dbd63aa1bd2c80 |
def create_widgets(self, ok_text='OK'): <NEW_LINE> <INDENT> self.frame = frame = Frame(self, padding=10) <NEW_LINE> frame.grid(column=0, row=0, sticky='news') <NEW_LINE> frame.grid_columnconfigure(0, weight=1) <NEW_LINE> entrylabel = Label(frame, anchor='w', justify='left', text=self.message) <NEW_LINE> self.entryvar =... | Create entry (rows, extras, buttons.
Entry stuff on rows 0-2, spanning cols 0-2.
Buttons on row 99, cols 1, 2. | 625941cc3eb6a72ae02ec5b9 |
def max_pool_2x2(input_vector): <NEW_LINE> <INDENT> ksize = [1, 2, 2, 1] <NEW_LINE> stride = [1, 2, 2, 1] <NEW_LINE> padding = 'SAME' <NEW_LINE> pooled = tf.nn.max_pool(input_vector, ksize=ksize, strides=stride, padding=padding) <NEW_LINE> return pooled | Applies max pooling to input vector (convolved input) using a 2x2 pool.
INPUT:
input_vector (int[4]) tensor of shape [batch, height, width, tot_in_channels] | 625941cca8ecb033257d31a9 |
def __init__(self,n_state,n_obs,S = None,A = None,B = None): <NEW_LINE> <INDENT> self.n_state = n_state <NEW_LINE> self.n_obs = n_obs <NEW_LINE> self.S = S <NEW_LINE> self.A = A <NEW_LINE> self.B = B | 初始化
Parameters
-----
n_state: int, 状态的个数
n_obs:int, 观测的种类数
S: 1*n的矩阵,表示的是:初始状态概率向量
A: n*n的矩阵,状态转移概率矩阵
B:n*m的矩阵,观测生成概率矩阵 | 625941ccec188e330fd5a87c |
def is_active(self, name): <NEW_LINE> <INDENT> if not self.exists(name): <NEW_LINE> <INDENT> raise errors.UnknownFeatureError('Unknown feature: %s' % name) <NEW_LINE> <DEDENT> if self._read_file()[name]['active']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Checks if a feature is on.
:param name: name of the feature.
:rtype: bool
:raises: UnknownFeatureError | 625941ccbd1bec0571d9070c |
def auto_float(self, data): <NEW_LINE> <INDENT> data = re.compile(r'\d+(\.\d+)?').sub(self.float_replace, data) <NEW_LINE> return data | Makes all digits/decimals into floats to prevent auto-rounding | 625941cc7cff6e4e81117a62 |
def __unicode__(self): <NEW_LINE> <INDENT> root_node_unicode = ET.tostring(self.root_element) <NEW_LINE> root_node_dom = minidom.parseString(root_node_unicode) <NEW_LINE> return root_node_dom.toprettyxml(indent=' ' * 4) | Generate and return a pretty-printable XML unicode string | 625941cc85dfad0860c3af37 |
def get_largest_jump(graph,verbose=False): <NEW_LINE> <INDENT> start = 1 <NEW_LINE> end = graph.m-1 <NEW_LINE> head = ranked_SCC(tarjan((graph.edges>0)*(graph.edges<=start))) <NEW_LINE> tail = ranked_SCC(tarjan((graph.edges>0)*(graph.edges<=end))) <NEW_LINE> largest_jump = 0 <NEW_LINE> if (tail-head)<(graph.n/100): jum... | Finds the largest jump resulting from the addition of one edge
Parameters
------
graph : graph object, as defined by graphs.py
verbose :
Returns
-----
jump : size of the largest jump resulting from the addition of one edge (int) | 625941cc7047854f462a14e6 |
def generate_query_collection(self): <NEW_LINE> <INDENT> self.persistent_query_keyword_1 = PersistentQueryKeyword( user_id="1", name="persistent_query_keyword_1" ).save() <NEW_LINE> self.persistent_query_keyword_2 = PersistentQueryKeyword( user_id="2", name="persistent_query_keyword_2" ).save() <NEW_LINE> self.persiste... | Generate a Persistent Query Keyword collection.
Returns: | 625941cc2ae34c7f2600d20e |
def taq_cross_response_year_physical_shift_data(ticker_i, ticker_j, year, tau): <NEW_LINE> <INDENT> if (ticker_i == ticker_j): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> function_name = taq_cross_response_year_physical_shift_data.__name__ <NEW_LINE> taq_data_tools_physical_shift ... | Computes the cross-response of a year.
Using the taq_cross_response_day_physical_data function computes the
cross-response function for a year.
:param ticker_i: string of the abbreviation of the stock to be analyzed
(i.e. 'AAPL').
:param ticker_j: string of the abbreviation of the stock to be analyzed
(i.e. 'AAPL')... | 625941cc5e10d32532c5f003 |
def max_pool_2x2(x): <NEW_LINE> <INDENT> return tf.nn.max_pool3d(x, ksize=[1,1, 4, 4, 1], strides=[1,1, 4, 4, 1], padding='SAME') | max_pool_2x2 downsamples a feature map by 2X. | 625941cc8c0ade5d55d3ea97 |
def t450521_x13(): <NEW_LINE> <INDENT> assert t450521_x1() <NEW_LINE> return 0 | State 0,1 | 625941cc851cf427c661a5ec |
def _interval_count(self): <NEW_LINE> <INDENT> dialog = IntervaLCountDialog(self.graph, self) <NEW_LINE> dialog.exec_() | 计算区间停站车次数量 | 625941ccab23a570cc25025f |
@protocolize() <NEW_LINE> def make_l2_freq_test_model(depends_on='../config/l2_freq_test_model.py'): <NEW_LINE> <INDENT> protocols.model_protocol(depends_on,parallel=False,write=True) | 625941cca05bb46b383ec8fe | |
def periodic(spacing, run_immediately=True): <NEW_LINE> <INDENT> if spacing <= 0: <NEW_LINE> <INDENT> raise ValueError("Periodicity/spacing must be greater than" " zero instead of %s" % spacing) <NEW_LINE> <DEDENT> def wrapper(f): <NEW_LINE> <INDENT> f._periodic = True <NEW_LINE> f._periodic_spacing = spacing <NEW_LINE... | Tags a method/function as wanting/able to execute periodically.
:param run_immediately: option to specify whether to run
immediately or not
:type run_immediately: boolean | 625941ccf548e778e58cd65a |
def shuffle(self): <NEW_LINE> <INDENT> shuffled = [] <NEW_LINE> indices = [] <NEW_LINE> for i in range(0, len(self.__orig)): <NEW_LINE> <INDENT> indices.append(i) <NEW_LINE> <DEDENT> random.shuffle(indices) <NEW_LINE> for i in indices: <NEW_LINE> <INDENT> shuffled.append(self.__orig[i]) <NEW_LINE> <DEDENT> return shuff... | Returns a random shuffling of the array.
:rtype: List[int] | 625941cc29b78933be1e5789 |
def _is_corp_member(self, token, char_id): <NEW_LINE> <INDENT> resp = self._eve.esi(token).v3.characters(char_id).get() <NEW_LINE> return resp.get("corporation_id") == self._config.get("corp.id") | "Return whether the given character is in the site's corp. | 625941cc4f6381625f114b18 |
def distance(v, w): <NEW_LINE> <INDENT> return sqrt(squared_distance(v, w)) | 두 벡터 v와 w 사이의 거리를 리턴 - sqrt(squared_distance)
:param v: n차원 벡터
:param w: n차원 벡터
:return: 숫자 | 625941ccf7d966606f6aa0e1 |
def close(self, db_session=None): <NEW_LINE> <INDENT> self.end_date = datetime.utcnow() <NEW_LINE> self.status = Event.statuses['closed'] <NEW_LINE> log.warning('ALERT: CLOSE: %s' % self) <NEW_LINE> self.send_alerts() | Closes an event and sends notification to affected users | 625941cc596a897236089b9e |
def _convert_all_channel4(self): <NEW_LINE> <INDENT> if self._noDataLoading: <NEW_LINE> <INDENT> self.read4(self.fileName, convert_after_read=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.multiProc is False: <NEW_LINE> <INDENT> [self._convert_channel4(channelName) for channelName in self] <NEW_LINE> <DEDE... | Converts all channels from raw data to converted data according to CCBlock information
Converted data will take more memory. | 625941ccf9cc0f698b1406d9 |
def spider(data_url, taken): <NEW_LINE> <INDENT> response = requests.get(data_url, headers=headers).text <NEW_LINE> response_jsonObj = json.loads(response) <NEW_LINE> room_type_list = jsonpath.jsonpath(response_jsonObj, '$.mergeList.data')[0] <NEW_LINE> id_data_list = jsonpath.jsonpath(response_jsonObj, '$.propagateDat... | spider
:param data_url:
:param taken:
:return: | 625941cc76e4537e8c35174f |
def delete(self): <NEW_LINE> <INDENT> url = self.get_party_url() <NEW_LINE> r = requests.delete(url, auth=self.pycapsule.auth) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Returns:
success(bool): True if successfully deleted else False | 625941cc7b180e01f3dc48da |
def __init__(self, name, fuel, reliability): <NEW_LINE> <INDENT> super().__init__(fuel, name) <NEW_LINE> self.reliability = reliability | Initialise a UnreliableCar instance, based on parent class Car. | 625941cc85dfad0860c3af38 |
def test_list_drivers(self): <NEW_LINE> <INDENT> resp = self.drivers_client.list_drivers() <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> drivers = resp.entity <NEW_LINE> driver_names = [driver.name for driver in drivers] <NEW_LINE> self.assertIn('fake', driver_names) | Verify that the driver is returned in the list of drivers. | 625941cc57b8e32f52483577 |
def findForegroundObject(self, maskImage, minAreaThresh = 100, maxAreaRatioThresh = 0.5): <NEW_LINE> <INDENT> forgroundObject = [] <NEW_LINE> foregroundInformation = cv2.connectedComponentsWithStats(maskImage, self.connectivity, cv2.CV_32S)[2] <NEW_LINE> maxAreaThresh = maskImage.shape[0] * maskImage.shape[1] * maxArea... | Use the foreground mask to find the foreground object.
`maskImage` is the foreground mask inputarray.
`minAreaThresh` is the threshold value to avoid the noise.
`maxAreaRatioThresh` is the ratio threshhold to avoid big noise. | 625941cc21a7993f00bc7dcc |
def test_board_topics_view_not_found_status_code(self): <NEW_LINE> <INDENT> url = reverse('board_topics', kwargs={'pk': 99}) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEquals(response.status_code, 404) | Testing for page NOT found. | 625941cc656771135c3eb94b |
def _deletes(self): <NEW_LINE> <INDENT> return {concat(a, b[1:]) for a, b in self.slices[:-1]} | th. | 625941ccd6c5a10208144128 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.compute_parent_updates() <NEW_LINE> for k in kwargs: <NEW_LINE> <INDENT> if k not in self.swagger_types: <NEW_LINE> <INDENT> raise ValueError("CreateMemberResponse got unexpected argument '%s'" % k) <NEW_LINE> <DEDENT> <DEDENT> get_parent().__init__(self, **kwargs) | CreateMemberResponse - a model defined in Swagger | 625941cc287bf620b61d3b41 |
def preprocess( output_directory, all_files, show_detailed=False, show_progress=True, hipify_caffe2=False): <NEW_LINE> <INDENT> total_count = len(all_files) <NEW_LINE> finished_count = 0 <NEW_LINE> stats = {"unsupported_calls": [], "kernel_launches": []} <NEW_LINE> for filepath in all_files: <NEW_LINE> <INDENT> preproc... | Call preprocessor on selected files.
Arguments)
show_detailed - Show a detailed summary of the transpilation process. | 625941cc7d43ff24873a2d7d |
def klBin(x, y, n): <NEW_LINE> <INDENT> x = min(max(x, eps), 1 - eps) <NEW_LINE> y = min(max(y, eps), 1 - eps) <NEW_LINE> return n * (x * np.log(x / y) + (1 - x) * np.log((1 - x) / (1 - y))) | Kullback-Leibler divergence for Binomial distributions. https://math.stackexchange.com/questions/320399/kullback-leibner-divergence-of-binomial-distributions
- It is simply the n times :func:`klBern` on x and y.
.. math:: \mathrm{KL}(\mathrm{Bin}(x, n), \mathrm{Bin}(y, n)) = n \times \left(x \log(\frac{x}{y}) + (1-x)... | 625941ccfbf16365ca6f62a1 |
def get_status(self, id): <NEW_LINE> <INDENT> cur = conn.cursor() <NEW_LINE> cur.execute( "SELECT ride_status FROM rides WHERE ride_id = (%s)", [id]) <NEW_LINE> status = [] <NEW_LINE> for s in cur.fetchall(): <NEW_LINE> <INDENT> status.append(s) <NEW_LINE> <DEDENT> return status | Function returns the status of a ride from the database | 625941cc0383005118ecf6c0 |
def threeSum(self, nums): <NEW_LINE> <INDENT> nums.sort() <NEW_LINE> arr = [] <NEW_LINE> for i in range(len(nums)-2): <NEW_LINE> <INDENT> l = i+1 <NEW_LINE> r = len(nums)-1 <NEW_LINE> while l < r: <NEW_LINE> <INDENT> key = 0-nums[i] <NEW_LINE> if nums[l] + nums[r] > key: <NEW_LINE> <INDENT> r -= 1 <NEW_LINE> <DEDENT> e... | :type nums: List[int]
:rtype: List[List[int]] | 625941cca17c0f6771cbe12d |
def test_interface(self): <NEW_LINE> <INDENT> form = data_form.Form('submit') <NEW_LINE> verify.verifyObject(IIterableMapping, form) | L{Form}s act as a read-only dictionary. | 625941cc5e10d32532c5f004 |
def evalOrderUIreorderIK(): <NEW_LINE> <INDENT> global gEvalOrder <NEW_LINE> win = 'evaluationOrderUI' <NEW_LINE> if not cmds.window(win, q=True, ex=True): <NEW_LINE> <INDENT> raise UserInputError('Evaluation Order UI is not open!!') <NEW_LINE> <DEDENT> gEvalOrder.ikReorder() <NEW_LINE> evalOrderUIrefreshList() | UI method for Evaluation Order setup tools
Reorder the evaluation order based on IK dependencies | 625941cc50485f2cf553ce77 |
def main(): <NEW_LINE> <INDENT> quick_sort_op = BigO('Quick Sort') <NEW_LINE> plotter = Plotter() <NEW_LINE> plotter.add_object(quick_sort_op) <NEW_LINE> for i in range(1000): <NEW_LINE> <INDENT> unsorted_array = np.random.randint(0, i+1, size=i+1) <NEW_LINE> quick_sort_op.time_function(quick_sort, array=unsorted_array... | Main function of this file. It runs a quick sort several times
Returns:
None: | 625941cc8e7ae83300e4b0aa |
def add_label(self, name, x=0, y=0, text='', color=(255, 255, 255), visible=True, **kwargs): <NEW_LINE> <INDENT> self.labels[name] = Label(self, name, x, y, text, color, visible, **kwargs) | Adds a label.
:type name: str
:param name: the label's name
:type x: float
:param x: x coord
:type y: float
:param y: y coord
:type text: str
:param text: label text
:type color: list(int * 3)
:param color: color | 625941cca4f1c619b28b0117 |
def numUniqueEmails(emails): <NEW_LINE> <INDENT> real_add_set = set() <NEW_LINE> for each in emails: <NEW_LINE> <INDENT> print(each) <NEW_LINE> local_one = each.split('@')[ 0 ] <NEW_LINE> yuming_one = each.split("@")[ 1 ] <NEW_LINE> print(yuming_one) <NEW_LINE> real_local = '' <NEW_LINE> for each in local_one: <NEW_LIN... | :type emails: List[str]
:rtype: int | 625941cc627d3e7fe0d68f2d |
def clean( self, step: Step = Step.PULL, *, part_names: Optional[List[str]] = None ) -> None: <NEW_LINE> <INDENT> self._executor.clean(initial_step=step, part_names=part_names) | Clean the specified step and parts.
Cleaning a step removes its state and all artifacts generated in that
step and subsequent steps for the specified parts.
:para step: The step to clean. If not specified, all steps will be
cleaned.
:param part_names: The list of part names to clean. If not specified,
all par... | 625941ccb5575c28eb68e0dd |
def sentenceToSpecialWord(self,sent): <NEW_LINE> <INDENT> if self.mask is None: <NEW_LINE> <INDENT> self.mask = readList('./data/user_dict.txt') <NEW_LINE> mask_dict = {} <NEW_LINE> for i in range(len(self.mask)): <NEW_LINE> <INDENT> mask_dict['word%d'%i] = self.mask[i] <NEW_LINE> <DEDENT> self.mask = mask_dict <NEW_LI... | 输入为一个句子,会将special word替换成特殊的词语
输出为替换了special word的句子 | 625941cc009cb60464c6348f |
def test_operations_without_creating_project(self): <NEW_LINE> <INDENT> simulate_cases = [False, True] <NEW_LINE> for simulate in simulate_cases: <NEW_LINE> <INDENT> for function in range(5): <NEW_LINE> <INDENT> yield (self._assert_normal_operation_no_instances, function, simulate) | Test operations when there is no instances in existence | 625941cce1aae11d1e749d94 |
def _isatty(self): <NEW_LINE> <INDENT> from sage.doctest import DOCTEST_MODE <NEW_LINE> if DOCTEST_MODE: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return os.isatty(sys.stdout.fileno()) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False | Test whether stdout is a TTY
If this test succeeds, you can assume that stdout is directly
connected to a terminal. Otherwise you should treat stdout as
being redirected to a file.
OUTPUT:
Boolean
EXAMPLES::
sage: from sage.misc.ascii_art import empty_ascii_art
sage: empty_ascii_art._isatty()
False | 625941cc99cbb53fe6792cc4 |
def __init__(self, old_owner): <NEW_LINE> <INDENT> self.tics = 0.0 <NEW_LINE> self.targetTics = 1.0 <NEW_LINE> self.suspendStart = None <NEW_LINE> self.set_default_prop('EndMessage', 'TimeUp') <NEW_LINE> self.set_default_prop('PulseMessage', 'TimeSet') <NEW_LINE> self.set_default_prop('Duration', 1.0) | Initialise a new timer. | 625941ccb5575c28eb68e0de |
def get_all_category_link(url, headless=False, disableimage=False): <NEW_LINE> <INDENT> options = Options() <NEW_LINE> if headless: <NEW_LINE> <INDENT> options.add_argument('--headless') <NEW_LINE> options.add_argument('--disable-gpu') <NEW_LINE> options.add_argument("window-size=1920,1080") <NEW_LINE> <DEDENT> if disa... | get all the items' link in the current category.
It returns a 2-element tuple list with url as the first element, categories list as the second element
example: [(urlA,[categoryA, categoryB]),(urlB,[categoryA, categoryB])]
It returns None when unexpected error happens
:param url:
:param headless:
:param disableimage:
:... | 625941cc07f4c71912b1155f |
def board_trade(self, playerState): <NEW_LINE> <INDENT> trait_cards = [playerState.trait_cards[i] for i in self.traits_for_species] <NEW_LINE> playerState.add_species_with_traits(trait_cards) | Effect: Remove any trait_cards at self.trait_card_index or in self.traits_for_species, adding a new species with
optional traits from the exchanged self.traits_for_species
:param playerState:
:return: Void | 625941cc24f1403a92600c44 |
def test_post(self): <NEW_LINE> <INDENT> self.assertRedirects(self.response, r('subscriptions:detail', 1)) | Valid POST must redirect to /inscricao/1/ | 625941cccc0a2c11143dcf6e |
def cb_add_files(self): <NEW_LINE> <INDENT> for a, b in self.factmap.items(): <NEW_LINE> <INDENT> print(a, b.__dict__) <NEW_LINE> <DEDENT> newfiles = tkfd.askopenfilenames( parent=self.root, title="Log selection", filetypes=(("Binary logs", "*.bin"),("Text logs", "*.log"), ("All files",'*'))) <NEW_LINE> for newfile in ... | Callback to add file(s) to our input file list. | 625941cc1b99ca400220ab8f |
def load_module(self, name): <NEW_LINE> <INDENT> self.find_module(name) <NEW_LINE> module = imp.new_module(name) <NEW_LINE> exec(self.current_module_code, module.__dict__) <NEW_LINE> sys.modules[name] = module <NEW_LINE> return module | Load module to sys.modules | 625941ccb7558d58953c4ff2 |
def queue_state(self, state_name: str, **kwargs: Any) -> None: <NEW_LINE> <INDENT> self.state_manager.queue_state(state_name, **kwargs) | Queue a state | 625941cc15baa723493c4053 |
def nonzero(self): <NEW_LINE> <INDENT> sel = sqlalchemy.sql.select([self._table.c.row,self._table.c.column]) <NEW_LINE> with self._engine.begin() as conn: <NEW_LINE> <INDENT> idx = conn.execute(sel).fetchall() <NEW_LINE> <DEDENT> return ([x[0] for x in idx],[x[1] for x in idx]) | Return a tuple of lists, representing the row and column indices,
respectively, of all of this matrix's stored values. It may actually
include stored zeros, just like nnz. | 625941cc283ffb24f3c559df |
def Render(self, dc): <NEW_LINE> <INDENT> e = AuiManagerEvent(wxEVT_AUI_RENDER) <NEW_LINE> e.SetManager(self) <NEW_LINE> e.SetDC(dc) <NEW_LINE> self.ProcessMgrEvent(e) | Fires a render event, which is normally handled by
L{OnRender}. This allows the render function to
be overridden via the render event.
This can be useful for painting custom graphics in the main window.
Default behavior can be invoked in the overridden function by calling
L{OnRender}.
:param `dc`: a `wx.DC` device co... | 625941cc97e22403b379d077 |
def get_error(self) -> int: <NEW_LINE> <INDENT> raise NotImplementedError('TBA') | * Get error code from upload
* @link https://www.php.net/manual/en/features.file-upload.errors.php | 625941ccfbf16365ca6f62a2 |
def del_fc(fc): <NEW_LINE> <INDENT> if arcpy.Exists(fc): <NEW_LINE> <INDENT> arcpy.Delete_management(fc) | Delete a feature class if it exists
:param fc: feature class to delete
:return: | 625941ccd58c6744b4257d3e |
def save_icon(self, icon_path: str): <NEW_LINE> <INDENT> zip_icon_path = self._apk.get_app_icon() <NEW_LINE> with apkfile.ZipFile(self._apk.apk_path) as z: <NEW_LINE> <INDENT> with z.open(zip_icon_path) as f: <NEW_LINE> <INDENT> with open(icon_path, 'wb') as w: <NEW_LINE> <INDENT> shutil.copyfileobj(f, w) | Args:
icon_path (str): should endwith .png | 625941cc460517430c394263 |
def roi_xy_bounds_check(self, pos): <NEW_LINE> <INDENT> new_h_pos = np.clip(pos[0], *self._scanning_logic.x_range) <NEW_LINE> new_v_pos = np.clip(pos[1], *self._scanning_logic.y_range) <NEW_LINE> in_bounds = new_h_pos == pos[0] and new_v_pos == pos[1] <NEW_LINE> return in_bounds, (new_h_pos, new_v_pos) | Check if the focus cursor is oputside the allowed range after drag
and set its position to the limit | 625941cc63b5f9789fde71c3 |
def set_up_patch(self, topatch, themock=None, **kwargs): <NEW_LINE> <INDENT> if themock is None: <NEW_LINE> <INDENT> themock = Mock() <NEW_LINE> <DEDENT> if "return_value" in kwargs: <NEW_LINE> <INDENT> themock.return_value = kwargs["return_value"] <NEW_LINE> <DEDENT> patcher = patch(topatch, themock) <NEW_LINE> self.a... | Patch a function or class
:param topatch: string The class to patch
:param themock: optional object to use as mock
:return: mocked object | 625941cc29b78933be1e578a |
def plot(y, x, logdir, name, xlabel=None, ylabel=None, title=None): <NEW_LINE> <INDENT> plt.close() <NEW_LINE> plt.plot(y,x) <NEW_LINE> if xlabel: <NEW_LINE> <INDENT> plt.xlabel(xlabel) <NEW_LINE> <DEDENT> if ylabel: <NEW_LINE> <INDENT> plt.ylabel(ylabel) <NEW_LINE> <DEDENT> if title: <NEW_LINE> <INDENT> plt.title = ti... | Make plot of training curves | 625941cce5267d203edcdd7c |
def _gather_scales(self, program, scope): <NEW_LINE> <INDENT> def _gather_input_scale(): <NEW_LINE> <INDENT> target_ops = [] <NEW_LINE> skip_ops = utils.fake_quantize_dequantize_op_types + ["moving_average_abs_max_scale"] <NEW_LINE> for block in program.blocks: <NEW_LINE> <INDENT> for op in block.ops: <N... | Get all scales from fake ops, save them into the corresponding ops
and delete all moving_average_abs_max_scale ops. | 625941ccd164cc6175782e2b |
def __call__(self, T, n, num=1, x0=None, method="exact", **kwargs): <NEW_LINE> <INDENT> if x0 is None: <NEW_LINE> <INDENT> x0 = self.x0 <NEW_LINE> <DEDENT> assert x0 >= 0 <NEW_LINE> num = int(num) <NEW_LINE> assert T>=0 and num>0 <NEW_LINE> assert n > 0 <NEW_LINE> h = T/n <NEW_LINE> if method == "exact": <NEW_LINE> <IN... | Function used to generate the discretized CIR process.
* Params:
T : Non-negative real number.
n : Positive integer. The number of discretized time points.
num : Positive integer. The number of independent CIR processes to generate.
x0 : Real number. The initial value of V. If x0 is None, self.x0 is us... | 625941ccbaa26c4b54cb11fe |
def options_for_frame(self, frame, vehicle, opts): <NEW_LINE> <INDENT> ret = None <NEW_LINE> frames = self.options[vehicle]["frames"] <NEW_LINE> if frame in frames: <NEW_LINE> <INDENT> ret = self.options[vehicle]["frames"][frame] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for p in ["octa", "tri", "y6", "firefly", "h... | Return informatiom about how to sitl for frame e.g. build-type==sitl | 625941cc63f4b57ef00011f8 |
def get_docID(list, index): <NEW_LINE> <INDENT> return int(list[index].split("/")[0]) | Takes in a list and an index and returns the document ID at that index. | 625941cc3d592f4c4ed1d14c |
def RPR_SetProjectMarker(markrgnindexnumber,isrgn,pos,rgnend,name): <NEW_LINE> <INDENT> a=_ft['SetProjectMarker'] <NEW_LINE> f=CFUNCTYPE(c_byte,c_int,c_byte,c_double,c_double,c_char_p)(a) <NEW_LINE> t=(c_int(markrgnindexnumber),c_byte(isrgn),c_double(pos),c_double(rgnend),rpr_packsc(name)) <NEW_LINE> r=f(t[0],t[1],t[2]... | Python: Boolean RPR_SetProjectMarker(Int markrgnindexnumber, Boolean isrgn, Float pos, Float rgnend, String name) | 625941ccb57a9660fec33961 |
def getTotalPop(self): <NEW_LINE> <INDENT> pass | Gets the current total virus population.
returns: The total virus population (an integer) | 625941ccb57a9660fec33962 |
def hash_client_test(): <NEW_LINE> <INDENT> hash_client = HashClient([('192.168.24.138', 11211),('192.168.24.139', 11211),('192.168.24.140', 11211)]) <NEW_LINE> hash_key_prefix='hash_test_key' <NEW_LINE> hash_value_prefix='hash_test_value' <NEW_LINE> kv_check(hash_client,hash_key_prefix,hash_value_prefix) | 一致性Hash客户端,通过一致性HASH算法,减少因为某个节点宕机而导致整个集群缓存失效的问题,但是由于set key的时候需要计算hash,所以效率会有一定的影响 | 625941cc099cdd3c635f0d39 |
def simulate(self, times, full=False, **kwargs): <NEW_LINE> <INDENT> y = scipy.integrate.odeint(self, self.y0, times, **kwargs) <NEW_LINE> if full: <NEW_LINE> <INDENT> return y <NEW_LINE> <DEDENT> elif self._do_agg: <NEW_LINE> <INDENT> return self.obs(y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return y | Use numerical integration to simulate the model. For more information,
`scipy.integrate.odeint`.
Parameters
==========
times : times
The system is evaluated at these times (optional).
full : bool
Return the full system, not just the observables variables.
(optional.)
Notes
=====
If neither `y0` nor `time... | 625941cc45492302aab5e3a0 |
@api_view(['GET', 'POST']) <NEW_LINE> def score_teacher_history(request): <NEW_LINE> <INDENT> scores = Take.objects.filter(course__course_id=request.data["cid"], teacher_id=request.data["pid"]).values_list( 'score', flat=True).order_by("score") <NEW_LINE> it = scores.iterator() <NEW_LINE> count = scores.count() <NEW_LI... | :param request.data["cid"], request.data["pid"]
:return number of all students in the course and teacher,
average grade point in the course and teacher | 625941ccf8510a7c17cf97da |
def test_log_parameter(): <NEW_LINE> <INDENT> with tempfile.TemporaryDirectory() as path: <NEW_LINE> <INDENT> client = MLClient(backend='local', backend_uri=path, experiment="test_exp") <NEW_LINE> with client.start_run(1) as run: <NEW_LINE> <INDENT> run.log_parameter('alpha', 0.05) <NEW_LINE> run.log_parameter('optimiz... | Test parameters logging | 625941ccad47b63b2c50a05d |
def decrypt_message(self): <NEW_LINE> <INDENT> best_permutation = { 'permutation': VOWELS_LOWER, 'valid_word_count': 0 } <NEW_LINE> for permutation in get_permutations(VOWELS_LOWER): <NEW_LINE> <INDENT> current_transpose_dict = self.build_transpose_dict(permutation) <NEW_LINE> transposed_message = self.apply_transpose(... | Attempt to decrypt the encrypted message
Idea is to go through each permutation of the vowels and test it
on the encrypted message. For each permutation, check how many
words in the decrypted text are valid English words, and return
the decrypted message with the most English words.
If no good permutations are found... | 625941ccc432627299f04d24 |
def test_invalid_add_code(self): <NEW_LINE> <INDENT> with self.client: <NEW_LINE> <INDENT> response = self.client.post( '/google', data=json.dumps({"headers": {"Authorization": {}}}), content_type='application/json', ) <NEW_LINE> data = json.loads(response.data.decode()) <NEW_LINE> self.assertEqual(response.status_code... | Ensure error is thrown if invalid access code is sent. | 625941cc6fb2d068a760f17b |
@task <NEW_LINE> def clean(context): <NEW_LINE> <INDENT> run('rm -rf build/') <NEW_LINE> run('rm -rf dist/') <NEW_LINE> run('rm -rf chanjo.egg-info') <NEW_LINE> run("find . -name '*.pyc' -delete") <NEW_LINE> run("find . -name '*.pyo' -delete") <NEW_LINE> run("find . -name '*~' -delete") <NEW_LINE> run('find . -name __p... | clean - remove build artifacts. | 625941cc187af65679ca51fd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.