code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def isPermanentWarPeace(): <NEW_LINE> <INDENT> return gc.getGame().isOption(GameOptionTypes.GAMEOPTION_NO_CHANGING_WAR_PEACE) | Returns True if the Permanent War/Peace option is enabled. | 625941d571ff763f4b549893 |
def _formatExample(example, substitutions): <NEW_LINE> <INDENT> yield u"**Example:** {}".format(example.doc) <NEW_LINE> yield u"" <NEW_LINE> yield u"Request" <NEW_LINE> yield u"" <NEW_LINE> yield u".. sourcecode:: http" <NEW_LINE> yield u"" <NEW_LINE> lines = (example.request % substitutions).splitlines() <NEW_LINE> li... | Generate the rst associated with an HTTP session example.
@param example: An L{Example} to format.
@param substitutions: A L{dict} to use to interpolate variables in the
example request and response.
@return: A generator which yields L{unicode} strings each of which should
be a line in the resulting rst docu... | 625941d5925a0f43d254a07d |
@keras_export('keras.activations.tanh') <NEW_LINE> @dispatch.add_dispatch_support <NEW_LINE> def tanh(x): <NEW_LINE> <INDENT> return nn.tanh(x) | Hyperbolic tangent activation function.
For example:
>>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32)
>>> b = tf.keras.activations.tanh(a)
>>> b.numpy()
array([-0.9950547, -0.7615942, 0., 0.7615942, 0.9950547], dtype=float32)
Arguments:
x: Input tensor.
Returns:
Tensor of same shape and ... | 625941d5aad79263cf390c49 |
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(1, 1), area_range=(0.05, 1.0), max_attempts=100, scope=None): <NEW_LINE> <INDENT> with tf.name_scope(scope, 'distorted_bounding_box_crop', [image, bbox]): <NEW_LINE> <INDENT> sample_distorted_bounding_box = tf.image.sample_distorte... | Generates cropped_image using a one of the bboxes randomly distorted.
See `tf.image.sample_distorted_bounding_box` for more documentation.
Args:
image: 3-D Tensor of image (it will be converted to floats in [0, 1]).
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate... | 625941d5d8ef3951e3243743 |
def _parse_A(browser, tag): <NEW_LINE> <INDENT> for item in tag.children: <NEW_LINE> <INDENT> if item.name == "a": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> id_ = re.match("#(Dia\d+)", item.get("href")).groups()[0] <NEW_LINE> a = browser.find("a", id=id_) <NEW_LINE> if a is not None: <NEW_LINE> <INDENT> td = a.next_... | Parses the "A" information (A is the "coupling constant")
The cell in column "Te" sometimes cites a reference; the anchor tag has an Id like "Dia19";
the value we are looking for is in (roughly in the form "A = some_number" | 625941d58c0ade5d55d3ebc1 |
def _get_inactive_permissions(self, old_permissions): <NEW_LINE> <INDENT> inactive_permissions = usergroup.ALL_PERMISSIONS - usergroup.ACTIVE_PERMISSIONS <NEW_LINE> return old_permissions & inactive_permissions | Retrieve permissions that have been set previously, but are inactive | 625941d50a366e3fb873ea20 |
def has_module_perms(self, perm, obj=None): <NEW_LINE> <INDENT> return True | Check if the user have permission
| 625941d530c21e258bdfa6a3 |
def test_adventures_show_route(self): <NEW_LINE> <INDENT> adventure = Adventure( creator_id=1, date=datetime.now() + timedelta(minutes=9), mode=ADVENTURES.RECREATIONAL, info='Some info today' ) <NEW_LINE> db.session.add(adventure) <NEW_LINE> db.session.commit() <NEW_LINE> user = User( username='john', password=generate... | Ensure that show adventure redirect us to the right place | 625941d54428ac0f6e5ba9f8 |
def get_summaryview(self, desktop_id): <NEW_LINE> <INDENT> return self.viewapi.Desktop_GetSummaryView(self.mor, desktop_id) | Fetch a summary for given desktop ID
:param desktop_id:
:return: | 625941d591f36d47f21ac6f9 |
def read_messages(self): <NEW_LINE> <INDENT> if self.rmessages is not None: <NEW_LINE> <INDENT> s = os.read(self.rmessages, 4096) <NEW_LINE> self.messages += bytes_to_str(s) <NEW_LINE> if len(s) == 0: <NEW_LINE> <INDENT> os.close(self.rmessages) <NEW_LINE> self.rmessages = None | In the master process, read from the pipe and store the data
read in the ``messages`` attribute.
.. NOTE::
This function may need to be called multiple times in
order to read all of the messages.
EXAMPLES::
sage: from sage.doctest.forker import DocTestWorker, DocTestTask
sage: from sage.doctest.sour... | 625941d57cff6e4e81117b8b |
def itkPolyLineParametricPath2_cast(*args): <NEW_LINE> <INDENT> return _itkPolyLineParametricPathPython.itkPolyLineParametricPath2_cast(*args) | itkPolyLineParametricPath2_cast(itkLightObject obj) -> itkPolyLineParametricPath2 | 625941d5a219f33f34628b6d |
def time_integrate(timebin_tables, n_bins, channels): <NEW_LINE> <INDENT> channels = ['total'] + channels <NEW_LINE> mass_arrays = {} <NEW_LINE> time_slice = timebin_tables.isel(time=slice(0, n_bins)) <NEW_LINE> totals = time_slice.sum(dim='time') <NEW_LINE> table = xr.Dataset() <NEW_LINE> for channel in channels: <NEW... | Integrate a set of models over a given no. of time bins
Returns : xr.Dataset
dim: [mass]
parameters
----------
timebin_tables : xr.Dataset
3D table of timebinned models, dim: [mass, time]
n_bins : int
no. of time bins to integrate over. Currently each bin is 5 ms
channels : [str]
list of channel names | 625941d596565a6dacc8f8d0 |
def __init__(self): <NEW_LINE> <INDENT> self.query_type = MAGQueryType.UNKNOWN <NEW_LINE> self.url = MAGConf.BASE_URL <NEW_LINE> self.body = {} <NEW_LINE> self.headers = {} | TODO: to be defined1. | 625941d531939e2706e4d06e |
def __init__(self, iRegA, iRegB, oRegC, n=4): <NEW_LINE> <INDENT> assert isinstance(iRegA, Register) and isinstance(iRegB, Register) <NEW_LINE> assert isinstance(oRegC, Register) <NEW_LINE> assert n == len(iRegA) == len(iRegB) == len(oRegC) <NEW_LINE> Circuit.__init__(self) <NEW_LINE> tRegT = Register(name="T", n=n) <N... | Arguments:
iRegA -- Input A (Register, initialized)
iRegB -- Input B (Register, initialized)
oRegC -- Output C (Register, not initialized)
Note:
Overflow carry is ignored
Implemented using Half- and FullAdder | 625941d50a366e3fb873ea21 |
def until(**kwargs): <NEW_LINE> <INDENT> hc = HealthCheck(**kwargs) <NEW_LINE> hc.wait() | Wait around until the status matches. | 625941d5dc8b845886cb573b |
def reverseString(self, s: List[str]) -> None: <NEW_LINE> <INDENT> i, j = 0, len(s)-1 <NEW_LINE> while i<j: <NEW_LINE> <INDENT> s[i], s[j] = s[j], s[i] <NEW_LINE> i += 1 <NEW_LINE> j -= 1 <NEW_LINE> <DEDENT> return s | Do not return anything, modify s in-place instead. | 625941d5cdde0d52a9e53239 |
def compute_stations(cursor): <NEW_LINE> <INDENT> pass1 = [] <NEW_LINE> for line in open("temp-inventory.txt"): <NEW_LINE> <INDENT> pass1.append(line[:11]) <NEW_LINE> <DEDENT> for line in open("prcp-inventory.txt"): <NEW_LINE> <INDENT> if line[:11] not in pass1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> sid = li... | Logic to resolve, which stations we care about and add necessary
station metadata about them! | 625941d5d53ae8145f87a473 |
def page50(self): <NEW_LINE> <INDENT> result = request5001.GET('/images/G/01/nav/amazon/amzn-logo-118w.gif') <NEW_LINE> return result | GET amzn-logo-118w.gif (request 5001). | 625941d544b2445a3393229a |
def delete(event, context): <NEW_LINE> <INDENT> return | Place your code to handle Delete events here
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events. | 625941d5bde94217f3682ff5 |
def test_04_prorata_init_cur_year(self): <NEW_LINE> <INDENT> asset = self.asset_model.create({ 'name': 'test asset', 'profile_id': self.ref('account_asset_management.' 'account_asset_profile_car_5Y'), 'purchase_value': 3333, 'salvage_value': 0, 'date_start': time.strftime('%Y-07-07'), 'method_time': 'year', 'method_num... | Prorata temporis depreciation with init value in curent year. | 625941d59c8ee82313fbb97b |
def _set_update(self, old=None, **kwargs): <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> super()._set_update(old, **kwargs) <NEW_LINE> update = False <NEW_LINE> for name in kwargs.keys(): <NEW_LINE> <INDENT> if name in self.pub_arg_dict['Holder_attr']: <NEW_LINE> <INDENT> update = True <NEW_LINE> <DEDENT> <DEDENT>... | Actualises its image on the screen after setting new values to attributes in most efficient way.
Private. | 625941d5097d151d1a22305e |
def test_teams_id_dynamic_datas_nk_designs_fk_delete(self): <NEW_LINE> <INDENT> pass | Test case for teams_id_dynamic_datas_nk_designs_fk_delete
Delete a related item by id for designs. | 625941d5009cb60464c635b6 |
def complex_format(z): <NEW_LINE> <INDENT> if type(z) == int: <NEW_LINE> <INDENT> return complex(z) <NEW_LINE> <DEDENT> elif type(z) == float: <NEW_LINE> <INDENT> return complex(integerise(z)) <NEW_LINE> <DEDENT> elif type(z) == complex: <NEW_LINE> <INDENT> a, b = map(integerise, [z.real, z.imag]) <NEW_LINE> return com... | Formats a complex number z = a + bi to ensure that real and/or
imaginary parts a and b are displayed as integers if they are actually
integers. This is because the display of Python native complex numbers
is a bit inconsistent: complex numbers with a 0 real part can sometimes
be displayed with the real part as -0. Also... | 625941d5ab23a570cc250389 |
def test_search_page_results(self): <NEW_LINE> <INDENT> app = self._get_test_app() <NEW_LINE> factories.Dataset(name="dataset-one", title='Dataset One') <NEW_LINE> factories.Dataset(name="dataset-two", title='Dataset Two') <NEW_LINE> factories.Dataset(name="dataset-three", title='Dataset Three') <NEW_LINE> search_url =... | Searching for datasets returns expected results. | 625941d5c432627299f04e4d |
def jackknife_lensums(data, jackreg_col=None, weights=None): <NEW_LINE> <INDENT> import jackknife <NEW_LINE> jdsum, jwsum = get_jackknife_sums(data, weights=weights, jackreg_col=jackreg_col) <NEW_LINE> dsig,dsig_cov=jackknife.wjackknife(vsum=jdsum, wsum=jwsum) <NEW_LINE> return dsig, dsig_cov | jackknife the data. If regions are sent, use them for jackknifing,
otherwise jackknife one object at a time
parameters
----------
data: array
An array with fields 'dsum' and 'wsum'. If shear style
is lensfit, dsensum is needed rather than wsum.
jackreg_col: string, optional
column name holding the jackknif... | 625941d5dd821e528d63b3ae |
def evaluate(self, targets): <NEW_LINE> <INDENT> gain = self._get_gain(targets) <NEW_LINE> discount = self._get_discount(min(self.k, len(gain))) <NEW_LINE> return np.sum(np.divide(gain, discount)) | :param targets: ranked list with relevance
:return: float | 625941d5ac7a0e7691ed42cf |
def get_servers(): <NEW_LINE> <INDENT> return [ ("localhost", 9200) ] | Get the ElasticSearch servers on this host.
Returns:
An iterable of tuples of (host, port) | 625941d5004d5f362079a538 |
def in_gamut(self, space=None, *, tolerance=util.DEF_FIT_TOLERANCE): <NEW_LINE> <INDENT> if space is not None: <NEW_LINE> <INDENT> c = self.convert(space) <NEW_LINE> return c.in_gamut(tolerance=tolerance) <NEW_LINE> <DEDENT> if self.GAMUT_CHECK is not None: <NEW_LINE> <INDENT> c2 = self.convert(self.GAMUT_CHECK) <NEW_L... | Check if current color is in gamut. | 625941d5ec188e330fd5a9a2 |
def compute_distances(self, x1, x2): <NEW_LINE> <INDENT> callbacks = StepwiseCallbacks(self.callback, [5, 5, 60, 30]) <NEW_LINE> if self.continuous.any(): <NEW_LINE> <INDENT> data1, data2 = self.continuous_columns( x1, x2, self.medians, 2 * self.mads) <NEW_LINE> distances = _distance.manhattan_rows_cont( data1, data2, ... | The method
- extracts normalized continuous attributes and computes distances
ignoring the possibility of nans
- recomputes the distances between pairs of rows that yielded nans
- adds the contributions of discrete columns using the same function as
the Euclidean distance | 625941d5f8510a7c17cf9902 |
def postorderTraversal(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> stack = [root] <NEW_LINE> result = [] <NEW_LINE> while stack: <NEW_LINE> <INDENT> current = stack[-1] <NEW_LINE> if not current.left and not current.right: <NEW_LINE> <INDENT> result.append(stack.pop()... | :type root: TreeNode
:rtype: List[int] | 625941d523e79379d52ee768 |
def render(self): <NEW_LINE> <INDENT> faker = self.field_faker_class(self.model, self.field) <NEW_LINE> return faker.render() | Render the appropriate template to get the field definition | 625941d5379a373c97cfad4c |
def getTypes(self): <NEW_LINE> <INDENT> environmentId = self.getEnviroment() <NEW_LINE> authorizationToken = self._getToken() <NEW_LINE> url = "https://" + environmentId + ".env.timeseries.azure.com/timeseries/types" <NEW_LINE> querystring = self._create_querystring() <NEW_LINE> payload = "" <NEW_LINE> headers = { 'x-m... | Gets all types from the specified TSI environment.
Returns:
dict: The types in form of the response from the TSI api call.
Contains id, name, description and variables per type.
Example:
>>> from TSIClient import TSIClient as tsi
>>> client = tsi.TSIClient()
>>> types = client.getTypes() | 625941d5baa26c4b54cb1324 |
def get_probe_array_as_json(probe_list): <NEW_LINE> <INDENT> result = '[' <NEW_LINE> for probe in probe_list: <NEW_LINE> <INDENT> result += '\n' + get_probe_as_json(probe) + ',' <NEW_LINE> <DEDENT> return result[:-1] + '\n]' | returns a list of temp probes as a json array | 625941d5d268445f265b5074 |
def setup(self,problem): <NEW_LINE> <INDENT> Kernel = self.Kernel <NEW_LINE> problem = Kernel.setup_learning(problem) <NEW_LINE> problem.objectives = [ [ self.likelihood_obj , 'logP' , -1.0 ] , ] <NEW_LINE> return problem | Kernel.setup(problem):
setup the marginal likelihood maximization problem
Inputs:
problem - an empty VyPy Problem() class
Outputs:
None | 625941d58a43f66fc4b54269 |
def grid_from_dataset(ds, earth_radius=6370000): <NEW_LINE> <INDENT> if hasattr(ds, "IOAPI_VERSION") or hasattr(ds, "P_ALP"): <NEW_LINE> <INDENT> return _ioapi_grid_from_dataset(ds, earth_radius=earth_radius) | Short summary.
Parameters
----------
ds : type
Description of parameter `ds`.
earth_radius : type
Description of parameter `earth_radius`.
Returns
-------
type
Description of returned object. | 625941d597e22403b379d1a0 |
def shift_centers_to_min_distance(center_data, min_distance=1.2): <NEW_LINE> <INDENT> shifts_made = True <NEW_LINE> while shifts_made: <NEW_LINE> <INDENT> shifts_made = False <NEW_LINE> d = distance.cdist(center_data.loc[:, ['x', 'y']].values, center_data.loc[:, ['x', 'y']].values) <NEW_LINE> c1_ix, c2_ix = np.where(d ... | Given x,y positions, changes the positions until `min_distance` apart.
Two elements that are closer than `min_distance` apart, will be pushed in opposite directions
a distance of 2*(`min_distance` - their current distance). This will be iteratively
performed on all elements until all are at minimum `min_distance` apar... | 625941d54f6381625f114c41 |
def loads(s: str, cls: Type[Config]) -> Config: <NEW_LINE> <INDENT> return structure(toml.loads(s), cls) | Create an instance of *cls* from the TOML in *s*. | 625941d550812a4eaa59c526 |
def max_window(self): <NEW_LINE> <INDENT> Seldom.driver.maximize_window() | Set browser window maximized.
Usage:
self.max_window() | 625941d51b99ca400220acb7 |
def _valid_ethaddr(self, ethaddr): <NEW_LINE> <INDENT> if not ethaddr or re.match('00:00:00:00:00:00', ethaddr): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Check if address is 00:00:00:00:00:00 | 625941d5bf627c535bc133d5 |
def test_new_node_catchup_plugin_ledger(txn_pool_node_set_post_creation, looper, some_requests, sdk_new_node_caught_up): <NEW_LINE> <INDENT> assert len(sdk_new_node_caught_up.getLedger(AUCTION_LEDGER_ID)) > 0 <NEW_LINE> for node in txn_pool_node_set_post_creation[:-1]: <NEW_LINE> <INDENT> assert len(sdk_new_node_caught... | A new node catches up the demo plugin's ledger too | 625941d529b78933be1e58af |
def displayGraph(pathLog,pathSaveGraph): <NEW_LINE> <INDENT> data = pd.read_csv(pathLog) <NEW_LINE> plot(data['epoch'], data['acc'], data['val_acc'], 'TRAIN_VAL_Accuracy', 'Epoch', 'Accuracy', 'upper left',pathSaveGraph) <NEW_LINE> plot(data['epoch'], data['loss'], data['val_loss'], 'TRAIN_VAL_Loss', 'Epoch', 'Loss', '... | # Fonction permettant de creer nos graph de suivi de metriques
:param pathLog: chemin du CSV contenant nos metrics
:param pathSaveGraph: chemin de destination pour sauvegarder nos 4 graphiques en jpg | 625941d59c8ee82313fbb97c |
def catalog_downloads(url, fileFilter, fileNamer, fileDocumenter, klass): <NEW_LINE> <INDENT> import formatter <NEW_LINE> import htmllib <NEW_LINE> import urllib <NEW_LINE> ifile = urllib.urlopen(url) <NEW_LINE> try: <NEW_LINE> <INDENT> p = htmllib.HTMLParser(formatter.NullFormatter()) <NEW_LINE> p.feed(ifile.read()) <... | returns dict of resources for downloading target data:
url: URL to a directory that gives links to the desired data
fileFilter: function that returns True for a desired file name
fileNamer: function that converts a file name into desired key value
fileDocumenter: function that returns a docstring based on file name
kla... | 625941d576d4e153a657ed38 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.articles = [] <NEW_LINE> self.translations = [] <NEW_LINE> self.hidden_articles = [] <NEW_LINE> self.hidden_translations = [] <NEW_LINE> self.drafts = [] <NEW_LINE> self.drafts_translations = [] <NEW_LINE> self.dates = {} <NEW_LINE> self.tags = defaultdict(l... | initialize properties | 625941d54f88993c3716c26c |
def test_search_recipes_cuisines_descending_user_votes_results(self): <NEW_LINE> <INDENT> self.driver.get("http://localhost:5000/search") <NEW_LINE> self.driver.implicitly_wait(0) <NEW_LINE> self.driver.find_element_by_id("search-text").send_keys('thai') <NEW_LINE> select = Select(self.driver.find_element_by_id("search... | Test searching for cuisines recipes with
descending user votes results | 625941d53eb6a72ae02ec6e7 |
def fs_busy(self, echo=True): <NEW_LINE> <INDENT> if self._num_fs_op > 0: <NEW_LINE> <INDENT> if echo: <NEW_LINE> <INDENT> Vim.ErrorMsg( 'Previous operation that might change the view is not done' ' yet. Try again later') <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Return True if num_fs_op>0. See Netranger.inc_num_fs_op. | 625941d54f88993c3716c26d |
def gen_augment_data(df): <NEW_LINE> <INDENT> aug_data = [] <NEW_LINE> for idx, row in df.iterrows(): <NEW_LINE> <INDENT> aug_row = gen_augment_row(row) <NEW_LINE> aug_data.append(aug_row) <NEW_LINE> <DEDENT> return aug_data | iterate through a df and generate equal amt of flipped data
generate flipped images, create pointer to the images, negate the steering angle
output list of dict (they are the data of flipped images)
assume the log file has headers
key arguments:
df -- DataFrame: dataframe to be iterated | 625941d5507cdc57c6306ee4 |
def resolve_tree_i18n_alias(self, alias): <NEW_LINE> <INDENT> if alias in _I18N_TREES: <NEW_LINE> <INDENT> current_language_code = self.lang_get().replace('_', '-').split('-')[0] <NEW_LINE> i18n_tree_alias = '%s_%s' % (alias, current_language_code) <NEW_LINE> trees_count = self.cache.get_entry('tree_aliases', i18n_tree... | Resolves internationalized tree alias.
Verifies whether a separate sitetree is available for currently active language.
If so, returns i18n alias. If not, returns the initial alias. | 625941d5d164cc6175782f54 |
def test_add_image_zero_size(self): <NEW_LINE> <INDENT> fixture_headers = {'x-image-meta-disk-format': 'ami', 'x-image-meta-container-format': 'ami', 'x-image-meta-size': '0', 'x-image-meta-name': 'empty image'} <NEW_LINE> req = webob.Request.blank("/images") <NEW_LINE> req.method = 'POST' <NEW_LINE> for k, v in fixtur... | Tests creating an active image with explicitly zero size | 625941d5a8ecb033257d32d2 |
def _hnsw_filtering(self, X, k): <NEW_LINE> <INDENT> n_train = X.shape[0] <NEW_LINE> try: <NEW_LINE> <INDENT> method = self.kwargs['nms__method'] <NEW_LINE> post = self.kwargs['nms__post'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> method = 'hnsw' <NEW_LINE> post = 2 <NEW_LINE> <DEDENT> if self.metric == ... | Find k approx. nearest neighbors for each vector in X with HNSW.
Returns indices of neighbors per object, their distances,
and the HNSW index. | 625941d5377c676e912723ae |
def head( self, alias, uri, headers=None, allow_redirects=None, timeout=None): <NEW_LINE> <INDENT> logger.warn("Deprecation Warning: Use Head Request in the future") <NEW_LINE> session = self._cache.switch(alias) <NEW_LINE> redir = False if allow_redirects is None else allow_redirects <NEW_LINE> response = self._head_r... | **Deprecated- See Head Request now**
Send a HEAD request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the HEAD request to
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``heade... | 625941d596565a6dacc8f8d1 |
def saveGame(self, command, client): <NEW_LINE> <INDENT> game = self.gameList[ command.getGameId() ] <NEW_LINE> if self.clients[client].getUsername() != game.creator: <NEW_LINE> <INDENT> client.gameError(game.getGameId(), ServerMessage([NOT_CREATOR])) <NEW_LINE> return <NEW_LINE> <DEDENT> game.pause() <NEW_LINE> for pl... | Save the game
@param command:
@param client: | 625941d50383005118ecf7e8 |
def container_id(self, container_instance): <NEW_LINE> <INDENT> from containers.models import Container <NEW_LINE> if isinstance(container_instance, Container): <NEW_LINE> <INDENT> field = container_instance.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> field = container_instance.slug <NEW_LINE> <DEDENT> try: <NEW... | Returns containers ID given the name. | 625941d5090684286d50eeed |
def eval_hop_function(ts, rxncenter): <NEW_LINE> <INDENT> hts = [] <NEW_LINE> hts.append(0) <NEW_LINE> numts = len(ts) <NEW_LINE> pdonor = [0] <NEW_LINE> for i in range(1,numts): <NEW_LINE> <INDENT> pcenter = rxncenter[i-1] <NEW_LINE> ccenter = rxncenter[i] <NEW_LINE> if pcenter == ccenter: <NEW_LINE> <INDENT> val = 0 ... | Evaluate the hop function from the MS-EVB3 paper. This is defined:
h(ts) = h(ts-1) + dh(ts)
h(0) = 0
( 0 , if no proton hop
dh(ts) = { 1 , if proton hops to new acceptor
( -1 , if proton hops to the last donor
Here, ts is the timestep, and ts-1 is the previous timestep. | 625941d54c3428357757c52e |
def leafSimilar_LeetCodeOfficial(self, root1, root2): <NEW_LINE> <INDENT> def dfs(node): <NEW_LINE> <INDENT> if node: <NEW_LINE> <INDENT> if not node.left and not node.right: <NEW_LINE> <INDENT> yield node.val <NEW_LINE> <DEDENT> for i in dfs(node.left): <NEW_LINE> <INDENT> yield i <NEW_LINE> <DEDENT> for i in dfs(node... | :type root1: TreeNode
:type root2: TreeNode
:rtype: bool | 625941d57b180e01f3dc4a01 |
def is_port_in_use(port: int) -> bool: <NEW_LINE> <INDENT> with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: <NEW_LINE> <INDENT> return sock.connect_ex(('localhost', port)) == 0 | Determines whether a given port is in use on this machine.
Credit: https://codereview.stackexchange.com/questions/116450/find-available-ports-on-localhost | 625941d5f8510a7c17cf9903 |
def getValue(self,lang: str) -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return_value = self._values.get(lang) <NEW_LINE> if not return_value: <NEW_LINE> <INDENT> return self._values['every'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return return_value <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LI... | Get specific value.
If lang unavailable, try to return the 'every' value | 625941d57d43ff24873a2ea7 |
def new_OFDPA_OAM_PM_ROLE_tp(): <NEW_LINE> <INDENT> return _OFDPA_python.new_OFDPA_OAM_PM_ROLE_tp() | new_OFDPA_OAM_PM_ROLE_tp() -> OFDPA_OAM_PM_ROLE_t * | 625941d5d99f1b3c44c67793 |
def TmProfile(protein, reference="neutral", grid=[0., 14., 0.1], Tm=None, Tms=None, ref=None, options=None): <NEW_LINE> <INDENT> Nres = 0 <NEW_LINE> for chain in protein.chains: <NEW_LINE> <INDENT> Nres += len(chain.residues) <NEW_LINE> <DEDENT> dS = 0.0173*Nres <NEW_LINE> pH_ref = 5.0; dG_ref = protein.calculateFoldin... | Calculates the folding profile | 625941d54527f215b584c65c |
def utcstr(ts=None): <NEW_LINE> <INDENT> assert(ts is None or isinstance(ts, datetime)) <NEW_LINE> if ts is None: <NEW_LINE> <INDENT> ts = datetime.utcnow() <NEW_LINE> <DEDENT> return u"{0}Z".format(ts.strftime(u"%Y-%m-%dT%H:%M:%S.%f")[:-3]) | Format UTC timestamp in ISO 8601 format.
Note: to parse an ISO 8601 formatted string, use the **iso8601**
module instead (e.g. ``iso8601.parse_date("2014-05-23T13:03:44.123Z")``).
:param ts: The timestamp to format.
:type ts: instance of :py:class:`datetime.datetime` or None
:returns: Timestamp formatted in ISO 8601... | 625941d563f4b57ef000131c |
@pytest.fixture(autouse=True) <NEW_LINE> def silence_warning(): <NEW_LINE> <INDENT> with mock.patch('ansible.module_utils.basic.AnsibleModule.warn') as this_mock: <NEW_LINE> <INDENT> yield this_mock | Warnings use global variable, same as deprecations. | 625941d55166f23b2e1a535f |
def _check_with_unit_name(self, field, value): <NEW_LINE> <INDENT> self.logger.debug('Validating unit_name: {}'.format(value)) <NEW_LINE> try: <NEW_LINE> <INDENT> PhysicalField(1, value) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self._error(field, 'Must be str of physical units') | Checks that the string can be used as units | 625941d5f548e778e58cd785 |
def countNumbersWithUniqueDigits(self, n): <NEW_LINE> <INDENT> dp = [0 for i in xrange(n+1)] <NEW_LINE> for i in xrange(n+1): <NEW_LINE> <INDENT> if i==0: <NEW_LINE> <INDENT> dp[i] = 1 <NEW_LINE> <DEDENT> elif i==1: <NEW_LINE> <INDENT> dp[i] = 9 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dp[i]= dp[i-1]*(11-i) <NEW_L... | :type n: int
:rtype: int | 625941d5d164cc6175782f55 |
def find_reference(name, element_types, version): <NEW_LINE> <INDENT> lib = load_library(version) <NEW_LINE> ref = lib.find(name, element_types) <NEW_LINE> return ref | Look for an element of the given name and version into the given types and return its reference structure
:type name: ``str``
:param name: the element name to look for (e.g. 'MSH')
:type types: ``list`` or ``tuple``
:param types: the element classes where to look for the element (e.g. (Group, Segment))
:type version: ... | 625941d53346ee7daa2b2f73 |
def _get_related_object_pks(self, m2m_fields_query, model_pk, field_name): <NEW_LINE> <INDENT> data = m2m_fields_query[field_name] <NEW_LINE> return self._get_single_field_related_object_pks(data, model_pk, field_name) | Return related object pks from query result via ManyToManyFields
Any object pk with value 0 or None values will be excluded in the final
list.
:param dict m2m_fields_query: the result returned from _query_m2m_fields
:param model_pk: whose object's related object pks will be retrieved
:type model_pk: int or long
:para... | 625941d592d797404e304391 |
def JonesMatrix_MultiFreq(self, frequencies, zenith, azimuth, out=None): <NEW_LINE> <INDENT> if out is None: <NEW_LINE> <INDENT> out_JM = np.zeros( (len(frequencies), 2,2), dtype=complex ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_JM = out <NEW_LINE> <DEDENT> good_frequencies = np.logical_and( frequencies>10.0E... | same as JonesMatrix, except that frequencies is expected to be an array. Returns an array of jones matrices | 625941d526238365f5f0f077 |
def test_interleave3_with_loop_comparison(self): <NEW_LINE> <INDENT> integers = (4, 42, 7) <NEW_LINE> interleaved = interleave.interleave3(*integers) <NEW_LINE> interleaved_with_loop = alternative_interleave.interleave3_with_loop( *integers ) <NEW_LINE> self.assertEqual(interleaved, interleaved_with_loop) | test that loop version of interleave3 produces the same results as
the original | 625941d55fc7496912cc3b85 |
def __init__(self, item_id, num): <NEW_LINE> <INDENT> super(AddToBasketThread, self).__init__() <NEW_LINE> self.item_id = item_id <NEW_LINE> self.num = num <NEW_LINE> self.error = None | 商品をバスケットに追加するためのスレッド
@param item_id 商品ID
@param num 個数 | 625941d5be383301e01b568a |
def _remove_handler(self, name, handler): <NEW_LINE> <INDENT> for frame in list(self._event_stack): <NEW_LINE> <INDENT> if name in frame and frame[name] == handler: <NEW_LINE> <INDENT> del frame[name] <NEW_LINE> if not frame: <NEW_LINE> <INDENT> self._event_stack.remove(frame) | Used internally to remove all handler instances for the given event name.
This is normally called from a dead ``WeakMethod`` to remove itself from the
event stack. | 625941d560cbc95b062c674a |
def to_xml(self, parent=None, tostring=True): <NEW_LINE> <INDENT> if parent is None: <NEW_LINE> <INDENT> tree = etree.Element('{%s}subject' % ns.SUMMARY, nsmap=ns.nsmap) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tree = etree.SubElement(parent, '{%s}subject' % n... | Serialize to XML representation. | 625941d57c178a314d6ef668 |
def save_models(self) -> None: <NEW_LINE> <INDENT> for model, file_name in [ (self.generator, self.GEN_PATH), (self.critic, self.CRIT_PATH), ]: <NEW_LINE> <INDENT> model.save_weights(self.save_dir / file_name) | Save the models to disk. | 625941d5fff4ab517eb2f643 |
def create_action(path_prefix, action_name, app_cfg): <NEW_LINE> <INDENT> _ = lambda k : os.path.normpath(os.path.join(path_prefix, k)) <NEW_LINE> generate_code('action.js', _(action_name + '.js'), app_cfg) <NEW_LINE> generate_code('action.less', _(action_name + '.less'), app_cfg) <NEW_LINE> generate_code('action.html'... | 生成action相关的代码 | 625941d515fb5d323cde0d18 |
def reduced_grid_name(grid_basename, precision, method=None): <NEW_LINE> <INDENT> method_name = 'fgr' <NEW_LINE> if method == 'QCGR': <NEW_LINE> <INDENT> method_name = 'qcgr' <NEW_LINE> <DEDENT> return grid_basename + '_red_%s_%s' % (int(precision), method_name) | TODO : doc | 625941d5d268445f265b5075 |
def create_generation(self, generation_number, replicate_ids): <NEW_LINE> <INDENT> networks = {} <NEW_LINE> if (not replicate_ids): <NEW_LINE> <INDENT> for network_number in range(self.num_networks_per_gen): <NEW_LINE> <INDENT> network_info = {"network": network_number, "generation": generation_number, "species": self.... | This method takes in the generation number and the ID's for the
networks that will be replicated. From here it will either create
networks or mutate the networks based on the replicate ID's
Input: Integer, List [<Integers>] | 625941d5283ffb24f3c55b06 |
def worker(): <NEW_LINE> <INDENT> global counter <NEW_LINE> with counter_lock: <NEW_LINE> <INDENT> oldcnt = counter <NEW_LINE> fuzz() <NEW_LINE> counter = oldcnt + 1 <NEW_LINE> fuzz() <NEW_LINE> with printer_lock: <NEW_LINE> <INDENT> print('The count is %d' % counter, end='') <NEW_LINE> fuzz() <NEW_LINE> print() <NEW_L... | My job is to increment the counter and print the current count | 625941d57047854f462a160f |
def test_circular_nodegroup_reference(self): <NEW_LINE> <INDENT> referenced_nodegroups = {"group1": "N@group2", "group2": "N@group1"} <NEW_LINE> ret = salt.utils.minions.nodegroup_comp("group1", referenced_nodegroups) <NEW_LINE> self.assertEqual(ret, []) | Test to see what happens if A refers to B
and B in turn refers back to A | 625941d54e4d5625662d45dd |
def set_rate_limit(self, frequency): <NEW_LINE> <INDENT> self.send_raw = Throttler(self.send_raw, frequency) | Set a `frequency` limit (messages per second) for this connection.
Any attempts to send faster than this rate will block. | 625941d57c178a314d6ef669 |
def translate_dna(dna_seq, pos=0): <NEW_LINE> <INDENT> assert check_DNA(dna_seq),"Invalid DNA sequence" <NEW_LINE> dna_input=dna_seq.upper() <NEW_LINE> aa_output="" <NEW_LINE> for i in range (pos,len(dna_input)-2,3): <NEW_LINE> <INDENT> codon=dna_input[i:i+3] <NEW_LINE> aa_output += translation_codon(codon) <NEW_LINE> ... | Convert a DNA sequence into an amino acid sequence. | 625941d5e8904600ed9f2136 |
def counter_types(cards=None): <NEW_LINE> <INDENT> cwords = preceding_words('counter', cards=cards) <NEW_LINE> cwords = {w for w in cwords if w and w[-1] not in '—-,.:\'"'} <NEW_LINE> common = {'a', 'all', 'and', 'be', 'control', 'each', 'had', 'have', 'is', 'may', 'more', 'of', 'or', 'spell', 'that', 'those', 'was', '... | Returns a list of counter types namd in the given cards. | 625941d55f7d997b87174ca0 |
def sortArrayByParityII(self, A): <NEW_LINE> <INDENT> res = [] <NEW_LINE> odd_list = [] <NEW_LINE> even_list = [] <NEW_LINE> for a in A: <NEW_LINE> <INDENT> if a % 2: <NEW_LINE> <INDENT> odd_list.append(a) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> even_list.append(a) <NEW_LINE> <DEDENT> <DEDENT> for i in range(len(... | :type A: List[int]
:rtype: List[int] | 625941d5bf627c535bc133d6 |
def test_with_deleting_normal_group(self): <NEW_LINE> <INDENT> self.vv_return['status'] = 'ACTIVE' <NEW_LINE> self._check_with_deleting(ScalingGroupStatus.ACTIVE) | Viewing manifest with `get_deleting=True` returns group manifest
including status when group is not deleting | 625941d5d18da76e235326de |
def make_redirect_uri(self, application_url): <NEW_LINE> <INDENT> log.debug("make_redirect_uri: application_url=%s base_url_path=%s " "redirect_uri=%s", application_url, self.base_url_path, self.redirect_uri) <NEW_LINE> return self._construct_url([application_url, self.base_url_path, self.redirect_uri]) | Constructs the redirect URI from components.
@type application_url: str
@param application_url: application base URL
@rtype: str
@return: full redirect URI | 625941d51f5feb6acb0c4d55 |
def delete_router_precommit(self, context, router_id): <NEW_LINE> <INDENT> pass | Pre-DB operation for delete_router API
This should be called before the DB operation to the
router has been performed. | 625941d58e7ae83300e4b1d4 |
def isotopic_abundance(argument, mass_numb=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> isotope = isotope_symbol(argument, mass_numb) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise ValueError("Invalid isotope in isotopic_abundance.") <NEW_LINE> <DEDENT> if isotope == 'n': <NEW_LINE> <INDENT> rai... | Returns the isotopic abundances if known, and otherwise zero.
Parameters
----------
argument: string or integer
A string representing an element or isotope, or an integer
representing the atomic number of an element.
mass_numb: integer
The mass number of an isotope, which is required if and only
if th... | 625941d5c432627299f04e4e |
def name(self): <NEW_LINE> <INDENT> return str(self) | Get human readable name for transaction. | 625941d530dc7b7665901b6c |
def test_number_of_pins_down (self): <NEW_LINE> <INDENT> self.assertRaises (PinsDownError, self.game.roll, -1) <NEW_LINE> self.assertRaises (PinsDownError, self.game.roll, 11) <NEW_LINE> self.game.roll (5) <NEW_LINE> self.assertEqual (self.game.score, 5) <NEW_LINE> self.assertRaises (PinsDownError, self.game.roll, 6) <... | Tests the number of pins down in a roll.
The number of pins down can't be less than zero and greater than ten. | 625941d5283ffb24f3c55b07 |
def test_no_args(self): <NEW_LINE> <INDENT> sources = [ { 'type': 'video/mp4', 'width': 720, 'height': 406, 'file': 'http://cdn.invalid/vid2.mp4', }, { 'type': 'video/mp4', 'width': 1920, 'height': 1080, 'file': 'http://cdn.invalid/vid1.mp4', }, { 'type': 'audio/mp4', 'file': 'http://cdn.invalid/vid_audio.mp4', }, ] <N... | Passing no arguments returns the "best" source. | 625941d5925a0f43d254a07f |
def __str__(self): <NEW_LINE> <INDENT> return "[Square] ({}) {}/{} - {}".format(self.id, self.x, self.y, self.width) | Overrides the str method | 625941d507f4c71912b1168b |
def connection_made(self, transport): <NEW_LINE> <INDENT> self.transport = transport | called from asyncio module | 625941d50fa83653e46571c2 |
def _find(self, sort_key): <NEW_LINE> <INDENT> node = self._root <NEW_LINE> while node: <NEW_LINE> <INDENT> node_key = node[_SORT_KEY] <NEW_LINE> if sort_key < node_key: <NEW_LINE> <INDENT> node = node[_LEFT] <NEW_LINE> <DEDENT> elif sort_key > node_key: <NEW_LINE> <INDENT> node = node[_RIGHT] <NEW_LINE> <DEDENT> else:... | Return a node with the given sort key, or raise KeyError if not found. | 625941d50a366e3fb873ea22 |
def _select_from_distribution(self, n_pre_samples, n_samples, sigma): <NEW_LINE> <INDENT> selected = [0] <NEW_LINE> while len(selected) < n_samples: <NEW_LINE> <INDENT> idx = int(np.clip(sigma * n_pre_samples * np.abs(self.random_state.randn()), 0, n_pre_samples - 1)) <NEW_LINE> if idx not in selected: <NEW_LINE> <INDE... | Select samples indices. | 625941d56fece00bbac2d948 |
def get_params(self): <NEW_LINE> <INDENT> raise NotImplementedError('%s' % self.__class__) | Returns the list parameters of the query | 625941d585dfad0860c3b062 |
def asyncChMod(self, sRemotePath, fMode, cMsTimeout = 30000, fIgnoreErrors = False): <NEW_LINE> <INDENT> return self.startTask(cMsTimeout, fIgnoreErrors, "chMod", self.taskChMod, (sRemotePath, fMode)); | Initiates a chmod task.
Returns True on success, False on failure (logged).
The task returns True on success, False on failure (logged). | 625941d5b57a9660fec33a8e |
def remove_resource_policy(self, resource_id='', policy_id=''): <NEW_LINE> <INDENT> resource_obj = self._validate_resource_id("resource_id", resource_id) <NEW_LINE> policy_obj = self._validate_resource_id("policy_id", policy_id, RT.Policy) <NEW_LINE> self._remove_resource_policy(resource_obj, policy_obj) <NEW_LINE> ret... | Removes an association for a policy to a specific resource
| 625941d530c21e258bdfa6a5 |
def path(self, path): <NEW_LINE> <INDENT> if not 'p' in vars(self): <NEW_LINE> <INDENT> self.start_process() <NEW_LINE> <DEDENT> if not self.p.returncode is None: <NEW_LINE> <INDENT> logger.warning('\'encfsctl encode\' process terminated. Restarting.', self) <NEW_LINE> del self.p <NEW_LINE> self.start_process() <NEW_LI... | write plain path to encfsctl stdin and read encrypted path from stdout | 625941d5d58c6744b4257e66 |
def MH_accept(self, x, x_, **params): <NEW_LINE> <INDENT> logp_old = self.logp(x, **params) <NEW_LINE> logp_new = self.logp(x_, **params) <NEW_LINE> return logp_new - logp_old >= np.log(np.random.rand(x.shape[0])) | The Metropolis-Hastings accept/reject step.
x: Array of shape [batch_size, dim]
Current position/momentum state.
x_: Array of shape [batch_size, dim]
Proposed position/momentum states.
Returns: Array of Bool with shape [batch_size] indicating if the state was accepted. | 625941d58da39b475bd6517c |
def display_phone_link(person): <NEW_LINE> <INDENT> phoneNumber = person.phone_number <NEW_LINE> if not phoneNumber: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> hiddenNumber = dsh_agi.hide_phone_digits(phoneNumber) <NEW_LINE> persons = dv2.db.models.Person.objects.filter(phone_number=phoneNumber) <NEW_LINE> if no... | called by Item list and Person list to display a phone number
column. hides the last four digts of the phone numbers.
displays icons for shared phones and phone owner. | 625941d5a219f33f34628b6f |
def test_ship_location_api(self): <NEW_LINE> <INDENT> api_client = APIClient() <NEW_LINE> response = api_client.get('/api/ships/') <NEW_LINE> def isDescending(list): <NEW_LINE> <INDENT> previous = list[0] <NEW_LINE> for number in list: <NEW_LINE> <INDENT> if number > previous: <NEW_LINE> <INDENT> return False <NEW_LINE... | Test ship location api | 625941d5cdde0d52a9e5323b |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_B3f().pack(_x.found, _x.x, _x.y, _x.z)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) <N... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941d566656f66f7cbc3b3 |
def handle(self, name, args, kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not _is_subtype(self.expected, self._base_type): <NEW_LINE> <INDENT> raise TypeError('%s() arg 1 must be %s' % (name, self._base_type_str)) <NEW_LINE> <DEDENT> if args and args[0] is None: <NEW_LINE> <INDENT> warnings.warn("callable i... | If args is empty, assertRaises/Warns is being used as a
context manager, so check for a 'msg' kwarg and return self.
If args is not empty, call a callable passing positional and keyword
arguments. | 625941d5dc8b845886cb573d |
def handle(self, data, token=None, *, session=None): <NEW_LINE> <INDENT> target = data.get("target", {}) <NEW_LINE> message = data.get("message", "") <NEW_LINE> source = data.get("source") <NEW_LINE> if not target or target.get("type") not in ("room", "token"): <NEW_LINE> <INDENT> self.server.log("Unknown message targe... | Handle a new incomming chat message | 625941d5cad5886f8bd271e0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.