code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def p_non_labeled_open_statement_2(p): <NEW_LINE> <INDENT> p[0] = p[1] | non_labeled_open_statement : open_while_statement | 625941f76fb2d068a760f723 |
def __init__(self, backend, map_data): <NEW_LINE> <INDENT> self.backend = backend <NEW_LINE> self.width = len(map_data[0]) <NEW_LINE> self.height = len(map_data) <NEW_LINE> self.raw_map = map_data <NEW_LINE> self.strip_raw_metadata() <NEW_LINE> self.build_tcod_map() | Initialize an area with given data | 625941f71d351010ab856195 |
def angles_between_point_vectors(v1, v2): <NEW_LINE> <INDENT> dot_prod = (v1 * v2).sum(axis=1) <NEW_LINE> v1_norm = np.linalg.norm(v1, axis=1) <NEW_LINE> v2_norm = np.linalg.norm(v2, axis=1) <NEW_LINE> cosine_of_angle = (dot_prod / (v1_norm * v2_norm)).reshape(11, 1) <NEW_LINE> angles = np.arccos(np.clip(cosine_of_angl... | Calculates angle between two point vectors.
Parameters
----------
v1 : numpy.ndarray
First vector
v2 : numpy.ndarray
Second vector
Returns:
--------
numpy.ndarray
Vector if one of the arguments is matrix and scalar if both arguments are vectors. | 625941f721a7993f00bc8378 |
def scan_tests_from_file(self, file_name): <NEW_LINE> <INDENT> if not ostools.file_exists(file_name): <NEW_LINE> <INDENT> raise ValueError("File %r does not exist" % file_name) <NEW_LINE> <DEDENT> self._config.scan_tests_from_file(self._scope, file_name) | Scan tests from another file than the one containg the test
bench. Useful for when the top level test bench does not
contain the tests.
Such a structure is not the preferred way of doing things in
VUnit but this method exists to accommodate legacy needs.
:param file_name: The name of another file to scan for tests
... | 625941f7a8370b7717052f18 |
def test_album_published(self): <NEW_LINE> <INDENT> album = Album.objects.first() <NEW_LINE> self.assertIsInstance(album.published, str) | Test album published. | 625941f7f8510a7c17cf9d7d |
def get_next_start_time(self): <NEW_LINE> <INDENT> return datetime.datetime.now() + self.get_observation_time() | Returns a datetime object when the job should next start.
:return: datetime object when job should start | 625941f7d164cc61757833ca |
def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> payments_lis = Pago.objects.all() <NEW_LINE> data = [] <NEW_LINE> for pago in payments_lis: <NEW_LINE> <INDENT> data.append({ "documentoIdentificacionArrendatario":pago.documentoIdentificacionArrendatario, "codigoInmueble":pago.codigoInmueble, "valorPagado":p... | Lista todos los pagos almacenados en la base de datos | 625941f729b78933be1e5d1f |
def write_to_stdin(self, line): <NEW_LINE> <INDENT> if self._reading: <NEW_LINE> <INDENT> if programs.is_module_installed('IPython', '>=1.0'): <NEW_LINE> <INDENT> self.kernel_client.stdin_channel.input(line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.kernel_manager.stdin_channel.input(line) | Send raw characters to the IPython kernel through stdin
but only if the kernel is currently looking for raw input. | 625941f7fbf16365ca6f684e |
def hessenberg(a, calc_q=False, overwrite_a=False): <NEW_LINE> <INDENT> a1 = asarray(a) <NEW_LINE> if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]): <NEW_LINE> <INDENT> raise ValueError('expected square matrix') <NEW_LINE> <DEDENT> overwrite_a = overwrite_a or (_datacopied(a1, a)) <NEW_LINE> gehrd,gebal = get_lapa... | Compute Hessenberg form of a matrix.
The Hessenberg decomposition is
A = Q H Q^H
where Q is unitary/orthogonal and H has only zero elements below the first
subdiagonal.
Parameters
----------
a : array, shape (M,M)
Matrix to bring into Hessenberg form
calc_q : boolean
Whether to compute the transformatio... | 625941f701c39578d7e754b7 |
def getFormatted(self, formatter): <NEW_LINE> <INDENT> res = [] <NEW_LINE> if self.title.text: <NEW_LINE> <INDENT> res.append(formatter.formatCommand(self.command, self.title.text, self.name.text)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res.append(formatter.formatCommand(self.command, self.name.text)) <NEW_LINE>... | Get formatted and normalized in dox format. | 625941f7c432627299f052c6 |
def read_and_detect(read_func,detect_func,param_read='',to_print = False): <NEW_LINE> <INDENT> AnomalyData, data_train, data_test, labels_train, labels_test=read_func(param_read) <NEW_LINE> if to_print: <NEW_LINE> <INDENT> detect_func(AnomalyData,data_train, data_test,labels_train,labels_test,to_print = to_print) <NEW_... | Function to trigger the process of reading data and anomaly detection
parameters:
- read_func: a function to read data, labels and parameters
- detect_func: a function to detect anomlies
- param_read: parameter for read_func -- for synthetic dataset
- to_print: to_print: a trigger of printing out all the visualization... | 625941f7f548e778e58cdbfc |
def load(include_fixtures: Iterable = None, **kwargs): <NEW_LINE> <INDENT> fixs = include_fixtures if include_fixtures is not None else fixtures <NEW_LINE> for f in fixs: <NEW_LINE> <INDENT> d = __import__(f'_app.initial_data.fixtures.{f}', globals(), locals(), ['apply'], 0) <NEW_LINE> s = f'[*] Applying fixture {f}: %... | Loads fixtures. If include_fixtures is empty, all fixtures will be loaded and applied
:param include_fixtures:
:param args:
:param kwargs:
:return: | 625941f7d18da76e23532b5a |
def convert(): <NEW_LINE> <INDENT> init_logger() <NEW_LINE> keras_model_path, out_dir, frozen_graph_name = get_args() <NEW_LINE> try: <NEW_LINE> <INDENT> if os.path.isfile(keras_model_path): <NEW_LINE> <INDENT> keras_model = load_model(keras_model_path, compile=False) <NEW_LINE> output_node_names = [node.op.name for no... | This function converts the keras model(.h5) to tensorflow frozen graph(.pb). | 625941f76fece00bbac2ddc2 |
def is_network_ip(ipstr): <NEW_LINE> <INDENT> result_ip = check_ip(ipstr) <NEW_LINE> if result_ip is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> result_special = check_special(ipstr) <NEW_LINE> if result_special is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> result_a1 = check_ipa1(ipstr) ... | check whether it is network ip | 625941f73346ee7daa2b33ee |
def _embed_watermark_single_channel(self, samples_to_mark, w, seed, mean): <NEW_LINE> <INDENT> assert self._num_bins > 2 * len( w), "Number of bins < 2*the length of the bitstring to embed" <NEW_LINE> hist, bins = self.generate_histogram(samples_to_mark, self.la, self._num_bins, mean) <NEW_LINE> bin_pairs = self._gener... | Embeds the watermark in a mono signal.
:param samples_to_mark: the samples to mark
:param w: the watermark
:param seed: the key - more precise: the seed for the PRNG
:param mean: the original mean of the signal
:return: marked_samples, bin_pairs: marked copy of the samples and
the bin pairs (detection key) | 625941f7e1aae11d1e74a33a |
def set_statistics_callback_configuration(self, period, value_has_to_change): <NEW_LINE> <INDENT> self.check_validity() <NEW_LINE> period = int(period) <NEW_LINE> value_has_to_change = bool(value_has_to_change) <NEW_LINE> self.ipcon.send_request(self, BrickletIsolator.FUNCTION_SET_STATISTICS_CALLBACK_CONFIGURATION, (pe... | The period is the period with which the :cb:`Statistics`
callback is triggered periodically. A value of 0 turns the callback off.
If the `value has to change`-parameter is set to true, the callback is only
triggered after the value has changed. If the value didn't change within the
period, the callback is triggered im... | 625941f7d99f1b3c44c67bfd |
def special_ability(self, game, player_who_played_the_card): <NEW_LINE> <INDENT> for player in game.players: <NEW_LINE> <INDENT> if player is not player_who_played_the_card: <NEW_LINE> <INDENT> player.hand.draw_card() | Each other player draws a card.
Args:
game (instance): The current game.
player (instance): The player who played the card | 625941f75fc7496912cc3ff9 |
def handle_createCfgFileReq(req, body): <NEW_LINE> <INDENT> global CONFIGFILE <NEW_LINE> path = body['path'] <NEW_LINE> CONFIGFILE = body['fname'] <NEW_LINE> (key_based, user, pwd, key_file) = get_cred(body['hostName'], body) <NEW_LINE> with produce_ABClusterHost(body['hostName'], key_based, user, pwd, key_file) as ch:... | Handler function for createCfgFileReq command.
req - top level message object
body - shortcut to the body part of the message
Plain file create on host. | 625941f756b00c62f0f14cd9 |
@raises(SkipEvaluationError) <NEW_LINE> def test_get_end_index_for_error(): <NEW_LINE> <INDENT> data = [1, NARealType()] <NEW_LINE> get_end_index(data, 0) | Test discerner.get_end_index for error case | 625941f7e64d504609d74ebb |
def x30_v_baffle(baffle_height, baffle_thickness, n_notch, delta, overhangs=(0,0), overhang_heights=(None,None), overhang_tapers=(False, False), margin=MARGIN, skip_notches=()): <NEW_LINE> <INDENT> overhang_heights = list(overhang_heights) <NEW_LINE> for i in range(2): <NEW_LINE> <INDENT> if overhang_heights[i] is None... | delta = DX/DY
overhangs = amount of extra plastic from center of last notch
overhang_heights = height of overhang. if None, baffle_height
overhang_tapers = straight~False, tapered~True,
margin = extra gap for slots | 625941f79c8ee82313fbbdf3 |
def maxEnvelopes(self, envelopes): <NEW_LINE> <INDENT> e = envelopes <NEW_LINE> if not e: return 0 <NEW_LINE> e.sort(key=lambda x: (x[0], -x[1])) <NEW_LINE> dp = [0] * len(e) <NEW_LINE> for i in xrange(len(e)): <NEW_LINE> <INDENT> dp[i] = 1 <NEW_LINE> for j in xrange(i): <NEW_LINE> <INDENT> if e[i][1] > e[j][1]: <NEW_L... | :type envelopes: List[List[int]]
:rtype: int | 625941f750812a4eaa59c996 |
def get_link_flags(): <NEW_LINE> <INDENT> flags = [] <NEW_LINE> if not _MONOLITHIC_BUILD: <NEW_LINE> <INDENT> flags.append('-L%s' % get_lib()) <NEW_LINE> flags.append('-ltensorflow_framework') <NEW_LINE> <DEDENT> return flags | Get the link flags for custom operators.
Returns:
The link flags. | 625941f767a9b606de4a8531 |
def test_1519_DB_TYPE_ROWID(self): <NEW_LINE> <INDENT> self.__test_compare(oracledb.DB_TYPE_ROWID, oracledb.ROWID) <NEW_LINE> self.__test_pickle(oracledb.DB_TYPE_ROWID) | 1519 - test oracledb.DB_TYPE_ROWID comparisons and pickling | 625941f763f4b57ef0001781 |
def get_non_ready_rs_pod_names(namespace): <NEW_LINE> <INDENT> pod_names = [] <NEW_LINE> rs_pods = get_pods(namespace, selector='redis.io/role=node') <NEW_LINE> if not rs_pods: <NEW_LINE> <INDENT> logger.info("Namespace '%s': cannot find redis enterprise pods", namespace) <NEW_LINE> return [] <NEW_LINE> <DEDENT> for rs... | get names of rs pods that are not ready | 625941f730bbd722463cc446 |
def gradientWeights(geometry, pnt1, pnt2, smooth=0): <NEW_LINE> <INDENT> if not cmds.objExists(geometry): <NEW_LINE> <INDENT> raise UserInputError('Object "' + geometry + '" does not exist!') <NEW_LINE> <DEDENT> pnt1 = glTools.utils.base.getMPoint(pnt1) <NEW_LINE> pnt2 = glTools.utils.base.getMPoint(pnt2) <NEW_LINE> pn... | Generate a gradient weight list for a specified geometry.
The weight gradient is defined between the 2 input points.
@param geometry: The geometry to generate weights for
@type geometry: str
@param pnt1: Start point of the gradient
@type pnt1: str
@param pnt2: End point of the gradient
@type pnt2: str
@param smooth: Nu... | 625941f73317a56b8693a2c3 |
def main(): <NEW_LINE> <INDENT> font = ImageFont.truetype( "/usr/share/fonts/liberation-mono/LiberationMono-Regular.ttf", 10, ) <NEW_LINE> ramp = np.zeros((72, 3), np.uint8) <NEW_LINE> data = np.zeros((30, 236), np.uint8) <NEW_LINE> for i, line in enumerate(open("../gempak/tables/luts/iem_eet.tbl")): <NEW_LINE> <INDENT... | Go Main Go. | 625941f710dbd63aa1bd321d |
def get_live_channel_history(self, channel_name): <NEW_LINE> <INDENT> resp = self.__do_object('GET', channel_name, params={Bucket.LIVE: '', Bucket.COMP: 'history'}) <NEW_LINE> return self._parse_result(resp, xml_utils.parse_live_channel_history, GetLiveChannelHistoryResult) | 获取live channel中最近的最多十次的推流记录,记录中包含推流的起止时间和远端的地址
param str channel_name: 要获取最近推流记录的live channel的名称
return: :class:`GetLiveChannelHistoryResult <oss2.models.GetLiveChannelHistoryResult>` | 625941f7f7d966606f6aa687 |
def test_running_workflow_without_events(monkeypatch): <NEW_LINE> <INDENT> mock(monkeypatch) <NEW_LINE> from tests.fixtures.flows import example <NEW_LINE> d = decider.DeciderWorker(example) <NEW_LINE> d.poll = MagicMock(return_value={}) <NEW_LINE> d.get_history = MagicMock() <NEW_LINE> d.run() <NEW_LINE> assert not d.... | Test running a workflow without having any events.
| 625941f74e4d5625662d4a49 |
def fit(mobile, target, mobile_state=0, target_state=0, quiet=1, matchmaker=0, cutoff=2.0, cycles=0, object=None, _self=cmd): <NEW_LINE> <INDENT> r = DEFAULT_ERROR <NEW_LINE> a=str(mobile) <NEW_LINE> b=str(target) <NEW_LINE> a = selector.process(a) <NEW_LINE> b = selector.process(b) <NEW_LINE> if object==None: object='... | DESCRIPTION
"fit" superimposes the model in the first selection on to the model
in the second selection. Only matching atoms in both selections will
be used for the fit.
USAGE
fit mobile, target [, mobile_state [, target_state [, quiet
[, matchmaker [, cutoff [, cycles [, object ]]]]]... | 625941f7e5267d203edce310 |
def f1_score(prediction, ground_truth): <NEW_LINE> <INDENT> return precision_recall_f1(prediction, ground_truth)[2] | This function calculates and returns the f1-score
Args:
prediction: prediction string or list to be matched
ground_truth: golden string or list reference
Returns:
floats of f1
Raises:
None | 625941f73d592f4c4ed1d6d7 |
def fetch_courses_and_sessions(dir="/input"): <NEW_LINE> <INDENT> outlist = [] <NEW_LINE> courses = [x for x in os.listdir(dir) if not '.' in x] <NEW_LINE> for course in courses: <NEW_LINE> <INDENT> sessions = [x for x in os.listdir('/'.join([dir, course])) if not '.' in x ] <NEW_LINE> for session in sessions: <NEW_LIN... | Fetch list of (course_name, session) tuples in dir.
:param dir: directory to search within; should have course/session subdirectories.
:return: list of (course_name, session) tuples. | 625941f7187af65679ca579d |
def to(self, to_addr): <NEW_LINE> <INDENT> self.to_addr = to_addr | Initialize receiver address | 625941f7d8ef3951e3243bb9 |
def getSendPeriod(self): <NEW_LINE> <INDENT> return self.sendperiod | Set the ai notification period s, executes sync if time from last read was earlier than period ago | 625941f74f6381625f1150b6 |
def get_signer_by_version(digest, ver): <NEW_LINE> <INDENT> if int(ver) == 1: <NEW_LINE> <INDENT> return V1Signer(digest) <NEW_LINE> <DEDENT> elif int(ver) == 2: <NEW_LINE> <INDENT> return V2Signer(digest) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Returns a new signer object for a digest and version combination.
Keyword arguments:
digest -- a callable that may be passed to the initializer of any Signer object in this library.
The callable must return a hasher object when called with no arguments.
ver -- the version of the signature. This may be any value co... | 625941f756b00c62f0f14cda |
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return MarketDetailsQuote( instrumentName = '0', instrumentToken = 56, lastUpdatedTime = 56, lastTradedTime = 56, lastPrice = 1.337, lastTradedQuantity = 56, totalBuyQuantity = 56, totalSellQuantity = 56, averageTra... | Test MarketDetailsQuote
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | 625941f7d7e4931a7ee9e59c |
def trimet_timestamp_to_datetime(timestamp) -> datetime: <NEW_LINE> <INDENT> if not timestamp: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> timestamp = timestamp / 1000 <NEW_LINE> result = datetime.fromtimestamp(timestamp, tz=LOCAL_TZ) <NEW_LINE> return result | Convert TriMet timestamp to datetime.
.. note:: Timestamps returned from the TriMet API are in Portland
local time *and* they're in milliseconds rather than seconds. | 625941f738b623060ff0b468 |
@require_http_methods(["GET", "POST"]) <NEW_LINE> @login_required(login_url="/login") <NEW_LINE> def import_csv(request: HttpRequest): <NEW_LINE> <INDENT> return import_view_template( request, historical_data_importer, ".csv", "app.can_import_historical") | A view to redirect after task queuing csv importer
| 625941f707f4c71912b11b01 |
def test_header(): <NEW_LINE> <INDENT> art = PdxArt() <NEW_LINE> header = art.header() <NEW_LINE> expected_header = [ 'record_id', 'artist' ] <NEW_LINE> assert_equal(expected_header, header[:2]) | Test PdxArt header | 625941f721a7993f00bc8379 |
@tf_export('assert_non_negative') <NEW_LINE> def assert_non_negative(x, data=None, summarize=None, message=None, name=None): <NEW_LINE> <INDENT> message = message or '' <NEW_LINE> with ops.name_scope(name, 'assert_non_negative', [x, data]): <NEW_LINE> <INDENT> x = ops.convert_to_tensor(x, name='x') <NEW_LINE> if data i... | Assert the condition `x >= 0` holds element-wise.
Example of adding a dependency to an operation:
```python
with tf.control_dependencies([tf.assert_non_negative(x)]):
output = tf.reduce_sum(x)
```
Non-negative means, for every element `x[i]` of `x`, we have `x[i] >= 0`.
If `x` is empty this is trivially satisfied.... | 625941f75510c4643540fa4f |
@doc_controls.do_not_generate_docs <NEW_LINE> def dtype_numpy(x): <NEW_LINE> <INDENT> return tf.as_dtype(x.dtype).as_numpy_dtype | Returns the numpy dtype of a Keras tensor or variable.
Args:
x: Tensor or variable.
Returns:
numpy.dtype, dtype of `x`. | 625941f721bff66bcd684fc8 |
def del_language(self, lang): <NEW_LINE> <INDENT> if lang not in self.get_languages(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> langlist = list(self._languages) <NEW_LINE> langlist.pop(langlist.index(lang)) <NEW_LINE> self._languages = tuple(langlist) | Delete language with corresponding messages | 625941f73617ad0b5ed68572 |
def plot_power(self, low=0, high=None, **options): <NEW_LINE> <INDENT> thinkplot.plot(self.fs[low:high], self.power[low:high], **options) | Plots power vs frequency.
low: int index to start at
high: int index to end at | 625941f7d268445f265b54eb |
@pytest.mark.parametrize("pkg", ["logrotate"]) <NEW_LINE> def test_packages(host, pkg): <NEW_LINE> <INDENT> package = host.package(pkg) <NEW_LINE> assert package.is_installed | Test that the appropriate packages were installed. | 625941f7167d2b6e31219210 |
def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(DetailTaskView, self).get_context_data(**kwargs) <NEW_LINE> context['activation'] = self.activation <NEW_LINE> return context | Context for a detail view.
:keyword activation: the task activation instance | 625941f7462c4b4f79d1dd4b |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941f7b830903b967e9f7f |
def _get_ref_cfgitems(): <NEW_LINE> <INDENT> from .stio import get_latest_file, irafconvert <NEW_LINE> for cfgitem, do_conv in ( (Conf.graphtable, True), (Conf.comptable, True), (Conf.thermtable, True), (Conf.area, False), (Conf.waveset, False)): <NEW_LINE> <INDENT> val = cfgitem() <NEW_LINE> if do_conv: <NEW_LINE> <IN... | Iterator for configuration items to be displayed. | 625941f78e05c05ec3eea9f7 |
def to_dict(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output['netid'] = self.netid <NEW_LINE> return output | Return a JSON-serializable dictionary | 625941f726068e7796caf365 |
def parse_custom_lexicon(self, lang): <NEW_LINE> <INDENT> if lang == "Polish": <NEW_LINE> <INDENT> fn = self.parse_polish_lexicon <NEW_LINE> <DEDENT> elif lang == "French": <NEW_LINE> <INDENT> fn = self.parse_french_lexicon <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> filename = "/resources/... | Parses a custom lexicon for this language, if one exists.
~
Currently only supports French and Polish.
:param lang: str, language to parse lexicon for
:return: dict, where...
key (str) - word lemma
val (List[str]) - all lexical forms of word lemma | 625941f77cff6e4e81118001 |
def dump_estimator_params(self, params: Dict[str, Any]) -> None: <NEW_LINE> <INDENT> _dump_params(self.estimator_params_path, params, self.overwrite_cb, ReferenceDumper) | Dump estimator params to yaml. | 625941f77cff6e4e81118002 |
def soma(x, y): <NEW_LINE> <INDENT> res = x + y <NEW_LINE> return res | soma (x, y) ----> result | 625941f73c8af77a43ae3e24 |
def __init__(self, filename, num_experience=5): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.num_experience = num_experience <NEW_LINE> self.userToId = dict() <NEW_LINE> self.idToUser = dict() <NEW_LINE> self.movieToId = dict() <NEW_LINE> self.idToMovie = dict() <NEW_LINE> self.ratingsPerUser = dict() <... | Reads the data file and create lookup tables.
:param filename: str : the path to the file | 625941f7dd821e528d63b81f |
def recvall(connection, n): <NEW_LINE> <INDENT> data = b'' <NEW_LINE> while len(data) < n: <NEW_LINE> <INDENT> packet = connection.recv(n - len(data)) <NEW_LINE> if not packet: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> data += packet <NEW_LINE> <DEDENT> return data | Helper function to recv n bytes or return None if EOF is hit
To read a message with an expected size and combine it to one object, even if it was split into more than one
packets.
:param connection: Connection to a socket
:param n: Size of the message to read in bytes
:type n: int
:return: Expected message combined ... | 625941f792d797404e304809 |
def test_finditer(self): <NEW_LINE> <INDENT> with open(mpath) as fd: <NEW_LINE> <INDENT> contents = fd.read() <NEW_LINE> <DEDENT> self.assertEqual(len(list(re.finditer(r'\w+', contents))), 14230) <NEW_LINE> self.assertEqual([m.group(1) for m in re.finditer(r'\n#hdr-editions(.*?)\n', contents)], [' a { text-decoration:n... | Simple tests for the ``finditer`` function. | 625941f7009cb60464c63a28 |
def join(self, terms, parens=True): <NEW_LINE> <INDENT> r = self._and.join([self.quote(t) for t in terms if t]) <NEW_LINE> if parens and len(terms) > 1: <NEW_LINE> <INDENT> r = '(%s)' % r <NEW_LINE> <DEDENT> return r | >>> q.join(("1", "2", "3 three"))
'(1 & 2 & "3 three")'
>>> q.join(("1", "2", "3 three"), parens=False)
'1 & 2 & "3 three"'
>>> q._and = ' AND '
>>> q.join(("1", "2", "3 three"))
'(1 AND 2 AND "3 three")'
>>> q.join(("1", "2", "3 three"), parens=False)
'1 AND 2 AND "3 three"' | 625941f7e5267d203edce311 |
def insert(self, name, uri): <NEW_LINE> <INDENT> name = self._create_unique_name(name, uri) <NEW_LINE> self._uri_from_name[name] = uri <NEW_LINE> self._name_from_uri[uri] = name <NEW_LINE> return name | Create a unique and MPD compatible name that maps to the given URI. | 625941f77b25080760e39ad1 |
def set_inlets(self, pores=None, **kwargs): <NEW_LINE> <INDENT> if 'inlets' in kwargs.keys(): <NEW_LINE> <INDENT> pores = kwargs['inlets'] <NEW_LINE> <DEDENT> self['pore.invaded'][pores] = 0 <NEW_LINE> Ts = self._net.find_neighbor_throats(pores=pores) <NEW_LINE> self.queue = [] <NEW_LINE> [hq.heappush(self.queue, T) fo... | Parameters
----------
pores : array_like
The list of inlet pores from which the Phase can enter the Network | 625941f7be7bc26dc91cdc6f |
def shorter_distance(sol_1, sol_2, num_neighbors: int, k: int = 0): <NEW_LINE> <INDENT> if sol_1.distances[k] == sol_2.distances[k]: <NEW_LINE> <INDENT> k += 1 <NEW_LINE> if k == num_neighbors: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return shorter_distance(sol_1, sol_2, num_neighbors, k) <NEW_LINE> <DEDEN... | Function that returns true if the first solution has a shorter distance or
both solutions are the same. Otherwise it will returns false. | 625941f7bd1bec0571d90cac |
def averages(grades): <NEW_LINE> <INDENT> averages = [] <NEW_LINE> for grades_list in grades: <NEW_LINE> <INDENT> total = 0 <NEW_LINE> for mark in grades_list: <NEW_LINE> <INDENT> total = total + mark <NEW_LINE> <DEDENT> averages.append(total / len(grades_list)) <NEW_LINE> <DEDENT> return averages | (list of list of number) -> list of float
Return a new list in which each item is the average of the grades in the
inner list at the corresponding position of grades.
>>> averages([[70,75,80],[70,80,90,100],[80,100]])
[75.0, 85.0, 90.0] | 625941f71f037a2d8b946878 |
def listOperations(numlist): <NEW_LINE> <INDENT> print("original list = {}".format(numlist)) <NEW_LINE> count = len(numlist) <NEW_LINE> print("number of elements = {}".format(count)) <NEW_LINE> uniqlist = set(numlist) <NEW_LINE> print("unique elements = {}".format(uniqlist)) <NEW_LINE> sortedList = sorted(numlist) <NEW... | Random list operations
Arguments:
numlist {list[integer]} -- input list of integers | 625941f7cad5886f8bd27654 |
@bp.route('/messages') <NEW_LINE> @login_required <NEW_LINE> def messages(): <NEW_LINE> <INDENT> current_user.last_message_read_time = datetime.utcnow() <NEW_LINE> current_user.add_notification('unread_message_count', 0) <NEW_LINE> db.session.commit() <NEW_LINE> page = request.args.get('page', 1, type = int) <NEW_LINE>... | show and paginate private messages | 625941f7b7558d58953c5582 |
def degre(M,i): <NEW_LINE> <INDENT> return len(voisins(M,i)) | Entrées :
* M(lst) : graphe
* i : noeud considéré
Sortie :
* (int) : nomnbre de voisins | 625941f7e8904600ed9f25b5 |
def propagate_back(weights, activation, input_matrix, targets): <NEW_LINE> <INDENT> sample_size = targets.shape[1] <NEW_LINE> dw = 1/sample_size * np.dot(input_matrix, (activation-targets).T) <NEW_LINE> db = 1/sample_size * np.sum(activation-targets) <NEW_LINE> assert(dw.shape == weights.shape) <NEW_LINE> assert(db.dty... | Performs propagate forward step for a single neural network node
:param activation:
:param input_matrix:
:param targets:
:return:
dw -- gradient of the loss with respect to w, thus same shape as w
db -- gradient of the loss with respect to b, thus same shape as b | 625941f7a79ad161976cc7c2 |
def get_11_ss(s): <NEW_LINE> <INDENT> xa = - ((-s.M[1][1]*s.mu[0] + s.M[0][1]*s.mu[1]) / (s.M[0][1]*s.M[1][0] - s.M[0][0]*s.M[1][1])) <NEW_LINE> xb = - ((s.M[1][0]*s.mu[0] - s.M[0][0]*s.mu[1]) / (s.M[0][1]*s.M[1][0] - s.M[0][0]*s.M[1][1])) <NEW_LINE> return np.array([xa, xb]) | Returns the coexistent steady state (x_a^*, x_b^*) of the 2D gLV
equations (assuming the equations are not nondimensionalized) | 625941f73cc13d1c6d3c79f3 |
def expandToDepth(self, p_int): <NEW_LINE> <INDENT> pass | expandToDepth(self, int) | 625941f7a219f33f34628fdc |
def can_move_down(board, curr_piece, piece_pos): <NEW_LINE> <INDENT> piece_pos = get_down_move(piece_pos) <NEW_LINE> return overlap_check(board, curr_piece, piece_pos) | Parameters:
-----------
board - matrix of the size of the board
curr_piece - matrix for the piece active in the game
piece_pos - [x,y] co-ordinates of the top-left cell in the piece matrix
w.r.t. the board
Returns:
--------
True - if we can move the piece downwards
False - if we cannot move the piece to th... | 625941f7f548e778e58cdbfd |
def sparsify(dfdum, traincols=[], trainsparse=False): <NEW_LINE> <INDENT> dfdum = pd.get_dummies(dfdum.astype(str)) <NEW_LINE> if len(traincols) == 0: <NEW_LINE> <INDENT> print('') <NEW_LINE> print('sparsifying data if necessary...') <NEW_LINE> outcols = dfdum.columns <NEW_LINE> trainsparse = False <NEW_LINE> sparsity_... | Needs to have two branches, one for train and one for test,
both cannot be created at same time due to memory issues.
Sparsify dataset of all categorical variables. | 625941f74f88993c3716c6dc |
def get_queryset(self): <NEW_LINE> <INDENT> return self.model.objects .all().select_related('metadata') .prefetch_related('actions', 'attachments', 'sponsors', 'references_in_legislation', 'metadata__locations', 'metadata__mentioned_legfiles', 'metadata__topics') | Select all the data relevant to the legislation. | 625941f78c0ade5d55d3f03e |
def test_rotate_180(): <NEW_LINE> <INDENT> original_bitmap = Bitmap.read_file(BMP_FILE_PATH) <NEW_LINE> transformed_bitmap = Bitmap(original_bitmap.transform_bitmap_rotate_180()) <NEW_LINE> assert (original_bitmap.pixel_array.tobytes()[:10] == transformed_bitmap.pixel_array.tobytes()[-10:][::-1]) | Check function transform_bitmap_rotate_180 function on the
BMP_FILE_PATH define above.
Check: the (first n bytes in old file) shall equal to the
(last n bytes in new file in reversed order). | 625941f776e4537e8c351cf5 |
def connection_lost(self, exc): <NEW_LINE> <INDENT> self.__exit.set_result(self.__transport.get_returncode()) <NEW_LINE> self.__transport = None | Process exited and all pipes have been disconnected | 625941f7cc40096d61595fca |
def lookup_mesh(phrase, client, mapping): <NEW_LINE> <INDENT> if phrase in mapping: <NEW_LINE> <INDENT> return mapping[phrase] <NEW_LINE> <DEDENT> rst = client.get_mesh_by_term_search(phrase) <NEW_LINE> print('{} {} => {} {}\r'.format(len(mapping), phrase, rst['ui'], ' '*50), end='') <NEW_LINE> if rst['ui'] != 'NONE': ... | Search MeSH terms in a phrase and build a MeSH dict via UTS API | 625941f756ac1b37e626483e |
def close(self): <NEW_LINE> <INDENT> self._socket.close() | Closes our socket connection. This is a pass-through for our socket's
:func:`~stem.socket.ControlSocket.close` method. | 625941f73346ee7daa2b33ef |
def domination(self, a, b): <NEW_LINE> <INDENT> compare = [] <NEW_LINE> criteria = len(a) <NEW_LINE> for i in xrange(criteria): <NEW_LINE> <INDENT> if a[i] < b[i]: <NEW_LINE> <INDENT> compare.append(1) <NEW_LINE> <DEDENT> elif a[i] == b[i]: <NEW_LINE> <INDENT> compare.append(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | Determine if either a or b dominates the other. | 625941f776e4537e8c351cf6 |
def _get_data_source_url(self): <NEW_LINE> <INDENT> if 'url' not in self.__dict__: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__getattribute__('url') | This method should return URL to identify Posts.
Different content types may store the URL in a different parameters or even create a dummy one | 625941f7377c676e91272823 |
def make_battle_state(pk1, pk2=None): <NEW_LINE> <INDENT> top = Element('battle_state') <NEW_LINE> x1 = pk1.make_xml() <NEW_LINE> top.append(x1) <NEW_LINE> if pk2 is not None: <NEW_LINE> <INDENT> x2 = pk2.make_xml() <NEW_LINE> top.append(x2) <NEW_LINE> <DEDENT> return etree.tostring(top, xml_declaration=True, pretty_pr... | Gera um battle_state. | 625941f71f5feb6acb0c51c6 |
def test_put_with_no_access(self): <NEW_LINE> <INDENT> self._login_user() <NEW_LINE> self._put_repository(False, expected_status=403) | Testing the PUT repositories/<id>/ API with no access | 625941f71f5feb6acb0c51c5 |
def synchronize(handle): <NEW_LINE> <INDENT> if handle not in _handle_map: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mpi_lib.horovod_torch_wait_and_clear(handle) <NEW_LINE> _, output = _handle_map.pop(handle) <NEW_LINE> return output | Synchronizes an asynchronous allreduce, allgather or broadcast operation until
it's completed. Returns the result of the operation.
Arguments:
handle: A handle returned by an allreduce, allgather or broadcast asynchronous
operation.
Returns:
An output tensor of the operation. | 625941f760cbc95b062c6bc0 |
def start(self): <NEW_LINE> <INDENT> return _ccsds_swig.send_nanolink_sptr_start(self) | start(send_nanolink_sptr self) -> bool | 625941f71f037a2d8b946879 |
def is_word_guessed(secret_word, letters_guessed): <NEW_LINE> <INDENT> return set(list(secret_word)).issubset(letters_guessed) | secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the letters of secret_word are in letters_guessed;
False otherwise | 625941f73eb6a72ae02ecb6d |
def do_endmeeting(self, nick, time_, **kwargs): <NEW_LINE> <INDENT> if not self.isChair(nick): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.oldtopic: <NEW_LINE> <INDENT> self.topic(self.oldtopic) <NEW_LINE> <DEDENT> self.endtime = time_ <NEW_LINE> self.config.save() <NEW_LINE> endtime = time.asctime(time_) <N... | End the meeting. | 625941f7d4950a0f3b08c9c2 |
def getSkyCircleCatalog(self, center, radius, filterList, epoch=None, catalogFormat='numpy'): <NEW_LINE> <INDENT> if self._fluxFilters is None or self._fluxFilters != filterList: <NEW_LINE> <INDENT> self._determineFluxFields(center, filterList) <NEW_LINE> <DEDENT> skyCircle = self.refObjLoader.loadSkyCircle(center, rad... | Get a multi-band reference catalog by specifying a center and radius.
The catalog will be in `numpy.ndarray`, with positions proper-motion
corrected to "epoch" (if specified, and if the reference catalog has
proper motions); sources cut on a reference selector (if
"config.doReferenceSelection = True"); and color-terms... | 625941f766656f66f7cbc82a |
def test_takeReading_IPTempSensor_wrongURLExtension(self): <NEW_LINE> <INDENT> self.testSenTemp.urlSensorExtension = 'tempp' <NEW_LINE> self.testSenTemp.takeReading() <NEW_LINE> time.sleep(2) <NEW_LINE> newReading = self.testSenTemp.getLastReadingInBuffer() <NEW_LINE> self.assertEqual(newReading,None) | Testing the takeReading method using a esp temperature sensor but with wrong url extension.
Must return an empty value | 625941f755399d3f05588d36 |
def parse_elementOptions(self, obj): <NEW_LINE> <INDENT> children = copy.copy(obj.children) <NEW_LINE> _o, children = self._parse_token(children, self.lexer.LT) <NEW_LINE> def pred_inside(children): <NEW_LINE> <INDENT> _o, children = self._parse_question_token(children, self.lexer.COMMA) <NEW_LINE> if not _o: return No... | elementOptions
: LT elementOption (COMMA elementOption)* GT
; | 625941f763d6d428bbe44b6f |
def _get_payload_schema(self, table): <NEW_LINE> <INDENT> return self.schema_wrapper[table] | Get payload avro schema from schema wrapper or from schema store | 625941f7a17c0f6771cbe6cb |
def findTarget(self, root, k): <NEW_LINE> <INDENT> from functools import partial <NEW_LINE> def _find(root, v): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if root.val == v: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif v < root.val: <NEW_LINE> <INDENT> return _find(... | :type root: TreeNode
:type k: int
:rtype: bool | 625941f730bbd722463cc447 |
def __get_repos_in_file(self, fn): <NEW_LINE> <INDENT> c=open(fn,'rt').read() <NEW_LINE> return map(lambda a: a[1:],self.repos_re.findall(c)) | return tubles repo,is_enabled | 625941f7004d5f362079a9ab |
def to_json(self): <NEW_LINE> <INDENT> return [p.to_json() for p in self.params] | Return a json serializable format. | 625941f745492302aab5e947 |
def fitdata(x,t,M): <NEW_LINE> <INDENT> X_matrix = np.array([x**m for m in range(M+1)]) <NEW_LINE> w = (inv(X_matrix@X_matrix.T)@X_matrix)@t <NEW_LINE> return w | fitdata(x,t,M): Fit a polynomial of order M to the data (x,t) | 625941f70c0af96317bb8864 |
def test_replace_host_key_no_known_hosts(self): <NEW_LINE> <INDENT> storage = FileSSHStorage() <NEW_LINE> storage.replace_host_key('host1', test_keys.rsa_key, test_keys.dsa_key) <NEW_LINE> filename = storage.get_host_keys_filename() <NEW_LINE> with open(filename, 'r') as fp: <NEW_LINE> <INDENT> lines = fp.readlines() <... | Testing FileSSHStorage.replace_host_key with no known hosts file | 625941f7091ae356686675d0 |
def compare_and_print_statsmodels(estimators, indice=0): <NEW_LINE> <INDENT> print("\n") <NEW_LINE> if indice in [0, 2]: <NEW_LINE> <INDENT> data_dict = {} <NEW_LINE> coeff = {} <NEW_LINE> i = 1 <NEW_LINE> keys = [] <NEW_LINE> if len(estimators) > 0: <NEW_LINE> <INDENT> for k, est in estimators.items(): <NEW_LINE> <IND... | Prints & saves comparitive results for different
StatsModels
:param estimators: Different statsmodel OLS models | 625941f7baa26c4b54cb1795 |
def test_teams_id_templates_nk_permission_put(self): <NEW_LINE> <INDENT> pass | Test case for teams_id_templates_nk_permission_put
Update permission of this model. | 625941f757b8e32f52483b1d |
def find(self, string, default=None): <NEW_LINE> <INDENT> return self.match(string) or self.search(string) or default | Return match or search result.
:rtype: list | 625941f723849d37ff7b3707 |
def mostCommonWord(self, paragraph, banned): <NEW_LINE> <INDENT> paragraph=paragraph.lower() <NEW_LINE> for i in banned: <NEW_LINE> <INDENT> paragraph=paragraph.replace(i,' ') <NEW_LINE> <DEDENT> paragraph=paragraph.replace("!",' ') <NEW_LINE> paragraph=paragraph.replace("?",' ') <NEW_LINE> paragraph=paragraph.replace(... | :type paragraph: str
:type banned: List[str]
:rtype: str | 625941f7236d856c2ad44e62 |
def __init__(self, rect, parent=None): <NEW_LINE> <INDENT> super(ScaleGui, self).__init__(parent) <NEW_LINE> self.setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemIsFocusable) <NEW_LINE> self.lengthInMM = 20 <NEW_LINE> self.updateRect(rect) | Constructor | 625941f729b78933be1e5d21 |
@app.route('/webhooks', methods=['POST']) <NEW_LINE> def webhooks(): <NEW_LINE> <INDENT> body = request.get_json() <NEW_LINE> try: <NEW_LINE> <INDENT> if body['data']['payload']['direction'] == 'inbound': <NEW_LINE> <INDENT> text = body['data']['payload']['text'] <NEW_LINE> sender_phone_number = body['data']['payload']... | Simple webhook to receive messages
Args:
Returns:
Returns 200 if the message received successfully, an error message otherwise. | 625941f75fc7496912cc3ffa |
def __init__( self, filename='Med_Calls_with_Tracts.pkl', flag_holidays=True, country='US', state='CA', prov=None, flag_weekends=True, test_size=0.25, random_state_split=None, random_state_fit=42, n_estimators=175, min_samples_split=200, max_features='log2', ): <NEW_LINE> <INDENT> self.original_df = get_medical_calls(f... | Read the pickled Pandas dataframe of medical incidents. | 625941f77b180e01f3dc4e6b |
def bootstrap(data, statistic, resamples=1000, alpha=0.05, output='ci', **kwargs): <NEW_LINE> <INDENT> samples = numpy.random.choice(data, size=(resamples, len(data)), replace=True) <NEW_LINE> stat = numpy.sort([statistic(row, **kwargs) for row in samples]) <NEW_LINE> if output == 'ci': <NEW_LINE> <INDENT> return (stat... | Returns the bootstrap estimate of the confidence interval for the given
statistic. The confidence interval is given by 100*(1-alpha). Passes a 1d
array to the function, statistic. Any arguments needed by statistic are
passed by **args.
@type data: list
@param data: The data on which the given statistic is calculated
@... | 625941f701c39578d7e754b9 |
def Reinitialize(self): <NEW_LINE> <INDENT> sess = self.GetSes() <NEW_LINE> sess.run(self.init) | Reinitialize variables and start the TensorFlow session | 625941f7a79ad161976cc7c3 |
def __lt__(self, other): <NEW_LINE> <INDENT> if self.priority == other.priority: <NEW_LINE> <INDENT> localkeys = self.next_value.keys() <NEW_LINE> otherkeys = other.next_value.keys() <NEW_LINE> shared_keys = sorted(set(localkeys).intersection(otherkeys)) <NEW_LINE> for key in shared_keys: <NEW_LINE> <INDENT> if self.ne... | Allow order testing via '<' operator, needed by priority queue. | 625941f74a966d76dd551694 |
def endday(self): <NEW_LINE> <INDENT> self.save() <NEW_LINE> topvotes = self.mostvotedplayers() <NEW_LINE> if len(topvotes) > 0: <NEW_LINE> <INDENT> random.seed() <NEW_LINE> random.shuffle(topvotes) <NEW_LINE> lynched = topvotes.pop() <NEW_LINE> if lynched.alive: <NEW_LINE> <INDENT> self.message(s.player_lynched.format... | Finisci la giornata, uccidi il più votato del giorno ed esegui gli endday di tutti i giocatori. | 625941f74c3428357757c9a0 |
def handle_request(self, pkt, datapath, in_port): <NEW_LINE> <INDENT> LOG.info("Handling dhcp 'Request' from %s datapath on %s port", datapath.id, in_port) <NEW_LINE> return super(DHCP, self).handle_request(pkt, datapath, in_port) | Handle request
This method provides hooks for extra processing, needs to be done
for specific to requirement. If no extra information is needed then
call super method. | 625941f7ff9c53063f47c86d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.