code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get(): <NEW_LINE> <INDENT> return _mouse.get_cursor() | Gets the current cursor settings.
Public. | 625941d7baa26c4b54cb1374 |
def get_downloaded_keywords(self): <NEW_LINE> <INDENT> keywords = dict() <NEW_LINE> cursor = self.db.papers.find() <NEW_LINE> for item in cursor: <NEW_LINE> <INDENT> if item['keyword'] in keywords: <NEW_LINE> <INDENT> keywords[item['keyword']] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> keywords[item['keyword']]... | Get the list of keywords downloaded so far
:return: Set of downloaded keywords | 625941d7627d3e7fe0d690a7 |
def create_data(): <NEW_LINE> <INDENT> rng = np.random.default_rng() <NEW_LINE> x = np.linspace(0, 2 * np.pi) <NEW_LINE> y = 3 * np.sin(x) + 2 * np.cos(x) + rng.normal(0, 0.2, len(x)) <NEW_LINE> np.savetxt("daten.txt", np.column_stack([x, y]), header="x y") | Create the data file | 625941d74527f215b584c6ab |
def _filter_coverage_for_added_lines(self, diff, coverage): <NEW_LINE> <INDENT> if not diff: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> diff_lines = diff.encode('utf-8').splitlines() <NEW_LINE> current_file = None <NEW_LINE> line_number = None <NEW_LINE> coverage_by_added_line = [] <NEW_LINE> for line in diff_... | This function takes a diff (text based) and a map of file names to the coverage for those files and
returns an ordered list of the coverage for each "addition" line in the diff.
If we don't have coverage for a specific file, we just mark the lines in those files as unknown or 'N'. | 625941d73d592f4c4ed1d2c0 |
def create_all_odd_vectors(n) -> [Qobj]: <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for i in range(2 ** n): <NEW_LINE> <INDENT> binformat = bin(i)[2:].zfill(n) <NEW_LINE> if 1 == binformat.count('0') % 2: <NEW_LINE> <INDENT> ret.append(create_vector_from_string(binformat)) <NEW_LINE> <DEDENT> <DEDENT> return ret | Creates an array of all the vectors in the computational basis with an odd number of 1's
:param n: basis size
:return: array | 625941d7442bda511e8be66c |
def execute(self, command, capture=False): <NEW_LINE> <INDENT> motor, command = self.parse(command) <NEW_LINE> context = self if not motor else self.context['motors'][motor] <NEW_LINE> if self.debug: <NEW_LINE> <INDENT> if motor: <NEW_LINE> <INDENT> self.status("EXEC: {0} -> {1}".format(motor, command)) <NEW_LINE> <DED... | Executes the command in the current context of this shell, if no
motor is indicated as the target of the command. If the command
indicates it's targeted at a motor, the command will be executed in
the context of that motor.
The output of the command is captured and returned if the capture
parameter is set. So anything... | 625941d73c8af77a43ae39f8 |
def RSI(df, n): <NEW_LINE> <INDENT> UpI = [0] <NEW_LINE> DoI = [0] <NEW_LINE> for k in range(len(df.index)-1): <NEW_LINE> <INDENT> UpMove = df['High'][k + 1] - df['High'][k] <NEW_LINE> DoMove = df['Low'][k] - df['Low'][k + 1] <NEW_LINE> if UpMove > DoMove and UpMove > 0: <NEW_LINE> <INDENT> UpD = UpMove <NEW_LINE> <DED... | Relative Strength Index | 625941d756ac1b37e6264423 |
def testCommentNextWithQueryString(self): <NEW_LINE> <INDENT> a = Article.objects.get(pk=1) <NEW_LINE> data = self.getValidData(a) <NEW_LINE> data["next"] = "/somewhere/else/?foo=bar" <NEW_LINE> data["comment"] = "This is another comment" <NEW_LINE> response = self.client.post("/post/", data) <NEW_LINE> self.assertRedi... | The `next` key needs to handle already having a query string (#10585) | 625941d74a966d76dd551267 |
def argtype_dir_r(prospective_dir): <NEW_LINE> <INDENT> if not os.path.isdir(prospective_dir): <NEW_LINE> <INDENT> raise Exception("readable_dir:{0} is not a valid directory path".format(prospective_dir)) <NEW_LINE> <DEDENT> if os.access(prospective_dir, os.R_OK): <NEW_LINE> <INDENT> return prospective_dir <NEW_LINE> <... | defines an argparse arg that's a readable directory | 625941d771ff763f4b5498e5 |
def MoreDetailedLevel(self, Downsample): <NEW_LINE> <INDENT> BestChoice = None <NEW_LINE> for Level in self.Levels: <NEW_LINE> <INDENT> if Level.Downsample < Downsample: <NEW_LINE> <INDENT> BestChoice = Level <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return BestChoice <NEW_LINE> <DEDENT> <DEDENT> return BestChoice | Return an existing level with more detail than the provided downsample level | 625941d7bde94217f3683045 |
def update(self, id, data): <NEW_LINE> <INDENT> db_obj = objects.registry.Plan.get_by_uuid(self.context, id) <NEW_LINE> db_obj.update(data) <NEW_LINE> self._update_raw_content(db_obj, data) <NEW_LINE> db_obj.save(self.context) <NEW_LINE> return db_obj | Modify a resource. | 625941d73346ee7daa2b2fc3 |
def jsonrpc(self, f): <NEW_LINE> <INDENT> self.jsonrpc_procedures[f.__name__] = f <NEW_LINE> return f | Example:
Use as::
service = Service()
@service.jsonrpc
def myfunction(a, b):
return a + b
def call():
return service()
Then call it with:
wget http://..../app/default/call/jsonrpc/myfunction?a=hello&b=world | 625941d7b545ff76a891406c |
def __init__(self, signal): <NEW_LINE> <INDENT> self.signal = np.matrix(signal) <NEW_LINE> self.sample_rate = DEFAULT_SAMPLE_RATE | signal - a list of numbers indicating values in the signal | 625941d7fff4ab517eb2f693 |
def position_get(db, id): <NEW_LINE> <INDENT> cur = db.cursor(); <NEW_LINE> list = cur.execute("select * from positions") <NEW_LINE> for row in list.fetchall(): <NEW_LINE> <INDENT> if row[0] == id: <NEW_LINE> <INDENT> return row <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None | Return the details of the position with the given id
or None if there is no position with this id
Returns a tuple (id, timestamp, owner, title, location, company, description) | 625941d77c178a314d6ef6b9 |
def uploadFile(self,path): <NEW_LINE> <INDENT> response = requests.post('https://api.imagga.com/v1/content', auth=(self.apikey, self.secret), files={'image': open(path, 'r')}) <NEW_LINE> json_data = json.loads(response.text) <NEW_LINE> uploadedData=json_data[u'uploaded'][0] <NEW_LINE> resourceId=uploadedData[u'id'] <NE... | Used to upload a file using the imagga API and recevies a resource Id in response from the API that
can be used later to fetch the tags for that image
:param path :
The file path where the image that we want to upload is located | 625941d7bde94217f3683046 |
def delete_cache(self, news_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> con = redis.Redis( connection_pool=pool ) <NEW_LINE> con.delete(news_id) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> del con | 删除已缓存的新闻 | 625941d715baa723493c41ce |
def _substitute_entities(self, xml_string, entity_dict): <NEW_LINE> <INDENT> for item in entity_dict.keys(): <NEW_LINE> <INDENT> xml_string = re.sub('&%s;' % item, entity_dict[item], xml_string) <NEW_LINE> <DEDENT> return xml_string | Give it an XML string that potentially contains entities, and a dictionary
of entity values, and it interpolates the entity values and returns the
processed string. | 625941d76fb2d068a760f2f7 |
def main(): <NEW_LINE> <INDENT> @value_range(value=[1, 3]) <NEW_LINE> def test1(a, b): <NEW_LINE> <INDENT> print(a + b) <NEW_LINE> <DEDENT> test1(1, 3) <NEW_LINE> @value_range(value=[1, 3]) <NEW_LINE> @type_limit <NEW_LINE> def test2(a: int, b: int) -> int: <NEW_LINE> <INDENT> return a + b <NEW_LINE> <DEDENT> result2 =... | 注释掉某些部分自己调试
:return: | 625941d730c21e258bdfa6f5 |
@app.route('/catalog/<int:category_id>/items') <NEW_LINE> def items(category_id): <NEW_LINE> <INDENT> category = dao.getCategory(category_id) <NEW_LINE> items = dao.getItemsByCategory(category_id) <NEW_LINE> return render_template('items.html', category=category, items=items) | Shows the list of items in the selected category
Args:
category_id: id of the category whose items will be shown in the page | 625941d7e64d504609d74a97 |
def put(self,surveyname): <NEW_LINE> <INDENT> data = resources.parsers.ParseSurveysPut.parser.parse_args() <NEW_LINE> survey = SurveyModel.find_survey_by_name(surveyname) <NEW_LINE> if survey is None: <NEW_LINE> <INDENT> return {'message': "Can not change status, survey '{}' does not exist".format(surveyname)}, 400 <NE... | Server REST resource:
Changes the status of a survey.
After a survey is created, it can be paused or it's status can be changed from 'created' -> 'active' -> 'done'. | 625941d7d58c6744b4257eb5 |
def random_int(self, min=0, max=9999, step=1): <NEW_LINE> <INDENT> return self.generator.random.randrange(min, max + 1, step) | Generate a random integer between two integers ``min`` and ``max`` inclusive
while observing the provided ``step`` value.
This method is functionally equivalent to randomly sampling an integer
from the sequence ``range(min, max + 1, step)``.
:sample:
:sample size=10: min=0, max=15
:sample size=10: min=0, max=15, step... | 625941d7d53ae8145f87a4c3 |
def _restore(self): <NEW_LINE> <INDENT> if 'custom' in self.metadata: <NEW_LINE> <INDENT> values = self.metadata['custom'].split() <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> self._yupana.custom[i] = int(values[i]) <NEW_LINE> <DEDENT> <DEDENT> if 'mode' in self.metadata: <NEW_LINE> <INDENT> if self.metadata['mode... | Restore the yupana state from metadata | 625941d75166f23b2e1a53b0 |
def read_cell_data_by_coordinates(self, sheetname, column, row): <NEW_LINE> <INDENT> my_sheet_index = self.sheetNames.index(sheetname) <NEW_LINE> sheet = self.wb.sheet_by_index(my_sheet_index) <NEW_LINE> cellValue = sheet.cell(int(row), int(column)).value <NEW_LINE> return cellValue | Uses the column and row to return the data from that cell.
Arguments:
| Sheet Name (string) | The selected sheet that the cell value will be returned from. |
| Column (int) | The column integer value that the cell value will be returned from. |
| Row (int) | The... | 625941d724f1403a92600dbb |
def get_artists(self, limit=50, cacheable=True, stream=False): <NEW_LINE> <INDENT> def _get_artists(): <NEW_LINE> <INDENT> for node in _collect_nodes( limit, self, self.ws_prefix + ".getArtists", cacheable, stream=stream ): <NEW_LINE> <INDENT> name = _extract(node, "name") <NEW_LINE> playcount = _number(_extract(node, ... | Returns a sequence of Album objects
if limit==None it will return all (may take a while) | 625941d776d4e153a657ed89 |
def scalar_assemble(a_scalar, a_conv, Ta , dt, M, scalar_components, nu, Schmidt, b, K, x_1, b0, **NS_namespace): <NEW_LINE> <INDENT> pass | Assemble scalar equation. | 625941d7d486a94d0b98e39d |
def momrelnorm(mom1, mom2): <NEW_LINE> <INDENT> ret = np.array(mom1)-np.array(mom2) <NEW_LINE> return np.sqrt(kdot(ret, ret)) | Find the norm of the relative momentum | 625941d7d164cc6175782fa5 |
def add_node(self, iri: URIRef, data: Optional[Dict] = None) -> Dict: <NEW_LINE> <INDENT> n = self.prefix_manager.contract(str(iri)) <NEW_LINE> if n == iri: <NEW_LINE> <INDENT> if self.prefix_manager.has_urlfragment(iri): <NEW_LINE> <INDENT> n = rdflib.namespace.urldefrag(iri).fragment <NEW_LINE> <DEDENT> <DEDENT> if n... | Add a node to cache.
Parameters
----------
iri: rdflib.URIRef
IRI of a node
data: Optional[Dict]
Additional node properties
Returns
-------
Dict
The node data | 625941d7b830903b967e9b60 |
def dhdP_h(P, h): <NEW_LINE> <INDENT> x = x_h(P, h) <NEW_LINE> return x * dhgdP(P) + (1 - x) * dhfdP(P) + dxdP_h(P, h) * dhfgdP(P) | Derivative of equilibrium specific enthalpy [kJ m^3 / kg kJ]
w.r.t. pressure @ a given equilibrium enthalpy | 625941d71d351010ab855d73 |
def predict(image_path, model, topk=5,device='cuda'): <NEW_LINE> <INDENT> img = process_image(image_path) <NEW_LINE> img_tensor = torch.from_numpy(img).type(torch.FloatTensor) <NEW_LINE> img_model = img_tensor.unsqueeze(0) <NEW_LINE> img_model = img_model.to(device).float() <NEW_LINE> model.to(device) <NEW_LINE> probs ... | Predict the class (or classes) of an image using a trained deep learning model.
| 625941d7dc8b845886cb578d |
def dateFromFilename(fn): <NEW_LINE> <INDENT> tokens = fn.split('-') <NEW_LINE> return date(2000 + int(tokens[3][0:2]), int(tokens[1]), int(tokens[2])) | [String] fn => [datetime] date embedded in the file name
The web and database backup files are named as:
web-mm-dd-yy.tar.gz
db-mm-dd-yy.sql.gz
convert the file name to a datetime.date object | 625941d79b70327d1c4e102d |
def hash_answer(o, precision=5): <NEW_LINE> <INDENT> def str_answer(o, memo): <NEW_LINE> <INDENT> if id(o) in memo: <NEW_LINE> <INDENT> return '...' <NEW_LINE> <DEDENT> memo.add(id(o)) <NEW_LINE> if isinstance(o, float): <NEW_LINE> <INDENT> s = 'float' + format(o, '.{}e'.format(precision)) <NEW_LINE> <DEDENT> elif isin... | return a hash to represent the answer in equality tests | 625941d7fff4ab517eb2f694 |
def get_duration(self, current_time): <NEW_LINE> <INDENT> return current_time - self.slam.get_data(node_name=self.last_point_name)['time'] | compute duration between current time and last time.
:param current_time: int, a current time in seconds.
:return: a duration since last time.
:rtype: int | 625941d7b545ff76a891406d |
def configure_user(self, user): <NEW_LINE> <INDENT> return user | Configures a user after creation and returns the updated user.
By default, returns the user unmodified. | 625941d7f548e778e58cd7d6 |
def set_axis_labels(self, *args): <NEW_LINE> <INDENT> self.data_info.set('nDims', len(args)) <NEW_LINE> axis_labels = [] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, dict): <NEW_LINE> <INDENT> axis_labels.append(arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> axis = arg... | Set the axis labels associated with each data dimension.
:arg str: Each arg should be of the form ``name.unit``. If ``name`` is a data_obj.meta_data entry, it will be output to the final .nxs file. | 625941d7046cf37aa974cf9d |
def test_get_networks(self): <NEW_LINE> <INDENT> mock_responses = [] <NEW_LINE> for page in fake_compute.LIST_NETWORKS_RESPONSES: <NEW_LINE> <INDENT> mock_responses.append(({'status': '200'}, page)) <NEW_LINE> <DEDENT> http_mocks.mock_http_response_sequence(mock_responses) <NEW_LINE> results = self.gce_api_client.get_n... | Test get networks. | 625941d7507cdc57c6306f36 |
def follow(self, account_name): <NEW_LINE> <INDENT> params = {"accountName": account_name} <NEW_LINE> qry = ServiceOperationQuery(self, "Follow", params, None, None, None) <NEW_LINE> self.context.add_query(qry) <NEW_LINE> return self | Add the specified user to the current user's list of followed users.
:param str account_name: Account name of the specified user. | 625941d766673b3332b922e9 |
def RemoveDuplicateSortedArray(string): <NEW_LINE> <INDENT> if not string: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return ''.join(sorted(set(string))) | >>> RemoveDuplicateSortedArray('0001123333')
'0123' | 625941d707f4c71912b116db |
def canJump(self, nums): <NEW_LINE> <INDENT> if len(nums) < 2: return True <NEW_LINE> if nums[0] == 0 : return False <NEW_LINE> max_length = 0 <NEW_LINE> for index, val in enumerate(nums[:-1]): <NEW_LINE> <INDENT> if max_length < index : return False <NEW_LINE> max_length = max(max_length, index+ val) <NEW_LINE> <DEDEN... | :type nums: List[int]
:rtype: bool | 625941d76fece00bbac2d998 |
def test_1(self): <NEW_LINE> <INDENT> self.start() <NEW_LINE> el = self.xpath('button') <NEW_LINE> el.click() <NEW_LINE> alert = self.driver.switch_to.alert <NEW_LINE> self.assertEqual('Some \btext', alert.text) | Test case 1 | 625941d7cb5e8a47e48b7cff |
def __init__(self, path): <NEW_LINE> <INDENT> self.glove_key_type = None <NEW_LINE> self.dic, self.vectors = self._load_glove(path) <NEW_LINE> self.rev = {val:key for key, val in self.dic.items()} <NEW_LINE> assert len(self.dic) == len(self.rev) <NEW_LINE> logging.info('%s: %d entries, %d dim - not trainable', os.path.... | Args:
path: file path | 625941d73539df3088e2e5a2 |
def get_info_about_array(self, array_name, included_info=None, mask_array_name=None, key_suffix=''): <NEW_LINE> <INDENT> included_info = included_info or {} <NEW_LINE> summary = self._get_summary_info(array_name, included_info, mask_array_name, key_suffix) <NEW_LINE> result = dict() <NEW_LINE> for key, value in six.ite... | :return: dictionary {label: value} about an attribute of type mapped.Array
Generic information, like Max/Min/Mean/Var are to be retrieved for this array_attr | 625941d730dc7b7665901bbc |
def _l1median(X,x0, method='SLSQP',tol=1e-8,options={'maxiter':2000},**kwargs): <NEW_LINE> <INDENT> mu = spo.minimize(_l1m_objective,x0,args=(X), jac=_l1m_jacobian,tol=tol,options=options,method=method) <NEW_LINE> return(mu) | Optimization for l1median | 625941d70a366e3fb873ea73 |
def grab_image(self, url): <NEW_LINE> <INDENT> if url is None: <NEW_LINE> <INDENT> logging.error("Error: No webcam URL") <NEW_LINE> return <NEW_LINE> <DEDENT> response = requests.get(url) <NEW_LINE> self.image = Image.open(BytesIO(response.content)) | Download an image from an URL.
:param url: URL of the image | 625941d7498bea3a759b9d06 |
def test_bad_bidipairedbrackettype(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> uniprops.get_unicode_property('bidipairedbrackettype', 'bad') | Test `Bidi Paired Bracket Type` property with bad value. | 625941d799fddb7c1c9de5e8 |
def trade_deals(self, pair, limit=1): <NEW_LINE> <INDENT> params = { "nonce": self._nonce, "pair": pair } <NEW_LINE> headers = self._sign_payload(params) <NEW_LINE> api_url = '/user_trades' <NEW_LINE> r = requests.post(self.URL+api_url, params, headers=headers, verify=True) <NEW_LINE> json_resp = r.json() <NEW_LINE> if... | Return last deal.
:param pair:
:param limit:
:return: | 625941d78e71fb1e9831da00 |
def create_default_plugins(request, placeholders, template, lang): <NEW_LINE> <INDENT> from cms.api import add_plugin <NEW_LINE> def _create_default_plugins(placeholder, confs, parent=None): <NEW_LINE> <INDENT> plugins, descendants = [], [] <NEW_LINE> addable_confs = (conf for conf in confs if has_plugin_permission(req... | Create all default plugins for the given ``placeholders`` if they have
a "default_plugins" configuration value in settings.
return all plugins, children, grandchildren (etc.) created | 625941d7009cb60464c63608 |
def test_vl_spec_for_detail_edge_values(): <NEW_LINE> <INDENT> detail = api.Detail('foobar') <NEW_LINE> try: <NEW_LINE> <INDENT> detail.shorthand = 'sum(foobar):O' <NEW_LINE> raise Exception('Should have thrown for illegal aggregation value.') <NEW_LINE> <DEDENT> except TraitError: <NEW_LINE> <INDENT> pass <NEW_LINE> <... | Check edge values | 625941d7ad47b63b2c50a1d7 |
def increment(self, delta=1, sample_rate=1.0): <NEW_LINE> <INDENT> self.send(delta, sample_rate) | Increment the counter.
:param float delta: The amount to increase the counter by.
:param float sample_rate: What rate this counter is sampled at. [0-1]. | 625941d7cc0a2c11143dd0e8 |
def get_field_from_identifier(self, node_identifier, sf_node_list, field_name='name'): <NEW_LINE> <INDENT> node_name = "" <NEW_LINE> for sf_node in sf_node_list: <NEW_LINE> <INDENT> if field_name not in sf_node.keys(): <NEW_LINE> <INDENT> raise AnsibleFilterError( '{} is not a valid ListAllNodes payload field'.format(f... | Uses the name, sip, or mip, or nodeID to return the specific NodeInfo field
from the ListAllNodes payload
:param int|ipaddr|str node_identifier: The Identifier to return the node ID for
:param list sf_node_list: List of nodes from the ListAllNodes API
:param str field_name: The field to return (default: name)
:return... | 625941d767a9b606de4a8110 |
def __set_y(self, *args): <NEW_LINE> <INDENT> return _moose.Compartment___set_y(self, *args) | __set_y(self, double y) | 625941d7656771135c3ebac8 |
def zoom_one(self): <NEW_LINE> <INDENT> im_size = self.current_scan.image.size <NEW_LINE> y_size = im_size[1] <NEW_LINE> y_clip = y_size * 0.15 <NEW_LINE> self.current_scan.axlimits = [0, self.current_scan.image.size[0], y_size - y_clip, y_clip] <NEW_LINE> self.redraw_scan() | Zooms the plot to only show the middle 70% of the y-axis.
Meant to encompass only the hand. | 625941d7090684286d50ef3f |
def zhuNaHotel(): <NEW_LINE> <INDENT> pass | 调用住哪的酒店api | 625941d7a79ad161976cc39d |
def centerOfMassDeterminator(self): <NEW_LINE> <INDENT> atomic_weight = np.array([atomicmass_dict[atom] for atom in self.atoms]) <NEW_LINE> multiplied_coords = atomic_weight*self.coords.T <NEW_LINE> return np.sum(multiplied_coords, axis =1)/np.sum(atomic_weight) | Calculates the position of the center of mass
input:
molecule: tuple as generated by the readData function
output:
the position of the center of mass | 625941d7be7bc26dc91cd854 |
def add_fd(self, fd, log_file, log_level=None): <NEW_LINE> <INDENT> if log_file is not None: <NEW_LINE> <INDENT> log_path = os.path.join(self._LOG_DIR, log_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_path = None <NEW_LINE> <DEDENT> writer = LogWriter(fd, log_path, log_level) <NEW_LINE> self._add_writers_que... | Begin handling new file descriptor
This method adds given file descriptor to the set monitored by
internal poll() call and creates new LogWriter instance for it.
Args:
fd (obj: python file descriptor): file descriptor from which log
lines should be read.
log_file (str): if not None - log all the gathe... | 625941d7283ffb24f3c55b57 |
def get_logger(appname=None, level=None): <NEW_LINE> <INDENT> avail_levels = {'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL} <NEW_LINE> appname = appname or os.environ.get('APPNAME', DEFAULT_APPNAME) <NEW_LINE> loglevel = str(level or os.e... | Get a logger object for application-wide use. | 625941d7fb3f5b602dac38ed |
def search_file_path(context, xml_file): <NEW_LINE> <INDENT> xml_file = set_native_slash(xml_file) <NEW_LINE> found_xml_file = get_actual_filename(context, xml_file) <NEW_LINE> if found_xml_file is None: <NEW_LINE> <INDENT> message( context, '{} file not exists. '.format(xml_file), 'error' ) <NEW_LINE> return None <NEW... | Util function for checking file in path. | 625941d70fa83653e4657212 |
def _attach(self, visual): <NEW_LINE> <INDENT> raise NotImplementedError(self) | Called when a filter should be attached to a visual.
Parameters
----------
visual : instance of BaseVisual
The visual that called this. | 625941d7462c4b4f79d1d928 |
def extract(self, Idx): <NEW_LINE> <INDENT> assert(Idx.shape[1] == 3) <NEW_LINE> n = Idx.shape[0] <NEW_LINE> tileWidth = self._Xb.shape[2] <NEW_LINE> if n > self._Xb.shape[0]: <NEW_LINE> <INDENT> self._Xb = np.zeros( (n,) + self._Xb.shape[1:], dtype=np.float32) <NEW_LINE> self._Yb = np.zeros( (n, self._Yb.shape[1]), dt... | Idx : an (n x 3) matrix, where the columns correspond to pixel
depth, row and column. | 625941d7d10714528d5fff3d |
def ecb_chosenprefix(encfunc, prefixindex=0, blocklen=16): <NEW_LINE> <INDENT> my_pad = int2byte(ord('A')) <NEW_LINE> plaintext = binary_type() <NEW_LINE> ciphertext = encfunc(binary_type()) <NEW_LINE> if prefixindex >= len(ciphertext): <NEW_LINE> <INDENT> return binary_type() <NEW_LINE> <DEDENT> prefixblock = prefixin... | An implementation of the chosen prefix attack against AES ECB.
This attack assumes that the attacker can insert an arbitrary string in the plaintext, and has access to an oracle encryption function which can provide the corresponding ciphertext.
NB: the attack can only decrypt the plaintext that follows the prefix.
A... | 625941d7dd821e528d63b400 |
@pytest.mark.parametrize("invalid_input", ['+','åäö']) <NEW_LINE> def test_invalid_char(invalid_input): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> mycrypt.encode(invalid_input) | Invalid characters should result in ValueError | 625941d745492302aab5e51d |
def source_to_obj_path(backend, filename): <NEW_LINE> <INDENT> _, source_file = os.path.split(filename) <NEW_LINE> source_prefix, _ = os.path.splitext(source_file) <NEW_LINE> return os.path.join(BUILD_DIRS[backend], source_prefix + '.o') | Converts a source code filename into an assembly output filename.
>>> source_to_obj_path('linux_x86', 'a/b/c/foo.lisp')
'build/linux_x86/foo.o' | 625941d77c178a314d6ef6ba |
def wiggleMaxLength(self, nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> up = down = 1 <NEW_LINE> for i in range(0, len(nums) - 1): <NEW_LINE> <INDENT> a, b = nums[i], nums[i + 1] <NEW_LINE> if a < b: <NEW_LINE> <INDENT> up, down = down + 1, down <NEW_LINE> <DEDENT> elif a > b:... | :type nums: List[int]
:rtype: int | 625941d755399d3f0558890c |
def terminate_connection(self, volume, connector): <NEW_LINE> <INDENT> volumename = volume['name'] <NEW_LINE> LOG.info(_LI("Terminate connection: %(volume)s."), {'volume': volumename}) <NEW_LINE> self._unmap_lun(volume, connector) | Disallow connection from connector.
:params volume: the volume Object
:params connector: the connector Object | 625941d77b25080760e396b0 |
def cleanRevisions(self): <NEW_LINE> <INDENT> rev = self.revisions() <NEW_LINE> rev2 = [] <NEW_LINE> now = time.time() <NEW_LINE> rule = settings.revisions["rules"] <NEW_LINE> revs = {} <NEW_LINE> for i in rule: <NEW_LINE> <INDENT> revs[i] = [] <NEW_LINE> <DEDENT> for r in rev: <NEW_LINE> <INDENT> for span in sorted(ru... | Keep only one some the revisions. | 625941d701c39578d7e75093 |
def load_ct_folder(folder, return_tags='middle'): <NEW_LINE> <INDENT> folder = pathlib.Path(folder) <NEW_LINE> files = [] <NEW_LINE> logger.info('glob: {}'.format(folder)) <NEW_LINE> for fpath in folder.glob('**/*'): <NEW_LINE> <INDENT> logger.debug("loading: %s", fpath) <NEW_LINE> files.append(pydicom.read_file(fpath)... | Parameters
----------
folder : string
string describing the location of a folder.
return_tags : string, optional, ['first', 'last', 'middle']
which dicom file to return with the image structure. Default is the central
Returns
-------
img3d : np.array
3d array containing CT data.
d : pydicom.Dataset
de... | 625941d7287bf620b61d3cba |
def set_context_menu_fn( self, fn_context_menu, fn_folder_menu, fn_empty_menu, fn_do_menu_command, fn_do_folder_menu_command, fn_do_empty_command, ): <NEW_LINE> <INDENT> self.fn_context_menu = fn_context_menu <NEW_LINE> self.fn_do_menu_command = fn_do_menu_command <NEW_LINE> self.fn_folder_context_menu = fn_folder_menu... | Set the function to call to get context menu items
fn_context_menu - a function that returns a list of menu items. The calling
signature is fn_menu(paths) and the return is a sequence
of two tuples of the form, (key, display_string).
fn_folder_menu - a function that returns a list of menu items fo... | 625941d77d43ff24873a2ef9 |
def get_auth_person_realm_member_org(self): <NEW_LINE> <INDENT> return self.auth.get("person_realm_member_org", False) | Sets pr_person.realm_entity to
organisation.pe_id of member_member | 625941d730c21e258bdfa6f6 |
def _revini(revini_i, _option = {'revini_i': ALL}): <NEW_LINE> <INDENT> r = 0 <NEW_LINE> for rev in revini_i.itervalues(): <NEW_LINE> <INDENT> r += rev <NEW_LINE> <DEDENT> return r | Revenu initial du ménage
'ind' | 625941d72c8b7c6e89b35a18 |
def connect(self, device_name): <NEW_LINE> <INDENT> if self._resource is not None: <NEW_LINE> <INDENT> self.disconnect() <NEW_LINE> <DEDENT> resource = self._library.connect(ctypes.c_uint32(self._resource_manager), ctypes.c_char_p(device_name)) <NEW_LINE> if resource == 0: <NEW_LINE> <INDENT> raise TSCError('Could not ... | Connect to a device.
:param device_name: The USB device ID for the TSC2017 touchpad. Typically, this should be
"USB0::0x0451::0x2FD7::NI-VISA-30004::3::RAW", perhaps with a number other than
30004.
To get the device ID, run NI-MAX and check out the list of d... | 625941d71f037a2d8b946456 |
def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> dists = np.multiply(np.dot(X,self.X_train.T),-2) <NEW_LINE> X_sum = np.sum(np.square(X),axis=1,keepdims=True) <NEW_LINE> X_train_s... | Compute the distance between each test point in X and each training point
in self.X_train using no explicit loops.
Input / Output: Same as compute_distances_two_loops | 625941d74d74a7450ccd441b |
@APP.shell_context_processor <NEW_LINE> def make_shell_context(): <NEW_LINE> <INDENT> return { 'db': DB, 'Meal': Meal, 'Order': Order, 'User': User, 'Menu':Menu } | context when flask shell runs to avoid cumbersome imports | 625941d76aa9bd52df036ffd |
def evaluate_configs(self, configs, criteria=('silhouette',)): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for i, config in enumerate(configs): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print('\rConfig {}/{}'.format(i+1, len(configs)), end='\n' if i == len(configs)-1 else '', flush=True) <NEW_LINE> <DEDE... | Evaluate clusterings from configs.
Arguments:
configs : array-like of dict
The configs to be evaluated.
criteria: array-like of str
The evaluation criteria to be computed.
Returns:
results : list of dict
The configs and scores for each criterion. | 625941d73539df3088e2e5a3 |
def bulk_process (cv_file_names, location, d_all): <NEW_LINE> <INDENT> d_crop, d_names, d_all = bulk_crop(cv_file_names, location, d_all) <NEW_LINE> d_inftemp, all_inf, d_all = bulk_analyze(cv_file_names, d_all) <NEW_LINE> return d_all, all_inf | Wrapper for all of the bulk functions. Runs the bulk cropper followed by the
bulk analyzer.
Parameters:
-----------
cv_file_names : list
list of all of the file names in a specified folder, needs
to be created before running the bulk wrapper
location : string
string containing the file location of the... | 625941d7be8e80087fb20e98 |
def getPlName(plyr): <NEW_LINE> <INDENT> conn = None <NEW_LINE> dict_cur = None <NEW_LINE> mod_error = "Error: unable to fetch data in Module function: getPlName()" <NEW_LINE> output = None <NEW_LINE> playerName = None <NEW_LINE> conn = connect() <NEW_LINE> dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCurs... | Performs a query on the given player ID and returns
the ID and the player's name from the players table
of the database.
Args:
plyr: id number of the player for which the name is needed
Return:
Return a list containing the player ID and their name. | 625941d75f7d997b87174cf2 |
def plot_heatmap(ax, hmap, xticklabels, yticklabels, xlabel=None, ylabel=None, zlabel=None, cmap=None, labels=True): <NEW_LINE> <INDENT> xticklabels = np.array(xticklabels, dtype='str').tolist() <NEW_LINE> yticklabels = np.array(yticklabels, dtype='str').tolist() <NEW_LINE> nx = len(xticklabels) <NEW_LINE> ny = len(yti... | hmap = 2d numpy array; 1st dim = xaxis, 2nd dim = yaxis
xticklabels = array of labels for x axis ticks
yticklabels = array of labels for y axis ticks
ax = axis to plot heatmap | 625941d7baa26c4b54cb1376 |
def local_terminate(self): <NEW_LINE> <INDENT> self.penalty = self.n_carrying + Configurator.base_penalty <NEW_LINE> self.terminated = True | simulates a terminate operation locally for an agent without updating the environment's entire state | 625941d7f7d966606f6aa25f |
def createBridgeRings(cfg, proxyList, key): <NEW_LINE> <INDENT> hashring = bridgerings.BridgeSplitter(crypto.getHMAC(key, "Hashring-Key")) <NEW_LINE> logging.debug("Created hashring: %r" % hashring) <NEW_LINE> ringParams = bridgerings.BridgeRingParameters(needPorts=cfg.FORCE_PORTS, needFlags=cfg.FORCE_FLAGS) <NEW_LINE>... | Create the bridge distributors defined by the config file
:type cfg: :class:`Conf`
:param cfg: The current configuration, including any in-memory settings
(i.e. settings whose values were not obtained from the config file,
but were set via a function somewhere)
:type proxyList: :class:`~bridgedb.proxy.ProxySe... | 625941d7442bda511e8be66e |
def test_create_order_zero_qty(self): <NEW_LINE> <INDENT> order_factory = _get_order_factory_with_items(1) <NEW_LINE> order_factory.order_items[0].quantity = 0 <NEW_LINE> resp = self.app.post('/orders', json=order_factory.serialize(), content_type='application/json') <NEW_LINE> self.assertEqual(resp.status_code, status... | Create an order with zero quantity | 625941d7ff9c53063f47c44b |
def getTermWindowSize(): <NEW_LINE> <INDENT> if magicConstant is None: <NEW_LINE> <INDENT> raise Exception("platform isn't supported: " + sys.platform) <NEW_LINE> <DEDENT> tstruct = ' ' * 20 <NEW_LINE> try: <NEW_LINE> <INDENT> rstruct = fcntl.ioctl(sys.stdout.fileno(), magicConstant, tstruct) <NEW_LINE> ysize, xsize = ... | return a tuple containing the y,x (rows,cols) size of the terminal window
in characters | 625941d7e64d504609d74a98 |
def get(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(args) > 3 or len(args) < 2: <NEW_LINE> <INDENT> raise ValueError("Invalid url") <NEW_LINE> <DEDENT> tenant_id = uuid.UUID(args[0]) <NEW_LINE> tenant = RUNTIME.tenants[tenant_id] <NEW_LINE> lvnf_id = uuid.UUID(args[1]) <NEW_LINE> lvnf = ... | List all ports.
Args:
[0]: the tenant id
[1]: the lvap id
[2]: the port id
Example URLs:
GET /api/v1/tenants/52313ecb-9d00-4b7d-b873-b55d3d9ada26/
lvnfs/49313ecb-9d00-4a7c-b873-b55d3d9ada34/ports
GET /api/v1/tenants/52313ecb-9d00-4b7d-b873-b55d3d9ada26/
lvnfs/49313ecb-9d00-4a7c-b... | 625941d726068e7796caef3a |
def write_async(self, value, handler): <NEW_LINE> <INDENT> self._private_write_async(libwarble.warble_gattchar_write_async, value, handler) | Writes value to the characteristic requiring an acknowledge from the remote device
@params:
value - Required : Bytes to write to the characteristic
handler - Required : `(Exception) -> void` function that is executed when the write operation is done | 625941d7cc40096d61595ba9 |
def test_stop(self): <NEW_LINE> <INDENT> fake_docker = FakeDockerClient() <NEW_LINE> api = ApplicationNodeDeployer(u'example.com', docker_client=fake_docker) <NEW_LINE> application = Application( name=u'site-example.com', image=DockerImage(repository=u'clusterhq/flocker', tag=u'release-14.0'), links=frozenset(), ) <NEW... | ``StopApplication`` accepts an application object and when ``run()``
is called returns a ``Deferred`` which fires when the container
has been removed. | 625941d76fece00bbac2d999 |
def _pg_re_escape(self, pattern: Text) -> Text: <NEW_LINE> <INDENT> s = list(pattern) <NEW_LINE> for i, c in enumerate(s): <NEW_LINE> <INDENT> if c not in self._alphanum: <NEW_LINE> <INDENT> if ord(c) >= 128: <NEW_LINE> <INDENT> s[i] = '\\u{:0>4x}'.format(ord(c)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s[i] = '\\... | Escape user input to place in a regex
Python's re.escape escapes unicode characters in a way which postgres
fails on, 'λ' to '\λ'. This function will correctly escape
them for postgres, 'λ' to '\u03bb'. | 625941d776e4537e8c3518cc |
def test_no_python_file(self): <NEW_LINE> <INDENT> quality = QualityReporter(pydocstyle_driver) <NEW_LINE> file_paths = ["file1.coffee", "subdir/file2.js"] <NEW_LINE> for path in file_paths: <NEW_LINE> <INDENT> result = quality.violations(path) <NEW_LINE> assert result == [] | Expect that we get no results because no Python files. | 625941d74a966d76dd551269 |
@pytest.mark.xfail(strict=False) <NEW_LINE> def test_user_add_recipe(recipes, users): <NEW_LINE> <INDENT> r = recipes[0] <NEW_LINE> u = MongoDriver.user_find_by_id(users[0].id) <NEW_LINE> assert len(u.recipe_ids) == 0 <NEW_LINE> result = MongoDriver.user_add_recipe(u, r.id) <NEW_LINE> assert len(u.recipe_ids) == 1 <NEW... | GIVEN a recipe to add to a user
WHEN calling MongoDriver.user_add_recipe(user, recipe_id)
THEN assert the recipe is added and proper return value returned
This test has issues with MongoMock, as far as I can tell.
The function works in practice but cannot test it properly. | 625941d73346ee7daa2b2fc5 |
def get_data_rectangle(self): <NEW_LINE> <INDENT> y_start = self.__top_legend.get_height() <NEW_LINE> x_start = self.__data.get_data_x_start() <NEW_LINE> return(x_start, y_start, self.__width - x_start, self.__data.get_height()) | ! Get Data Rectangle
@param self this object
@return rectangle | 625941d7be7bc26dc91cd855 |
def unit_manager_list_pilots(self, unit_manager_uid): <NEW_LINE> <INDENT> if self._s is None: <NEW_LINE> <INDENT> raise Exception("No active session.") <NEW_LINE> <DEDENT> cursor = self._p.find({"unitmanager": unit_manager_uid}) <NEW_LINE> pilot_ids = [] <NEW_LINE> for obj in cursor: <NEW_LINE> <INDENT> pilot_ids.appen... | Lists all pilots associated with a unit manager.
| 625941d756ac1b37e6264425 |
def average_score_from_group(students_list): <NEW_LINE> <INDENT> average_score = 0 <NEW_LINE> for student in students_list: <NEW_LINE> <INDENT> average_score += sum(student['дз']) / len(student['дз']) / len(students_list) <NEW_LINE> <DEDENT> return average_score | Средняя оценка за домашнее задание по группе | 625941d77c178a314d6ef6bb |
def actions(self, state): <NEW_LINE> <INDENT> num_cities = len(state) - 1 <NEW_LINE> actions = [] <NEW_LINE> for i in range(6): <NEW_LINE> <INDENT> num1 = randrange(1, num_cities) <NEW_LINE> num2 = randrange(1, num_cities) <NEW_LINE> action = [num1, num2] <NEW_LINE> actions.append(action) <NEW_LINE> <DEDENT> return act... | This method generates two random integers to be used as indexes in a move.
| 625941d70a366e3fb873ea74 |
def add_partial(partials, x): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for y in partials: <NEW_LINE> <INDENT> if abs(x) < abs(y): <NEW_LINE> <INDENT> x, y = y, x <NEW_LINE> <DEDENT> hi = x + y <NEW_LINE> lo = y - (hi - x) <NEW_LINE> if lo: <NEW_LINE> <INDENT> partials[i] = lo <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> x = hi <N... | Helper function for full-precision summation.
Arguments:
partials list containing numeric partial sums
x number to add in-place to partials
``add_partials`` supports high-preciation summation of floats and
Decimals. It can also be used for ints and Fractions, although there
is little benefit in ... | 625941d730dc7b7665901bbd |
def main(): <NEW_LINE> <INDENT> rtc = ExpanderPi.RTC() <NEW_LINE> writeval = 176247 <NEW_LINE> print("Writing to memory: ", writeval) <NEW_LINE> writearray = int_to_array(writeval) <NEW_LINE> rtc.write_memory(0x08, writearray) <NEW_LINE> readarray = rtc.read_memory(0x08, 4) <NEW_LINE> print("Reading from memory: ", arr... | Main program function | 625941d7236d856c2ad44a35 |
def _add(testcase, testconfig): <NEW_LINE> <INDENT> nodes = [testconfig.xpath('//{0}'.format(element)) for element in testcase['element']] <NEW_LINE> nodeList = list(itertools.chain(*nodes)) <NEW_LINE> for node in nodeList: <NEW_LINE> <INDENT> node.attrib['status'] = 'created,modified' | Add status = 'created,modified' to each element in the tree
:return: None | 625941d715baa723493c41d0 |
def new_asset_archive(*args): <NEW_LINE> <INDENT> return _asset_archive_resource_type(*args) | Instantiates a new AssetArchive, passing the given arguments to the constructor. | 625941d76fb2d068a760f2f9 |
def get_local_tasks(tq_id = None): <NEW_LINE> <INDENT> if tq_id is not None: <NEW_LINE> <INDENT> tqs = filter(lambda x: x['_id'] == tq_id, get_local_task_queues()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tqs = get_local_task_queues() <NEW_LINE> <DEDENT> for tq in tqs: <NEW_LINE> <INDENT> for t in circular_buffer(... | Return a list of task pointers for the local reactor. | 625941d74f88993c3716c2bf |
def compose(self): <NEW_LINE> <INDENT> return dict( id=self.client.get_next_message_id(), channel=self.name, version=self.client.version, minimumVersion=self.client.minimum_version, supportedConnectionTypes=['long-polling'], ) | Compose a handshake request message | 625941d730c21e258bdfa6f7 |
def testNormalOddNumReplicas(self): <NEW_LINE> <INDENT> samps_ = self._getNormalREMCSamples( inverse_temperatures=[1., 0.3, 0.1, 0.03, 0.01]) <NEW_LINE> self.assertAllClose(samps_.mean(), 0., atol=0.1, rtol=0.1) <NEW_LINE> self.assertAllClose(samps_.std(), 1., atol=0.1, rtol=0.1) | Sampling from the Standard Normal Distribution. | 625941d7e64d504609d74a99 |
def get_neighbours(self, cell: Cell) -> Cells: <NEW_LINE> <INDENT> neighbours = [] <NEW_LINE> for i in range(-1, 2): <NEW_LINE> <INDENT> for j in range(-1, 2): <NEW_LINE> <INDENT> h = cell[0] + i <NEW_LINE> w = cell[1] + j <NEW_LINE> if 0 <= w < self.cols and 0 <= h < self.rows and (i, j) != (0, 0): <NEW_LINE> <INDENT>... | Вернуть список соседних клеток для клетки `cell`.
Соседними считаются клетки по горизонтали, вертикали и диагоналям,
то есть, во всех направлениях.
Parameters
----------
cell : Cell
Клетка, для которой необходимо получить список соседей. Клетка
представлена кортежем, содержащим ее координаты на игровом поле.
... | 625941d7bf627c535bc13428 |
def attention(self, prev_alpha, r, embedded_c, phase=True, activation=tf.nn.tanh, reuse=True, scope=""): <NEW_LINE> <INDENT> r = tf.tile(tf.expand_dims(r, axis=1), tf.constant([1, self.c_max_len, 1])) <NEW_LINE> embedded_c = (1 - tf.transpose(prev_alpha, [0, 2, 1])) * embedded_c <NEW_LINE> z = tf.concat([r, embedded_c]... | calculate attention with g_theta
Args:
r (decoder output, [batch_size, word_embed])
embedded_c ([batch_size, c_max_len, word_embed]) | 625941d73317a56b86939ead |
def test_alternative_resources_attribute_is_working_properly(self): <NEW_LINE> <INDENT> new_task = Task(**self.kwargs) <NEW_LINE> self.data_created.append(new_task) <NEW_LINE> self.assertEqual( sorted(new_task.alternative_resources, key=lambda x: x.name), sorted([self.test_user3, self.test_user4, self.test_user5], key=... | testing if the alternative_resources attribute value can be
correctly set | 625941d7e1aae11d1e749f12 |
def test_basics(self): <NEW_LINE> <INDENT> tournament = mommy.make(Tournament, name='My Test Tournament') <NEW_LINE> tournament.players.add(mommy.make(Player)) <NEW_LINE> tournament.players.add(mommy.make(Player)) <NEW_LINE> self.assertEqual(tournament.name, 'My Test Tournament') <NEW_LINE> self.assertEqual(tournament.... | Test the basic functionality of Tournament | 625941d7d58c6744b4257eb7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.