code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def create_volume_from_snapshot(self, volume, snapshot): <NEW_LINE> <INDENT> vol_size = volume.size <NEW_LINE> snap_size = snapshot.volume_size <NEW_LINE> self._clone_snapshot(snapshot.provider_id, volume.name, snapshot.volume_id) <NEW_LINE> share = self._get_provider_location(snapshot.volume_id) <NEW_LINE> volume['pro... | Creates a volume from snapshot. | 625941e8cad5886f8bd27461 |
def fb_access_token_response(r): <NEW_LINE> <INDENT> values = urlparse.parse_qs(r.text) <NEW_LINE> values = dict([(k, v[0]) for k, v in values.items()]) <NEW_LINE> values['token_type'] = 'bearer' <NEW_LINE> fr = MicroMock(text=json.dumps(values)) <NEW_LINE> return fr | A fix for facebook.
For some reason facebook doesn't return JSON for the access_token page,
even though the spec says they should. A spec which they co-author. Right. | 625941e81f037a2d8b946686 |
def write(self, call): <NEW_LINE> <INDENT> import ebusdpy <NEW_LINE> name = call.data.get('name') <NEW_LINE> value = call.data.get('value') <NEW_LINE> try: <NEW_LINE> <INDENT> _LOGGER.debug("Opening socket to ebusd %s", name) <NEW_LINE> command_result = ebusdpy.write( self._address, self._circuit, name, value) <NEW_LIN... | Call write methon on ebusd. | 625941e83539df3088e2e7d4 |
def get_char_ids_tensor(seg_lists, c2i, max_char_len=16, pad_idx=0, oov_idx=1): <NEW_LINE> <INDENT> max_seq_len = max([len(l) for l in seg_lists]) <NEW_LINE> rv = np.zeros((len(seg_lists), max_seq_len, max_char_len)) <NEW_LINE> rv.fill(pad_idx) <NEW_LINE> for i, seg_list in enumerate(seg_lists): <NEW_LINE> <INDENT> for... | return batch_size x seq_len x 16 | 625941e815baa723493c4402 |
def rnn_train (self, x, m, t, f): <NEW_LINE> <INDENT> tf.compat.v1.reset_default_graph() <NEW_LINE> with tf.compat.v1.Session() as sess: <NEW_LINE> <INDENT> target = tf.placeholder(tf.float32, [self.seq_len, None, 1]) <NEW_LINE> mask = tf.placeholder(tf.float32, [self.seq_len, None, 1]) <NEW_LINE> rnn = biGRUCell(3, se... | Train RNN for each feature.
Args:
- x: incomplete data
- m: mask matrix
- t: time matrix
- f: feature index | 625941e84527f215b584c8db |
def index_response_descriptor_policies_machine_policy_machine_policy_resource_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = ['skip', 'take'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all... | Get a list of MachinePolicyResources # noqa: E501
Lists all of the machine policies in the supplied Octopus Deploy Space. The results will be sorted alphabetically by name. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> threa... | 625941e84d74a7450ccd464d |
def denormalize(im): <NEW_LINE> <INDENT> imagenet_stats = np.array([[0.485, 0.456, 0.406], [0.229, 0.224, 0.225]]) <NEW_LINE> return (im * imagenet_stats[1]) + imagenet_stats[0] | Denormalize images. | 625941e823849d37ff7b3514 |
def broadcast(self, a, root): <NEW_LINE> <INDENT> assert 0 <= root < self.size <NEW_LINE> assert is_contiguous(a) <NEW_LINE> self.comm.broadcast(a, root) | Share data from a single process to all ranks in a group.
Parameters:
a: ndarray
Data, i.e. send buffer on root rank, receive buffer elsewhere.
Note that after the broadcast, all ranks have the same data.
root: int
Rank of the root process, from which the data is to be shared.
Example::
# All ranks ha... | 625941e8e5267d203edce120 |
def __simulation_iteration_valeur(self): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> politique = self.board.iteration_valeur() <NEW_LINE> end = time.time() <NEW_LINE> print("Temps éxécution = ", end - start) <NEW_LINE> for y in range(len(politique)): <NEW_LINE> <INDENT> for x in range(len(politique[y])): <NEW_LI... | :return: | 625941e894891a1f4081bf34 |
def _extractDetectorName(self, dataId): <NEW_LINE> <INDENT> return "0" | Normally this extracts the detector (CCD) name from the dataset
identifier. The name in question is the detector name used by
lsst.afw.cameraGeom.
We don't need anything meaninful here, so just override so as not to
throw (in the base class impl) | 625941e8a79ad161976cc5ce |
def _collectPositves(self, imgPath, segments): <NEW_LINE> <INDENT> positiveSegments = 0 <NEW_LINE> ppath = pathlib.PurePath(imgPath) <NEW_LINE> googleDrive = self.google_services['drive'] <NEW_LINE> for segmentInfo in segments: <NEW_LINE> <INDENT> if segmentInfo['score'] > .5: <NEW_LINE> <INDENT> if hasattr(settings, '... | Collect all positive scoring segments
Copy the images for all segments that score highter than > .5 to google drive folder
settings.positivePictures. These will be used to train future models.
Also, copy the full image for reference.
Args:
imgPath (str): path name for main image
segments (list): List of dicti... | 625941e816aa5153ce362901 |
def renameResource(old_id, new_id): <NEW_LINE> <INDENT> pass | Change the id of a registered resource. | 625941e873bcbd0ca4b2c4fe |
def import_data(self): <NEW_LINE> <INDENT> self.models = [] <NEW_LINE> for o in self.loader.load(): <NEW_LINE> <INDENT> klass = self.type_for(o) <NEW_LINE> if hasattr(klass, "from_api"): <NEW_LINE> <INDENT> self.models.append(klass.from_api(o)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.models.append(klass(o)) ... | Import all model data using the loader. | 625941e8dc8b845886cb59c0 |
def _getRootDir(self): <NEW_LINE> <INDENT> root_clus = self._fat.bpb.BPB_RootClus <NEW_LINE> return Directory(self._fat, '/', root_clus) | get the Directory for the root directory of the file system.
rtype: Directory | 625941e84e4d5625662d485a |
def supported_document_fields(settings: dict, org_id: str, flow_id: str): <NEW_LINE> <INDENT> data_type = settings.get('data_type') <NEW_LINE> field_types = supported_mapping(data_type) <NEW_LINE> field_list = flow.field_list(org_id, flow_id, field_types) <NEW_LINE> return field_to_resource_fields(field_list) | Create a list of supported document fields for a given flow. | 625941e8377c676e91272630 |
def testAllGatherRaiseDifferentRank(self, strategy, pure_eager): <NEW_LINE> <INDENT> if _is_tpu_strategy(strategy): <NEW_LINE> <INDENT> self.skipTest('TODO(b/169108777): raise a clear error message in xla.') <NEW_LINE> <DEDENT> if strategy.num_replicas_in_sync <= 1: <NEW_LINE> <INDENT> self.skipTest('Test for more than... | Different rank: [1,], [1, 2] -> raise error. | 625941e80a366e3fb873eca7 |
def _connectionLost(self, reason): <NEW_LINE> <INDENT> self.log.debug('_connectionLost: {reason}', reason=reason) <NEW_LINE> if not self.factory.isServer and self.serverConnectionDropTimeoutCall is not None: <NEW_LINE> <INDENT> self.log.debug("serverConnectionDropTimeoutCall.cancel") <NEW_LINE> self.serverConnectionDro... | This is called by network framework when a transport connection was
lost. | 625941e8a17c0f6771cbe4d8 |
def cosh(x : float,useTaylor : bool = False,iterations = 100) -> float: <NEW_LINE> <INDENT> if not useTaylor: <NEW_LINE> <INDENT> return (powers.power(e,x) + powers.power(e,-x)) / 2 <NEW_LINE> <DEDENT> return sum([ powers.power(x,2*n) / functions.factorial(2*n) for n in range(iterations) ]) | Hyperbolic Cosine,
domain : 'All real numbers', | 625941e830c21e258bdfa92b |
def legacyJDBCInit(): <NEW_LINE> <INDENT> from org.springframework.mock.jndi import SimpleNamingContextBuilder <NEW_LINE> from org.postgresql.ds import PGSimpleDataSource <NEW_LINE> from net.sourceforge.jtds.jdbcx import JtdsDataSource <NEW_LINE> if not SimpleNamingContextBuilder.getCurrentContextBuilder(): <NEW_LINE> ... | Create JDBC DataSources and register under appropriate JNDI names.
Use only when running djangoshop outsite Tomcat environment (jython shell or django webserver).
Tomcat when used, is itself responsible for JNDI bindings. | 625941e8293b9510aa2c371a |
def penalized_tanh(self,x): <NEW_LINE> <INDENT> alpha = 0.25 <NEW_LINE> return torch.max(torch.tanh(x), alpha*torch.tanh(x)) | http://aclweb.org/anthology/D18-1472 | 625941e8cb5e8a47e48b7f2c |
def enqueue(self, state_dict): <NEW_LINE> <INDENT> in_open = False <NEW_LINE> in_close = False <NEW_LINE> for i in range(len(self.close)): <NEW_LINE> <INDENT> if state_dict['state']==self.close[i]['state']: <NEW_LINE> <INDENT> in_close = True <NEW_LINE> if state_dict['g'] < self.close[i]['g']: <NEW_LINE> <INDENT> del s... | Items in the priority queue are dictionaries:
- 'state': the current state of the puzzle
- 'h': the heuristic value for this state
- 'parent': a reference to the item containing the parent state
- 'g': the number of moves to get from the initial state to
this state, the "cost" of this state
... | 625941e8eab8aa0e5d26dfe3 |
def admin_inline(request, inline_id): <NEW_LINE> <INDENT> inline_type = get_object_or_404(InlineType, pk=inline_id) <NEW_LINE> app_label, model_name, model = get_model_for_inline(inline_type) <NEW_LINE> template = ["admin/%(app_label)s/inline_list_%(model_name)s.html" % {'app_label': app_label, 'model_name': model_name... | Returns HTML that displays a list of supplied inlines for embedding in the Admin | 625941e88e7ae83300e4b457 |
def corenlp_downloader(custompath=False): <NEW_LINE> <INDENT> import os <NEW_LINE> from corpkit.build import download_large_file <NEW_LINE> from corpkit.process import get_corenlp_path <NEW_LINE> from corpkit.constants import CORENLP_URL as url <NEW_LINE> cnlp_dir = os.path.join(os.path.expanduser("~"), 'corenlp') <NEW... | Very simple CoreNLP downloader
:param custompath: A path where you want to put CoreNLP
:type custompath: ``str``
:Usage:
python -m corpkit.download.corenlp | 625941e8a17c0f6771cbe4d9 |
def getDatatagNameid(engine,datatagname,schemaname=''): <NEW_LINE> <INDENT> datatagnameid = 0 <NEW_LINE> if datatagname=='online': return datatagnameid <NEW_LINE> return datatagnameid | select datatagnameid from DATATAGS where datatagname=%datatagname | 625941e844b2445a3393251c |
def test_ip_interface(self): <NEW_LINE> <INDENT> n = 10**4 <NEW_LINE> data = [ ('1.2.3.4/30'), ('1:2:3:4:5:6::/112'), ] <NEW_LINE> fns = ip.ip_interface, eip.ip_interface <NEW_LINE> for args in data: <NEW_LINE> <INDENT> generic_test(self.report_u, fn_name(), n, fns, args) | Test the ip_interface function. | 625941e831939e2706e4d2ed |
def rcv_dmg(self, atker, dmg): <NEW_LINE> <INDENT> self.hp -= dmg <NEW_LINE> if self.hp <= 0: <NEW_LINE> <INDENT> self.die() <NEW_LINE> <DEDENT> return dmg | Receive dmg from a skill by an atker. | 625941e857b8e32f52483927 |
@register.filter <NEW_LINE> def has_taken(value, course): <NEW_LINE> <INDENT> if not isinstance(value, Student): <NEW_LINE> <INDENT> try: value = value.student <NEW_LINE> except AttributeError: return False <NEW_LINE> <DEDENT> return Enrollment.objects.filter(student=value) .filter(section__c... | Returns ``True`` if value (an instance of :model:`courses.Student` or ``User``) has taken ``course`` (an
instance of :model:`courses.Course`. | 625941e807f4c71912b1190e |
def fake_urlopen(url): <NEW_LINE> <INDENT> parsed_url = urlparse(url) <NEW_LINE> resource_file = os.path.normpath('tests/resources%s' % parsed_url.path) <NEW_LINE> return open(resource_file, mode='rb') | A stub urlopen() implementation that load json responses from
the filesystem. | 625941e8fb3f5b602dac3b21 |
def test_ceo_and_employee_are_same(self): <NEW_LINE> <INDENT> self.assertEqual(Employee.closetCommonManager(self.Bill, self.Bill, self.Milton), self.Bill) | 特殊情况,当ceo也是比较的雇员时
:return: | 625941e885dfad0860c3b2e5 |
def Kuiper(self): <NEW_LINE> <INDENT> return clib.IKS_Kuiper(self.wp) | Kuiper statistic. Both groups must have the same number of observations.
Returns:
The Kuiper statistic. | 625941e88c0ade5d55d3ee48 |
def __init__(self, names=const.SITE): <NEW_LINE> <INDENT> self.names = names.split() | names is a space separated site names in preferred order. | 625941e82c8b7c6e89b35c47 |
def as_wires(val, bitwidth=None, truncating=True, block=None): <NEW_LINE> <INDENT> from .memory import _MemIndexed <NEW_LINE> block = working_block(block) <NEW_LINE> if isinstance(val, (int, six.string_types)): <NEW_LINE> <INDENT> return Const(val, bitwidth=bitwidth, block=block) <NEW_LINE> <DEDENT> elif isinstance(val... | Return wires from val which may be wires, integers, strings, or bools.
:param val: a wirevector-like object or something that can be converted into
a Const
:param bitwidth: The bitwidth the resulting wire should be
:param bool truncating: determines whether bits will be dropped to achieve
the desired bitwidth if it... | 625941e810dbd63aa1bd302b |
def hit_goal(t, y, S): <NEW_LINE> <INDENT> return y[1] - 1000 | Function that gives 0 when rocket is at the required height | 625941e856b00c62f0f14ae6 |
def __init__(self, length, color_start=None, color_end=None): <NEW_LINE> <INDENT> self.length = length <NEW_LINE> if color_start: <NEW_LINE> <INDENT> self.color_start = color_start <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.color_start = self.random_color() <NEW_LINE> <DEDENT> if color_end: <NEW_LINE> <INDENT> ... | Set the colors for the gradient | 625941e897e22403b379d425 |
def validate_timezone(self, time_zone): <NEW_LINE> <INDENT> if not time_zone.data in all_timezones: <NEW_LINE> <INDENT> raise ValidationError('Invalid time zone.') | Validate form time zone field
Parameters:
self: The RegisterForm form to validate
time_zone: The time zone to validate exists
Raises:
ValidationError: A validation error if the time zone does not exist | 625941e8baa26c4b54cb15a4 |
def get_rich_menu_id_of_user(self, user_id, timeout=None): <NEW_LINE> <INDENT> response = self._get( '/v2/bot/user/{user_id}/richmenu'.format(user_id=user_id), timeout=timeout ) <NEW_LINE> return response.json.get('richMenuId') | Call get rich menu ID of user API.
https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-id-of-user
:param str user_id: IDs of the user
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read timeout) float tuple.
De... | 625941e86e29344779a62a9a |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BeaconStatementObject): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e8293b9510aa2c371b |
def form_valid(self,form): <NEW_LINE> <INDENT> form.instance.author=self.request.user <NEW_LINE> form.instance.hood=self.request.user.profile.neighbourhood <NEW_LINE> return super().form_valid(form) | setting up the form instance user property to the current user before saving it | 625941e821a7993f00bc8182 |
def generator(self): <NEW_LINE> <INDENT> for entries in self.variantEntries: <NEW_LINE> <INDENT> character = entries[0] <NEW_LINE> for i, variantType in enumerate(self.typeList): <NEW_LINE> <INDENT> variantInfo = entries[i+1] <NEW_LINE> if variantInfo: <NEW_LINE> <INDENT> matchR, findR = self.VARIANT_REGEX_MAPPING[vari... | Provides one entry per variant and character. | 625941e863b5f9789fde7570 |
def main(self, *args, **kwargs): <NEW_LINE> <INDENT> servers = self.get('Servers', None) <NEW_LINE> title = self.get('Title', 'Test Notify Title') <NEW_LINE> body = self.get('Body', 'Test Notify Body') <NEW_LINE> theme = NOTIFY_THEMES_MAP[self.get('Theme', 'general')] <NEW_LINE> notify_type = self.get('NotificationType... | CLI
| 625941e8796e427e537b0a54 |
def test_from_string(): <NEW_LINE> <INDENT> states = {"x": "sigma*(y-x)", "y": "x*(rho-z)-y", "z": "x*y-beta*z"} <NEW_LINE> parameters = {"sigma": 10, "beta": 8 / 3, "rho": 28} <NEW_LINE> ss = StateSpaceModel.from_string(states=states, parameters=parameters) <NEW_LINE> assert len(ss.state_vector) == len(states) <NEW_LI... | test that the correct State-Space model is built from strings | 625941e8e1aae11d1e74a145 |
def _get_score_from_csm(csm_scores, block, weight): <NEW_LINE> <INDENT> score = csm_scores.get(block.location) <NEW_LINE> has_valid_score = score and score.total is not None <NEW_LINE> if has_valid_score: <NEW_LINE> <INDENT> if score.correct is not None: <NEW_LINE> <INDENT> first_attempted = score.created <NEW_LINE> ra... | Returns the score values from the courseware student module, via
ScoresClient, if found. | 625941e8d53ae8145f87a6f0 |
def __conv_left(self): <NEW_LINE> <INDENT> conv_ops = self._model.get_operations_by_type() <NEW_LINE> conv_left = [] <NEW_LINE> for conv in conv_ops: <NEW_LINE> <INDENT> if conv.name not in self.drop_conv: <NEW_LINE> <INDENT> conv_left.append(conv) <NEW_LINE> <DEDENT> <DEDENT> tf.logging.debug('drop conv {}'.format(sel... | Get the left convolutions after pruning so far | 625941e8ff9c53063f47c67b |
def __init__(self, item_list, attributes=dir, unique=False): <NEW_LINE> <INDENT> self._attributes = [] <NEW_LINE> if isinstance(attributes, collections.Iterable): <NEW_LINE> <INDENT> self._attributes = attributes <NEW_LINE> <DEDENT> elif len(item_list) > 0: <NEW_LINE> <INDENT> self._attributes = attributes(item_list[0]... | Init ListAttrAccessor.
Args:
item_list -- list of items that have common attributes
attributes -- (default: None) explicit list of attributes, None (all attributes) or a function
unique -- (default: dir) Only return unique values, preservering order
The first item is used to get the attributes that are... | 625941e8b830903b967e9d90 |
def plot_series(series, label=None, kind='line', use_index=True, rot=None, xticks=None, yticks=None, xlim=None, ylim=None, ax=None, style=None, grid=None, legend=False, logx=False, logy=False, secondary_y=False, **kwds): <NEW_LINE> <INDENT> kind = _get_standard_kind(kind.lower().strip()) <NEW_LINE> if kind == 'line': <... | Plot the input series with the index on the x-axis using matplotlib
Parameters
----------
label : label argument to provide to plot
kind : {'line', 'bar', 'barh'}
bar : vertical bar plot
barh : horizontal bar plot
rot : int, default 30
Rotation for tick labels
use_index : boolean, default True
Plot ind... | 625941e8be7bc26dc91cda81 |
def track_size(self, ts, sizer): <NEW_LINE> <INDENT> obj = self.ref() <NEW_LINE> self.snapshots.append( (ts, sizer.asized(obj, detail=self._resolution_level)) ) <NEW_LINE> if obj is not None: <NEW_LINE> <INDENT> self.repr = safe_repr(obj, clip=128) | Store timestamp and current size for later evaluation.
The 'sizer' is a stateful sizing facility that excludes other tracked
objects. | 625941e88e71fb1e9831dc31 |
def mkdir_with_mode(name, mode=0o770): <NEW_LINE> <INDENT> head, tail = path.split(name) <NEW_LINE> if not tail: <NEW_LINE> <INDENT> head, tail = path.split(head) <NEW_LINE> <DEDENT> if head and tail and not path.exists(head): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mkdir_with_mode(head, mode) <NEW_LINE> <DEDENT> ... | Creates a directory with specified permissions.
:param directory: directory path
:param mode: permissions to set to the directory | 625941e85166f23b2e1a55e3 |
def getVersion(): <NEW_LINE> <INDENT> return _structural.getVersion() | getVersion() -> char * | 625941e830c21e258bdfa92c |
def test_load_all(self) -> None: <NEW_LINE> <INDENT> loaded = ImageStream.load_all(os.path.join(self.data_dir, "template", "is")) <NEW_LINE> assert len(loaded) == 11 | Test loading objects from data dir. | 625941e8596a897236089f44 |
def get_minima_positions(dataset, above, N=21, P=0.5, Sig=25): <NEW_LINE> <INDENT> window = general_gaussian(N, p=P, sig=Sig) <NEW_LINE> filtered = fftconvolve(window, dataset) <NEW_LINE> filtered = (np.average(dataset) / np.average(filtered)) * filtered <NEW_LINE> filtered = np.roll(filtered, int((N-1)/2)) <NEW_LINE> ... | get the position of the local minima
in the 1d numpy array >dataset< after
smoothing it with a gaussian
Returns: indices of the local minima,
where the value of dataset[indices] is
smaller than >above< | 625941e8a934411ee3751b1e |
def round(self): <NEW_LINE> <INDENT> min = int("%.0f" % (self.min + 0.001)) <NEW_LINE> max = int("%.0f" % (self.max + 0.001)) <NEW_LINE> return DeliveryTime(min=min, max=max, unit=self.unit) | Rounds the min/max of the delivery time to an integer and returns a
new DeliveryTime object. | 625941e8ec188e330fd5ac20 |
def _test_factory(case, dec): <NEW_LINE> <INDENT> a, b, q, r, e, s, knownfailure = case <NEW_LINE> if knownfailure: <NEW_LINE> <INDENT> pytest.xfail(reason=knownfailure) <NEW_LINE> <DEDENT> x = solve_continuous_are(a, b, q, r, e, s) <NEW_LINE> res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q <NEW_LINE> out... | Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true | 625941e8656771135c3ebcfe |
def get_swarm_units_coords_and_update_map(s_env): <NEW_LINE> <INDENT> swarm_shipyards_coords = [] <NEW_LINE> swarm_ships_coords = [] <NEW_LINE> for player in range(len(s_env["obs"].players)): <NEW_LINE> <INDENT> shipyards = list(s_env["obs"].players[player][1].values()) <NEW_LINE> for shipyard in shipyards: <NEW_LINE> ... | get lists of coords of Swarm's units and update locations of ships and shipyards on the map | 625941e8d10714528d600172 |
def setResPath(self, resPath): <NEW_LINE> <INDENT> self.RES_PATH = resPath | 设置资源路径 | 625941e85e10d32532c5f3af |
def __init__(self, out_of_order_listener, ordering_timeout_in_seconds: float): <NEW_LINE> <INDENT> self._outOfOrderListener = out_of_order_listener <NEW_LINE> self._orderingTimeoutInSeconds = ordering_timeout_in_seconds <NEW_LINE> self._isOutOfOrderEmitted = {} <NEW_LINE> self._waitListSizeLimit = 100 <NEW_LINE> self._... | Inits the class.
Args:
out_of_order_listener: A function which will receive out of order packet events.
ordering_timeout_in_seconds: Packet ordering timeout. | 625941e8167d2b6e3121901f |
def rmttest_negative_01(self): <NEW_LINE> <INDENT> config, req = create_parameters() <NEW_LINE> config.inventors = ["meinereiner", "keinerseiner"] <NEW_LINE> rt = ReqInventedBy(config) <NEW_LINE> with pytest.raises(RMTException) as rmte: <NEW_LINE> <INDENT> rt.rewrite("InventedBy-test", req) <NEW_LINE> assert 5 == rmte... | Requirement Tag Invented by - no tag given | 625941e857b8e32f52483928 |
def get_link_text(url, mime_type, data=None): <NEW_LINE> <INDENT> tld = get_tld(url) <NEW_LINE> result = "File on " + tld <NEW_LINE> if mime_type.startswith("image"): <NEW_LINE> <INDENT> result = "Image on " + tld <NEW_LINE> <DEDENT> elif mime_type == "application/pdf": <NEW_LINE> <INDENT> result = "PDF on " + tld <NEW... | Take URL, MIME type, and optional data to produce the link text. | 625941e8fb3f5b602dac3b22 |
def equals(self, other): <NEW_LINE> <INDENT> return self.shape.equals(other.shape) | Returns True if geometries are equal, else False
| 625941e82ae34c7f2600d5ba |
def reply(self, ticket_id: typing.Union[str, int], text: str = '', cc: str = '', bcc: str = '', content_type: str = 'text/plain', files: typing.Optional[typing.List[typing.Tuple[str, typing.IO, typing.Optional[str]]]] = None) -> bool: <NEW_LINE> <INDENT> return self.__correspond(ticket_id, text, 'correspond', cc, bcc, ... | Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.
Form of message according to documentation::
id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with the same indentation as first
Cc: <...>
... | 625941e838b623060ff0b277 |
def estimate_height(observed_width, observed_height, poly_fit, fit_width_var, fit_height_var): <NEW_LINE> <INDENT> sigma_vv = fit_width_var + poly_fit[0]**2 * fit_height_var <NEW_LINE> sigma_uv = -poly_fit[0] * fit_height_var <NEW_LINE> v = observed_width - poly_fit[1] - poly_fit[0] * observed_height <NEW_LINE> return ... | Estimates optimal height using error in variables approach | 625941e855399d3f05588b41 |
def retrieve_openevent(self, args): <NEW_LINE> <INDENT> triggeredSendDefinitionObjectID = self.retrieve_triggeredsend(args) <NEW_LINE> getOpenEvent = FuelSDK.ET_OpenEvent() <NEW_LINE> getOpenEvent.auth_stub = self.client <NEW_LINE> getOpenEvent.props = [ "SendID", "SubscriberKey", "EventDate", "Client.ID", "EventType",... | retrieve all open event with triggered send's customer key.
:param string customer_key: data extension's customer key
:return: data extension's name array. | 625941e8fff4ab517eb2f8c9 |
@task <NEW_LINE> def configure(): <NEW_LINE> <INDENT> with sudo(): <NEW_LINE> <INDENT> setup_config() <NEW_LINE> for user in blueprint.get('users'): <NEW_LINE> <INDENT> username, password = user['username'], user['password'] <NEW_LINE> if 'homedir' in user: <NEW_LINE> <INDENT> user_home = user['homedir'] <NEW_LINE> <DE... | Configure PureFTP | 625941e876d4e153a657efbd |
def is_compatible(self, typevar, its_type): <NEW_LINE> <INDENT> result = True <NEW_LINE> binding = self.binding_of(typevar) <NEW_LINE> if binding is None: <NEW_LINE> <INDENT> self.bind(typevar, its_type) <NEW_LINE> <DEDENT> elif issubclass(binding, its_type): <NEW_LINE> <INDENT> self.bind(typevar, its_type) <NEW_LINE> ... | Checks whether its_type conforms to typevar.
If the typevar is not yet bound, it will be bound to its_type.
The covariance/contravariance checking described in the respective section
of PEP484 applies to declared types, but here we have actual types;
therefore, (1) subtypes are always compatible, (2) we may have to
reb... | 625941e88a349b6b435e85fd |
def test_office_value(self): <NEW_LINE> <INDENT> response = self.client.post( '/api/v2/petitions', data=json.dumps(petition_office_value), content_type='application/json', headers=self.get_token()) <NEW_LINE> result = json.loads(response.data.decode()) <NEW_LINE> self.assertEqual(result['message'], 'input is in wrong f... | Test input format of the office name. | 625941e8187af65679ca55aa |
def command_ranking_up(self, message): <NEW_LINE> <INDENT> if self.rank == 7 : <NEW_LINE> <INDENT> self.sendJSON(dict(command="notice", style="info", text="You are already the highest ranked player in your faction.")) <NEW_LINE> return <NEW_LINE> <DEDENT> if self.rank == 6 : <NEW_LINE> <INDENT> query = QSqlQuery(self.p... | Handling ranking up | 625941e89c8ee82313fbbc01 |
def rotate(self, nums, k): <NEW_LINE> <INDENT> new = [None]*len(nums) <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> new[(i+k)%len(nums)] = nums[i] <NEW_LINE> <DEDENT> for i in range(len(nums)): <NEW_LINE> <INDENT> nums[i] = new[i] | :type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead. | 625941e81d351010ab855fa5 |
def test_success_stats(self): <NEW_LINE> <INDENT> area = "aaa" <NEW_LINE> @stats.progress_indicator(area) <NEW_LINE> def no_exception(job_id): <NEW_LINE> <INDENT> return 999 <NEW_LINE> <DEDENT> kvs = self.connect() <NEW_LINE> key = stats.key_name(11, area, no_exception.__name__, "i") <NEW_LINE> previous_value = kvs.get... | The success counter is incremented when the wrapped function
terminates without raising an exception. | 625941e8d4950a0f3b08c7d3 |
def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> worksheet.set_start_page(1) <NEW_LINE> worksheet.set_paper(9) <NEW_LINE> worksheet.write('A1', 'Foo') <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual() | Test the creation of a simple XlsxWriter file with printer settings. | 625941e8a934411ee3751b1f |
def ros_srv_loader(type_dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module = importlib.import_module(type_dict['module'] + '.srv') <NEW_LINE> return module.__dict__[type_dict['type']] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError('ROS2 service type: {} not included in service module: {... | Dynamically import ROS2 service modules.
:param type_dict: A dictionary which values say if the ROS service type is complex (not basic), which is its parent
ROS2 service module, its type, if it is an array and if so, its size.
:return: The ROS2 service class. If the provided type does not exist, rais... | 625941e863f4b57ef0001596 |
def opt_symbol_lookup(ticker, date, delta=None, strike=None, strike_mode=None, callput=None, expiry=None, tenor=None): <NEW_LINE> <INDENT> pass | Find the option symbol that is the closest match for the supplied criteria
:param ticker: underlying ticker
:param date: reference date
:param delta: option delta, e.g. -0.5 for 50% delta put
:param strike: desired option strike, depends on strike_mode e.g. 175 (spot), 100% (spot, forward)
:param strike_mode: absolute... | 625941e8a8ecb033257d3556 |
def format_body_by_rely(body, rely_data): <NEW_LINE> <INDENT> if isinstance(body, dict): <NEW_LINE> <INDENT> body = json.dumps(body) <NEW_LINE> <DEDENT> rely_filed_list = re.findall(r'\"(\$.*?)\"', body) <NEW_LINE> for rely_filed in rely_filed_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rely_value = str(jsonpath... | 根据依赖关系格式化请求参数
:param body:
:param rely_data:
:return: | 625941e8442bda511e8be89c |
def CutExcessPart_vertic(INFO_i, v, boundaryLimits, n) : <NEW_LINE> <INDENT> i, x, y, r = map(int, INFO_i) <NEW_LINE> x1, y1, x2, y2 = map(int, v) <NEW_LINE> start_x, start_y, end_x, end_y = map(int, boundaryLimits) <NEW_LINE> w = x2 - x1 <NEW_LINE> h = y2 - y1 <NEW_LINE> area = calculateArea(v) <NEW_LINE> diff = area ... | # INFO_i : 入力で与えられる情報 [i,x,y,r]
# v : 四角形の頂点4つ [x1,y1,x2,y2]
# boundaryLimits : 広告スペースを区切った際の始点と終点 [start_x,start_y,end_x,end_y]
# n : 企業数
縦縞で区切るときにy2をyに近づけて得点が得られるvを返す。
v : [x1,y1,x2,y2] | 625941e867a9b606de4a8341 |
@core_helper <NEW_LINE> def humanize_entity_type(entity_type, object_type, purpose): <NEW_LINE> <INDENT> if entity_type == object_type: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> log.debug( u'Humanize %s of type %s for %s', entity_type, object_type, purpose) <NEW_LINE> templates = { u'add link': _(u"Add {object_typ... | Convert machine-readable representation of package/group type into
human-readable form.
Returns capitalized `entity_type` with all underscores converted
into spaces.
Example::
>>> humanize_entity_type('group', 'custom_group', 'add link')
'Add Custom Group'
>>> humanize_entity_type('group', 'custom_group', 'bre... | 625941e83346ee7daa2b31fa |
def add_handlers(dispatcher: Dispatcher) -> None: <NEW_LINE> <INDENT> select_level_handlers = [ CallbackQueryHandler(_show_help, pattern=f'^{SHOW_HELP}$'), ] <NEW_LINE> select_action_handlers = [ CallbackQueryHandler(_send_form, pattern=f'^{SEND_FORM}$'), CallbackQueryHandler(_withdraw_form, pattern=f'^{WITHDRAW_FORM}$... | Add handlers for private conversation. | 625941e89b70327d1c4e1262 |
def _cal_taun_taup(self): <NEW_LINE> <INDENT> self.vals['tau_e'] = 1. / self._cal_dts['Nt'] / self.vals['sigma_e'] / self.vel_th_e <NEW_LINE> self.vals['tau_h'] = 1. / self._cal_dts['Nt'] / self.vals['sigma_h'] / self.vel_th_h | Determines the SRH lifetime values
from the capture cross sections | 625941e830dc7b7665901dec |
def getDstance(self, target: str, source: str): <NEW_LINE> <INDENT> pass | :param target:
:param source:
:return: | 625941e87c178a314d6ef8f1 |
def test_recall_bulk_k(demo_recs): <NEW_LINE> <INDENT> train, test, recs = demo_recs <NEW_LINE> assert test['user'].value_counts().max() > 5 <NEW_LINE> rla = topn.RecListAnalysis() <NEW_LINE> rla.add_metric(precision, name='pk', k=5) <NEW_LINE> rla.add_metric(precision) <NEW_LINE> rla.add_metric(lambda *a, **k: precisi... | bulk and normal match | 625941e86aa9bd52df037232 |
def update(self, ea_names): <NEW_LINE> <INDENT> self._names = ea_names <NEW_LINE> self._addrs = ea_names.keys() <NEW_LINE> self._addrs.sort() | Updates the ea/names map | 625941e830bbd722463cc253 |
def createConfig(self, system, protocol, property_map={}): <NEW_LINE> <INDENT> if not isinstance(system, _System): <NEW_LINE> <INDENT> raise TypeError("'system' must be of type 'BioSimSpace._SireWrappers.System'") <NEW_LINE> <DEDENT> if isinstance(protocol, _Metadynamics): <NEW_LINE> <INDENT> return self._createMetadyn... | Create a PLUMED configuration file.
Parameters
----------
system : :class:`System <BioSimSpace._SireWrappers.System>`
A BioSimSpace system object.
protocol : :class:`Protocol.Metadynamics <BioSimSpace.Protocol.Metadynamics>`, :class:`Protocol.Steering <BioSimSpace.Protocol.Steering>`, ... | 625941e87cff6e4e81117e10 |
def setUp(self): <NEW_LINE> <INDENT> self.tempdir = TESTFN + "_dir" <NEW_LINE> self.mktemp('.hidden', 'a.txt') <NEW_LINE> self.mktemp('.hidden', 'b.file') <NEW_LINE> self.mktemp('.hidden_file') <NEW_LINE> self.mktemp('a.txt') <NEW_LINE> self.mktemp('b.file') <NEW_LINE> self.mktemp('c.txt.bak') <NEW_LINE> self.default_f... | Setup. | 625941e80fa83653e4657443 |
def getMonth(self, p_date): <NEW_LINE> <INDENT> l_date = str(p_date) <NEW_LINE> if l_date != '': <NEW_LINE> <INDENT> try: return str(DateTime(l_date).month()) <NEW_LINE> except: return '' <NEW_LINE> <DEDENT> else: return '' | return month from a given date | 625941e856ac1b37e6264651 |
def getfulldata(company_dict, fields_txt_file): <NEW_LINE> <INDENT> fields_list = fields_tolist(fields_txt_file) <NEW_LINE> deep_df = pd.DataFrame(columns = fields_list) <NEW_LINE> nondeep_df = pd.DataFrame(columns = fields_list) <NEW_LINE> almostdeep_df = pd.DataFrame(columns = fields_list) <NEW_LINE> df_dict = {'deep... | takes the json object generated with getjson, and the fields_txt_file as parameters makes three API calls with companies id | 625941e8d486a94d0b98e5d1 |
def shp2raster(input_shp, input_img, output_raster, rasterize_field, rasterize_type='binary'): <NEW_LINE> <INDENT> if isinstance(rasterize_field, str) is False or rasterize_field is None: <NEW_LINE> <INDENT> raise ValueError("Rasterize field name must be string type") <NEW_LINE> <DEDENT> source_ds = ogr.Open(input_shp)... | :brief 实现矢量转栅格功能,可选结果类型为二值栅格图,分类栅格图。
:param input_shp: shape文件的绝对路径
:param output_raster: 结果图的绝对路径
:param rasterize_field: 栅格化指定的字段
:param rasterize_type: 栅格化类型,binary为二值图,category为根据指定字段生成的分类图。
:return: None | 625941e8adb09d7d5db6cc17 |
def getPreferredLanguages(self): <NEW_LINE> <INDENT> user = getSecurityManager().getUser() <NEW_LINE> if user.has_role('Authenticated'): <NEW_LINE> <INDENT> return ['en', 'en'] <NEW_LINE> <DEDENT> return None | Languages
| 625941e845492302aab5e753 |
def get_file_contents(filename): <NEW_LINE> <INDENT> with open(filename, mode='r') as f: <NEW_LINE> <INDENT> text = f.read() <NEW_LINE> <DEDENT> return text; | Read in the contents of a text file. | 625941e8851cf427c661a995 |
def extract_shell(vr, vtheta, vphi, r_pl, shell=params['r_hill'], delta=[params['delta']], box=params['box']): <NEW_LINE> <INDENT> if(len(delta) == 1): <NEW_LINE> <INDENT> delta_inner = delta[0] <NEW_LINE> delta_outer = delta[0] <NEW_LINE> <DEDENT> elif(len(delta) == 2): <NEW_LINE> <INDENT> delta_inner = delta[0] <NEW_... | This function takes the values of vr, vtheta, vphi and extracts the velocity vectors who reside
in the given shell r_hill +/- delta*box
returns: vr, vtheta, vphi (extracted) | 625941e88c3a87329515884b |
def remove_degenerate_faces(self, height=tol.merge): <NEW_LINE> <INDENT> nondegenerate = triangles.nondegenerate(self.triangles, areas=self.area_faces, height=height) <NEW_LINE> self.update_faces(nondegenerate) <NEW_LINE> return nondegenerate | Remove degenerate faces (faces without 3 unique vertex indices)
from the current mesh.
If a height is specified, it will remove any face with a 2D oriented
bounding box with one edge shorter than that height.
If not specified, it will remove any face with a zero normal.
Parameters
------------
height : float
If sp... | 625941e8462c4b4f79d1db5a |
def test_update_name(self): <NEW_LINE> <INDENT> self.r1.name = "Computer" <NEW_LINE> self.r2.name = "Computer or Laptop" <NEW_LINE> self.r1.name = "Computer" <NEW_LINE> self.assertEqual(self.r1.name, "Computer") <NEW_LINE> self.assertEqual(self.r2.name, "Computer or Laptop") | Check for update user name attributes | 625941e838b623060ff0b278 |
def save_image(self, cat, img, data): <NEW_LINE> <INDENT> filename = self.path(cat, img) <NEW_LINE> mkdir(filename) <NEW_LINE> if type(data) == np.ndarray: <NEW_LINE> <INDENT> data = Image.fromarray(data).convert('RGB') <NEW_LINE> <DEDENT> data.save(filename) | Saves a new image. | 625941e8925a0f43d254a306 |
def setChannel(self, channel): <NEW_LINE> <INDENT> if channel != self.__channel: <NEW_LINE> <INDENT> self.__channel = channel | Set the channel description. | 625941e8be7bc26dc91cda82 |
def test_when_less_than_pi(self): <NEW_LINE> <INDENT> P1 = axelrod.Pi() <NEW_LINE> P2 = axelrod.Player() <NEW_LINE> P1.history = ['C','C','C','C'] <NEW_LINE> P2.history = ['C','C','D','D'] <NEW_LINE> self.assertEqual(P1.strategy(P2), 'C') | tests that if the ratio of Cs to Ds is less than pi then strategy co-operates | 625941e84d74a7450ccd4650 |
def total(self) -> DOSData: <NEW_LINE> <INDENT> data = self.sum_all() <NEW_LINE> data.info.update({'label': 'Total'}) <NEW_LINE> return data | Sum all the DOSData in this Collection and label it as 'Total' | 625941e8f548e778e58cda0a |
def bit_fliping_userdata(padding): <NEW_LINE> <INDENT> padding_block = 'P' * padding <NEW_LINE> flipping_block = 'F' * 16 <NEW_LINE> semi_colon = flipbit(';', 0) <NEW_LINE> equals = flipbit('=', 0) <NEW_LINE> admin_block = '{s}admin{e}true'.format( s=semi_colon, e=equals ) <NEW_LINE> return padding_block + flipping_blo... | The userdata to use in the bit flipping attack
:returns: The string to use for userdata
:rtype: str | 625941e8627d3e7fe0d692dc |
def storage_array_stats_list_info(self): <NEW_LINE> <INDENT> return self.request( "storage-array-stats-list-info", { }, { 'array-stat-info': [ StorageArrayStatsInfo, True ], } ) | Used to get dynamic information about backend arrays. | 625941e894891a1f4081bf36 |
def _get_job_progress(job_list): <NEW_LINE> <INDENT> progress = dict() <NEW_LINE> progress['total_jobs'] = len(job_list) <NEW_LINE> progress['unlabeled_jobs'] = progress['labeling_jobs'] = progress['finished_jobs'] = 0 <NEW_LINE> for job in job_list: <NEW_LINE> <INDENT> if job.job_state == ConstantCodes.Unlabeled: <NEW... | Calculate progress given a job list. | 625941e8711fe17d825427ec |
def wrap_dict(dict_class: Type[Context]) -> Type[Context]: <NEW_LINE> <INDENT> Wrapped = type( "WrappedDict-" + str(uuid.uuid4()), (_ThreadLocalDictWrapper,), {} ) <NEW_LINE> Wrapped._tl = ThreadLocal() <NEW_LINE> Wrapped._dict_class = dict_class <NEW_LINE> return Wrapped | Wrap a dict-like class and return the resulting class.
The wrapped class and used to keep global in the current thread.
:param dict_class: Class used for keeping context. | 625941e8ff9c53063f47c67c |
def get_search_results( query_str, domain, topn=None ): <NEW_LINE> <INDENT> from whoosh.qparser import QueryParser <NEW_LINE> from whoosh import scoring <NEW_LINE> from whoosh.index import open_dir <NEW_LINE> ix = open_dir("./search/"+domain+"/indexdir") <NEW_LINE> with ix.searcher(weighting=scoring.Frequency) as searc... | gets indexed document ids and document contents
params:
query_str -- a single string of comma seperated words, e.g. "james bond,gadgets,MI6,007,moneypenny" for fantasy spy film genre
domain -- the data domain, e.g. "movies" for Stanford movie reviews
topn (optional) -- the numer of search hits to return, def... | 625941e873bcbd0ca4b2c500 |
def get_connection(self, server): <NEW_LINE> <INDENT> cnx = self._do_get_connection(server) <NEW_LINE> while cnx: <NEW_LINE> <INDENT> assert server.user != None and cnx.user == server.user <NEW_LINE> if cnx.is_valid_mysql_connection(): <NEW_LINE> <INDENT> return cnx <NEW_LINE> <DEDENT> cnx = self._do_get_connection(ser... | Get a connection.
The method gets a connection from a pool if there is any or
create a fresh one. | 625941e8b545ff76a89142a0 |
def signal(self): <NEW_LINE> <INDENT> out = ( hp.ud_grade(map_in=self.planck_templatemap, nside_out=self.target_nside) << u.K_CMB ) <NEW_LINE> if self.include_high_galactic_latitude_clouds: <NEW_LINE> <INDENT> out += self.simulate_high_galactic_latitude_CO() <NEW_LINE> <DEDENT> if self.has_polarization: <NEW_LINE> <IND... | Simulate CO signal | 625941e82eb69b55b151cd41 |
def delete(self, id: int) -> dict: <NEW_LINE> <INDENT> user = User.query.filter_by(id=id).first() <NEW_LINE> if not user: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> db.session.delete(user) <NEW_LINE> db.session.commit() <NEW_LINE> return {"status": "success"} | Removes a selected user.
.. :quickref: Users; Delete a single user.
:param id: id of a requested user
:returns: whether the operation has been successful | 625941e856b00c62f0f14ae7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.