code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def benchmark_irnn_mnist_bs_256(self): <NEW_LINE> <INDENT> batch_size = 256 <NEW_LINE> metrics, wall_time, extras = benchmark_util.measure_performance( self._build_model, x=self.x_train, y=self.y_train, batch_size=batch_size, optimizer=tf.keras.optimizers.RMSprop(learning_rate=self.learning_rate), loss='categorical_cro... | Measure performance with batch_size=256. | 625941b9d7e4931a7ee9dd96 |
def make_file_state(file_path, clear) -> None: <NEW_LINE> <INDENT> if clear: <NEW_LINE> <INDENT> main.remove_import_pdb(file_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> main.put_import_pdb(file_path) | Remove or put import pdb statement. | 625941b93c8af77a43ae3618 |
@plugin_function("plugins.version") <NEW_LINE> def version(): <NEW_LINE> <INDENT> return VERSION | Returns the version number of the plugin manager.
Returns:
str | 625941b991af0d3eaac9b88f |
def get_collaborators(self, per_page=30, q=None, exclude_project=None): <NEW_LINE> <INDENT> params = filter_locals(locals()) <NEW_LINE> query_params = dict_to_query_params(params) <NEW_LINE> path = "organizations/{}/collaborators{}".format(self.id, query_params) <NEW_LINE> return [ Collaborator(x, organization=self, cl... | get collaborators for this organization | 625941b9ff9c53063f47c077 |
def distanceMots(texte): <NEW_LINE> <INDENT> motFreq={} <NEW_LINE> mots=texte.split() <NEW_LINE> for mot in mots: <NEW_LINE> <INDENT> motFreq[mot]=motFreq.get(mot,0)+1/len(mots) <NEW_LINE> <DEDENT> return motFreq | la fonction prend un texte comme entrée
et elle retourne un dictionnaire avec les fréquences relatives de chaque mot | 625941b9adb09d7d5db6c60d |
def eigenx(x): <NEW_LINE> <INDENT> if typex(x) != 'oper': <NEW_LINE> <INDENT> raise TypeError('not an oper') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if x.shape[0] != x.shape[1]: <NEW_LINE> <INDENT> raise TypeError('not a square oper') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> w, v = LA.eigh(x) <NEW_LINE> vk =... | eigenvalue and eigenvector
Parameters:
-----------
x : operator
Returns:
--------
w : [..., ...] ndarray
vk : [[...,...],[...,...]] matrix
vk[i] is the normalized "ket" eigenvector
accroding to eigenvelue w[i] | 625941b938b623060ff0ac6a |
def main(): <NEW_LINE> <INDENT> male_set = {'male', 'm'} <NEW_LINE> female_set = {'female', 'f'} <NEW_LINE> result_dict = {} <NEW_LINE> with open(data_path, 'r', newline='') as csvfile: <NEW_LINE> <INDENT> rows = csv.reader(csvfile) <NEW_LINE> for i, row in enumerate(rows): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <IN... | 主函数 | 625941b960cbc95b062c63c3 |
def get_queryset(self, request): <NEW_LINE> <INDENT> qs = super(DocumentAdmin, self).get_queryset(request) <NEW_LINE> if request.user.is_superuser: <NEW_LINE> <INDENT> return qs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return qs.filter(user=request.user) | only show the current user's docs | 625941b97c178a314d6ef2d4 |
def find_prime_polynomials(generator=2, c_exp=8, fast_primes=False, single=False): <NEW_LINE> <INDENT> root_charac = 2 <NEW_LINE> field_charac = int(root_charac**c_exp - 1) <NEW_LINE> field_charac_next = int(root_charac**(c_exp+1) - 1) <NEW_LINE> prim_candidates = [] <NEW_LINE> if fast_primes: <NEW_LINE> <INDENT> prim_... | Compute the list of prime polynomials for the given generator and galois field characteristic exponent. | 625941b9bde94217f3682c77 |
def pick_questions(): <NEW_LINE> <INDENT> return Questions[0:2] | Pick questions based on expected length of response and other factors in tags | 625941b90a366e3fb873e692 |
def onInit( isReload ): <NEW_LINE> <INDENT> pass | base cell 都有 回调函数 | 625941b9fff4ab517eb2f2b4 |
def get_data_tushare(self,code,ktype ='D',start='2020-01-01',end="2020-12-31"): <NEW_LINE> <INDENT> dfData = tushare.get_k_data(code = code, start= start, end = end, ktype =ktype, retry_count=3, pause=0.001).sort_index() <NEW_LINE> dfData.index = pd.to_datetime(dfData.date) <NEW_LINE> dfData['openinterest'] = 0 <NEW_LI... | 单代码获取数据
:return: | 625941b9a934411ee3751515 |
def evaluate(self, expr, binds=None): <NEW_LINE> <INDENT> if binds: <NEW_LINE> <INDENT> scope_builder = ScopeBuilder() <NEW_LINE> for key, value in binds.items(): <NEW_LINE> <INDENT> scope_builder.let(key, _arg_to_ast(value)) <NEW_LINE> <DEDENT> scope_builder.ret(expr) <NEW_LINE> expr = scope_builder.get() <NEW_LINE> <... | Evaluate a Relay expression on the executor.
Parameters
----------
expr: tvm.relay.Expr
The expression to evaluate.
binds: Map[tvm.relay.Var, tvm.relay.Expr]
Additional binding of free variable.
Returns
-------
val : Union[function, Value]
The evaluation result. | 625941b926068e7796caeb54 |
def __field_wrapped(self, field, value, output_format): <NEW_LINE> <INDENT> if (len(value) > 0): <NEW_LINE> <INDENT> return self.__format_line_wrapped(field, value, output_format) + ',\n' <NEW_LINE> <DEDENT> return '' | add the value into the return structure, only if a value was defined in Solr
:param field:
:param value:
:param output_format:
:return: | 625941b9d268445f265b4cf0 |
def __data_generation(self, list_IDs_temp): <NEW_LINE> <INDENT> y = np.empty((self.batch_size,), dtype=self.labeltype) <NEW_LINE> X = self.ie.get_batch(list_IDs_temp, from_set = self.from_set) <NEW_LINE> for i, ID in enumerate(list_IDs_temp): <NEW_LINE> <INDENT> y[i] = self.labels[ID] <NEW_LINE> <DEDENT> return X, y | Generates data containing batch_size samples | 625941b915baa723493c3ded |
def write_vector(vector, outfile): <NEW_LINE> <INDENT> out_dir = os.path.dirname(outfile) <NEW_LINE> if not os.path.exists(out_dir): <NEW_LINE> <INDENT> os.makedirs(out_dir) <NEW_LINE> <DEDENT> vector = vector.copy() <NEW_LINE> for k in vector: <NEW_LINE> <INDENT> if isinstance(vector[k], np.ndarray): <NEW_LINE> <INDEN... | Save vector data for a timestep as JSON | 625941b994891a1f4081b923 |
def load_private_key_file(path): <NEW_LINE> <INDENT> with open(path, 'rb') as f: <NEW_LINE> <INDENT> data = f.read() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> key = load_pem_private_key(data, None, default_backend()) <NEW_LINE> log_debug("Successfully loaded PEM encoded private key from {0}.".format(path)) <NEW_LINE... | Loads the private key from the specified file (can be DER or PEM encoded).
Args:
path (str) : Path of the private key file to load.
Returns:
The loaded private key (cryptography private key, not OpenSSL private key!) | 625941b9ec188e330fd5a621 |
def reviewer_stats(df): <NEW_LINE> <INDENT> reviewer_scores = df.groupby(['Reviewer Full Name', 'Control Number', 'Topic'])['Weighted Original Score'].sum() <NEW_LINE> reviewer_avgs = reviewer_scores.groupby('Reviewer Full Name').mean() <NEW_LINE> reviewer_stdevs = reviewer_scores.groupby('Reviewer Full Name').std(ddof... | Isolates scores from individual reviewers and returns each reviewer's mean score and standard deviation
as a tuple of pandas Series in the format (all means, all stdevs)
df: pandas DataFrame. Cleaned df of the format returned by import_data() | 625941b9de87d2750b85fc09 |
def obtener_intervenciones_por_dia(self, ano, mes, dia): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> intervenciones = self.intervencionquirurgica_set.filter(fecha_intervencion__year=ano, fecha_intervencion__month=mes, fecha_intervencion__day=dia, reservacion__estado='A').order_by('hora_inicio') <NEW_LINE> return inter... | Devuelve un diccionario en donde se tiene para un dia, las intervenciones quirurgicas
Parametros:
ano -> Ano de la fecha a consultar
mes -> Mes de la fecha a consultar
dia -> Dia de la fecha a consultar | 625941b98da39b475bd64df2 |
def static_caller(flickr_method,static = False): <NEW_LINE> <INDENT> def decorator(method) : <NEW_LINE> <INDENT> @wraps(method) <NEW_LINE> def static_call(*args,**kwargs): <NEW_LINE> <INDENT> token,kwargs = _get_token(None,**kwargs) <NEW_LINE> method_args,format_result = method(*args,**kwargs) <NEW_LINE> method_args["a... | This decorator binds a static method to the flickr method given
by 'flickr_method'.
The wrapped method should return the argument dictionnary
and a function that format the result of method_call.call_api.
Some method can propagate authentication tokens. For instance a
Person object can propagate its token to photos ... | 625941b9fff4ab517eb2f2b5 |
def euler_angles_from_matrix(R): <NEW_LINE> <INDENT> phi = 0.0 <NEW_LINE> if np.isclose(R[2,0], -1.0): <NEW_LINE> <INDENT> theta = np.pi / 2.0 <NEW_LINE> psi = np.arctan2(R[0,1], R[0,2]) <NEW_LINE> <DEDENT> elif np.isclose(R[2,0], 1.0): <NEW_LINE> <INDENT> theta = -np.pi / 2.0 <NEW_LINE> psi = np.arctan2(-R[0,1], -R[0,... | See http://www.close-range.com/docs/Computing_Euler_angles_from_a_rotation_matrix.pdf
Parameters
----------
R: np.array (3,3).
Rotation matrix.
Returns
-------
psi: float.
Roll angle (in degrees).
theta: float.
Pitch angle (in degrees).
phi: float.
Yaw angle (in degrees). | 625941b97047854f462a1288 |
def errorToString(errorCode): <NEW_LINE> <INDENT> cErr = ctypes.c_int32(errorCode) <NEW_LINE> errStr = ("\0"*constants.MAX_NAME_SIZE).encode("ascii") <NEW_LINE> _staticLib.LJM_ErrorToString(cErr, errStr) <NEW_LINE> return _decodeASCII(errStr) | Returns the the name of an error code.
Args:
errorCode: The error code to look up.
Returns:
The error name string.
Note:
If the constants file that has been loaded does not contain
errorCode, this returns a message saying so. If the constants
file could not be opened, this returns a string saying... | 625941b916aa5153ce3622f3 |
def addAction(self, id, name, action, condition='', permission='', category='Plone', visible=1, appId=None, icon_expr='', description='', REQUEST=None, ): <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> raise ValueError('A name is required.') <NEW_LINE> <DEDENT> a_expr = action and Expression(text=str(action)) or ... | Add an action to our list.
| 625941b99f2886367277a70c |
def nltk_ibm_one(data, iter=5): <NEW_LINE> <INDENT> dual_text = [] <NEW_LINE> for d_i in range(len(data)): <NEW_LINE> <INDENT> fr_sent = word_tokenize(data[d_i]['fr']) <NEW_LINE> eng_sent = word_tokenize(data[d_i]['en']) <NEW_LINE> dual_text.append(AlignedSent(fr_sent, eng_sent)) <NEW_LINE> <DEDENT> ibm_one = IBMModel1... | Returns probability scores of translations based on nltk.translate.ibm1 module | 625941b93cc13d1c6d3c71ff |
def setVisible(self, isVisible): <NEW_LINE> <INDENT> self._isSensitive = isVisible <NEW_LINE> if isVisible: <NEW_LINE> <INDENT> self.dialog = GladeWidget( root='anagrafica_complessa_detail_dialog', callbacks_proxy=self, path='anagrafica_complessa_detail_dialog.glade') <NEW_LINE> self.dialogTopLevel = self.dialog.getTop... | Make the window visible/invisible | 625941b9b7558d58953c4d96 |
def inArea(x, y ,settings): <NEW_LINE> <INDENT> if 0<=x<settings.block_ynum and 0<=y<settings.block_xnum: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | 定界函数,判断坐标(x,y)是否合法 | 625941b929b78933be1e5534 |
def builtin(self, predname): <NEW_LINE> <INDENT> if predname in self.preddict: <NEW_LINE> <INDENT> return self.preddict[predname][0] <NEW_LINE> <DEDENT> return None | Return a CongressBuiltinPred with name PREDNAME or None. | 625941b9d99f1b3c44c67412 |
def reorderComps(self, sortIDs): <NEW_LINE> <INDENT> for key in self._FieldDims: <NEW_LINE> <INDENT> arr = getattr(self, key) <NEW_LINE> dims = self._FieldDims[key] <NEW_LINE> if arr.ndim == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if dims[0] == 'K' and 'K' not in dims[1:]: <NEW_LINE> <INDENT> arr = arr[sort... | Rearrange internal order of all fields along dimension 'K'
| 625941b90c0af96317bb8064 |
@app.route('/api/v1/recipe/:id', ['GET', 'OPTIONS']) <NEW_LINE> def api_v1_recipe(id): <NEW_LINE> <INDENT> if bottle.request.method == 'OPTIONS': <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return { 'recipes': [ recipe.to_dict() for recipe in db.Recipe.select().where( db.Recipe.id == id ) ] } | Get a given recipe from db | 625941b95f7d997b87174916 |
def solve(matrix, visible): <NEW_LINE> <INDENT> current = list(list(r) for r in matrix) <NEW_LINE> while True: <NEW_LINE> <INDENT> changes = tuple(get_changes(current, visible)) <NEW_LINE> if not changes: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> for col, row, val in changes: <NEW_LINE> <INDENT> current[row][col] =... | shift positions until equilibrium is reached. | 625941b9fbf16365ca6f6038 |
def test_authorize(self): <NEW_LINE> <INDENT> order = make_test_order(self.US, '') <NEW_LINE> self.assertEqual(order.balance, order.total) <NEW_LINE> self.assertEqual(order.total, Decimal('125.00')) <NEW_LINE> processor = utils.get_processor_by_key('PAYMENT_DUMMY') <NEW_LINE> processor.create_pending_payment(order=orde... | Test making an authorization using DUMMY. | 625941b9b57a9660fec336fc |
def readPositioners(self): <NEW_LINE> <INDENT> for p in self.positioners: <NEW_LINE> <INDENT> p.read() | Reads current values of all positioner fields from record) | 625941b9dc8b845886cb53b0 |
def fit(self, X, y): <NEW_LINE> <INDENT> super(GCPEiVelocity, self).fit(X, y) <NEW_LINE> self.POU = 0 <NEW_LINE> if len(y) >= self.r_minimum: <NEW_LINE> <INDENT> top_y = sorted(y)[-self.N_BEST_Y:] <NEW_LINE> velocities = [top_y[i + 1] - top_y[i] for i in range(len(top_y) - 1)] <NEW_LINE> self.POU = np.exp(self.MULTIPLI... | Train a gaussian process like normal, then compute a "Probability Of
Uniform selection" (POU) value. | 625941b9435de62698dfdacf |
def add_node_prop(self, prop, prop_map): <NEW_LINE> <INDENT> self.node_props.append(prop) <NEW_LINE> for i in range(len(self.json_graph["nodes"])): <NEW_LINE> <INDENT> self.json_graph["nodes"][i][prop] = prop_map[self.json_graph["nodes"][i]["id"]] | Adds a node property to the json_graph
*Positional arguments:*
.. option:: prop
The name of the property to add
.. option:: prop_map
A mapping from node ID's to property values | 625941b9bf627c535bc13052 |
def f(xpts, *gaussParams): <NEW_LINE> <INDENT> return f_raw(xpts, *gaussParams).ravel() | The normal function call for this function. Performs checks on valid arguments, then calls the "raw" function.
:return: | 625941b923849d37ff7b2f0d |
def doctest_Game(): <NEW_LINE> <INDENT> pass | Tests for Game
>>> from pyspacewar.game import Game
>>> g = Game()
>>> g.world.objects
[]
>>> g.time_source.ticks_per_second == Game.TICKS_PER_SECOND
True | 625941b9462c4b4f79d1d54c |
def test_arXiv_comments(self): <NEW_LINE> <INDENT> self.assertEqual( self.hepform_json['note'], self.record['public_notes'][0]['value'] ) | Test if arXiv comments are created correctly. | 625941b9004d5f362079a1b2 |
def testzerowidth(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError) as e: <NEW_LINE> <INDENT> a = Rectangle(0, 5) <NEW_LINE> <DEDENT> self.assertEqual(e.exception.args[0], "width must be > 0") | Tries a zero width | 625941b985dfad0860c3acd4 |
def get_requirements(parent, reqs, dependencies, ambiguities, query, hints, filters, whatreqs, pick_first): <NEW_LINE> <INDENT> requirements = [] <NEW_LINE> for require in reqs: <NEW_LINE> <INDENT> required_packages = query.filter(provides=require, latest=True, arch=primary_arch) <NEW_LINE> if len(required_packages) ==... | Share code for recursing into requires or recommends | 625941b976e4537e8c3514f3 |
def _do_request(self, method, url, headers={}, params={}, data={}, json=None, files={}, raise_for_status=True, stream=False): <NEW_LINE> <INDENT> if method == 'get': <NEW_LINE> <INDENT> func = requests.get <NEW_LINE> <DEDENT> elif method == 'post': <NEW_LINE> <INDENT> func = requests.post <NEW_LINE> <DEDENT> elif metho... | Does a standard requests call with the passed params but also:
1. Sets the authorization header
2. Will check for server errors in the response and back off if
needed or raise an exception if appropriate.
:param method: one of 'get', 'post', 'put', 'delete'
:param server_error_retries: set to the number... | 625941b97cff6e4e81117801 |
def link_conf_matrix_plotter(self, *parents): <NEW_LINE> <INDENT> self.conf_matrix_plotters = [] <NEW_LINE> prev = parents <NEW_LINE> for i in range(1, len(self.decision.confusion_matrixes)): <NEW_LINE> <INDENT> mp = plotting_units.MatrixPlotter( self, name=(CLASS_NAME[i] + " matrix")) .link_attrs(self.d... | Creates the list of instances of
:class:`veles.plotting_units.MatrixPlotter`.
Links the first :class:`veles.plotting_units.MatrixPlotter` unit
with \*parents.
Links each :class:`veles.plotting_units.MatrixPlotter` unit from
previous :class:`veles.plotting_units.MatrixPlotter` unit.
Links attributes of :class:`veles.plo... | 625941b973bcbd0ca4b2bef9 |
def agent_identity(self, agent_uuid): <NEW_LINE> <INDENT> if '/' in agent_uuid or agent_uuid in ['.', '..']: <NEW_LINE> <INDENT> raise ValueError('invalid agent') <NEW_LINE> <DEDENT> identity_file = os.path.join(self.install_dir, agent_uuid, 'IDENTITY') <NEW_LINE> with ignore_enoent, open(identity_file, 'rt') as file: ... | Return the identity of the agent that is installed.
The IDENTITY file is written to the agent's install directory the
the first time the agent is installed. This function reads that
file and returns the read value.
@param agent_uuid:
@return: | 625941b9091ae35668666de1 |
def gauss(x, *p): <NEW_LINE> <INDENT> A, mu, sigma = p <NEW_LINE> return A*np.exp(-(x-mu)**2/(2.*sigma**2)) | Model gaussian to fit to data. | 625941b95166f23b2e1a4fd5 |
def test_release_lock_and_re_acquire(self, lock_server): <NEW_LINE> <INDENT> name = uuid.uuid4().hex <NEW_LINE> client_1 = lock_server.get_client() <NEW_LINE> client_1.connect() <NEW_LINE> acquired = client_1.lock(name) <NEW_LINE> assert acquired <NEW_LINE> client_1.release() <NEW_LINE> client_1.close() <NEW_LINE> luck... | Test that a locks can be acquired again after it's released | 625941b9566aa707497f43f5 |
def main(): <NEW_LINE> <INDENT> gset = Gtk.Settings.get_default() <NEW_LINE> themename = gset.get_property("gtk-theme-name") <NEW_LINE> cache(themename) <NEW_LINE> prefdark = gset.get_property("gtk-application-prefer-dark-theme") <NEW_LINE> css = Gtk.CssProvider.get_named(themename).to_string() <NEW_LINE> lines = css.s... | main | 625941b9be383301e01b5308 |
def get_tasks(self): <NEW_LINE> <INDENT> return self.session.query(Task).all() | return all the tags | 625941b94d74a7450ccd403e |
def draw_board(self, fg, bg, font_sz): <NEW_LINE> <INDENT> self.coord = {} <NEW_LINE> self.label = {} <NEW_LINE> self.board = [] <NEW_LINE> for i in range(self.degree): <NEW_LINE> <INDENT> self.board.append([0] * self.degree) <NEW_LINE> frm = Frame(self) <NEW_LINE> frm.pack(expand=YES, fill=BOTH) <NEW_LINE> for j in ra... | draws the game board | 625941b93eb6a72ae02ec356 |
def get(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(BaseElasticsearchManyMappedAPIView, self).get(*args, **kwargs) | Get all of the reports of the requested data type associated with the referenced parent instance. | 625941b9a8370b771705271c |
def get_state(self): <NEW_LINE> <INDENT> return self.n_consumed,self.prev_eos_probs | State consists of the number of consumed words, and the
accumulator for previous EOS probability estimates if we
don't use point estimates. | 625941b9711fe17d825421ee |
def AddTestRunnerOptions(option_parser, default_timeout=60): <NEW_LINE> <INDENT> option_parser.add_option('-t', dest='timeout', help='Timeout to wait for each test', type='int', default=default_timeout) <NEW_LINE> option_parser.add_option('-c', dest='cleanup_test_files', help='Cleanup test files on the device after run... | Decorates OptionParser with options applicable to all tests. | 625941b997e22403b379ce15 |
def _write_cache_index_map_section(self): <NEW_LINE> <INDENT> self._write_report('%s %s\n'%(_MARKER_SECTION_BEGIN, _SECTION_NAME_CACHE_INDEX_MAP)) <NEW_LINE> self._write_report('%s %d\n'%(_FIELD_NAME_NUM_CACHE_INDICES, len(self._cache_idx_to_tensor_idx))) <NEW_LINE> for cache_idx in range(0, len(self._cache_idx_to_tens... | Writes the mapping from cache index to tensor index to the report. | 625941b95fc7496912cc3802 |
@task <NEW_LINE> def readme(ctx): <NEW_LINE> <INDENT> ctx.run("restructuredtext-lint README.rst") | Lint the README for reStructuredText syntax issues | 625941b985dfad0860c3acd5 |
def test_index_gates(self): <NEW_LINE> <INDENT> qr = QuantumRegister(2) <NEW_LINE> qc = QuantumCircuit(qr) <NEW_LINE> qc.h(0) <NEW_LINE> qc.cx(0, 1) <NEW_LINE> qc.h(1) <NEW_LINE> qc.h(0) <NEW_LINE> self.assertEqual(qc.data.index((HGate(), [qr[0]], [])), 0) <NEW_LINE> self.assertEqual(qc.data.index((CXGate(), [qr[0], qr... | Verify finding the index of a inst/qarg/carg tuple in circuit.data. | 625941b9ad47b63b2c509e05 |
def query_repositories(clobber=False): <NEW_LINE> <INDENT> global REPOSITORIES <NEW_LINE> if clobber: <NEW_LINE> <INDENT> REPOSITORIES = {} <NEW_LINE> if os.path.exists(REPOSITORIES_FILE): <NEW_LINE> <INDENT> os.remove(REPOSITORIES_FILE) <NEW_LINE> <DEDENT> <DEDENT> if REPOSITORIES: <NEW_LINE> <INDENT> return REPOSITOR... | Return dictionary with information about the various repositories.
The data about a repository looks like this:
.. code-block:: python
"ash": {
"repo": "https://hg.mozilla.org/projects/ash",
"graph_branches": ["Ash"],
"repo_type": "hg"
} | 625941b98a349b6b435e7ff0 |
@task <NEW_LINE> def dump(schema=None): <NEW_LINE> <INDENT> schemas = blueprint.get('schemas', {}).keys() <NEW_LINE> if not schemas: <NEW_LINE> <INDENT> info("No schemas were provided in Postgres settings.") <NEW_LINE> return <NEW_LINE> <DEDENT> if not schema: <NEW_LINE> <INDENT> if len(schemas) == 1: <NEW_LINE> <INDEN... | Dump and download all configured, or given, schemas.
:param schema: Specific schema to dump and download. | 625941b9507cdc57c6306b50 |
def formatwarning(message, category, filename, lineno, line=None): <NEW_LINE> <INDENT> if issubclass(category, ExecutionWarning): <NEW_LINE> <INDENT> s = u"%s: %s\n" % (category.__name__, message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = u'%s: %s, at line %s, in "%s"\n' % (category.__name__, message, lineno, f... | Redefined format warning for maya. | 625941b9293b9510aa2c3115 |
@pytest.mark.parametrize("data, horizon, expected", [([1, 2, 3, 4, 5], 12, 12), ([1, 2, 3, 4, 5], 24, 24), ([1, 2, 3], 8, 8) ]) <NEW_LINE> def test_average_forecast_input_series(data, horizon, expected): <NEW_LINE> <INDENT> model = b.Average() <NEW_LINE> model.fit(pd.Series(data)) <NEW_LINE> preds = model.predict(horiz... | test the average class accepts pandas series | 625941b930dc7b76659017e6 |
def __init__(self, name, network): <NEW_LINE> <INDENT> _BaseObject.__init__(self, network) <NEW_LINE> _Taggable.__init__(self, 'artist') <NEW_LINE> self.name = name | Create an artist object.
# Parameters:
* name str: The artist's name. | 625941b9dd821e528d63b027 |
def top(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise ValueError("Stack is Empty") <NEW_LINE> <DEDENT> return self._head.value | 查询栈顶元素 | 625941b99b70327d1c4e0c50 |
def get_rupture_enclosing_polygon(self, dilation=0): <NEW_LINE> <INDENT> max_rup_radius = self._get_max_rupture_projection_radius() <NEW_LINE> return self.location.to_polygon(max_rup_radius + dilation) | Returns a circle-shaped polygon with radius equal to ``dilation`` plus
:meth:`_get_max_rupture_projection_radius`.
See :meth:`superclass method
<openquake.hazardlib.source.base.SeismicSource.get_rupture_enclosing_polygon>`
for parameter and return value definition. | 625941b9d8ef3951e32433b9 |
def Load(self,m): <NEW_LINE> <INDENT> if isinstance(m,mspace.mspace): <NEW_LINE> <INDENT> self.m=m <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('invalid mspace object') | Load the mspace into mspaceExp | 625941b92ae34c7f2600cfae |
def extract_data(self, target): <NEW_LINE> <INDENT> angle = px2angle(target.width) <NEW_LINE> x_difference = (target.x - self.img_centerX) / self.img_centerX <NEW_LINE> diag_dist = px2dist(target.width) <NEW_LINE> horiz_dist = dist2horizontal(diag_dist) <NEW_LINE> self.distance_stabilizer.insert_measure(horiz_dist) <NE... | 625941b9e64d504609d746bd | |
def dots_test(self): <NEW_LINE> <INDENT> self._assert_username(".", False) <NEW_LINE> self._assert_username("..", False) <NEW_LINE> self._assert_username("...", True) | Test dots. | 625941b93c8af77a43ae3619 |
def _register_directory(self, directory_type, use_name="name"): <NEW_LINE> <INDENT> if use_name == "name": <NEW_LINE> <INDENT> dir_location = "/".join([self._parent_dir, directory_type, self.NAME]) <NEW_LINE> <DEDENT> elif use_name == "generic": <NEW_LINE> <INDENT> dir_location = "/".join([self._parent_dir, directory_t... | Sets an attribute ``component.<directory_type>_dir`` and creates the
directory if it doesn't exist.
Parameters
----------
directory_type : str
The name of the directory type you want to register/create
use_name : str, optional
Default is "name". If this is set, the directory type will contain a
sub-directo... | 625941b944b2445a33931f1c |
def echo(msg): <NEW_LINE> <INDENT> pass | only for debug | 625941b94e4d5625662d4259 |
def weight(self, svid): <NEW_LINE> <INDENT> N = self.N <NEW_LINE> if not svid in N: <NEW_LINE> <INDENT> return 0.01 <NEW_LINE> <DEDENT> if N[svid] > 20: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> return 1.0 - (20 - N[svid])/20.0 | return weighting to be used in position least squares | 625941b98e7ae83300e4ae48 |
def level_emission(self, level): <NEW_LINE> <INDENT> return self.emission | Emission for level. override it to assign different emissions for different levels
@param level: level where 0 is the root
@return: a emission matrix (indexable object) with rows as states and columns as values for emission | 625941b9498bea3a759b992d |
def get_name_utf8(self): <NEW_LINE> <INDENT> return escape_as_utf8(self.name.encode('utf-8 ')if isinstance(self.name, str) else self.name) | Not all names are utf-8, attempt to construct it as utf-8 anyway. | 625941b9711fe17d825421ef |
def _init_revision(self, options): <NEW_LINE> <INDENT> with mo.MMALCameraInfo() as camera_info: <NEW_LINE> <INDENT> camera_num = options['camera_num'] <NEW_LINE> info = camera_info.control.params[mmal.MMAL_PARAMETER_CAMERA_INFO] <NEW_LINE> revision = 'ov5647' <NEW_LINE> if camera_info.info_rev > 1: <NEW_LINE> <INDENT> ... | Query the firmware for the attached camera revision; older firmwares
can't return the revision but only support the OV5647 sensor so we can
assume that revision in such a case. This is also where the placeholder
objects for MAX_RESOLUTION and MAX_FRAMERATE are replaced with their
actual values | 625941b955399d3f05588530 |
def create_table(self, table_name, *fields): <NEW_LINE> <INDENT> q = f" CREATE TABLE {table_name} (" <NEW_LINE> if fields: <NEW_LINE> <INDENT> for field in fields: <NEW_LINE> <INDENT> q += f'{field}, ' <NEW_LINE> <DEDENT> q = q[:len(q)-2] <NEW_LINE> q += ' )' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Creatin... | Parameters:
table_name = The name of the table you want to create.
fields = The fields along with their Type whic needs to be added to the Table.
Ex :('firstname text', 'salary integer')
Description:
To Create Table in the Database along with specific fields. | 625941b97b180e01f3dc4682 |
def add_cardlist(self, new_cardlist: CardList): <NEW_LINE> <INDENT> duplicate_cardlist = self.find_cardlist(new_cardlist) <NEW_LINE> if duplicate_cardlist is None: <NEW_LINE> <INDENT> self.cardlists.append(new_cardlist) <NEW_LINE> logger.info("Cardlist ({}) was added on the Board ({})".format(new_cardlist.id, self.id)) | Adding new cardlist
:param new_cardlist: new cardlist
:return: | 625941b992d797404e304006 |
def get_step_data(self, request, step): <NEW_LINE> <INDENT> return request.session[self.data_session_key][step] | Retrieves data for the specified step | 625941b9ec188e330fd5a622 |
def set_session(session): <NEW_LINE> <INDENT> global _SESSION <NEW_LINE> _SESSION = session | Sets the global TensorFlow session.
# Arguments
session: A TF Session. | 625941b945492302aab5e13d |
def log(self, msg): <NEW_LINE> <INDENT> self.ansible.log(msg) | Prints log message to system log.
Arguments:
msg {str} -- Log message | 625941b9cad5886f8bd26e5f |
def __getitem__(self,key): <NEW_LINE> <INDENT> return self.d[key] | Return item with given key. | 625941b9aad79263cf3908b8 |
def get_security_token(self): <NEW_LINE> <INDENT> if UtilClient.is_unset(self._credential): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> token = self._credential.get_security_token() <NEW_LINE> return token | Get security token by using credential
@rtype: unicode
@return: security token | 625941b98c0ade5d55d3e83c |
def test_site_ga_id(self): <NEW_LINE> <INDENT> settings.SITE_GA_ID = 'UA-42868657-2' <NEW_LINE> request = self.factory.get('/') <NEW_LINE> context_extras = page(request) <NEW_LINE> page_context = context_extras['page'] <NEW_LINE> expected_page_context = { 'ga_id': settings.SITE_GA_ID } <NEW_LINE> self.assertEqual(page_... | Tests that only SITE_GA_ID is defined | 625941b9d58c6744b4257add |
def getMatches(link,title,types=['ODI','T20I']): <NEW_LINE> <INDENT> http = urllib3.PoolManager() <NEW_LINE> r = http.request('GET', link) <NEW_LINE> soup = BeautifulSoup(r.data, 'lxml') <NEW_LINE> match = soup.findAll("div", {"class": 'cb-srs-mtchs-tm'}) <NEW_LINE> results,venue,links,typ = [],[],[],[] <NEW_LINE> for ... | link : series link
title: title of series
types: 'list to filter match' | 625941b930bbd722463cbc3f |
def find_link(self, soup, img_num=0): <NEW_LINE> <INDENT> link = soup.findAll('a')[int(img_num) + 3] <NEW_LINE> return [ self.images_domain + link['href'], link.text] | extract link to page holding image we want | 625941b950485f2cf553cc15 |
def against_contigs(log, blast_db, query_file, hits_file, **kwargs): <NEW_LINE> <INDENT> cmd = [] <NEW_LINE> if kwargs['protein']: <NEW_LINE> <INDENT> cmd.append('tblastn') <NEW_LINE> cmd.append('-db_gencode {}'.format(kwargs['blast_db_gencode'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd.append('blastn') <NEW_... | Blast the query sequence against the contigs.
The blast output will have the scores for later processing. | 625941b91f037a2d8b94607b |
@decorators.check_perm <NEW_LINE> def get_custom_monitor_num(request, cc_biz_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> monitor_num = len(Monitor.objects.filter(biz_id=cc_biz_id, monitor_type='custom', is_enabled=True)) <NEW_LINE> res = { 'result': True, 'message': '', 'data': monitor_num } <NEW_LINE> <DEDENT> e... | 获取自定义监控数量
:param request:
:param cc_biz_id:
:return: | 625941b923849d37ff7b2f0e |
def alert(request, status, message): <NEW_LINE> <INDENT> return render( request, "exam/alert.html", { "status": status, "message": message } ) | Shows page with message
:param request:
:param status: status (success, danger ... for bootstrap)
:param message: message
:return: | 625941b938b623060ff0ac6c |
def test_password_quality(self): <NEW_LINE> <INDENT> factories.PasswordQualityFactory.create(participant=self.old, is_insecure=True) <NEW_LINE> factories.PasswordQualityFactory.create(participant=self.tim, is_insecure=False) <NEW_LINE> self._migrate() <NEW_LINE> self.assertFalse(self.tim.passwordquality.is_insecure) | Only password quality from the newer participant is kept. | 625941b90a366e3fb873e694 |
def draw(self, surface): <NEW_LINE> <INDENT> if self.__visible: <NEW_LINE> <INDENT> if self.active and self.active_image: <NEW_LINE> <INDENT> surface.blit(self.active_image, self.active_rect) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> surface.blit(self.image, self.rect) <NEW_LINE> <DEDENT> if self.text: <NEW_LINE> <... | :param surface:
:return: | 625941b9a934411ee3751517 |
def is_full(board): <NEW_LINE> <INDENT> board_is_full = True <NEW_LINE> for row in board: <NEW_LINE> <INDENT> for col in row: <NEW_LINE> <INDENT> if col == 0: <NEW_LINE> <INDENT> board_is_full = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return board_is_full | Returns True if board is full. | 625941b930bbd722463cbc40 |
def test_home_view_returns_response(): <NEW_LINE> <INDENT> from PeerMid.views.default import home_page <NEW_LINE> request = testing.DummyRequest() <NEW_LINE> response = home_page(request) <NEW_LINE> assert isinstance(response, Response) | Home view returns a Response object. | 625941b94428ac0f6e5ba66f |
def reset_parcov(self, arg=None): <NEW_LINE> <INDENT> self.logger.statement("resetting parcov") <NEW_LINE> self.__parcov = None <NEW_LINE> if arg is not None: <NEW_LINE> <INDENT> self.parcov_arg = arg | reset the parcov attribute to None
Args:
arg (`str` or `pyemu.Matrix`): the value to assign to the parcov
attribute. If None, the private __parcov attribute is cleared
but not reset | 625941b963b5f9789fde6f62 |
def init ( self, parent ): <NEW_LINE> <INDENT> self.control = LEDNumberCtrl( parent, -1 ) <NEW_LINE> self.control.SetAlignment( LEDStyles[ self.factory.alignment ] ) <NEW_LINE> self.set_tooltip() | Finishes initializing the editor by creating the underlying toolkit
widget. | 625941b9fff4ab517eb2f2b7 |
def makeCompMove(self): <NEW_LINE> <INDENT> row, col = -1, -1 <NEW_LINE> while not self.makeMove(row, col, 'O'): <NEW_LINE> <INDENT> col = random.randint(1,boardSize) <NEW_LINE> row = random.randint(1,boardSize) <NEW_LINE> <DEDENT> print("Computer chose: "+str(row)+","+str(col)) | function ALPHA-BETA-SEARCH(state) returns an action
v ←MAX-VALUE(state,−∞,+∞)
return the action in ACTIONS(state) with value v
function MAX-VALUE(state,α, β) returns a utility value
if TERMINAL-TEST(state) then return UTILITY(state) # determine if state is terminal or not, a terminal state is when the boar... | 625941b9a4f1c619b28afebe |
def _message_symbol(self, msgid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)] <NEW_LINE> <DEDENT> except UnknownMessageError: <NEW_LINE> <INDENT> return msgid | Get the message symbol of the given message id
Return the original message id if the message does not
exist. | 625941b963d6d428bbe4436c |
def serialize_property(self, value): <NEW_LINE> <INDENT> if isinstance(value, self.LITERAL_PROPERTY_TYPES): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return port.to_u(value) | Serialize a Mixpanel property value. According to
https://mixpanel.com/docs/properties-or-segments/property-data-types
the allowed types are string, numeric, boolean, date (represented as a
string) and list. | 625941b99c8ee82313fbb5f2 |
def post_order(self): <NEW_LINE> <INDENT> return super(AVLBST, self).post_order() | Inherit method from superclass. | 625941b930dc7b76659017e7 |
def conv_backward_naive(dout, cache): <NEW_LINE> <INDENT> dx, dw, db = None, None, None <NEW_LINE> x, w, b, conv_param = cache <NEW_LINE> pad = conv_param['pad'] <NEW_LINE> stride = conv_param['stride'] <NEW_LINE> F, C, HH, WW = w.shape <NEW_LINE> N, C, H, W = x.shape <NEW_LINE> H_new = 1 + (H + 2 * pad - HH) / stride ... | A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b | 625941b9b830903b967e9793 |
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return DriverExternalIds( ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return DriverExternalIds( ) | Test DriverExternalIds
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | 625941b9b7558d58953c4d98 |
def get_geo_info(filename, band=1): <NEW_LINE> <INDENT> sourceds = gdal.Open(filename, GA_ReadOnly) <NEW_LINE> ndv = sourceds.GetRasterBand(band).GetNoDataValue() <NEW_LINE> xsize = sourceds.RasterXSize <NEW_LINE> ysize = sourceds.RasterYSize <NEW_LINE> geot = sourceds.GetGeoTransform() <NEW_LINE> projection = osr.Spat... | Gets information from a Raster data set
| 625941b9eab8aa0e5d26d9db |
def test_save_multiple_users(self): <NEW_LINE> <INDENT> self.user.saveUser() <NEW_LINE> test_user = User("Ray", "12345678") <NEW_LINE> test_user.saveUser() <NEW_LINE> self.assertEqual(len(User.userList), 2) | method to test multiple saved users | 625941b9e8904600ed9f1da6 |
def find_xml_generator(name="castxml"): <NEW_LINE> <INDENT> if sys.version_info[:2] >= (3, 3): <NEW_LINE> <INDENT> path = _find_xml_generator_for_python_greater_equals_33(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = _find_xml_generator_for_legacy_python(name) <NEW_LINE> <DEDENT> if path == "" or path is N... | Try to find a c++ parser (xml generator)
Args:
name (str): name of the c++ parser (e.g. castxml)
Returns:
path (str), name (str): path to the xml generator and it's name
If no c++ parser is found the function raises an exception.
pygccxml does currently only support castxml as c++ parser. | 625941b9379a373c97cfa9c7 |
def emit(self, ev_name): <NEW_LINE> <INDENT> for callback in self.callbacks[ev_name]: <NEW_LINE> <INDENT> callback(self) | Emit an event, triggered every callback registered to it. | 625941b9925a0f43d2549cf1 |
def renderHook(self): <NEW_LINE> <INDENT> pass | Hook for post processing | 625941b929b78933be1e5536 |
def _emitNewImageInfo(self): <NEW_LINE> <INDENT> printInfo("INFO: %s: MARKETPLACE_AND_IMAGEID %s %s" % (os.path.basename(self.args[0]), self.targetMarketplace, self.snapshotMarketplaceId)) | To be able to recover image ID from log file by image creation test. | 625941b90fa83653e4656e3a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.