code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def i_na(self, V, m, h, gbar, m_pow, h_pow, e_ion): <NEW_LINE> <INDENT> return gbar * m**m_pow * h**h_pow * (V - e_ion) | calculates sodium-like ion current | 625941e03617ad0b5ed6826a |
def test_requests_per_second(): <NEW_LINE> <INDENT> res = ab.requests_per_second(ab.sample()) <NEW_LINE> assert res == 556.44 | Test requests per second parser. | 625941e010dbd63aa1bd2f16 |
def read_object(filename): <NEW_LINE> <INDENT> with open(filename, 'rb') as file: <NEW_LINE> <INDENT> obj = pickle.load(file) <NEW_LINE> return obj | Convenience function for retrieving object from file using pickle.
Arguments:
filename {str} -- path to file
Returns:
object -- object in file (uses pickle) | 625941e023849d37ff7b3400 |
def get_momentum(self, learning_rate, momentum): <NEW_LINE> <INDENT> return tf.train.MomentumOptimizer(learning_rate, momentum).minimize(self.cost) | Momentum optimizer
:param learning_rate: The learning rate
:param momentum: The momentum parameter for the optimizer
:return: the optimizer | 625941e01f5feb6acb0c4ebe |
def subsets2(self, nums): <NEW_LINE> <INDENT> res = [[]] <NEW_LINE> for num in sorted(nums): <NEW_LINE> <INDENT> res += [item + [num] for item in res] <NEW_LINE> <DEDENT> return res | Some fellow coder's iterative solution | 625941e0851cf427c661a880 |
def test_list_taxonomy(self, client, admin_headers): <NEW_LINE> <INDENT> response = client.get(reverse('damtaxonomy-list'), **admin_headers) <NEW_LINE> assert self.validate_status_response(response, 200) | List taxonomies as an admin | 625941e0656771135c3ebbe6 |
def merge(self, nums1, m, nums2, n): <NEW_LINE> <INDENT> num1_copy = deepcopy(nums1) <NEW_LINE> idx1 = 0 <NEW_LINE> idx2 = 0 <NEW_LINE> while idx1 < m and idx2 < n: <NEW_LINE> <INDENT> if num1_copy[idx1] < nums2[idx2]: <NEW_LINE> <INDENT> nums1[idx1+idx2] = num1_copy[idx1] <NEW_LINE> idx1 += 1 <NEW_LINE> <DEDENT> else:... | :type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead. | 625941e0c4546d3d9de72daa |
def ReadHMIFiles(): <NEW_LINE> <INDENT> StatusReporter.Report.ListHMIFiles(PageDir) | Update the list of available HMI files.
| 625941e0f548e778e58cd8f3 |
def value_size(self, obj): <NEW_LINE> <INDENT> if self._orientation == ORIENTATION_HORIZONTAL: <NEW_LINE> <INDENT> return obj.height() <NEW_LINE> <DEDENT> return obj.width() | Returns the size of the value axis of a QSize/QRect/... | 625941e0b545ff76a8914189 |
@click.command('overview', short_help="Construct overviews in an existing dataset.") <NEW_LINE> @options.file_in_arg <NEW_LINE> @click.option('--build', callback=build_handler, metavar=u"f1,f2,…|b^min..max", help="A sequence of decimation factors specied as " "comma-separated list of numbers or a base and range of " "e... | Construct overviews in an existing dataset.
A pyramid of overviews computed once and stored in the dataset can
improve performance in some applications.
The decimation levels at which to build overviews can be specified as
a comma separated list
rio overview --build 2,4,8,16
or a base and range of exponents.
r... | 625941e02eb69b55b151cc27 |
def read(self, char): <NEW_LINE> <INDENT> self.curr_codon.append(char) <NEW_LINE> if len(self.curr_codon) == 3: <NEW_LINE> <INDENT> new_amino = self.translate(self.curr_codon) <NEW_LINE> if new_amino == '*STOP*': <NEW_LINE> <INDENT> self.is_open = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sequence.append... | Reads next RNA base.
RNA base character is appended to curr_codon. If len(curr_codon) = 3
the codon will be translated into an additional amino acid character
added to sequence and cudd_codon cleared. | 625941e060cbc95b062c68b7 |
def __init__(self, image_title, content, uploader, url, templates, commonsconflict=0): <NEW_LINE> <INDENT> super(TkdialogIC, self).__init__() <NEW_LINE> self.root = Tkinter.Tk() <NEW_LINE> self.root.geometry("600x200+100-100") <NEW_LINE> self.root.title(image_title) <NEW_LINE> self.changename = '' <NEW_LINE> self.skip ... | Constructor. | 625941e024f1403a92600ed7 |
def train(train_dataset, test_dataset, model, batch_size=8, use_gpu=True, learnrate=5e-4, epoch=5, lr_gamma=0.95, lr_step=1, print_every=1, sample_every=800, resume_from=0, save_model_every=5): <NEW_LINE> <INDENT> optimizer = optim.SGD(model.parameters(), lr=learnrate, momentum=0.9) <NEW_LINE> lr_scheduler = torch.opti... | Loop through epoch and execute train_single | 625941e04f88993c3716c3d8 |
def insert_at_rear(self,lower_case): <NEW_LINE> <INDENT> if self.capacity==self.rear: <NEW_LINE> <INDENT> print("Dequeue is full") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in lower_case: <NEW_LINE> <INDENT> self.dequeue.append(i) <NEW_LINE> self.rear+=1 | it will insert elements to the dequeue
:return:it will not return anything | 625941e0fbf16365ca6f653e |
def rot270(a, b): <NEW_LINE> <INDENT> return add(b, mp([[0, 1], [-1, 0]], diff(a, b))) | rotates point a 90 degrees about point b | 625941e04e696a04525c97c1 |
def insertion_last(self, node): <NEW_LINE> <INDENT> if self.head is None: <NEW_LINE> <INDENT> self.insertion_start(node) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp = self.head <NEW_LINE> while temp.next is not self.head: <NEW_LINE> <INDENT> temp = temp.next <NEW_LINE> <DEDENT> temp.next = node <NEW_LINE> node.n... | If there is no elements in circular linked list | 625941e050485f2cf553d10f |
def smooth_path(path, mindist, density=5., interpolator=None): <NEW_LINE> <INDENT> fullpath = [] <NEW_LINE> coords1 = path[0] <NEW_LINE> for i in range(1, len(path)): <NEW_LINE> <INDENT> coords2 = path[i] <NEW_LINE> dist, coords1, coords2 = mindist(coords1, coords2) <NEW_LINE> newpath = InterpolatedPathDensity(coords1,... | return a smooth (interpolated) path
useful for making movies. Especially for min-ts-min pathways
returned by DoubleEndedConnect.
Parameters
----------
path : list of arrays
the pathway to smooth
mindist : callable
function that returns the mindist distance between two structures ::
dist, newcoor... | 625941e0566aa707497f48d8 |
def get_impact_scores(property_correlation_matrix, deviations): <NEW_LINE> <INDENT> assert np.shape(property_correlation_matrix) == (6, 6) <NEW_LINE> assert np.shape(deviations) == (20, 6) <NEW_LINE> R_inv = np.linalg.inv(property_correlation_matrix) <NEW_LINE> impact_scores = [] <NEW_LINE> for deviation_row in deviati... | This is step 7b in the methods section of the MAPP paper.
@param property_correlation_matrix: a 6x6 matrix of property correlations
@param deviations: a 20x6 array that gives the deviation of each amino acid from the estimated distribution of each property
@return: a sequence of twenty impact scores | 625941e03346ee7daa2b30e2 |
@deprecate <NEW_LINE> def _Fkernel_shape(X_shape, basis, periodic_axes): <NEW_LINE> <INDENT> a = np.ones(len(basis._axes), dtype=float) * 2 <NEW_LINE> a[list(periodic_axes)] = 1 <NEW_LINE> basis._axes_shape = tuple((np.array(X_shape)[basis._axes] * a).astype(int)) | Assigns the shape of the kernel in Fourier space with non-periodic padding
to the basis.
Args:
`X_shape`: The shape of discretized microstructure function,
`(n_samples, n_x, ..., n_states)` where `n_samples` is the number
of samples, `n_x` is the spatial discretization, and n_states is
the ... | 625941e02ae34c7f2600d4a5 |
def get_health_monitor(self, lb_id, pool_id, params=None): <NEW_LINE> <INDENT> url = self._HEALTH_MONITORS_URL.format(lb_id=lb_id, pool_id=pool_id) <NEW_LINE> if params: <NEW_LINE> <INDENT> url = "{0}?{1}".format(url, parse.urlencode(params)) <NEW_LINE> <DEDENT> resp, body = self.get(url) <NEW_LINE> body = jsonutils.lo... | Get health monitor details. | 625941e0d53ae8145f87a5de |
def __init__(self, scope, parent, name, result, paren=False): <NEW_LINE> <INDENT> CodeEntity.__init__(self, scope, parent) <NEW_LINE> self.name = name <NEW_LINE> self.result = result <NEW_LINE> self.parenthesis = paren | Constructor for expressions.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
name (str): The name of the expression in the program.
result (str): The return type of the expression in the program.
Kwargs:
paren (b... | 625941e0bde94217f3683162 |
def free_line(p, eps, s, dps1, dps2, ds): <NEW_LINE> <INDENT> px = p[0] <NEW_LINE> py = p[1] <NEW_LINE> s1x = s[0, 0] <NEW_LINE> s1y = s[0, 1] <NEW_LINE> s2x = s[1, 0] <NEW_LINE> s2y = s[1, 1] <NEW_LINE> if s1x == s2x and s1y == s2y: <NEW_LINE> <INDENT> if eucl_dist(p, s[0]) > eps: <NEW_LINE> <INDENT> lf = [-1, -1] <NE... | Usage
-----
Return the free space in the segment s, from point p.
This free space is the set of all point in s whose distance from p is at most eps.
Since s is a segment, the free space is also a segment.
We return a 1x2 array whit the fraction of the segment s which are in the free space.
If no part of s are in the fr... | 625941e060cbc95b062c68b8 |
def on_select(self, cluster_ids, **kwargs): <NEW_LINE> <INDENT> self.update_spike_clusters() <NEW_LINE> self._view.update() | Update the view after a new selection has been made.
Must be overriden. | 625941e01b99ca400220ae27 |
def result_struct_to_msg(query_result): <NEW_LINE> <INDENT> df_result_msg = DialogflowResult() <NEW_LINE> df_result_msg.fulfillment_text = str(query_result.fulfillment_text) <NEW_LINE> df_result_msg.query_text = str(query_result.query_text) <NEW_LINE> df_result_msg.action = str(query_result.action) <NEW_LINE> df_result... | Utility function that fills the result received from Dialogflow into
the ROS msg.
:param query_result: The query_result received from Dialogflow.
:type query_result: QueryResult
:return: The ROS DialogflowResult msg.
:rtype: DialogflowResult | 625941e05fdd1c0f98dc05a9 |
def pair(self, maxtries): <NEW_LINE> <INDENT> print('Pairing transceiver with console...') <NEW_LINE> maxwait = 90 <NEW_LINE> ntries = 0 <NEW_LINE> while ntries < maxtries or maxtries == 0: <NEW_LINE> <INDENT> if self.station.transceiver_is_paired(): <NEW_LINE> <INDENT> print('Transceiver is paired to console') <NEW_LI... | Pair the transceiver with the station console. | 625941e08c3a873295158733 |
def assertIn(self, target, source): <NEW_LINE> <INDENT> if source not in target: <NEW_LINE> <INDENT> message = u'%s not in %s.' % (repr(source), repr(target)) <NEW_LINE> raise AssertionError(message.encode('utf-8')) | Overwrite stdlib to swap the arguments. | 625941e08a349b6b435e84e7 |
def test_fasta_from_biom(self): <NEW_LINE> <INDENT> input_biom_file = join(self.test_data_dir, 'final.s4.biom') <NEW_LINE> table = load_table(input_biom_file) <NEW_LINE> output_fasta = join(self.working_dir, 'final.s4.seqs.fa') <NEW_LINE> fasta_from_biom(table, output_fasta) <NEW_LINE> self.assertTrue(isfile(output_fas... | Test the fasta file from biom table function fasta_from_biom()
| 625941e06e29344779a62984 |
def _parse_with_children(self, *args, **kwargs): <NEW_LINE> <INDENT> self._xmlstate.parse(*args, **kwargs) <NEW_LINE> for propname in self._all_child_props(): <NEW_LINE> <INDENT> for p in xmlutil.listify(getattr(self, propname, [])): <NEW_LINE> <INDENT> p._parse_with_children(None, self._xmlstate) | Set new backing XML objects in ourselves and all our child props | 625941e07cff6e4e81117cfa |
def mws_xml_to_dotdict(data, encoding=MWS_ENCODING, result_key=None, force_cdata=False): <NEW_LINE> <INDENT> xmldict = mws_xml_to_dict(data, encoding=encoding, force_cdata=force_cdata) <NEW_LINE> result = DotDict(xmldict) <NEW_LINE> if result_key: <NEW_LINE> <INDENT> result = result.get(result_key, result) <NEW_LINE> <... | Convert XML expected from MWS to a DotDict object.
first using `mws_xml_to_dict` for our default args to `xmltodict.parse`
and then sending the res | 625941e09f2886367277ac00 |
def set_default_bw(self, loc, bwm=None): <NEW_LINE> <INDENT> sd = loc.std(0) <NEW_LINE> q25, q75 = np.percentile(loc, [25, 75], axis=0) <NEW_LINE> iqr = (q75 - q25) / 1.349 <NEW_LINE> bw = np.where(iqr < sd, iqr, sd) <NEW_LINE> bw *= 0.9 / loc.shape[0] ** 0.2 <NEW_LINE> if bwm is not None: <NEW_LINE> <INDENT> bw *= bwm... | Set default bandwiths based on domain values.
Parameters
----------
loc : array_like
Values from the domain to which the kernel will
be applied.
bwm : scalar, optional
A non-negative scalar that is used to multiply
the default bandwidth. | 625941e04428ac0f6e5bab69 |
def union(dict1, dict2, combiner): <NEW_LINE> <INDENT> keys1 = set(dict1.keys()) <NEW_LINE> keys2 = set(dict2.keys()) <NEW_LINE> result = dict1.copy().update(dict2.copy()) <NEW_LINE> result.update(intersection(dict1, dict2, combiner)) <NEW_LINE> return result | Gives the union of dict1 and dict2, such that if k is in both, then
result[k]=combiner(k, dict1[k], dict2[k]). combiner should be commutative
with regards to the last two variables | 625941e00c0af96317bb855c |
def average_metric_value(words, metric): <NEW_LINE> <INDENT> return sum(map(metric, words)) / len(words) | Apply the metric function to each word in words, returning the average
result. | 625941e094891a1f4081be20 |
def mayavi_scraper(block, block_vars, gallery_conf): <NEW_LINE> <INDENT> from mayavi import mlab <NEW_LINE> image_path_iterator = block_vars['image_path_iterator'] <NEW_LINE> image_paths = list() <NEW_LINE> e = mlab.get_engine() <NEW_LINE> for scene, image_path in zip(e.scenes, image_path_iterator): <NEW_LINE> <INDENT>... | Scrape Mayavi images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
rst : str
The ReSTructuredText that will be rendered ... | 625941e03cc13d1c6d3c76ed |
def intersect(self, nums1, nums2): <NEW_LINE> <INDENT> if not nums1 or not nums2: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> result = [] <NEW_LINE> n = dict() <NEW_LINE> for i in nums1: <NEW_LINE> <INDENT> if i in n: <NEW_LINE> <INDENT> n[i] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n[i] = 1 <NEW_LINE> ... | :type nums1: List[int]
:type nums2: List[int]
:rtype: List[int] | 625941e03539df3088e2e6bf |
def __init__(self, parent=None, btns_dict=None, *args): <NEW_LINE> <INDENT> super().__init__(parent, *args) <NEW_LINE> self.pack() <NEW_LINE> self.buttons = [] <NEW_LINE> if btns_dict: <NEW_LINE> <INDENT> for btn, callback in btns_dict.items(): <NEW_LINE> <INDENT> img_file=os.path.join("img", "{}.gif".format(btn)) <NEW... | Для инициализации кнопок нужно передать словарь в формате
{'имя_кнопки1' : callback-функция, ...} | 625941e0aad79263cf390dbb |
def consume_gold(self, num, reason): <NEW_LINE> <INDENT> logger.debug("consume_gold============= %s" % num) <NEW_LINE> if num > self._finances[const.GOLD]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self._finances[const.CONSUME_GOLD] += num <NEW_LINE> self._finances[const.GOLD] -= num <NEW_LINE> self._owner.a... | 消耗元宝 | 625941e08a349b6b435e84e8 |
def test_serve(self): <NEW_LINE> <INDENT> media_files = ['file.txt', 'file.txt.gz'] <NEW_LINE> for filename in media_files: <NEW_LINE> <INDENT> response = self.client.get('/views/%s/%s' % (self.prefix, filename)) <NEW_LINE> file_path = path.join(media_dir, filename) <NEW_LINE> with open(file_path) as fp: <NEW_LINE> <IN... | The static view can serve static media | 625941e0adb09d7d5db6cb02 |
def test_exc_missingfile(self): <NEW_LINE> <INDENT> self.f['ext'] = ExternalLink('mongoose.hdf5','/foo') <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> self.f['ext'] | KeyError raised when attempting to open missing file | 625941e0711fe17d825426d8 |
def filelist(self, timerange): <NEW_LINE> <INDENT> directories = self.range(timerange) <NEW_LINE> filesurls = [] <NEW_LINE> if directories[0][0:3] == "ftp": <NEW_LINE> <INDENT> return self._ftpfileslist(timerange) <NEW_LINE> <DEDENT> for directory in directories: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> opn = urlop... | Returns the list of existent files in the archive for the
given time range.
Parameters
----------
timerange : `~sunpy.time.TimeRange`
Time interval where to find the directories for a given
pattern.
Returns
-------
filesurls : list of strings
List of all the files found between the time range given.
Ex... | 625941e0d18da76e2353284f |
def build_datasets(self): <NEW_LINE> <INDENT> (X_train, y_train), (X_test, y_test) = self.get_raw_data(self.dataset_name) <NEW_LINE> self.set_datasets(X_train, y_train, X_test, y_test) | Sets the train/validation/test datasets
:return: None | 625941e0f8510a7c17cf9a74 |
def get_output(self, save=True, delete_file=None, update=True, raise_on_error=True): <NEW_LINE> <INDENT> _logme.log(('Getting output, save={}, clean_files={}, ' 'delete_file={}').format( save, self.clean_files, delete_file ), 'debug') <NEW_LINE> if delete_file is None: <NEW_LINE> <INDENT> delete_file = self.clean_outpu... | Get output of function or script.
This is the same as stdout for a script, or the function output for
a function.
By default, output file is kept unless delete_file is True or
self.clean_files is True.
Parameters
----------
save : bool, optional
Save the output to self.out, default True. Would be a good idea to... | 625941e0f8510a7c17cf9a73 |
def get_wagon_path(workspace_path): <NEW_LINE> <INDENT> workspace_file_list = [file for file in os.listdir(workspace_path) if file.endswith('.wgn')] <NEW_LINE> try: <NEW_LINE> <INDENT> filename = workspace_file_list[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return os.path.j... | get the path to the current wagon
We will build the wagon of the current code in a previous test job.
We mount a folder containing the wagon in the test container.
This is the path to the folder containing the wagon.
There should be only one *.wgn file in that folder.
:param workspace_path: the workspace path as atta... | 625941e0d486a94d0b98e4bb |
def read_config(filename): <NEW_LINE> <INDENT> return literal_eval(Path(filename).read_text()) | Read pipeline config file
Since the pipeline configuration makes use of both tuple, and list, a
config file cannot be treated as a standard JSON file. This function
bypasses the issue by using ast.literal_eval(..) instead.
>>> type(read_config("etc/pipeline-opts.py"))
<class 'dict'> | 625941e0b7558d58953c5282 |
def data_generator(all_image_objs, batch_size, input_shape, anchors, num_classes): <NEW_LINE> <INDENT> n = len(all_image_objs) <NEW_LINE> i = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> image_data = [] <NEW_LINE> box_data = [] <NEW_LINE> for b in range(batch_size): <NEW_LINE> <INDENT> if i==0: <NEW_LINE> <INDENT> np.r... | data generator for fit_generator | 625941e0460517430c3944f2 |
def _macroFor(self, rootstr, istr, ilo, ihi, expr_in_i): <NEW_LINE> <INDENT> retdict = {} <NEW_LINE> q = QuantSpec('__temp__', expr_in_i) <NEW_LINE> eval_pieces = {} <NEW_LINE> for ix, tok in enumerate(q): <NEW_LINE> <INDENT> if tok[0] == '[': <NEW_LINE> <INDENT> eval_str = tok[1:-1] <NEW_LINE> if istr in eval_str: <NE... | Internal utility function to build multiple instances of expression
'expr_in_i' where integer i has been substituted for values from ilo to ihi.
Returns dictionary keyed by rootstr+str(i) for each i. | 625941e050812a4eaa59c693 |
def test_005_log(self): <NEW_LINE> <INDENT> now_time = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) <NEW_LINE> real_name = "蔡坨坨" + now_time <NEW_LINE> payload = {"id": 25261, "userUuid": "aa1eeb04-f676-4a95-949c-6fe0a4eab85b", "userName": "ctt01", "realName": real_name, "age": 12, "role": 1, "sex": 1, "bi... | 考试系统前台_查看用户动态 | 625941e0be8e80087fb20fb3 |
def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) < 1: <NEW_LINE> <INDENT> raise TypeError('call requires at least one positional argument') <NEW_LINE> <DEDENT> func = args[0] <NEW_LINE> args = args[1:] <NEW_LINE> if inspect.ismethod(func): <NEW_LINE> <INDENT> obj = six.get_method_self(func) <NEW_LI... | Call a function, injecting the keyword arguments desired by the
function from the keys defined in this mapping. The first
positional parameter must be the function to invoke.
Additional positional arguments are passed directly to the
function, and additional keyword arguments override values
from this mapping. This i... | 625941e0bf627c535bc13544 |
def test_rsvp_no(self): <NEW_LINE> <INDENT> response = self.client.post( '/api/v1/meetups/1/rsvps', data=json.dumps(self.rsvp_items_no), content_type='application/json') <NEW_LINE> self.assertEqual(response.status_code, 201) <NEW_LINE> result = json.loads(response.data.decode('utf-8')) <NEW_LINE> self.assertEqual(resul... | test rsvp a meetup | 625941e0b830903b967e9c7d |
def showAboutWindow(self): <NEW_LINE> <INDENT> about ="About" <NEW_LINE> global aboutstring <NEW_LINE> msgBox = QtGui.QMessageBox(self) <NEW_LINE> msgBox.setWindowIcon(self.about_icon) <NEW_LINE> msgBox.about(msgBox,about,aboutString) | Shows about window | 625941e0ab23a570cc2504fa |
def hashfile(self, filename): <NEW_LINE> <INDENT> results = None <NEW_LINE> with open(filename, 'rb') as hwd: <NEW_LINE> <INDENT> cipher = M2Crypto.EVP.MessageDigest(self._alg) <NEW_LINE> for chunk in iter(lambda: hwd.read(self.CHUNK_SIZE, b'')): <NEW_LINE> <INDENT> cipher.update(chunk) <NEW_LINE> <DEDENT> results = ci... | main process for hashing file contents | 625941e02ae34c7f2600d4a6 |
def create_remote_jokes(self, url=None): <NEW_LINE> <INDENT> url = url or 'https://demo.plone.org/en/demo' <NEW_LINE> plone_view = api.content.get_view('plone', self.context, self.request) <NEW_LINE> jokes = self.random_jokes() <NEW_LINE> headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} <NEW... | Create some jokes on demo.plone.org | 625941e0cad5886f8bd2734e |
def execute(self, talent, modifier=-0): <NEW_LINE> <INDENT> objective, impossible = self._estimae_objective( talent=talent, modifier=modifier, attribute_source=self.SKILL_CHECKS) <NEW_LINE> if impossible: <NEW_LINE> <INDENT> msg = (f'Die Erschwernis von {abs(modifier)} ' 'macht diese Probe unmöglich.') <NEW_LINE> retur... | Perform a test on a certin talent, w.r.t. skikll value and modifier.
Core functionality.
This method allow the execution of the dsa signature content: the
3D20 test. For more details see Held._perform_test or the official
rules at https://ulisses-regelwiki.de/index.php/GR_Proben.html
Parameters
----------
talent : st... | 625941e0cc0a2c11143dd206 |
def normal(loc=0.0, scale=1.0, size=None, dtype=float): <NEW_LINE> <INDENT> rs = generator.get_random_state() <NEW_LINE> return (rs.normal(0, 1, size, dtype) * scale + loc).astype(dtype) | Returns an array of normally distributed samples.
Args:
loc (float or array_like of floats): Mean of the normal distribution.
scale (float or array_like of floats):
Standard deviation of the normal distribution.
size (int or tuple of ints): The shape of the array. If ``None``, a
zero-dimens... | 625941e06fb2d068a760f417 |
def remove_image_from_directory(self, photo: Photo) -> None: <NEW_LINE> <INDENT> if photo not in self.photos: <NEW_LINE> <INDENT> logger.error(f"Can't delete from photo directory cache: Unique entry for deleted image not found.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.photos.remove(photo) <NEW_LINE> logger.... | find the directory entry for the image and remove it; physical deletion of the file
is handled elsewhere; the full original path acts as key here | 625941e0e5267d203edce00e |
@log_call(namespace=__xmlrpc_namespace__) <NEW_LINE> def get_case_run_history(request, case_id): <NEW_LINE> <INDENT> raise NotImplementedError('Not implemented RPC method') | Get the list of case-runs for all runs this case appears in.
To limit this list by build or other attribute, see
:meth:`TestCaseRun.filter <tcms.xmlrpc.api.testcaserun.filter>`.
:param case_id: case ID.
:type case_id: int or str
:return: list of mappings of case runs.
Example::
>>> TestCase.get_case_run_history... | 625941e00a366e3fb873eb92 |
def merge_sort(list1): <NEW_LINE> <INDENT> if len(list1) <= 1: <NEW_LINE> <INDENT> return list1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> midpoint = len(list1)/2 <NEW_LINE> aux1 = list1[0:midpoint] <NEW_LINE> aux2 = list1[midpoint:] <NEW_LINE> aux1 = merge_sort(aux1) <NEW_LINE> aux2 = merge_sort(aux2) <NEW_LINE> re... | Sort the elements of list1.
Return a new sorted list with the same elements as list1.
This function should be recursive. | 625941e01b99ca400220ae28 |
def get_fields(self): <NEW_LINE> <INDENT> fields = super().get_fields() <NEW_LINE> if 'view' in self.context: <NEW_LINE> <INDENT> fields['instance'].queryset = self.context['view'].request.user.instances() <NEW_LINE> <DEDENT> return fields | Get fields for example for django rest framework generated forms | 625941e0c432627299f04fbe |
def read_data(): <NEW_LINE> <INDENT> data = defaultdict(list) <NEW_LINE> with gzip.open('data/data.gz') as file: <NEW_LINE> <INDENT> for i,line in enumerate(file): <NEW_LINE> <INDENT> if line.startswith('ab'): <NEW_LINE> <INDENT> username , boardname = line.strip().split('\t') <NEW_LINE> data[username].append(boardname... | Read data from the data/data.gz
Arrange the data in a dictionary, with board name being the key and users being the values.
#for test purpose, only a subset of users being considered
:return: dictionary of board and users | 625941e0dd821e528d63b51c |
def __init__(self, wrapped, tight=False): <NEW_LINE> <INDENT> self.__tight = tight <NEW_LINE> self.__wrapped = array(wrapped) if tight else wrapped <NEW_LINE> self.__hash = int(xxh64(wrapped.view(uint8)).hexdigest(), 16) | Creates a new hashable object encapsulating an ndarray.
wrapped
The wrapped ndarray.
tight
Optional. If True, a copy of the input ndaray is created.
Defaults to False. | 625941e03346ee7daa2b30e3 |
def __init__(self): <NEW_LINE> <INDENT> self.__max = 0 | A normalizer that uses the all-time absolute max of the passed values. | 625941e0796e427e537b093d |
def SetGradientMagnitudeThreshold(self, *args): <NEW_LINE> <INDENT> return _itkLevelSetMotionRegistrationFilterPython.itkLevelSetMotionRegistrationFilterID3ID3IVF33_SetGradientMagnitudeThreshold(self, *args) | SetGradientMagnitudeThreshold(self, double arg0) | 625941e0e76e3b2f99f3ab7c |
def get_all_buffers(): <NEW_LINE> <INDENT> buffers = [] <NEW_LINE> infolist = w.infolist_get('buffer', '', '') <NEW_LINE> while w.infolist_next(infolist): <NEW_LINE> <INDENT> buffer_type = w.buffer_get_string(w.infolist_pointer(infolist, 'pointer'), 'localvar_type') <NEW_LINE> if buffer_type == 'private': <NEW_LINE> <I... | Returns list with pointers of all open buffers. | 625941e0e1aae11d1e74a02f |
def get_deleted(self, idx, wrapped=True): <NEW_LINE> <INDENT> new_cont=self._storage.copy() <NEW_LINE> del new_cont.r[idx] <NEW_LINE> return Table2DWrapper(new_cont) if wrapped else new_cont | Return a new table with the rows at `idx` deleted.
If ``wrapped==True``, return a new wrapper contating the table; otherwise, just return the table. | 625941e032920d7e50b28548 |
def upgrade(): <NEW_LINE> <INDENT> with op.batch_alter_table('task_instance', schema=None) as batch_op: <NEW_LINE> <INDENT> batch_op.add_column(sa.Column('external_executor_id', sa.String(length=250), nullable=True)) | Apply Add external executor ID to TI | 625941e06aa9bd52df03711b |
def __create_sockets(self, inputs: List[int], outputs: List[int], reset: bool=True): <NEW_LINE> <INDENT> if reset: <NEW_LINE> <INDENT> if hasattr(self, 'inputs') and hasattr(self, 'outputs'): <NEW_LINE> <INDENT> for socket in self.inputs + self.outputs: <NEW_LINE> <INDENT> self.scene.graphics_scene.removeItem(socket.gr... | Creates and adds the Sockets for the Node.
Args:
input (List[int]): The input Socket's representing integer
values.
output (List[int]): The output Socket's representing integer
values.
reset (bool): Flag for if the Sockets should be recreated. | 625941e0a79ad161976cc4ba |
@service(component = "simulation") <NEW_LINE> def deactivate(component_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> blenderapi.persistantstorage().componentDict[component_name]._active = False <NEW_LINE> <DEDENT> except KeyError as detail: <NEW_LINE> <INDENT> logger.warn("Component %s not found. Can't deactivate... | Stop the specified component from calling its default_action method
| 625941e0f548e778e58cd8f4 |
def eval_input_fn(image_filenames,label_filenames=None,batch_size=1): <NEW_LINE> <INDENT> def _parse_function(filename,is_label): <NEW_LINE> <INDENT> if not is_label: <NEW_LINE> <INDENT> image_filename,label_filename=filename,None <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> image_filename,label_filename=filename <NE... | 将图像文件夹处理成模型接收data格式
参数:
image_filenames:图片目录
label_filenames:测试数据没有label
把batch_size:测试默认batch为1
返回值:
data形式的数据包含image和label
| 625941e0a8ecb033257d3441 |
def enter(self, obj, prev_state=None): <NEW_LINE> <INDENT> self.check_configured() <NEW_LINE> if self.on_enter is not None: <NEW_LINE> <INDENT> self.on_enter(obj, prev_state, self.state) | Enter the state
| 625941e0d4950a0f3b08c6c0 |
def plot_chebyshev_problem(A, b, radius = 0, center = [0,0]): <NEW_LINE> <INDENT> n, m = A.shape <NEW_LINE> if n != b.shape[0]: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> lower_lim = center[0] - 1.1*radius - 1 <NEW_LINE> upper_lim = center[0] + 1.1*radius + 1 <NEW_LINE> x = np.linspace(lower_lim, upper_li... | Plots the solution to a chebyshev center problem
The constraints are given by A and b,
And the found ball is given by radius and center | 625941e0eab8aa0e5d26decf |
def checkPartLogic(self, part, se_vals): <NEW_LINE> <INDENT> output = part.isInSeVals(se_vals) <NEW_LINE> return output | Check that the part or it's parents are inside the current logic terms.
See TuflowPart isInSeVals method for further information.
Args:
part(TuflowPart): the part to check logic terms for.
se_vals(dict): containing the current scenario and event values.
Return:
bool - True if it's in the logic terms, or ... | 625941e066656f66f7cbc522 |
def pytest_configure(config): <NEW_LINE> <INDENT> config.option.netbox_versions = [ version.Version(version_string) for version_string in config.option.netbox_versions.split(",") ] | Hook that runs after test collection is completed.
Here we can modify items in the collected tests or parser args. | 625941e0167d2b6e31218f0a |
def generate_output(self, writer): <NEW_LINE> <INDENT> self.write_archive() | Write the assets based on configuration. | 625941e085dfad0860c3b1d1 |
def __init__(self, event, user=None, ssml=True): <NEW_LINE> <INDENT> super(GoogleHomeSkill, self).__init__(event, user) <NEW_LINE> self.skill_type = "APIAI" <NEW_LINE> self.event = event <NEW_LINE> self.ssml = ssml <NEW_LINE> self._contexts = {} <NEW_LINE> if user: <NEW_LINE> <INDENT> self.user = user <NEW_LINE> <DEDEN... | Constructor for Google Home (API.AI) requests.
:param event: <dict> JSON
:param user: <BaseUser> User object | 625941e0498bea3a759b9e24 |
def __init__(self, model, *args, **kwargs): <NEW_LINE> <INDENT> super(CensorsDict, self).__init__(*args, **kwargs) <NEW_LINE> self.model = model <NEW_LINE> return None | A dictionary sub-class that allows for wavelength censoring masks to be
applied to Cannon models.
:param model:
The Cannon model for which this censored dictionary will be applied.
Note: This custom class is necessary because if you have a dictionary
attribute that is a `@property` of a class then it ca... | 625941e001c39578d7e751b1 |
def timedcalls(n, fn, *args): <NEW_LINE> <INDENT> if isinstance(n, int): <NEW_LINE> <INDENT> times = [timedcall(fn, *args)[0] for _ in range(n)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t0 = time.clock() <NEW_LINE> times = [] <NEW_LINE> while (time.clock() - t0 < n): <NEW_LINE> <INDENT> times.append(timedcall(fn, ... | Call fn(*args) repeatedly: n times if n is an int, or up to
n seconds if n is a float; return the min, avg, and max time | 625941e056ac1b37e626453f |
def ef_UrbanArea(self, MAX_GAP=100, MIN_PEAKS=1): <NEW_LINE> <INDENT> if self.dat2p0: <NEW_LINE> <INDENT> urbanArea = self.get_bit( self.mat["mudp"]["eyeq"]["Lights"]["vis_light_sensor_data_info"]["activeLightSensorInfo"]["light_Sensor_Detections_byte"], bit_number_from_right=2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | EF 10: Urban area ON
EF goes through mat indexes and check if UA flag change comparing to previous index.
If so, index is added to indexes list. EF finds only changes in UA signal, so only frequent
flickering is reported, constant detection is discarded (depends on groupIndexes params)
:param MAX_GAP: maxGap parameter... | 625941e0be383301e01b57f5 |
def test_init(self): <NEW_LINE> <INDENT> self.util = CloudStore(self.testenv) <NEW_LINE> self.assertIsNotNone(self.util) | Verify that the CloudStore object initializes correctly. | 625941e08a43f66fc4b543d7 |
def __init__( self, actual_vector=None, predict_vector=None, matrix=None, digit=5, threshold=None, file=None, sample_weight=None, transpose=False): <NEW_LINE> <INDENT> self.actual_vector = actual_vector <NEW_LINE> self.predict_vector = predict_vector <NEW_LINE> self.digit = digit <NEW_LINE> self.weights = None <NEW_LIN... | Init method.
:param actual_vector: Actual Vector
:type actual_vector: python list or numpy array of any stringable objects
:param predict_vector: Predicted Vector
:type predict_vector: python list or numpy array of any stringable objects
:param matrix: direct matrix
:type matrix: dict
:param digit: precision digit (de... | 625941e0f9cc0f698b14096e |
@generate <NEW_LINE> def next() -> Next: <NEW_LINE> <INDENT> key = yield symbol <NEW_LINE> yield assign_signs <NEW_LINE> xs = yield domain <NEW_LINE> res = Next(key, xs) <NEW_LINE> return res | matches v1 <- {a, b, c}, where a, b, c are values in the domain | 625941e092d797404e304501 |
def response(self, code, **kw): <NEW_LINE> <INDENT> typ, dat = self._untagged_response(code, [None], code.upper()) <NEW_LINE> return self._deliver_dat(typ, dat, kw) | (code, [data]) = response(code)
Return data for response 'code' if received, or None.
Old value for response 'code' is cleared. | 625941e02eb69b55b151cc29 |
def evaluate(ast, env): <NEW_LINE> <INDENT> raise NotImplementedError("DIY") | Evaluate an Abstract Syntax Tree in the specified environment. | 625941e0379a373c97cfaebc |
def stream_factory(total_content_length): <NEW_LINE> <INDENT> if total_content_length > 1024 * 500: <NEW_LINE> <INDENT> return TemporaryFile('wb+') <NEW_LINE> <DEDENT> return BytesIO() | Creates a stream depending on content_length. | 625941e08e71fb1e9831db1d |
def test_expand_glob_valid_str(self, api_objects): <NEW_LINE> <INDENT> obj = "ApiList" <NEW_LINE> exp = api_objects.module.expand_global(obj) <NEW_LINE> assert issubclass(exp, pytan3.api_models.ApiList) | Test expand_global in modules. | 625941e07d43ff24873a3018 |
def deal_cards(deck, count=5): <NEW_LINE> <INDENT> return [deck.pop() for elem in range(len(deck)) if elem < count] | Remove the given number of cards from the deck and returns them | 625941e03c8af77a43ae3b19 |
@pac.command() <NEW_LINE> def news(): <NEW_LINE> <INDENT> raw_news = requests.get('https://www.archlinux.org/feeds/news/').text <NEW_LINE> news_feed = minidom.parseString(raw_news) <NEW_LINE> items = news_feed.getElementsByTagName('item') <NEW_LINE> for item in reversed(items[:SHOWN_POSTS]): <NEW_LINE> <INDENT> ni = Ne... | Show the latest news from the Arch Linux RSS feed
| 625941e063d6d428bbe44866 |
def collect_stats(components, real_states, real_obs, testing_obs, weights, vars, Model): <NEW_LINE> <INDENT> weights = np.matrix(weights) <NEW_LINE> training_states = get_states_matrix(components) <NEW_LINE> llj = compute_likelihood(real_obs, training_states, weights, vars) <NEW_LINE> testing_states = sample_testing_st... | Returns stats about the current approx of the posterior | 625941e0796e427e537b093e |
def write(self, data): <NEW_LINE> <INDENT> data_len = len(data) <NEW_LINE> while data_len: <NEW_LINE> <INDENT> if self._ssl is None: <NEW_LINE> <INDENT> self._raise_closed() <NEW_LINE> <DEDENT> result = libssl.SSL_write(self._ssl, data, data_len) <NEW_LINE> self._raw_write() <NEW_LINE> if result <= 0: <NEW_LINE> <INDEN... | Writes data to the TLS-wrapped socket
:param data:
A byte string to write to the socket
:raises:
socket.socket - when a non-TLS socket error occurs
oscrypto.errors.TLSError - when a TLS-related error occurs
ValueError - when any of the parameters contain an invalid value
TypeError - when any of th... | 625941e09b70327d1c4e114c |
def meta_data_update(obj, major_path): <NEW_LINE> <INDENT> path = os.path.join(major_path, PATH_META_SELF, 'access.json') <NEW_LINE> with open(path) as f: <NEW_LINE> <INDENT> d = json.load(f) <NEW_LINE> <DEDENT> now = timestr() <NEW_LINE> d['time-last'] = now <NEW_LINE> submitter = dict() <NEW_LINE> submitter['name'] =... | meta-own.json and meta-foreign.json | 625941e060cbc95b062c68b9 |
def __init__(self, executor: IWorkflowExecutor, max_fails: int = 0, cannot_fail: List[str] = ()): <NEW_LINE> <INDENT> self.executor = executor <NEW_LINE> self.max_fails = max_fails <NEW_LINE> self.cannot_fail = cannot_fail | :param executor: the executor to run the workflows. ex: LinearWorkflowExecutor
:param max_fails: max workflows that can fail without failing the run. put `-1` for unlimited failures.
:param cannot_fail: if max_fails is used, you can specify a workflow that if it fails everything fails. | 625941e0167d2b6e31218f0b |
def set_unc(self,value): <NEW_LINE> <INDENT> func=self._link.o2scl.o2scl_fermion_deriv_nr_set_unc <NEW_LINE> func.argtypes=[ctypes.c_void_p,ctypes.c_void_p] <NEW_LINE> func(self._ptr,value._ptr) <NEW_LINE> return | Set object of type :class:`fermion_deriv` | 625941e06fb2d068a760f418 |
def delete_volume(self, volume): <NEW_LINE> <INDENT> if self._volume_not_present(volume['name']): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.vg.lv_has_snapshot(volume['name']): <NEW_LINE> <INDENT> LOG.error(_('Unabled to delete due to existing snapshot ' 'for volume: %s') % volume['name']) <NEW_LINE> r... | Deletes a logical volume. | 625941e00a366e3fb873eb93 |
def normal_training_cifar(model, datasets, num_of_epochs, num_of_tasks, nn_cnn, batch_size=32): <NEW_LINE> <INDENT> original_accuracies = [] <NEW_LINE> X_train, y_train, X_test, y_test = datasets[0] <NEW_LINE> history, accuracies, _ = train_model(model, X_train, y_train, X_test, y_test, num_of_epochs, nn_cnn, batch_siz... | Train model for 'num_of_tasks' tasks, each task is a different disjoint set of CIFAR-100 images.
Check how accuracy for the first set of images is changing through tasks using normal training.
:param model: Keras model instance
:param datasets: list of disjoint datasets with corresponding train and test set
:param num... | 625941e0187af65679ca5496 |
def process_files(count=None): <NEW_LINE> <INDENT> pbar = enlighten.Counter(total=count, desc='Simple', unit='ticks', bar_format=BAR_FMT, counter_format=COUNTER_FMT) <NEW_LINE> for _ in range(100): <NEW_LINE> <INDENT> time.sleep(0.05) <NEW_LINE> pbar.update(1.1) | Process files with a single progress bar | 625941e091f36d47f21ac86c |
def is_staled(self, id_): <NEW_LINE> <INDENT> key = self._get_key_for_job_id(id_) <NEW_LINE> return not bool(self.client.exists( self._get_metadata_key(key, "heartbeat") )) | Return True if job at id_ is staled. | 625941e026238365f5f0f1e9 |
def initGui(self): <NEW_LINE> <INDENT> icon_path = ':/plugins/Cartography_tricks/icon.png' <NEW_LINE> self.add_action( icon_path, text=self.tr(u'Artificial sun'), callback=self.run, parent=self.iface.mainWindow()) | Create the menu entries and toolbar icons inside the QGIS GUI. | 625941e076d4e153a657eea8 |
def __init__(self, arg_name_list, value_map): <NEW_LINE> <INDENT> self.__dict__['_arg_names'] = arg_name_list <NEW_LINE> self.__dict__['resource'] = None <NEW_LINE> for argname in arg_name_list: <NEW_LINE> <INDENT> if argname in value_map: <NEW_LINE> <INDENT> self.__dict__[argname] = value_map[argname] <NEW_LINE> <DEDE... | Creates a object with attribute being the ones in arg_list
parameter. The arguments are initialized to
:class:`shaperetrieval.workflow.core.Uninit`, except if has
entry in `value_map`.
Args:
arg_name_list (list of str): List of attribute names to
countain in this instances.
value_map (dict of str: objec... | 625941e0cad5886f8bd2734f |
def get_selected_streams(catalog): <NEW_LINE> <INDENT> selected_streams = [] <NEW_LINE> for stream in catalog['streams']: <NEW_LINE> <INDENT> stream_metadata = metadata.to_map(stream['metadata']) <NEW_LINE> if metadata.get(stream_metadata, (), "selected") or metadata.get(stream_metadata, (), "inclusion") == 'a... | Gets selected streams. Checks for an empty breadcrumb
and metadata with a 'selected' or an 'inclusion' == automatic entry | 625941e015fb5d323cde0e8a |
def read_identity_whitelist_tidy(self, mount_point=AWS_DEFAULT_MOUNT_POINT): <NEW_LINE> <INDENT> api_path = utils.format_url( "/v1/auth/{mount_point}/config/tidy/identity-whitelist", mount_point=mount_point, ) <NEW_LINE> response = self._adapter.get(url=api_path) <NEW_LINE> return response.get("data") | Read previously configured periodic whitelist tidying settings.
:param mount_point: The path the AWS auth method was mounted on.
:type mount_point: str
:return: The response of the request.
:rtype: requests.Response | 625941e055399d3f05588a2c |
def get_updates(self, offset=0): <NEW_LINE> <INDENT> timeout = (self.timeout, self.poll_timeout + 1) <NEW_LINE> params = dict(offset=offset, timeout=self.poll_timeout) <NEW_LINE> return requests.post(urljoin(self.url, 'getUpdates'), timeout=timeout, json=params).json() | Get input updates from the server
It uses long polling to get the updates from the server without making
a request every so. Performs a long standing request that will resolve
either when timeout is out or when the server sends some results.
The ``.poll_timeout`` variable is used to know how much to wait for
results ... | 625941e0d58c6744b4257fd4 |
def Update(self, data): <NEW_LINE> <INDENT> return | Updates the current state of the hasher with a new block of data.
Repeated calls to update are equivalent to one single call with the
concatenation of the arguments.
Args:
data (bytes): data with which to update the context of the hasher. | 625941e0be8e80087fb20fb4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.