code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, graph_property, value, strategy=SaveAlways): <NEW_LINE> <INDENT> self._create_private_fields() <NEW_LINE> self.graph_property = graph_property <NEW_LINE> self._previous_value = copy.copy(value) <NEW_LINE> self.value = value <NEW_LINE> self.strategy = strategy <NEW_LINE> if not issubclass(self.strateg... | Initialize the value manager.
:param graph_property: The graph property to manage
:type graph_property: mogwai.properties.base.GraphProperty
:param value: The initial value of the column
:type value: Object
:param strategy: The callable condition to compare against. If none given, it won't be used
:type strategy: mogw... | 625941debf627c535bc13511 |
def cv(x, y, model, K=4): <NEW_LINE> <INDENT> skf = cross_validation.StratifiedKFold(y, n_folds=K, shuffle=True, random_state=0) <NEW_LINE> result_list = [] <NEW_LINE> for train_index, test_index in skf: <NEW_LINE> <INDENT> x_train, y_train = x[train_index], y[train_index] <NEW_LINE> model.fit(x_train, y_train) <NEW_LI... | cross validation for model
@Parameters
x: numpy.array, with shape: (n, m)
y: numpy.array, with shape: (n,)
model: model,
e.x.: model = RandomForestClassifier(n_jobs=-1, n_estimators=100,
criterion='entropy', max_depth=8, random_state=123)
K: n_folds
@Return
info: trained result in... | 625941de7047854f462a1748 |
def rebuild(self, context, instance, image_meta, injected_files, admin_password, bdms, detach_block_devices, attach_block_devices, network_info=None, recreate=False, block_device_info=None, preserve_ephemeral=False): <NEW_LINE> <INDENT> LOG.debug('Rebuild called for instance', instance=instance) <NEW_LINE> instance.tas... | Rebuild/redeploy an instance.
This version of rebuild() allows for supporting the option to
preserve the ephemeral partition. We cannot call spawn() from
here because it will attempt to set the instance_uuid value
again, which is not allowed by the Ironic API. It also requires
the instance to not have an 'active' prov... | 625941de8e7ae83300e4b30f |
def _do_validate_sale_order(self, sale, domain_filter): <NEW_LINE> <INDENT> if not self.env["sale.order"].search_count( [("id", "=", sale.id)] + domain_filter ): <NEW_LINE> <INDENT> return "{} {} job bypassed".format(sale.display_name, sale) <NEW_LINE> <DEDENT> sale.action_confirm() <NEW_LINE> return "{} {} confirmed s... | Validate a sales order, filter ensure no duplication | 625941dec4546d3d9de72d78 |
def compareVersion(self, version1, version2): <NEW_LINE> <INDENT> v1lst = version1.split('.') <NEW_LINE> v2lst = version2.split('.') <NEW_LINE> m,n = map(len, [v1lst, v2lst]) <NEW_LINE> tlen = min(m,n) <NEW_LINE> last_idx = 0 <NEW_LINE> for i in range(tlen) : <NEW_LINE> <INDENT> if(int(v1lst[i]) > int(v2lst[i])) : retu... | :type version1: str
:type version2: str
:rtype: int | 625941de460517430c3944c0 |
def vecsyz(vs, x=0): <NEW_LINE> <INDENT> return [vecyz(v, x) for v in vs] | Convert vxy[] to Vector[] | 625941ded8ef3951e3243880 |
def check_origin(*args, **kwargs): <NEW_LINE> <INDENT> return True | for deploy it with nginx reverse proxy
Since Tornado 4.0, it has some changes. | 625941de55399d3f055889f8 |
def on_key(self,event): <NEW_LINE> <INDENT> if event.key == 't': <NEW_LINE> <INDENT> self.key = 't' <NEW_LINE> <DEDENT> if event.key == 'x': <NEW_LINE> <INDENT> self.key = 'x' <NEW_LINE> <DEDENT> if event.key == 'enter': <NEW_LINE> <INDENT> inv=False <NEW_LINE> case = '' <NEW_LINE> if self.pos1 !='' and self.pos2 !='':... | Events on key stroke | 625941de0c0af96317bb852a |
def _proc_killer(): <NEW_LINE> <INDENT> def killer(): <NEW_LINE> <INDENT> while not BlueBird.exit_flag: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> <DEDENT> print("\n--- Sending SIGINT to self ---\n") <NEW_LINE> os.kill(os.getpid(), signal.SIGINT) <NEW_LINE> <DEDENT> threading.Thread(target=killer).start() | Starts another thread which waits for BlueBird.exit_flag to be set, then sends
SIGINT to our own process. This is apparently the easiest way to clean things up and
cause the Flask server to exit if you decide to run it in another thread ¯\_(ツ)_/¯ | 625941deb7558d58953c5251 |
@config.command() <NEW_LINE> @click.option("--glob", is_flag=True) <NEW_LINE> @click.option("--local", is_flag=True) <NEW_LINE> def show(glob, local): <NEW_LINE> <INDENT> console.info("Read rogue environment") <NEW_LINE> if glob: <NEW_LINE> <INDENT> path = DEFAULT_CONFIG_FILE <NEW_LINE> <DEDENT> elif local: <NEW_LINE> ... | Add rogue configuration | 625941de5f7d997b87174ddd |
def new_cuts(partition): <NEW_LINE> <INDENT> return { tuple(sorted((node, neighbor))) for node in partition.flips for neighbor in partition.graph.neighbors(node) if partition.crosses_parts((node, neighbor)) } | The edges that were not cut, but now are | 625941de462c4b4f79d1da12 |
def train_step_dipole(self, step): <NEW_LINE> <INDENT> Ncase_train = self.TData.NTrain <NEW_LINE> start_time = time.time() <NEW_LINE> train_loss = 0.0 <NEW_LINE> train_energy_loss = 0.0 <NEW_LINE> train_dipole_loss = 0.0 <NEW_LINE> train_grads_loss = 0.0 <NEW_LINE> num_of_mols = 0 <NEW_LINE> pre_output = np.zeros((sel... | Perform a single training step (complete processing of all input), using minibatches of size self.batch_size
Training object including dipole.
Args:
step: the index of this step. | 625941de30dc7b7665901ca5 |
def point_in_polygon(xc, yc, polygon): <NEW_LINE> <INDENT> x0, y0 = polygon[0] <NEW_LINE> xt, yt = polygon[-1] <NEW_LINE> if (x0, y0) != (xt, yt): <NEW_LINE> <INDENT> polygon.append((x0, y0)) <NEW_LINE> <DEDENT> ray_count = np.zeros(xc.shape, dtype=int) <NEW_LINE> num = len(polygon) <NEW_LINE> j = num - 1 <NEW_LINE> fo... | Use the ray casting algorithm to determine if a point
is within a polygon. Enables very fast
intersection calculations!
Parameters
----------
xc : np.ndarray
2d array of xpoints
yc : np.ndarray
2d array of ypoints
polygon : iterable (list)
polygon vertices [(x0, y0),....(xn, yn)]
note: polygon can be o... | 625941de6fece00bbac2da84 |
def exportPl(self, speaker, pl, force, details): <NEW_LINE> <INDENT> fileName = pl.title.replace('/', '_').replace('\\', '_') + '.xspf' <NEW_LINE> if not force and os.path.isfile(fileName): <NEW_LINE> <INDENT> print('Error: file already exists: ' + fileName) <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT... | Export playlist from speaker to an XSPF file. | 625941de1f5feb6acb0c4e8d |
def remove(name, **kwargs): <NEW_LINE> <INDENT> cmd = "sysrc -v" <NEW_LINE> if "file" in kwargs: <NEW_LINE> <INDENT> cmd += " -f " + kwargs["file"] <NEW_LINE> <DEDENT> if "jail" in kwargs: <NEW_LINE> <INDENT> cmd += " -j " + kwargs["jail"] <NEW_LINE> <DEDENT> cmd += " -x " + name <NEW_LINE> sysrcs = __salt__["cmd.run"]... | Remove system rc configuration variables
CLI Example:
.. code-block:: bash
salt '*' sysrc.remove name=sshd_enable | 625941dea219f33f34628ca8 |
def Update(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Update') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) | Updates an autoscaler in the specified project using the data included in the request.
Args:
request: (ComputeRegionAutoscalersUpdateRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(Operation) The response message. | 625941de0fa83653e46572fb |
def main(global_config, **settings): <NEW_LINE> <INDENT> engine = engine_from_config(settings, 'sqlalchemy.') <NEW_LINE> config = Configurator(settings=settings) <NEW_LINE> initialize_sql(engine) <NEW_LINE> config.scan('tvflix.models') <NEW_LINE> config.include("cornice") <NEW_LINE> config.add_static_view('static', 'st... | This function returns a Pyramid WSGI application.
| 625941de4a966d76dd551354 |
def _rm_checkpoint(self, name): <NEW_LINE> <INDENT> raise NotImplementedError() | Remove a checkpoint
Args:
name(str): name that indentifies the checkpoint
(it may be a filepath) | 625941de8a43f66fc4b543a4 |
def _tie_breaker_score(self) -> str: <NEW_LINE> <INDENT> diff = self.player_one.score - self.player_two.score <NEW_LINE> if self._check_winner(diff, POINT_LIMIT_TIE_BREAKER): <NEW_LINE> <INDENT> return f'Winner {self.winner.name}' <NEW_LINE> <DEDENT> return f'{self.player_one.score} - {self.player_two.score}' | Check which player is winning and establish the correct score just for tie breaker games | 625941dedc8b845886cb5879 |
def add_file(self, path, tag): <NEW_LINE> <INDENT> self.assert_not_queried() <NEW_LINE> self._files.append({ "path": path, "tag": tag }) <NEW_LINE> pass | 添加文件
| 625941de6aa9bd52df0370e8 |
def by_entity(entity): <NEW_LINE> <INDENT> for klass in _registry: <NEW_LINE> <INDENT> if entity in _registry[klass]: <NEW_LINE> <INDENT> return Entry(entity, _registry[klass][entity]) | Generator that yields all the components of a given entity | 625941de3cc13d1c6d3c76bc |
def splice(self, *args: Any) -> None: <NEW_LINE> <INDENT> new_dict = {} <NEW_LINE> if len(args) == 2: <NEW_LINE> <INDENT> for key in list(self._dict.keys())[args[0] : args[0] + args[1]]: <NEW_LINE> <INDENT> new_dict[key] = self._dict[key] <NEW_LINE> <DEDENT> <DEDENT> elif len(args) > 2 and args[1] == 0: <NEW_LINE> <IND... | Cut or replace array. | 625941defff4ab517eb2f780 |
def get_excluded_node_set(node): <NEW_LINE> <INDENT> return list(leaves_list_ind - set([l.ind for l in node])) | this function serve to get T-A according to Farris
algorithm | 625941de26238365f5f0f1b5 |
def get_descriptive_name(self): <NEW_LINE> <INDENT> long_name = str(self.year) + ' ' + self.make + ' ' + self.model <NEW_LINE> return long_name.title() | Returns a neatly formatted descriptive name | 625941de5e10d32532c5f269 |
def __init__(self, size=100): <NEW_LINE> <INDENT> self.count = 0 <NEW_LINE> self.size = size <NEW_LINE> self.inited = False <NEW_LINE> self.openArray = np.zeros(size) <NEW_LINE> self.highArray = np.zeros(size) <NEW_LINE> self.lowArray = np.zeros(size) <NEW_LINE> self.closeArray = np.zeros(size) <NEW_LINE> self.volumeAr... | Constructor | 625941de004d5f362079a674 |
def connect(self, destpair): <NEW_LINE> <INDENT> if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): <NEW_LINE> <INDENT> raise GeneralProxyError((5, _generalerrors[5])) <NEW_LINE> <DEDENT> if self.__proxy[0] == PROXY_TYPE_SOCKS5: <NEW_LINE> <I... | connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy(). | 625941de85dfad0860c3b19f |
def testROIArbitraryDegrees(self): <NEW_LINE> <INDENT> self.shot.ticksPaddleCentered = 0 <NEW_LINE> self.shot.roi.alt = -50.0 <NEW_LINE> arbNum = 0.213 <NEW_LINE> self.shot.setROIAltitude(arbNum, 1.0) <NEW_LINE> deg = 45.0 - ( arbNum * 45.0 ) <NEW_LINE> altDiff = self.DISTANCE * math.tan(math.radians(deg)) <NEW_LINE> s... | Try passing in an arbitrary number (0.213) to setROIAltitude | 625941de1d351010ab855e5e |
def sety(self, y): <NEW_LINE> <INDENT> assert type(y) is NP.ndarray, 'y must be a numpy.ndarray.' <NEW_LINE> assert len(y.shape)==1, 'y must be a 1-dimensional array.' <NEW_LINE> assert y.shape[0] > 0 <NEW_LINE> uniquey = list(set(y)) <NEW_LINE> assert len(uniquey)==2, 'y must have two unique values.' <NEW_LINE> unique... | set the phenotype y.
--------------------------------------------------------------------------
Input:
y : [N] 1-dimensional array of phenotype values (-1.0 or 1.0)
-------------------------------------------------------------------------- | 625941dee5267d203edcdfdc |
def pchain(*args): <NEW_LINE> <INDENT> rets = deque() <NEW_LINE> for p in args: <NEW_LINE> <INDENT> rets.append((yield from p)) <NEW_LINE> <DEDENT> return tuple(rets) | Like `itertools.chain` but using `yield from`
This ensures than `.send` works as expected and the underlying
plans get the return values
Parameters
----------
args :
generators (plans)
Yields
------
msg : Msg
The messages from each plan in turn | 625941de30c21e258bdfa7e2 |
def _max_coindependent(self, X): <NEW_LINE> <INDENT> return X - self._matroid._augment(self._contractions.union(self._groundset - X), X) | Compute a maximal coindependent subset.
INPUT:
- ``X`` -- An object with Python's ``frozenset`` interface containing
a subset of ``self.groundset()``.
OUTPUT:
A maximal coindependent subset of ``X``.
EXAMPLES::
sage: from sage.matroids.advanced import *
sage: M = MinorMatroid(matroids.named_matroids.Vam... | 625941de1f037a2d8b946540 |
def resnet272bn_cifar100(classes=100, **kwargs): <NEW_LINE> <INDENT> return get_resnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="resnet272bn_cifar100", **kwargs) | ResNet-272(BN) model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~... | 625941de442bda511e8be757 |
def spalign(self, other): <NEW_LINE> <INDENT> if isinstance(other, SparseCSR): <NEW_LINE> <INDENT> self._csr.align(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._csr.align(other._csr) | See `SparseCSR.align` for details | 625941dec432627299f04f8b |
def agent_step(self, reward, observation): <NEW_LINE> <INDENT> if np.random.random() < self.epsilon: <NEW_LINE> <INDENT> action = np.random.randint(0, len(self.actions)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shuf = np.random.permutation(self.actions.shape[0]) <NEW_LINE> action = shuf[np.argmax(self.q_values[obs... | A step taken by the agent.
Args:
reward (float): the reward received for taking the last action taken
observation (Numpy array): the state observation from the
environment's step based, where the agent ended up after the
last step
Returns:
The action the agent is taking. | 625941de9c8ee82313fbbab9 |
def _plot_avg(self) -> None: <NEW_LINE> <INDENT> title = '{}: {}% {}, {}% {}. P={} W/cm²'.format(self.cte.lattice['name'], self.concentration.S_conc, self.cte.states['sensitizer_ion_label'], self.concentration.A_conc, self.cte.states['activator_ion_label'], exp_to_10(self.power_dens)) <NEW_LINE> index_GS_S = 0 <NEW_LIN... | Overrides the Solution method to plot
the average offset-corrected simulated data (list_avg_data) and experimental data. | 625941deb5575c28eb68e346 |
def processors(interface=IProcessor, recurse=True): <NEW_LINE> <INDENT> return implementations(interface, recurse) | Returns the processors implementing a given interface and, if recurse,
any of the descendants of this interface. | 625941de4e4d5625662d4717 |
def getClozeItems(self, matches): <NEW_LINE> <INDENT> matches.sort(key=lambda x: int(x[0])) <NEW_LINE> groups = groupby(matches, itemgetter(0)) <NEW_LINE> items = [] <NEW_LINE> keys = [] <NEW_LINE> for key, data in groups: <NEW_LINE> <INDENT> phrases = tuple(item[1] for item in data) <NEW_LINE> keys.append(key) <NEW_LI... | Returns a list of items that were clozed by the user | 625941ded7e4931a7ee9e261 |
def get_geo(self, address: str) -> Optional[CoordinatesAddress]: <NEW_LINE> <INDENT> service = GmapsCacheableReverseByAddressService(storage=self.storage, api=self.api) <NEW_LINE> return service.get_geo(address) | Return address coordinates and geocoded address by template. | 625941ded486a94d0b98e48a |
def get_last_row(csv_filename): <NEW_LINE> <INDENT> with open(csv_filename, 'r') as f: <NEW_LINE> <INDENT> lastrow = None <NEW_LINE> for row in csv.reader(f): <NEW_LINE> <INDENT> if (row != []): <NEW_LINE> <INDENT> lastrow = row <NEW_LINE> <DEDENT> <DEDENT> return lastrow | Function which returns just the last row of a CSV file. We have to
read every line of the file, there was no stackoverflow example of
reading just the last line.
http://stackoverflow.com/questions/20296955/reading-last-row-from-csv-file-python-error | 625941defb3f5b602dac39da |
def test_IndependentSetGenerator_parameters(): <NEW_LINE> <INDENT> generator = ecole.instance.IndependentSetGenerator(graph_type="erdos_renyi") <NEW_LINE> assert generator.graph_type.name == "erdos_renyi" | Parameters are bound in the constructor and as attributes. | 625941de627d3e7fe0d69194 |
def _fit_at_zbest_group(ix, fnu_corr, efnu_corr, zbest, zp, get_err, fitter, tempfilt, TEF, ARRAY_DTYPE, _self): <NEW_LINE> <INDENT> NOBJ = len(ix) <NEW_LINE> NTEMP = tempfilt.NTEMP <NEW_LINE> NDRAWS = 100 <NEW_LINE> if get_err > 1: <NEW_LINE> <INDENT> NDRAWS = int(get_err) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Standalone function for fitting individual objects and getting
coefficients and random draws | 625941ded58c6744b4257fa1 |
def start(self, manage_manually=False): <NEW_LINE> <INDENT> if self.is_active(): <NEW_LINE> <INDENT> self._stack.append(self._current_frame.fork(manage_manually)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._stack.append(RevisionContextStackFrame(manage_manually)) | Begins a revision for this thread.
This MUST be balanced by a call to `end`. It is recommended that you
leave these methods alone and instead use the revision context manager
or the `create_revision` decorator. | 625941de5fcc89381b1e1a04 |
def postprocess_failed(self): <NEW_LINE> <INDENT> pass | Postprocessing after the job was reported as failed. By default do nothing. | 625941de0383005118ecf924 |
def needed_qt_libs(mname, qt_libs): <NEW_LINE> <INDENT> LIB_DEPS = { "QtCore": [], "QtDeclarative": ["QtNetwork", "QtGui"], "QtGui": ["QtCore"], "QtHelp": ["QtGui"], "QtMultimedia": ["QtGui"], "QtNetwork": ["QtCore"], "QtOpenGL": ["QtGui"], "QtScript": ["QtCore"], "QtScriptTools": ["QtScript", "QtGui", "QtCore"], "QtSq... | Add any additional Qt libraries needed by a module to an existing list.
mname is the name of the module.
qt_libs is the current list of libraries. | 625941dede87d2750b8600d8 |
def test_attrs_stick(self): <NEW_LINE> <INDENT> c = CallFile('call', 'action', 'archive', 'filename', 'tempdir', 'user', 'spool_dir') <NEW_LINE> self.assertEqual(c.call, 'call') <NEW_LINE> self.assertEqual(c.action, 'action') <NEW_LINE> self.assertEqual(c.archive, 'archive') <NEW_LINE> self.assertEqual(c.filename, 'fil... | Ensure attributes stick. | 625941ded7e4931a7ee9e262 |
def test_demand_saving_with_indexed_array(self, tmpdir): <NEW_LINE> <INDENT> model = load_model("demand_saving2.json") <NEW_LINE> model.timestepper.end = "2016-01-31" <NEW_LINE> model.check() <NEW_LINE> h5file = tmpdir.join('output.h5') <NEW_LINE> import tables <NEW_LINE> with tables.open_file(str(h5file), 'w') as h5f:... | Test recording various items from demand saving example
| 625941de38b623060ff0b130 |
def removeNode(self, nodeId: int) -> Awaitable[Dict]: <NEW_LINE> <INDENT> return self.client.send("DOM.removeNode", {"nodeId": nodeId}) | Removes node with given id.
See `https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-removeNode`
:param nodeId: Id of the node to remove.
:return: The results of the command | 625941de96565a6dacc8fa0d |
def __init__(self, imm, addr, blocks = False, recursion = False): <NEW_LINE> <INDENT> self.address = addr <NEW_LINE> self.imm = imm <NEW_LINE> self.blocks = {} <NEW_LINE> self.predecessors = {} <NEW_LINE> self.iterativepredecessors = {} <NEW_LINE> self.dominators = {} <NEW_LINE> self.immediatedominators = {} <NEW_LINE>... | This class takes a function start address and calculate all Dominator Tree related tables:
- Predecessors
- Iterated Predecessors
- Dominators
- Immediate Dominators
- Post Dominators
- Immediate Post Dominators
@type imm: Debbuger OBJECT
@param imm: Debbuger
@type addr: DWORD
@param addr: function start address
@... | 625941dedd821e528d63b4ea |
def calcWeightedAgg(assessment, sigType, pk): <NEW_LINE> <INDENT> data = AssessmentData.objects.filter(assessmentVersion=assessment) <NEW_LINE> if sigType == 1: <NEW_LINE> <INDENT> data = data.exclude(pk=pk) <NEW_LINE> <DEDENT> totalStudents = 0 <NEW_LINE> totalProf = 0 <NEW_LINE> for dat in data: <NEW_LINE> <INDENT> t... | Calculates the weighted aggregate value based upon assessment data for
the given :class:`~makeReports.models.assessment_models.AssessmentVersion`
Args:
assessment (~makeReports.models.assessment_models.AssessmentVersion) : the assessment to calculate the aggregate for
sigType (int): signal type - 0 is post-sa... | 625941de10dbd63aa1bd2ee5 |
def delDbFiles(self, files): <NEW_LINE> <INDENT> for f in files: <NEW_LINE> <INDENT> del self.db[f] <NEW_LINE> <DEDENT> self.clearVars() | Entfernt Dateien aus dem Korpus | 625941deb57a9660fec33bcc |
def factor_comu(self): <NEW_LINE> <INDENT> d = [] <NEW_LINE> for i in range(self.files): <NEW_LINE> <INDENT> for j in range(self.columnes): <NEW_LINE> <INDENT> k = self[i,j] <NEW_LINE> <DEDENT> if (isinstance(k,int) or isinstance(k,Integer)): <NEW_LINE> <INDENT> d.append(k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Retorna quin factor comú podem treure de la matriu | 625941de287bf620b61d3da5 |
def test_07(self): <NEW_LINE> <INDENT> base = Base([1, 2, 3]) <NEW_LINE> self.assertEqual(base.id, [1, 2, 3]) | test id list | 625941de66656f66f7cbc4f0 |
def arena_free(arena_addr): <NEW_LINE> <INDENT> assert isinstance(arena_addr, fakearenaaddress) <NEW_LINE> assert arena_addr.offset == 0 <NEW_LINE> arena_addr.arena.reset(False) <NEW_LINE> assert not arena_addr.arena.objectptrs <NEW_LINE> arena_addr.arena.mark_freed() | Release an arena. | 625941de96565a6dacc8fa0e |
def build(self, library, cleanup=True, create_archive=None): <NEW_LINE> <INDENT> if library == 'py2exe': <NEW_LINE> <INDENT> self.build_py2exe(cleanup=cleanup, create_archive=create_archive) <NEW_LINE> <DEDENT> elif library == 'cx_Freeze': <NEW_LINE> <INDENT> self.build_cx_freeze(cleanup=cleanup, create_archive=create_... | Build executable with given library.
library:
* 'py2exe': deploy using the `py2exe` library
* 'cx_Freeze': deploy using the `cx_Freeze` library
cleanup: remove 'build/dist' directories before building distribution
create_archive (requires the executable `zip`):
* None or False: do nothing
* 'add': ad... | 625941de3617ad0b5ed68239 |
def createBaseType(self, name, size, encoding=None, nativeDeclaration=None, adminData=None): <NEW_LINE> <INDENT> return self.createSwBaseType(name, size, encoding, nativeDeclaration, adminData) | AUTOSAR4
alias for createSwBaseType | 625941dee76e3b2f99f3ab4a |
def clean(): <NEW_LINE> <INDENT> local("rm -rf holbertonwebapp.tar.gz") | clean tar file on local | 625941dede87d2750b8600d9 |
@logic.side_effect_free <NEW_LINE> def get_bookable_releases(context, data_dict): <NEW_LINE> <INDENT> output = _stub_msg <NEW_LINE> return output | Returns a list of the products, issues and formats that a user may edit, based on the provided FRC codes
:param: frcCodes: A list of FRC Codes
:return: A dictionary containing the products, associated issues and formats for articles for the specified
product and issue
:rtype: dict | 625941de8a349b6b435e84b6 |
def create_custom_token(self, uid, developer_claims=None, tenant_id=None): <NEW_LINE> <INDENT> if developer_claims is not None: <NEW_LINE> <INDENT> if not isinstance(developer_claims, dict): <NEW_LINE> <INDENT> raise ValueError('developer_claims must be a dictionary') <NEW_LINE> <DEDENT> disallowed_keys = set(developer... | Builds and signs a Firebase custom auth token. | 625941de21bff66bcd684c93 |
def test_init_rec_true(): <NEW_LINE> <INDENT> assert signalData.SignalData(1).rec('frame') | Confirm recording a signal converts it truthy | 625941de004d5f362079a675 |
def mixSetUp(self): <NEW_LINE> <INDENT> if self.family == socket.AF_INET: <NEW_LINE> <INDENT> self.inaddrany = "0.0.0.0" <NEW_LINE> self.localhost = "127.0.0.1" <NEW_LINE> clinaddrany = self.inaddrany <NEW_LINE> cllocalhost = self.localhost <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.inaddrany = "::0" <NEW_LINE>... | unittest test setup code | 625941deb545ff76a8914159 |
def test_user_create(db_conn): <NEW_LINE> <INDENT> request = { 'params': { 'name': 'test', 'email': 'test@example.com', 'password': 'abcd1234', }, 'db_conn': db_conn } <NEW_LINE> code, response = routes.user.create_user_route(request) <NEW_LINE> assert code == 200 <NEW_LINE> assert response['user']['name'] == 'test' | Ensure a user can be created. | 625941de090684286d50f02c |
def randomforest_regressor(x_train,y_train,x_validate,y_validate): <NEW_LINE> <INDENT> model = RandomForestRegressor(n_estimators=100, min_samples_leaf=10, random_state=1) <NEW_LINE> model.fit(x_train, y_train) <NEW_LINE> predictions = model.predict(x_validate) <NEW_LINE> mean_square_error = mean_squared_error(predicti... | RandomForest regression model
Parameters:
-----------
data : training and validation data with their response
response: Predictions, RSquare score and mean square error on validation data
Returns:
--------
mean square error and RSquare Score | 625941de090684286d50f02d |
def stop(self): <NEW_LINE> <INDENT> threads = [] <NEW_LINE> with self._lock: <NEW_LINE> <INDENT> for check in self._hosts.values(): <NEW_LINE> <INDENT> check['timer'].cancel() <NEW_LINE> threads.append(check['timer']) <NEW_LINE> check['deferred'].reject(CancelledError()) <NEW_LINE> <DEDENT> self._hosts = {} <NEW_LINE> ... | Stop all current checks. | 625941de5510c4643540f720 |
def test_shifting(self): <NEW_LINE> <INDENT> vec1 = vector.Vector(0b10011, 5) <NEW_LINE> vec2 = vector.Vector(0b01100, 5) <NEW_LINE> vec3 = vector.Vector(0b00100, 5) <NEW_LINE> vec4 = vector.Vector(0b00001, 5) <NEW_LINE> vec_empty = vector.Vector() <NEW_LINE> self.assertEqual(vec2, vec1 << 2) <NEW_LINE> self.assertEqua... | Test vector shift operators. | 625941de63d6d428bbe44833 |
def __init__(self): <NEW_LINE> <INDENT> pass | Initialise a new A-RELEASE-RQ PDU. | 625941de5fdd1c0f98dc0578 |
def CheckPointerReferenceSpacing(filename, clean_lines, linenum, error): <NEW_LINE> <INDENT> line = clean_lines.elided[linenum] <NEW_LINE> wrong_type_match = Search(r'^\s*([\w_])+( const)?(?P<type>[&\*])\s*\w', line) <NEW_LINE> if wrong_type_match: <NEW_LINE> <INDENT> pos = wrong_type_match.start(1) <NEW_LINE> _, _, op... | Checks the */& are attached to variable names rather than types
A pointer or reference type should have the */& attached to the variable
name rather than the type. I.e. a pointer to an int should be:
int *var_name;
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing... | 625941de31939e2706e4d1a9 |
def send_welcome_email(request, user): <NEW_LINE> <INDENT> current_site = get_current_site(request) <NEW_LINE> site_name = current_site.name <NEW_LINE> domain = current_site.domain <NEW_LINE> context = { 'user': user, 'domain': domain, 'protocol': 'https' if request.is_secure() else 'http', } <NEW_LINE> from_email = f'... | Send a welcome email to a recently register user. | 625941de82261d6c526ab7e7 |
def _parse_settings_bond_4(opts, iface, bond_def): <NEW_LINE> <INDENT> bond = {'mode': '4'} <NEW_LINE> for bo in ['miimon', 'downdelay', 'updelay', 'lacp_rate']: <NEW_LINE> <INDENT> if bo in opts: <NEW_LINE> <INDENT> if bo == 'lacp_rate': <NEW_LINE> <INDENT> if opts[bo] == 'fast': <NEW_LINE> <INDENT> opts.update({bo: '... | Fiters given options and outputs valid settings for bond4.
If an option has a value that is not expected, this
fuction will log what the Interface, Setting and what it was
expecting. | 625941de925a0f43d254a1bd |
def test_stop_after_five_garbage_lines(self): <NEW_LINE> <INDENT> MAX_ALLOWED_ERRORS = settings.PTS_MAX_ALLOWED_ERRORS_CONTROL_COMMANDS <NEW_LINE> self.set_input_lines( ['help'] + ['garbage'] * MAX_ALLOWED_ERRORS + ['#command']) <NEW_LINE> self.control_process() <NEW_LINE> self.assert_response_sent() <NEW_LINE> self.as... | Tests that processing stops after encountering five garbage lines. | 625941ded58c6744b4257fa2 |
def database_exists(url): <NEW_LINE> <INDENT> url = copy(make_url(url)) <NEW_LINE> database = url.database <NEW_LINE> if url.drivername.startswith('postgresql'): <NEW_LINE> <INDENT> url.database = 'template1' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url.database = None <NEW_LINE> <DEDENT> engine = create_engine(ur... | Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
create_database('postgres://postgres@localhost/name')
database_exists('postgres:/... | 625941de2eb69b55b151cbf7 |
def findMedianSortedArrays(self, num1, num2): <NEW_LINE> <INDENT> l = len(num1) + len(num2) <NEW_LINE> print(l//2) <NEW_LINE> return self.findKth(num1, num2, l//2) if l%2==1 else (self.findKth(num1, num2,l//2 - 1) + self.findKth(num1, num2, l//2))/2 | :param num1:
:param num2:
:return: | 625941de4f88993c3716c3a8 |
def f(w, lamb): <NEW_LINE> <INDENT> out = 0 <NEW_LINE> for i in range(d): <NEW_LINE> <INDENT> for j in range(d): <NEW_LINE> <INDENT> out += kernel[i, j] * w[i] * w[j] <NEW_LINE> <DEDENT> <DEDENT> for i in range(d): <NEW_LINE> <INDENT> out += lamb * w[i] ** 2 <NEW_LINE> <DEDENT> return out | input:
- w: (d,) np.ndarray
- lamb: scaler lambda
output:
- out: scalar value of function f(w) | 625941debaa26c4b54cb1460 |
def bid_for_start(bid0, bid1, goal=GOAL_SCORE): <NEW_LINE> <INDENT> assert bid0 >= 0 and bid1 >= 0, "Bids should be non-negative!" <NEW_LINE> assert type(bid0) == int and type(bid1) == int, "Bids should be integers!" <NEW_LINE> if bid0 == bid1: <NEW_LINE> <INDENT> return goal, goal, 0 <NEW_LINE> <DEDENT> if bid0 == bid... | Given the bids BID0 and BID1 of each player, returns three values:
- the starting score of player 0
- the starting score of player 1
- the number of the player who rolls first (0 or 1) | 625941deff9c53063f47c536 |
def test_add_default_values_method_call(self): <NEW_LINE> <INDENT> default_method_call = { "class_context": ""} <NEW_LINE> technique = ncf.add_default_values_technique_method_call(default_method_call) <NEW_LINE> result = technique['class_context'] == "any" <NEW_LINE> self.assertTrue(result) | Test if a missing data in technique metadata are correctly replaced with default values | 625941de3d592f4c4ed1d3a9 |
def main_prev_frame(): <NEW_LINE> <INDENT> frame = _get_prev_frame() <NEW_LINE> if frame is None: <NEW_LINE> <INDENT> frame = lib.get_prev_frame_maya() <NEW_LINE> <DEDENT> maya.cmds.currentTime(frame, edit=True) <NEW_LINE> return | Move the current time to the previous root frame.
If no Root Frames are available, use Maya's native "Previous Keyframe"
tool. | 625941de56b00c62f0f1499f |
def basicDF(): <NEW_LINE> <INDENT> path = cwd + '\\CSVs' <NEW_LINE> all_files = glob.glob(path + '/*.csv') <NEW_LINE> print("All files have been downloaded") <NEW_LINE> df = pd.concat((pd.read_csv(f, index_col=None, header=0) for f in all_files),ignore_index=True) <NEW_LINE> print(df.head(10)) <NEW_LINE> print("Datafra... | basic dataframe construction, no filtering, etc | 625941de566aa707497f48a8 |
def set_encoding(self, value=DEFAULT_ENCODING): <NEW_LINE> <INDENT> if self._conn.encoding != value: <NEW_LINE> <INDENT> self._conn.set_client_encoding(value) | Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use | 625941dea05bb46b383ecb63 |
def test_get_list_continuous_queries(self): <NEW_LINE> <INDENT> data = { "results": [ { "statement_id": 0, "series": [ { "name": "testdb01", "columns": ["name", "query"], "values": [["testname01", "testquery01"], ["testname02", "testquery02"]] }, { "name": "testdb02", "columns": ["name", "query"], "values": [["testname... | Test getting a list of continuous queries. | 625941de9f2886367277abcf |
def _initPhysics(self): <NEW_LINE> <INDENT> config = self.config <NEW_LINE> enthalpyconverter = PISM.EnthalpyConverter(config) <NEW_LINE> if PISM.OptionBool("-ssa_glen", "SSA flow law Glen exponent"): <NEW_LINE> <INDENT> config.set_string("stress_balance.ssa.flow_law", "isothermal_glen") <NEW_LINE> config.scalar_from_o... | Override of :meth:`SSARun._initPhysics` that sets the physics based on command-line flags. | 625941de7cff6e4e81117cc9 |
def moveOrganizer(self, targetUid, organizerUid): <NEW_LINE> <INDENT> data = locals().copy() <NEW_LINE> del data["self"] <NEW_LINE> resp = client.make_request(self.url_path, "ReportRouter", "moveOrganizer", [data]) <NEW_LINE> return create_response(resp) | Move the organizer uid to be underneath the organizer
specified by the targetUid.
@type targetUid: string
@param targetUid: New parent of the organizer
@type organizerUid: string
@param organizerUid: The organizer to move
@rtype: DirectResponse
@return: B{Properties}:
- data: (dictionary) Moved organizer | 625941dedd821e528d63b4eb |
def reconcile_countries_by_code(codeinfo, plot_countries, gdp_countries): <NEW_LINE> <INDENT> plot_to_gdp_countries = {} <NEW_LINE> plot_cc_not_in_gdp = set() <NEW_LINE> plot_to_isp_dict = build_country_code_converter(codeinfo) <NEW_LINE> plot_to_isp_keys_dict = {key.lower():key for key in plot_to_isp_dict} <NEW_LINE> ... | Inputs:
codeinfo - A country code information dictionary
plot_countries - Dictionary whose keys are plot library country codes (2 Char)
and values are the corresponding country names
(e.g. pygal country codes)
gdp_countries - Dictionary whose keys are country codes use... | 625941decc40096d61595c93 |
def __init__(self, session=None, myarg=None): <NEW_LINE> <INDENT> self.uri = "/rest/auth-token" <NEW_LINE> self.ip = None <NEW_LINE> self.user = None <NEW_LINE> self.auth_token = None <NEW_LINE> self.mgr = None <NEW_LINE> if session is not None: <NEW_LINE> <INDENT> self.ip = session.get("ip_addr") <NEW_LINE> self.user ... | This constructor for the class representing an AuthToken.
.. Attributes:
session : The switch session associated with the AuthToken.
myarg: The argument for AuthToken as a dictonary or another instance of the same class. | 625941de1f037a2d8b946541 |
def get_data(csv_file: Union[str, Path]): <NEW_LINE> <INDENT> if not isinstance(csv_file, Path): <NEW_LINE> <INDENT> csv_file = Path(csv_file) <NEW_LINE> <DEDENT> readings = [] <NEW_LINE> with open(csv_file) as f: <NEW_LINE> <INDENT> reader = csv.reader(f) <NEW_LINE> mode, systems = parse_header(reader) <NEW_LINE> for ... | See bluelab_logs directory for csv files with format
| 625941de925a0f43d254a1be |
def do(self, cur): <NEW_LINE> <INDENT> if not self.sequence.next_has_continuous(1): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.sequence.next_word(1).word_lower not in SET_MODAL: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.matched('their_be') <NEW_LINE> cur.replace_autocap("there") <NEW_LINE> self.se... | Keyword: their
Src: _ <modal>
Dst: [there] <modal> | 625941de44b2445a339323d8 |
def set_volume(self, volume): <NEW_LINE> <INDENT> if not 0 <= volume < 63 : <NEW_LINE> <INDENT> raise ValueError("Volume has to be in [0,63]!") <NEW_LINE> <DEDENT> self.volume = volume | Set output volume of ADAU1761.
Parameters
----------
volume : int
The volume level. Minimum : 0=-57dB, Maximum : 63=+6dB.
Returns
-------
None | 625941de3317a56b86939f95 |
def parse_message(message_list): <NEW_LINE> <INDENT> message_line_list = list() <NEW_LINE> for item in message_list: <NEW_LINE> <INDENT> attributes_list = list() <NEW_LINE> separate_fields = item.split(']') <NEW_LINE> attributes_list.append(separate_fields[0][2:]) <NEW_LINE> attributes_list.append(separate_fields[1][1:... | Parses the message section of the Snort alerts, called from parse().
Receives a list of entries with the format "[ID] Message" and splits
the entry, saving the ID and Message as separate attributes.
Returns the parsed list to parse().
message_list - list of the message sections from parse(). | 625941de8e71fb1e9831daec |
def shuffle(self, count: str = None, utc: str = None): <NEW_LINE> <INDENT> post_data = "" <NEW_LINE> url = PATHS["SHUFFLE"].format(self.profile_id) <NEW_LINE> if count: <NEW_LINE> <INDENT> post_data += "count={}&".format(count) <NEW_LINE> <DEDENT> if utc: <NEW_LINE> <INDENT> post_data += "utc={}".format(utc) <NEW_LINE>... | Randomize the order at which statuses for a social media
profile will be sent out. | 625941def7d966606f6aa34c |
def factor(self): <NEW_LINE> <INDENT> return self.parent.factor(self) | Find all ways to factor this generator into a product of two
generators. Make sense only if parent module implements factor(). | 625941de6fece00bbac2da86 |
def is_point_in_rect(point, rect): <NEW_LINE> <INDENT> x0, y0, x1, y1 = rect <NEW_LINE> x, y = point <NEW_LINE> if x0 <= x <= x1 and y0 <= y <= y1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Checks whether is coordinate point inside the rectangle or not.
Rectangle is defined by bounding box.
:type point: list
:param point: testing coordinate point
:type rect: list
:param rect: bounding box
:rtype: boolean
:return: boolean check result | 625941decad5886f8bd2731d |
def increment_count(self, for_dog, increment_by=1): <NEW_LINE> <INDENT> if not getattr(for_dog, "pk", None): <NEW_LINE> <INDENT> dog, dog_created = Dog.objects.get_or_create(name=for_dog.lower(), age=6) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dog = for_dog <NEW_LINE> <DEDENT> stool, created = self.get_or_create(d... | Increment the poop count for a dog | 625941de15fb5d323cde0e58 |
def snap_to_roads(client, path, interpolate=False): <NEW_LINE> <INDENT> params = {"path": convert.location_list(path)} <NEW_LINE> if interpolate: <NEW_LINE> <INDENT> params["interpolate"] = "true" <NEW_LINE> <DEDENT> return client._get("/v1/snapToRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract... | Snaps a path to the most likely roads travelled.
Takes up to 100 GPS points collected along a route, and returns a similar
set of data with the points snapped to the most likely roads the vehicle
was traveling along.
:param path: The path to be snapped.
:type path: a single location, or a list of locations, where a
... | 625941de6fb2d068a760f3e6 |
def list_projects(self): <NEW_LINE> <INDENT> return self.server.urlopen_json('get-all-project-metadata')['projects'] | Return a dict of projects indexed by id.
{u'1877818633188': {
'id': u'1877818633188', u'name': u'akg',
u'modified': u'2011-04-07T12:30:07Z',
u'created': u'2011-04-07T12:30:07Z'
}, | 625941de0a366e3fb873eb61 |
def play_note(self, note, duration, volume, play_type): <NEW_LINE> <INDENT> frequency = _NOTES[note] <NEW_LINE> self.play_tone(frequency, duration, volume, play_type) | Play a musical note
Parameters:
note (int): The name of the note ['C4'..'B6'] (use # for sharp)
duration (float): The duration of the note in seconds
volume (int): The playback volume in percent [0..100]
play_type (PlayType): Controls how many times the sound is played
and when the function ret... | 625941de956e5f7376d711b0 |
def GetVersion(self, runspace, pipeline): <NEW_LINE> <INDENT> meta = ObjectMeta("Version") <NEW_LINE> value = runspace.serialize(self.version, meta) <NEW_LINE> return value | MI: 2
SHOULD return the version number of the hosting application.
https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshost.version
:param runspace: The runspace the host call relates to
:param pipeline: The pipeline (if any) that the call relates to
:return: Version number of the hosting a... | 625941de293b9510aa2c35d7 |
def generate(self, generate_bundle=True, generate_bundle_from_bundle_coords=False): <NEW_LINE> <INDENT> if generate_bundle and (generate_bundle_from_bundle_coords or self.bundle_geometry is not None): <NEW_LINE> <INDENT> super().generate() <NEW_LINE> self.generate_bundle_from_bundle_coords() <NEW_LINE> <DEDENT> elif ge... | Generate structure data. | 625941de5fc7496912cc3cc2 |
def build_vocab(self, sentences, update=False, progress_per=10000, keep_raw_vocab=False, trim_rule=None, **kwargs): <NEW_LINE> <INDENT> total_words, corpus_count = self.vocabulary.scan_vocab( sentences, progress_per=progress_per, trim_rule=trim_rule) <NEW_LINE> self.corpus_count = corpus_count <NEW_LINE> report_values ... | Build vocabulary from a sequence of sentences (can be a once-only generator stream).
Each sentence is a iterable of iterables (can simply be a list of unicode strings too).
Parameters
----------
sentences : iterable of iterables
The `sentences` iterable can be simply a list of lists of tokens, but for larger corpo... | 625941de442bda511e8be758 |
def _get_paperinfo(self): <NEW_LINE> <INDENT> return self._get_volume(), self._get_page(), self._get_year() | :return: | 625941de4f6381625f114d80 |
def _TestRunBoard(self, pinfolist, upgrade=False, staged_changes=False): <NEW_LINE> <INDENT> targetlist = [pinfo.user_arg for pinfo in pinfolist] <NEW_LINE> upstream_only_pinfolist = [pinfo for pinfo in pinfolist if not pinfo.cpv] <NEW_LINE> cmdargs = targetlist <NEW_LINE> if upgrade: <NEW_LINE> <INDENT> cmdargs = ['--... | Test Upgrader.RunBoard. | 625941de8c0ade5d55d3ed02 |
def get_stderr_bytes(): <NEW_LINE> <INDENT> import sys <NEW_LINE> return _get_bytes_stream(sys.stderr) | Get a reference to the standard error stream that accepts bytes, not
unicode characters.
Returns: a file-like object hooked up to the process’ standard error.
Usually, you want to write text to a process's standard error stream
(“stderr”), so you want :data:`sys.stderr` to be a stream that accepts
Unicode. The functi... | 625941de596a897236089e01 |
def add(self, backup): <NEW_LINE> <INDENT> date = backup.mtime.date() <NEW_LINE> if date not in self.backups: <NEW_LINE> <INDENT> s = set() <NEW_LINE> s.add(backup) <NEW_LINE> self.backups[date] = s <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.backups[date].add(backup) | add a backup to the collection | 625941defbf16365ca6f650e |
def ternary_search_iter(f, left, right, absolute_precision): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> if abs(right - left) < absolute_precision: <NEW_LINE> <INDENT> return (left + right) / 2 <NEW_LINE> <DEDENT> left_third = left + (right - left) / 3 <NEW_LINE> right_third = right - (right - left) / 3 <NEW_LI... | Implementation of Ternary search algorithm (iterative version)
Find maximum of unimodal function f() within [left, right]
To find the minimum, revert the if/else statement or revert the comparison. | 625941de956e5f7376d711b1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.