code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@app.route('/login', methods=['GET', 'POST']) <NEW_LINE> def login(): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> login_us = request.form.get('username').encode('utf-8') <NEW_LINE> login_ps = request.form.get('username').encode('utf-8') <NEW_LINE> corret_usr = mongo.db.user.find_one({'uname': l...
Login Form
625941cf15fb5d323cde0c56
def connect_blocks(block_a, block_b, direction_a_to_b): <NEW_LINE> <INDENT> if direction_a_to_b == Direction.north: <NEW_LINE> <INDENT> for j in range(2): <NEW_LINE> <INDENT> connect_quartets(block_a.quartets[0 * 2 + j], block_b.quartets[1 * 2 + j], Direction.north) <NEW_LINE> <DEDENT> <DEDENT> elif direction_a_to_b ==...
Use the quartet connection function to conveniently connect two quartets along an axis defined by direction_a_to_b. :param direction_a_to_b: the cardinal direction between processing elements a and b :param block_a: the first block :param block_b: the second block
625941cf91af0d3eaac9bb5f
def _get_id2KEGGID_csv(self, id2KEGGID_filename_I): <NEW_LINE> <INDENT> id2KEGGID = {} <NEW_LINE> with open(id2KEGGID_filename_I,mode='r') as infile: <NEW_LINE> <INDENT> reader = csv.reader(infile) <NEW_LINE> for i,r in enumerate(reader): <NEW_LINE> <INDENT> if not(i==0): <NEW_LINE> <INDENT> id = r[0].replace('-','_DAS...
Read in the id2KEGGID mapping
625941cfff9c53063f47c33a
def convert_value(self, value): <NEW_LINE> <INDENT> val_type = type(value) <NEW_LINE> if val_type in self.type_converters: <NEW_LINE> <INDENT> return self.type_converters[val_type](value) <NEW_LINE> <DEDENT> if self.str_fallback and not isinstance(value, JSON_SAFE_TYPES): <NEW_LINE> <INDENT> return str(value) <NEW_LINE...
Converts and returns the value using the appropriate type converter. If no suitable type converter is found and the value is not of a known safe type, a default conversion to string is performed.
625941cfd7e4931a7ee9e064
def do_DELETE(self): <NEW_LINE> <INDENT> resource_parts = self.get_resource_parts() <NEW_LINE> if len(resource_parts) != 2: <NEW_LINE> <INDENT> self.write_invalid_api_uri_format_response() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resource = resource_parts[0] <NEW_LINE> resource_id = resource_parts[1] <NEW_LINE> re...
Look for the resource and deletes it if exists
625941cf10dbd63aa1bd2cea
def stage_input(self, params): <NEW_LINE> <INDENT> file_path = None <NEW_LINE> if 'file' in params: <NEW_LINE> <INDENT> file_path = os.path.abspath(params['file']['path']) <NEW_LINE> <DEDENT> elif 'shock_id' in params: <NEW_LINE> <INDENT> print('Downloading file from SHOCK node: ' + str(params['shock_id'])) <NEW_LINE> ...
Setup the input_directory by fetching the files and returning the path to the file
625941cf2eb69b55b151c9f6
def _getfield_is_safe(oldtype, newtype, offset): <NEW_LINE> <INDENT> new_fields = _get_all_field_offsets(newtype, offset) <NEW_LINE> old_fields = _get_all_field_offsets(oldtype) <NEW_LINE> _check_field_overlap(new_fields, old_fields)
Checks safety of getfield for object arrays. As in _view_is_safe, we need to check that memory containing objects is not reinterpreted as a non-object datatype and vice versa. Parameters ---------- oldtype : data-type Data type of the original ndarray. newtype : data-type Data type of the field being accessed...
625941cfec188e330fd5a8e5
def is_local(self): <NEW_LINE> <INDENT> if self.ttype == 'LOCAL': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Check if the target is a directory :returns: bool -- True if it is a directory
625941cf6aa9bd52df036eeb
def sort(self, sort_attr='JNAME', sort_order='asc', inplace=False): <NEW_LINE> <INDENT> if sort_attr is not None: <NEW_LINE> <INDENT> self.sort_key = sort_attr.upper() <NEW_LINE> <DEDENT> if self.sort_key not in self.columns: <NEW_LINE> <INDENT> raise KeyError("Sorting by attribute '{}' is not possible as it " "is not ...
Sort the generated catalogue :class:`~pandas.DataFrame` on a given attribute and in either ascending or descending order. Args: sort_attr (str): The parameter on which to perform the sorting of the query output. Defaults to 'JNAME'. sort_order (str): Set to 'asc' to sort the parameter values in ...
625941cfd10714528d5ffe2a
def rotate(self, matrix): <NEW_LINE> <INDENT> N = len(matrix) <NEW_LINE> n = N//2 <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> for j in range(N-1-2*i): <NEW_LINE> <INDENT> matrix[i][i+j],matrix[i+j][N-1-i],matrix[N-1-i][N-1-j-i],matrix[N-1-j-i][i] = matrix[N-1-j-i][i],matrix[i][i+j],matrix[i+j][N-1-i],matrix[N-1-i...
:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
625941cf31939e2706e4cfb0
def test_wrong_surname(self): <NEW_LINE> <INDENT> response = self.client.post( '/api/v1/library/register', data=json.dumps(wrong_surname), content_type='application/json', headers=self.get_registrar_token()) <NEW_LINE> result = json.loads(response.data.decode()) <NEW_LINE> self.assertEqual(result['message'], 'surname i...
Test registering with wrong surname format.
625941cf82261d6c526ab5e6
def fourSum(self, nums, target): <NEW_LINE> <INDENT> res=[] <NEW_LINE> nums.sort() <NEW_LINE> for i in range(len(nums)-3): <NEW_LINE> <INDENT> if i>0 and nums[i]==nums[i-1]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for j in range(i+1,len(nums)-2): <NEW_LINE> <INDENT> if j>i+1 and nums[j]==nums[j-1]: <NEW_LINE> ...
:type nums: List[int] :type target: int :rtype: List[List[int]]
625941cf507cdc57c6306e22
def validWordAbbreviation(self, word, abbr): <NEW_LINE> <INDENT> i, j = 0, 0 <NEW_LINE> while i < len(word) and j < len(abbr): <NEW_LINE> <INDENT> jj = j <NEW_LINE> while jj < len(abbr) and abbr[jj].isdigit(): <NEW_LINE> <INDENT> jj += 1 <NEW_LINE> <DEDENT> if jj > j and abbr[j] != '0': <NEW_LINE> <INDENT> occur = int(...
:type word: str :type abbr: str :rtype: bool
625941cf9c8ee82313fbb8bc
def batchnorm_forward(x, gamma, beta, bn_param): <NEW_LINE> <INDENT> mode = bn_param['mode'] <NEW_LINE> eps = bn_param.get('eps', 1e-5) <NEW_LINE> momentum = bn_param.get('momentum', 0.9) <NEW_LINE> N, D = x.shape <NEW_LINE> running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype)) <NEW_LINE> running_var ...
Forward pass for batch normalization. During training the sample mean and (uncorrected) sample variance are computed from minibatch statistics and used to normalize the incoming data. During training we also keep an exponentially decaying running mean of the mean and variance of each feature, and these averages are us...
625941cf1b99ca400220abf8
def mul(self): <NEW_LINE> <INDENT> if len(self.stack) < 2: <NEW_LINE> <INDENT> raise IndexError ('Less than 2 numbers inside the stack') <NEW_LINE> <DEDENT> a= self.stack.pop() <NEW_LINE> b = self.stack.pop() <NEW_LINE> c = b*a <NEW_LINE> self.stack.push(c)
pre: value stack has at least two elements post: Top two elements have been popped off the value stack and their division result has been pushed onto the value stack Exceptions: IndexError if value stack does not have two elements
625941cf55399d3f055887fb
@app.route('/shark/query/<queryId>/update', methods=["POST"]) <NEW_LINE> def shark_query_update(queryId): <NEW_LINE> <INDENT> query = request.args.get("query") <NEW_LINE> error, user, account, cluster, handle = getRequestParameters(forceCluster=False) <NEW_LINE> if error is not None: <NEW_LINE> <INDENT> return error, N...
Save a query for later. GetParams: account: an account user: a user query: The sql query to save Returns: A json object containing a representation of a saved query
625941cf4f6381625f114b81
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ScopeLevel): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict()
Returns true if both objects are equal
625941cf097d151d1a222fa0
def plLogBase2(*args): <NEW_LINE> <INDENT> return _pypl.plLogBase2(*args)
plLogBase2(plFloat v) -> plFloat
625941cf711fe17d825424b2
def accumulate_record(self, params, sample_state, record, weight=1): <NEW_LINE> <INDENT> weighted_record = tf.nest.map_structure(lambda t: weight * t, record) <NEW_LINE> return self.accumulate_preprocessed_record( sample_state, (weighted_record, tf.cast(weight, tf.float32)))
Accumulates record, multiplying by weight.
625941cf16aa5153ce3625bf
def staging(): <NEW_LINE> <INDENT> env['path'] = '/environments/staging' <NEW_LINE> env.host_string = staging_server
Staging server settings
625941cf2ae34c7f2600d278
def trailer(self): <NEW_LINE> <INDENT> title_no_spaces = re.sub(" ", "+", self.title()) <NEW_LINE> request = requests.get( 'https://www.google.com/search?q=%s+trailer' % title_no_spaces ) <NEW_LINE> index_start = re.search( r'http://www.youtube.com/watch%3Fv%3D\w+', request.text ).start() <NEW_LINE> index_end = re.sear...
method to return trailer url for movie
625941cfd7e4931a7ee9e065
def __new__( cls ): <NEW_LINE> <INDENT> if cls.__initialized is False: <NEW_LINE> <INDENT> cls.__instance = super(ContextManager, cls).__new__(cls) <NEW_LINE> <DEDENT> return cls.__instance
Return the stored instance if it exists. :returns: generated or already existing instance. :rtype: cls
625941cf8a43f66fc4b541ac
def test_rgs(self): <NEW_LINE> <INDENT> assert self.state.rgs == ( self.ct.rgs['rg1'], self.ct.rgs['rg2'], )
Test that RGs are sorted by RG id.
625941cf44b2445a339321dc
def player_input(): <NEW_LINE> <INDENT> player1 = input("\nPlayer 1 - Please pick a marker 'X' or 'O': ").upper() <NEW_LINE> val = validate(player1) <NEW_LINE> if val[0]: <NEW_LINE> <INDENT> player2 = val[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> out = {'p1': [player1], 'p2': [pl...
Take in a player input and assign their marker as 'X' or 'O'. Think about using while loops to continually ask until you get a correct answer.
625941cf3cc13d1c6d3c74c1
def test_view(self): <NEW_LINE> <INDENT> view = handlers.PageHandler.view <NEW_LINE> expected = views.PageDetail.as_view() <NEW_LINE> self.assertEqual(view.__name__, expected.__name__) <NEW_LINE> self.assertEqual(view.__module__, expected.__module__)
PageHandler uses the PageDetail view.
625941cfa8370b77170529e6
def extract( self, pat: str, flags: int = 0, expand: bool = True ) -> SeriesOrIndex: <NEW_LINE> <INDENT> if not _is_supported_regex_flags(flags): <NEW_LINE> <INDENT> raise NotImplementedError( "unsupported value for `flags` parameter" ) <NEW_LINE> <DEDENT> data, index = libstrings.extract(self._column, pat, flags) <NEW...
Extract capture groups in the regex `pat` as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression `pat`. Parameters ---------- pat : str Regular expression pattern with capturing groups. flags : int, default 0 (no flags) Flags to pass through...
625941cf29b78933be1e57f2
def singleton(cls): <NEW_LINE> <INDENT> instances = {} <NEW_LINE> def getinstance(): <NEW_LINE> <INDENT> if cls not in instances: <NEW_LINE> <INDENT> instances[cls] = cls() <NEW_LINE> <DEDENT> return instances[cls] <NEW_LINE> <DEDENT> return getinstance
Ensure that only one instance of the class ever exists.
625941cf30dc7b7665901aad
def test_eval_running_mode1(self): <NEW_LINE> <INDENT> self.root.database.prepare_to_run() <NEW_LINE> test = '{val1}/{val2}' <NEW_LINE> formatted = self.root.format_and_eval_string(test) <NEW_LINE> assert formatted == 0.1 <NEW_LINE> assert self.root._eval_cache <NEW_LINE> assert test in self.root._eval_cache <NEW_LINE>...
Test eval expression with only standard operators.
625941cfbaa26c4b54cb1266
def _init_centroids(X, k, init, random_state=None, x_squared_norms=None, init_size=None): <NEW_LINE> <INDENT> random_state = check_random_state(random_state) <NEW_LINE> n_samples = X.shape[0] <NEW_LINE> if x_squared_norms is None: <NEW_LINE> <INDENT> x_squared_norms = row_norms(X, squared=True) <NEW_LINE> <DEDENT> if i...
Compute the initial centroids Parameters ---------- X: array, shape (n_samples, n_features) k: int number of centroids init: {'k-means++', 'random' or ndarray or callable} optional Method for initialization random_state: integer or numpy.RandomState, optional The generator used to initialize the centers. If...
625941cf460517430c3942cb
def page(self, end_date=values.unset, friendly_name=values.unset, minutes=values.unset, start_date=values.unset, task_channel=values.unset, split_by_wait_time=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> params = values.of({ 'EndDate': serialize.iso8601_d...
Retrieve a single page of TaskQueuesStatisticsInstance records from the API. Request is executed immediately :param datetime end_date: The end_date :param unicode friendly_name: The friendly_name :param unicode minutes: The minutes :param datetime start_date: The start_date :param unicode task_channel: The task_channe...
625941cfa4f1c619b28b017f
def _resv_id_from_token(self, context, client_token): <NEW_LINE> <INDENT> resv_id = None <NEW_LINE> sys_metas = self.compute_api.get_all_system_metadata( context, search_filts=[{'key': ['EC2_client_token']}, {'value': [client_token]}]) <NEW_LINE> for sys_meta in sys_metas: <NEW_LINE> <INDENT> if sys_meta and sys_meta.g...
Get reservation ID from db.
625941cf85dfad0860c3afa2
def test_get_city(): <NEW_LINE> <INDENT> c = Client(mock=True) <NEW_LINE> city1 = c.get_city(2) <NEW_LINE> city2 = c.get_city(4) <NEW_LINE> city3 = c.get_city(0) <NEW_LINE> assert_true(city1 is not None) <NEW_LINE> assert_equal(city1['name'], "City B") <NEW_LINE> assert_equal(city1['population'], 100000) <NEW_LINE> ass...
Basic get city API routine.
625941cf07d97122c41789d3
def get_hash(data): <NEW_LINE> <INDENT> md5 = hashlib.md5() <NEW_LINE> md5.update(data) <NEW_LINE> return md5.hexdigest()
:param data: Any byte or 2.X str :return: the MD5 hash of the data as a hexidecimal string :rtype: str
625941cf796e427e537b070d
def test_is_str__valid(self): <NEW_LINE> <INDENT> result = utils.is_str('TEST') <NEW_LINE> self.assertEqual(result, 'TEST') <NEW_LINE> result = utils.is_str(u'TEST') <NEW_LINE> self.assertEqual(result, u'TEST')
with a string
625941cfc4546d3d9de72b7c
def get_text(response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return pprint.pformat(response.json()) <NEW_LINE> <DEDENT> except JSONDecodeError: <NEW_LINE> <INDENT> return pprint.pformat(response.text)
Returns the best looking text from a response :param response: :return: string
625941cf9c8ee82313fbb8bd
def load(self, weboob, modname, instname, config, nofail=False): <NEW_LINE> <INDENT> cfg = BackendConfig() <NEW_LINE> cfg.modname = modname <NEW_LINE> cfg.instname = instname <NEW_LINE> cfg.weboob = weboob <NEW_LINE> for name, field in self.iteritems(): <NEW_LINE> <INDENT> value = config.get(name, None) <NEW_LINE> if v...
Load configuration from dict to create an instance. :param weboob: weboob object :type weboob: :class:`weboob.core.ouiboube.Weboob` :param modname: name of the module :type modname: :class:`str` :param instname: name of this backend :type instname: :class:`str` :param params: parameters to load :type params: :class:`d...
625941cf24f1403a92600cad
def get_bcaddress_version(strAddress): <NEW_LINE> <INDENT> addr = b58decode(strAddress,25) <NEW_LINE> if addr is None: return None <NEW_LINE> version = addr[0] <NEW_LINE> checksum = addr[-4:] <NEW_LINE> vh160 = addr[:-4] <NEW_LINE> h3=SHA256.new(SHA256.new(vh160).digest()).digest() <NEW_LINE> if h3[0:4] == checksum: <N...
Returns None if strAddress is invalid. Otherwise returns integer version of address.
625941cfdc8b845886cb567c
def _deduplicate_names(names): <NEW_LINE> <INDENT> new_names = [] <NEW_LINE> existing_names = set() <NEW_LINE> for name in names: <NEW_LINE> <INDENT> orig_name = name <NEW_LINE> i = 1 <NEW_LINE> while name in existing_names: <NEW_LINE> <INDENT> name = orig_name + '_' + str(i) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> new_n...
Ensure there are no duplicates in ``names`` This is done by iteratively adding ``_<N>`` to the name for increasing N until the name is unique.
625941cfd4950a0f3b08c496
def fourier_wf(sz,xcyc_aperture,ycyc_aperture,amp,phase): <NEW_LINE> <INDENT> x = np.arange(sz) - sz//2 <NEW_LINE> xy = np.meshgrid(x,x) <NEW_LINE> xx = xy[0] <NEW_LINE> yy = xy[1] <NEW_LINE> zz = 2*np.pi*(xx*xcyc_aperture/sz + yy*ycyc_aperture/sz) <NEW_LINE> aberration = np.exp( 1j * amp * (np.cos(phase)*np.cos(zz) + ...
This function creates a phase aberration, centered on the middle of a python array Parameters ---------- dim: int Size of the 2D array xcyc_aperture: float cycles per aperture in the x direction. ycyc_aperture: float cycles per aperture in the y direction. amp: float amplitude of the aberration in radi...
625941cf15baa723493c40bd
def default(self,*args): <NEW_LINE> <INDENT> self.append(u"def :") <NEW_LINE> self.update_line(args[0]) <NEW_LINE> self.append(unicode(args[0]))
/dev/zero dump for all visitor methods when not handled in derived class
625941cf01c39578d7e74f83
def __init__(self, raw): <NEW_LINE> <INDENT> self.raw = raw <NEW_LINE> self.buffer_size = io.DEFAULT_BUFFER_SIZE <NEW_LINE> self._read_buf = b'' <NEW_LINE> self._read_pos = 0 <NEW_LINE> self._pos = 0 <NEW_LINE> self._lineno = 1 <NEW_LINE> self._colno = 1
Create a new buffered reader using the given readable raw IO object.
625941cf57b8e32f524835e2
@validator <NEW_LINE> def list_living_married(individuals, families): <NEW_LINE> <INDENT> living = [] <NEW_LINE> for family in families: <NEW_LINE> <INDENT> husband_id = family.husband <NEW_LINE> wife_id = family.wife <NEW_LINE> husband = None <NEW_LINE> wife = None <NEW_LINE> for individual in individuals: <NEW_LINE> ...
US15 - List the living married people
625941cf956e5f7376d70fb4
def async_operation_data_get(context, entity_id, key=None, default=None): <NEW_LINE> <INDENT> return IMPL.async_operation_data_get(context, entity_id, key, default)
Get one, list or all key-value pairs for given entity_id.
625941cf627d3e7fe0d68f97
def softmax_v1(x): <NEW_LINE> <INDENT> e_x = np.exp(x - np.max(x)) <NEW_LINE> return e_x / e_x.sum(axis=1)
Compute softmax values for each sets of scores in x.
625941cf656771135c3eb9b6
def format(self, record): <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> record.hour = now.hour <NEW_LINE> record.minute = now.minute <NEW_LINE> return logging.Formatter.format(self, record)
Add special placeholders for shorter messages.
625941cfc432627299f04d8d
def before_save(self, source: Any, handler: 'Handler'): <NEW_LINE> <INDENT> assert isinstance(source, Holder), "Whatever is saving this item, should be a holder" <NEW_LINE> assert self in source.items, "If this happens, then a Holder is trying to save an item that it doesn't have"
source should == self.holder
625941cf0c0af96317bb832f
def refDead(self): <NEW_LINE> <INDENT> tag = i18n.translate(self.site, deadLinkTag) <NEW_LINE> if not tag: <NEW_LINE> <INDENT> dead_link = self.refLink() <NEW_LINE> <DEDENT> elif '%s' in tag: <NEW_LINE> <INDENT> dead_link = '<ref%s>%s</ref>' % (self.refname, tag % self.link) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Dead link, tag it with a {{dead link}}.
625941cf66673b3332b921d9
def cast(*args): <NEW_LINE> <INDENT> return _itkReconstructionByDilationImageFilterPython.itkReconstructionByDilationImageFilterIF3IF3_Superclass_cast(*args)
cast(itkLightObject obj) -> itkReconstructionByDilationImageFilterIF3IF3_Superclass
625941cf63d6d428bbe44637
def set_target_post_build_events(self, context, name, command_value, node): <NEW_LINE> <INDENT> del name <NEW_LINE> if self.__is_excluded_from_build(node): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__set_target_build_events( context, node, 'post_build_events', 'Post build', command_value )
Setting of post build event to context :param context: :param name: :param command_value: :param node: :return:
625941cfcdde0d52a9e5317b
def encrypt(self, msg, alg='aes_128_cbc', padding='PKCS#7', b64enc=True, block_size=AES_BLOCK_SIZE): <NEW_LINE> <INDENT> self.__class__._deprecation_notice() <NEW_LINE> if padding == 'PKCS#7': <NEW_LINE> <INDENT> _block_size = block_size <NEW_LINE> <DEDENT> elif padding == 'PKCS#5': <NEW_LINE> <INDENT> _block_size = 8 ...
:param key: The encryption key :param msg: Message to be encrypted :param padding: Which padding that should be used :param b64enc: Whether the result should be base64encoded :param block_size: If PKCS#7 padding which block size to use :return: The encrypted message
625941cfe5267d203edcdde4
def csave(dbo, username, post): <NEW_LINE> <INDENT> def valid_code(s): <NEW_LINE> <INDENT> VALID_CODES = ("XX", "XXX", "NN", "NNN", "UUUU", "UUUUUUUUUU") <NEW_LINE> for v in VALID_CODES: <NEW_LINE> <INDENT> if s.find(v) != -1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT>...
Takes configuration data passed as a web post and saves it to the database.
625941cf4e4d5625662d451f
@patch('webcompat.webhooks.model.make_request') <NEW_LINE> def test_close_private_issue(mock_mr): <NEW_LINE> <INDENT> json_event, signature = event_data('private_issue_opened.json') <NEW_LINE> payload = json.loads(json_event) <NEW_LINE> issue = WebHookIssue.from_dict(payload) <NEW_LINE> issue.close_private_issue() <NEW...
Test issue state and API request that is sent to GitHub.
625941cf5f7d997b87174be0
def get(self, request): <NEW_LINE> <INDENT> template = loader.get_template('base/index.html') <NEW_LINE> context = { } <NEW_LINE> return HttpResponse(template.render(context, request))
Return html for main application page.
625941cf293b9510aa2c33dd
def get_proper_divisors(n): <NEW_LINE> <INDENT> divisors = set([1]) <NEW_LINE> if n <= 2: <NEW_LINE> <INDENT> return divisors <NEW_LINE> <DEDENT> for x in range(2, int(math.ceil(math.sqrt(n)) + 1)): <NEW_LINE> <INDENT> if n % x == 0: <NEW_LINE> <INDENT> divisors.add(x) <NEW_LINE> divisors.add(n // x) <NEW_LINE> <DEDENT...
Gets the divisors up to but not including itself Args: n (int): The number to divide
625941cf236d856c2ad44923
def login(self): <NEW_LINE> <INDENT> if self._token is None: <NEW_LINE> <INDENT> self._parse_token() <NEW_LINE> <DEDENT> url = 'https://tinychat.com/login' <NEW_LINE> form_data = { 'login_username': self.account, 'login_password': self.password, 'remember': '1', 'next': 'https://tinychat.com/', '_token': self._token } ...
Makes a HTTP login POST to tinychat.
625941cfc432627299f04d8e
def best_model(model_path: Path, standard='val_f1'): <NEW_LINE> <INDENT> best_score = 0 <NEW_LINE> best_path = 'latest_model.h5' <NEW_LINE> for path in model_path.glob('*.h5'): <NEW_LINE> <INDENT> if 'ckpt_model' in path.stem and standard in path.stem: <NEW_LINE> <INDENT> score = float(path.stem.split('-')[1]) <NEW_LIN...
find the best model from a given path Arguments: model_path: pathlib.Path where the cache model saved standard: criteria for finding the best model Returns: a string of the best model's path
625941cf8c3a873295158503
def errors(self, y): <NEW_LINE> <INDENT> if y.ndim != self.y_pred.ndim: <NEW_LINE> <INDENT> raise TypeError('y should have the same shape as self.y_pred', ('y', y.type, 'y_pred', self.y_pred.type)) <NEW_LINE> <DEDENT> if y.dtype.startswith('int'): <NEW_LINE> <INDENT> return T.mean(T.neq(self.y_pred, y)) <NEW_LINE> <DED...
compute zero-one loss note, y is in integer form, not one-hot
625941cf4d74a7450ccd430b
def test_django_date_trunc(self): <NEW_LINE> <INDENT> updated = datetime.datetime(2010, 2, 20) <NEW_LINE> models.SchoolClass.objects.create(year=2009, last_updated=updated) <NEW_LINE> years = models.SchoolClass.objects.dates('last_updated', 'year') <NEW_LINE> self.assertEqual(list(years), [datetime.date(2010, 1, 1)])
Test the custom ``django_date_trunc method``, in particular against fields which clash with strings passed to it (e.g. 'year') - see #12818__. __: http://code.djangoproject.com/ticket/12818
625941cf07f4c71912b115ca
def Stokes2geo(S0, S1, S2, S3, tol=0.0): <NEW_LINE> <INDENT> S1n, S2n, S3n = normalizeStokes(S0, S1, S2, S3, tol=tol) <NEW_LINE> Phi = np.sqrt(S1n**2 + S2n**2 + S3n**2) <NEW_LINE> a = np.sqrt(Phi*S0) <NEW_LINE> theta = 0.5 * np.arctan2(S2n, S1n) <NEW_LINE> chi = 0.5 * np.arcsin(S3n/Phi) <NEW_LINE> return a, theta, chi,...
Return geometric parameters from Stokes parameters. It returns the decomposition in a, theta, chi and degree of polarization Phi. Parameters ---------- S0, S1, S2, S3 : array_type tol : float, optional Returns ------- a, theta, chi, Phi : array_type See also -------- quat2euler normalizeStokes geo2Stokes
625941cf627d3e7fe0d68f98
def blend_train(als=None, sgd=None, user__mean=None, knn_user=None, knn_item=None, svd=None, svdpp=None, nnmf=None, alpha=None, label=None): <NEW_LINE> <INDENT> m_train = np.concatenate((als, sgd, user__mean, knn_user, knn_item, svd, svdpp, nnmf), axis=1) <NEW_LINE> y_train = lable <NEW_LINE> w = np.linalg.solve(m_trai...
This function train blending model for our prediction of algorithms :param als: is prediction array of als algrithm with shape of n*1 :param sgd: is prediction array of sgd algrithm with shape of n*1 :param user__mean: is prediction array of user__mean algrithm with shape of n*1 :param knn_user is prediction array ...
625941cfac7a0e7691ed4214
def CheckURI(uri, timeout=5): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = requests.get(uri, timeout = timeout) <NEW_LINE> return True <NEW_LINE> <DEDENT> except requests.RequestException: <NEW_LINE> <INDENT> return False
Check whether this URI is reachable, i.e. does it return a 200 OK? This function returns True if a GET request to uri returns a 200 OK, and False if that GET request returns any other response, or doesn't return (i.e. times out).
625941cf2c8b7c6e89b35908
def __init__(self, strategyManager, eventEngine, parent=None): <NEW_LINE> <INDENT> super(StrategyEngineWidget, self).__init__(parent) <NEW_LINE> self.strategyManager = strategyManager <NEW_LINE> self.eventEngine = eventEngine <NEW_LINE> self.strategyLoaded = False <NEW_LINE> self.initUi() <NEW_LINE> self.registerEvent(...
Constructor
625941cfb5575c28eb68e148
def getActiveKeysForAccount(self, name): <NEW_LINE> <INDENT> return self.getKeysForAccount(name, "active")
Obtain list of all owner Active Keys for an account from the wallet database
625941cf85dfad0860c3afa3
def language_code_to_translation(language_code): <NEW_LINE> <INDENT> if not isinstance(language_code, str): <NEW_LINE> <INDENT> message = "Invalid argument {}. Expected str instance.".format( repr(language_code)) <NEW_LINE> raise TypeError(message) <NEW_LINE> <DEDENT> if language_code not in list_languages(): <NEW_LINE...
Translate a language code. Note that all language names are written in their language so that people can read them in their language. :rtype: str :return: the translated language :param str language_code: a language code from :func:`list_languages` :raises ValueError: if the code is not in :func:`list_languages` :raise...
625941cfa17c0f6771cbe198
def UpdateSink(self, request, timeout, metadata=None, with_call=False, protocol_options=None): <NEW_LINE> <INDENT> raise NotImplementedError()
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: `destination`, `filter`, `output_version_format`, `start_time`, and `end_time`. The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` field.
625941cfa05bb46b383ec969
def password_mode_off(self): <NEW_LINE> <INDENT> self._iac_wont(ECHO) <NEW_LINE> self._note_reply_pending(ECHO, True)
Tell client we are done echoing (we lied) and show typing again.
625941cff8510a7c17cf9843
def testNyquist(self, siso): <NEW_LINE> <INDENT> nyquist(siso.ss1) <NEW_LINE> nyquist(siso.tf1) <NEW_LINE> nyquist(siso.tf2) <NEW_LINE> w = logspace(-3, 3) <NEW_LINE> nyquist(siso.tf2, w) <NEW_LINE> (real, imag, freq) = nyquist(siso.tf2, w, plot=False)
Call nyquist()
625941cf167d2b6e31218cde
def make_manual_returnVal(buffer, output_list): <NEW_LINE> <INDENT> buffer.write('\n {\n int i = 0;') <NEW_LINE> buffer.write('\n PyObject *t = NULL;') <NEW_LINE> buffer.write( '\n returnVal = PyTuple_New(%d);' % len(output_list)) <NEW_LINE> count = 0; <NEW_LINE> for count in range(len(output_list)): <NEW_LINE> <IN...
This returnVal function is used when the output dimensions are dynamic. For instance, a double * and an integer specifying the number of elements in that array are passed in. In order to properly build the return tuple, this function can be used.
625941cfd164cc6175782e96
def _get_random_names(num_names: int) -> List[str]: <NEW_LINE> <INDENT> assert num_names > 0 <NEW_LINE> names = [] <NEW_LINE> for i in range(num_names): <NEW_LINE> <INDENT> names.append(f"Steve #{i + 1}") <NEW_LINE> <DEDENT> return names
random is a misnomer. They're just names used during testing.
625941cf851cf427c661a656
def test_aa_argumet_c(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> Base(5, 4) <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> Base([1, 3], [3, 5])
check send more of one argument to funtion
625941cfbe7bc26dc91cd747
def preprocess_data(self): <NEW_LINE> <INDENT> data = pd.read_csv(DataPreparator.dir_name + "/../../data_files/merged_dataset.csv") <NEW_LINE> data["document"] = data["title"].map(str) + " " + data["content"].map(str) <NEW_LINE> for col in ["document"]: <NEW_LINE> <INDENT> data = data[~data[col].str.contains("[\u0600-\...
Create document corpus and preprocess textual data for each document.
625941cf435de62698dfdd95
def show_fit(self, bin_centers, bincontent, fitx, decay, p, covar, chisquare, nbins): <NEW_LINE> <INDENT> self.ax.lines = [] <NEW_LINE> self.ax.plot(bin_centers, bincontent, "b^", fitx, decay(p, fitx), "b-") <NEW_LINE> self.ax.set_xlabel(self.xlabel) <NEW_LINE> self.ax.set_ylabel(self.ylabel) <NEW_LINE> error = [] <NEW...
Plot the fit onto the diagram :param bin_centers: bin centers :param bincontent: bincontents :param fitx: the fit :type fitx: numpy.ndarray :param decay: decay function :type decay: function :param p: fit parameters :type p: list :param covar: covariance matrix :type covar: matrix :param chisquare: chi-squared :type c...
625941cf5510c4643540f52b
def possible_choices(pos_a, pos_b): <NEW_LINE> <INDENT> pos_a = game_map.normalize(pos_a) <NEW_LINE> pos_b = game_map.normalize(pos_b) <NEW_LINE> choices = [] <NEW_LINE> ax, ay, bx, by = pos_a.x, pos_a.y, pos_b.x, pos_b.y <NEW_LINE> if bx < ax: <NEW_LINE> <INDENT> if ax - bx < bx + game_map.width - ax: <NEW_LINE> <INDE...
:param pos_a: :param pos_b: :return: choices
625941cf5fc7496912cc3ac6
def pickle_to_json(which_file: Path) -> None: <NEW_LINE> <INDENT> assert isinstance(which_file, Path) <NEW_LINE> print(f'\nUnpickling and converting {which_file.name} ...') <NEW_LINE> try: <NEW_LINE> <INDENT> with open(which_file, 'rb') as pickle_file: <NEW_LINE> <INDENT> data = pickle.load(pickle_file) <NEW_LINE> if n...
Attempt to decode WHICH_FILE, which must be a pickled data structure, to a corresponding JSON file in the same directory. Try to issue an informative error message if decoding or encoding fails.
625941cf091ae356686670a6
def test_event_init(self): <NEW_LINE> <INDENT> dst = space_time.generate_flat_spacetime(2, 2) <NEW_LINE> e = event.Event(space_time=dst, event_key=1) <NEW_LINE> assert isinstance(e, event.Event) <NEW_LINE> assert id(e.space_time) == id(dst)
Test event init from spacetime and key
625941cf3eb6a72ae02ec626
@COMMANDS.command(dependencies=['foo', 'print'], aliases=['view'], parser=ca.command('', ca.positional('lala', type=str))) <NEW_LINE> def show(args, dependencies): <NEW_LINE> <INDENT> dependencies['print'](args, "BREAK", dependencies)
Print then arguments.
625941cfa4f1c619b28b0180
def locateTuple(self, *args): <NEW_LINE> <INDENT> return _MEDCouplingRemapper.DataArrayInt_locateTuple(self, *args)
locateTuple(self, ivec tupl) -> int 1
625941cf090684286d50ee2e
def get_testbed_by_name(self, name, testbed_list=None): <NEW_LINE> <INDENT> if not testbed_list: <NEW_LINE> <INDENT> tb_list = self.list_testbeds() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tb_list = testbed_list <NEW_LINE> <DEDENT> testbed = None <NEW_LINE> for item in tb_list: <NEW_LINE> <INDENT> if item['name'] ...
Get a testbed JSON object by its name. :param name: testbed name, e.g. '1042_VLAN593_Greg_iSCSI_NFS_CIFS' :param testbed_list: return of list_testbeds(), memory data might be out of date :return: :dict: dict of the testbed :rtype: dict
625941cffff4ab517eb2f584
def _minutes_to_exclude(self): <NEW_LINE> <INDENT> market_opens = self._market_opens.values.astype('datetime64[m]') <NEW_LINE> market_closes = self._market_closes.values.astype('datetime64[m]') <NEW_LINE> minutes_per_day = (market_closes - market_opens).astype(np.int64) <NEW_LINE> early_indices = np.where( minutes_per_...
Calculate the minutes which should be excluded when a window occurs on days which had an early close, i.e. days where the close based on the regular period of minutes per day and the market close do not match. Returns ------- List of DatetimeIndex representing the minutes to exclude because of early closes.
625941cf91af0d3eaac9bb61
def close(self): <NEW_LINE> <INDENT> self.serial.close() <NEW_LINE> self.serial = None <NEW_LINE> logging.info('Closed serial port: %s', self.__serialOpts['port'])
Close the serial port.
625941cf925a0f43d2549fc0
def _create_api_client(api_key): <NEW_LINE> <INDENT> api = xmlrpclib.ServerProxy('https://rpc.gandi.net/xmlrpc/') <NEW_LINE> _ = api.version.info(api_key) <NEW_LINE> return api
gandi api to update an ip address
625941cf7d847024c06be405
def parse(self, **globalargs): <NEW_LINE> <INDENT> if self.buildfile not in ParseContext._parsed: <NEW_LINE> <INDENT> buildfile_family = tuple(self.buildfile.family()) <NEW_LINE> pants_context = self.default_globals(Config.load()) <NEW_LINE> with ParseContext.activate(self): <NEW_LINE> <INDENT> for buildfile in buildfi...
The entry point to parsing of a BUILD file. from twitter.pants.targets.sources import SourceRoot See locate().
625941cfd8ef3951e3243686
def delta_byyear(self, datas): <NEW_LINE> <INDENT> code = "delta_year" <NEW_LINE> timecode = '%Y' <NEW_LINE> return self.delta_period(datas, code, timecode)
Consolidate datas by year datas : Array(2) - datetime - value
625941cf10dbd63aa1bd2cec
def savecache(): <NEW_LINE> <INDENT> caches = dict( streams=g.streams, userdata=g.username_query_cache) <NEW_LINE> with open(g.CACHEFILE, "wb") as cf: <NEW_LINE> <INDENT> pickle.dump(caches, cf, protocol=2) <NEW_LINE> <DEDENT> dbg(c.p + "saved cache file: " + g.CACHEFILE + c.w)
Save stream cache.
625941cfbf627c535bc13317
def execute(request): <NEW_LINE> <INDENT> folder_models = FolderModel.objects.all() <NEW_LINE> folder_json = FolderModel.get_json(folder_models) <NEW_LINE> return HttpResponse(folder_json, content_type='application/json')
folderデータの一覧を返す
625941cf26238365f5f0efb7
def piEstCalcule(self): <NEW_LINE> <INDENT> return self.pi_calcule
Accesseur :return: True si le PI est calcule, False sinon.
625941cf99fddb7c1c9de4d9
def clamp(x: Union[Tensor, np.ndarray], min_val: float = None, max_val: float = None) -> Union[Tensor, np.ndarray]: <NEW_LINE> <INDENT> min_val = x.min() if min_val is None else min_val <NEW_LINE> max_val = x.max() if max_val is None else max_val <NEW_LINE> x[x < min_val] = min_val <NEW_LINE> x[x > max_val] = max_val <...
Clamps an image between min_val and max_val
625941cffbf16365ca6f630e
def el(self): <NEW_LINE> <INDENT> el = self.data['el1'] + self.data['el2'] <NEW_LINE> self.el_cost = round((el - self.past_data['el']) * DB.ELECTRICITY, 2)
electricity counting two tariff
625941cf8a43f66fc4b541ad
def regular(self, count: int) -> List[Tuple[float]]: <NEW_LINE> <INDENT> colors = list() <NEW_LINE> for i in range(count): <NEW_LINE> <INDENT> colors.append(self.root.rotate_hue((360 // count) * i).rgb()) <NEW_LINE> <DEDENT> return colors
Creates a palette of colors evenly spaced around the hue wheel. :param count: Number of colors to generate. :returns: Colors as RGB values.
625941cfd18da76e2353261f
def dry_run(self, batch, phase, alpha): <NEW_LINE> <INDENT> encoder,generator = self.encoder,self.generator <NEW_LINE> generator.eval() <NEW_LINE> encoder.eval() <NEW_LINE> x = batch[0] <NEW_LINE> batch_size = x.shape[0] <NEW_LINE> utils.requires_grad(generator, False) <NEW_LINE> utils.requires_grad(encoder, False) <NE...
dry run model on the batch
625941cf96565a6dacc8f814
@cli.app.CommandLineApp <NEW_LINE> def utbone(app): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path, file_name, bone, topping = app.params.path, app.params.test_file_name, app.params.bone, app.params.topping <NEW_LINE> bone_filename = get_bone_filename(bone, topping) <NEW_LINE> srcfile = os.path.dirname(os.path.realp...
Create test template by path to locate, test file name, bone name and optional `topping` flag. Explanations: - there is two types of templates: simple bone, bone with `mock` and `ddt` package inside. - flag `--topping` (or just `-t`) control which type of template need to be generated. Topping means addi...
625941cfbde94217f3682f39
def pc_output_buffers_full_var(self, *args): <NEW_LINE> <INDENT> return _EnergyBeamforming_swig.randphpert_f_sptr_pc_output_buffers_full_var(self, *args)
pc_output_buffers_full_var(randphpert_f_sptr self, int which) -> float pc_output_buffers_full_var(randphpert_f_sptr self) -> pmt_vector_float
625941cf1b99ca400220abfa
def on_failure(self, exc, task_id, args, kwargs, einfo): <NEW_LINE> <INDENT> sentry_client.captureException() <NEW_LINE> super(BaseTask, self).on_failure(exc, task_id, args, kwargs, einfo)
Log the exceptions to something like sentry.
625941cfc4546d3d9de72b7d
def is_url(self, text): <NEW_LINE> <INDENT> return text.partition("://")[0] in ('http', 'https')
docstring for is_url
625941cf4f6381625f114b83
def dataset_upload(request, population_id): <NEW_LINE> <INDENT> population = get_object_or_404(Population, pk=population_id) <NEW_LINE> if request.FILES: <NEW_LINE> <INDENT> upload_file = request.FILES['file'] <NEW_LINE> path = os.path.join(UPLOADE_DIR, upload_file.name) <NEW_LINE> destination = open(path, 'wb') <NEW_L...
Upload Dataset
625941cf851cf427c661a657
def _shutdown_node(): <NEW_LINE> <INDENT> sleep(3) <NEW_LINE> if IS_WINDOWS: <NEW_LINE> <INDENT> system("shutdown /p /f") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> system("shutdown -h now")
Shutdown local node.
625941cfbe383301e01b55ce
def do_OPTIONS(self): <NEW_LINE> <INDENT> self.send_response(200) <NEW_LINE> self.send_header("Access-Control-Allow-Origin", self.allow_origin) <NEW_LINE> self.send_header("Access-Control-Allow-Methods", "GET, PUT") <NEW_LINE> self.send_header("Access-Control-Allow-Headers", "accept, origin, x-requested-with, authoriza...
Serve a OPTIONS request.
625941cf91af0d3eaac9bb62
def _compounds_array_field(self, field_or_meth, as_array=True, call_args=()): <NEW_LINE> <INDENT> values = [getattr(v, field_or_meth) for v in self.compounds] <NEW_LINE> if callable(values[0]): <NEW_LINE> <INDENT> values = [v(*call_args) for v in values] <NEW_LINE> <DEDENT> if as_array: <NEW_LINE> <INDENT> values = np....
helper to construct an array-like from compound's properties
625941cf3617ad0b5ed68040
def extract(document): <NEW_LINE> <INDENT> tweets = [] <NEW_LINE> i = 1 <NEW_LINE> with open(document, 'r') as data_in: <NEW_LINE> <INDENT> data_in = csv.reader(data_in, delimiter='\t') <NEW_LINE> for row in data_in: <NEW_LINE> <INDENT> if row[2] == '0': <NEW_LINE> <INDENT> sentiment = 'negative' <NEW_LINE> <DEDENT> el...
Extraire les tweets depuis le data set avec leur sentiment correspondant Input: dataset exemple: 12 2 this car is amazing 2 13 3 This is a horrible movie 0 Output: Liste de tweets labelisés sous forme de dictionnaire exemple: [('this car is amazing','positive'),('This is a hor...
625941cf4e4d5625662d4520
@cli.command() <NEW_LINE> def show(): <NEW_LINE> <INDENT> pp({name: list(cases) for name, cases in CASES.items()})
show all cases
625941cf3cc13d1c6d3c74c3