body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def prepare_auth(self, auth, url=''):
'Prepares the given HTTP auth data.'
if (auth is None):
url_auth = get_auth_from_url(self.url)
auth = (url_auth if any(url_auth) else None)
if auth:
if (isinstance(auth, tuple) and (len(auth) == 2)):
auth = HTTPBasicAuth(*auth)
... | 5,152,842,564,660,482,000 | Prepares the given HTTP auth data. | src/oci/_vendor/requests/models.py | prepare_auth | LaudateCorpus1/oci-python-sdk | python | def prepare_auth(self, auth, url=):
if (auth is None):
url_auth = get_auth_from_url(self.url)
auth = (url_auth if any(url_auth) else None)
if auth:
if (isinstance(auth, tuple) and (len(auth) == 2)):
auth = HTTPBasicAuth(*auth)
r = auth(self)
self.__dict__... |
def prepare_cookies(self, cookies):
'Prepares the given HTTP cookie data.\n\n This function eventually generates a ``Cookie`` header from the\n given cookies using cookielib. Due to cookielib\'s design, the header\n will not be regenerated if it already exists, meaning this function\n ca... | -4,880,843,362,105,130,000 | Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
:class:`PreparedRequest <PreparedRequ... | src/oci/_vendor/requests/models.py | prepare_cookies | LaudateCorpus1/oci-python-sdk | python | def prepare_cookies(self, cookies):
'Prepares the given HTTP cookie data.\n\n This function eventually generates a ``Cookie`` header from the\n given cookies using cookielib. Due to cookielib\'s design, the header\n will not be regenerated if it already exists, meaning this function\n ca... |
def prepare_hooks(self, hooks):
'Prepares the given hooks.'
hooks = (hooks or [])
for event in hooks:
self.register_hook(event, hooks[event]) | -4,515,863,383,951,718,400 | Prepares the given hooks. | src/oci/_vendor/requests/models.py | prepare_hooks | LaudateCorpus1/oci-python-sdk | python | def prepare_hooks(self, hooks):
hooks = (hooks or [])
for event in hooks:
self.register_hook(event, hooks[event]) |
def __bool__(self):
'Returns True if :attr:`status_code` is less than 400.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code, is between 200 and 400, this will return True. This\n ... | -7,938,503,880,147,866,000 | Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK`... | src/oci/_vendor/requests/models.py | __bool__ | LaudateCorpus1/oci-python-sdk | python | def __bool__(self):
'Returns True if :attr:`status_code` is less than 400.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code, is between 200 and 400, this will return True. This\n ... |
def __nonzero__(self):
'Returns True if :attr:`status_code` is less than 400.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code, is between 200 and 400, this will return True. This\n ... | 4,933,757,067,486,797,000 | Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK`... | src/oci/_vendor/requests/models.py | __nonzero__ | LaudateCorpus1/oci-python-sdk | python | def __nonzero__(self):
'Returns True if :attr:`status_code` is less than 400.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code, is between 200 and 400, this will return True. This\n ... |
def __iter__(self):
'Allows you to use a response as an iterator.'
return self.iter_content(128) | -7,277,316,857,547,251,000 | Allows you to use a response as an iterator. | src/oci/_vendor/requests/models.py | __iter__ | LaudateCorpus1/oci-python-sdk | python | def __iter__(self):
return self.iter_content(128) |
@property
def ok(self):
'Returns True if :attr:`status_code` is less than 400, False if not.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code is between 200 and 400, this will return ... | -6,177,503,495,560,946,000 | Returns True if :attr:`status_code` is less than 400, False if not.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code is between 200 and 400, this will return True. This
is **not** a check to see if the response code... | src/oci/_vendor/requests/models.py | ok | LaudateCorpus1/oci-python-sdk | python | @property
def ok(self):
'Returns True if :attr:`status_code` is less than 400, False if not.\n\n This attribute checks if the status code of the response is between\n 400 and 600 to see if there was a client error or a server error. If\n the status code is between 200 and 400, this will return ... |
@property
def is_redirect(self):
'True if this Response is a well-formed HTTP redirect that could have\n been processed automatically (by :meth:`Session.resolve_redirects`).\n '
return (('location' in self.headers) and (self.status_code in REDIRECT_STATI)) | 8,650,224,052,504,523,000 | True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`). | src/oci/_vendor/requests/models.py | is_redirect | LaudateCorpus1/oci-python-sdk | python | @property
def is_redirect(self):
'True if this Response is a well-formed HTTP redirect that could have\n been processed automatically (by :meth:`Session.resolve_redirects`).\n '
return (('location' in self.headers) and (self.status_code in REDIRECT_STATI)) |
@property
def is_permanent_redirect(self):
'True if this Response one of the permanent versions of redirect.'
return (('location' in self.headers) and (self.status_code in (codes.moved_permanently, codes.permanent_redirect))) | 6,790,407,169,252,320,000 | True if this Response one of the permanent versions of redirect. | src/oci/_vendor/requests/models.py | is_permanent_redirect | LaudateCorpus1/oci-python-sdk | python | @property
def is_permanent_redirect(self):
return (('location' in self.headers) and (self.status_code in (codes.moved_permanently, codes.permanent_redirect))) |
@property
def next(self):
'Returns a PreparedRequest for the next request in a redirect chain, if there is one.'
return self._next | 6,609,836,077,647,073,000 | Returns a PreparedRequest for the next request in a redirect chain, if there is one. | src/oci/_vendor/requests/models.py | next | LaudateCorpus1/oci-python-sdk | python | @property
def next(self):
return self._next |
@property
def apparent_encoding(self):
'The apparent encoding, provided by the chardet library.'
return chardet.detect(self.content)['encoding'] | -1,142,759,535,317,406,500 | The apparent encoding, provided by the chardet library. | src/oci/_vendor/requests/models.py | apparent_encoding | LaudateCorpus1/oci-python-sdk | python | @property
def apparent_encoding(self):
return chardet.detect(self.content)['encoding'] |
def iter_content(self, chunk_size=1, decode_unicode=False):
'Iterates over the response data. When stream=True is set on the\n request, this avoids reading the content at once into memory for\n large responses. The chunk size is the number of bytes it should\n read into memory. This is not n... | -1,745,230,368,267,707,000 | Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
chunk_size must be ... | src/oci/_vendor/requests/models.py | iter_content | LaudateCorpus1/oci-python-sdk | python | def iter_content(self, chunk_size=1, decode_unicode=False):
'Iterates over the response data. When stream=True is set on the\n request, this avoids reading the content at once into memory for\n large responses. The chunk size is the number of bytes it should\n read into memory. This is not n... |
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None):
'Iterates over the response data, one line at a time. When\n stream=True is set on the request, this avoids reading the\n content at once into memory for large responses.\n\n .. note:: This method is not re... | 5,187,716,744,981,455,000 | Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
.. note:: This method is not reentrant safe. | src/oci/_vendor/requests/models.py | iter_lines | LaudateCorpus1/oci-python-sdk | python | def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None):
'Iterates over the response data, one line at a time. When\n stream=True is set on the request, this avoids reading the\n content at once into memory for large responses.\n\n .. note:: This method is not re... |
@property
def content(self):
'Content of the response, in bytes.'
if (self._content is False):
if self._content_consumed:
raise RuntimeError('The content for this response was already consumed')
if ((self.status_code == 0) or (self.raw is None)):
self._content = None
... | 4,100,658,395,437,519,400 | Content of the response, in bytes. | src/oci/_vendor/requests/models.py | content | LaudateCorpus1/oci-python-sdk | python | @property
def content(self):
if (self._content is False):
if self._content_consumed:
raise RuntimeError('The content for this response was already consumed')
if ((self.status_code == 0) or (self.raw is None)):
self._content = None
else:
self._content ... |
@property
def text(self):
'Content of the response, in unicode.\n\n If Response.encoding is None, encoding will be guessed using\n ``chardet``.\n\n The encoding of the response content is determined based solely on HTTP\n headers, following RFC 2616 to the letter. If you can take advanta... | -7,794,038,974,435,198,000 | Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you ... | src/oci/_vendor/requests/models.py | text | LaudateCorpus1/oci-python-sdk | python | @property
def text(self):
'Content of the response, in unicode.\n\n If Response.encoding is None, encoding will be guessed using\n ``chardet``.\n\n The encoding of the response content is determined based solely on HTTP\n headers, following RFC 2616 to the letter. If you can take advanta... |
def json(self, **kwargs):
'Returns the json-encoded content of a response, if any.\n\n :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n :raises ValueError: If the response body does not contain valid json.\n '
if ((not self.encoding) and self.content and (len(self.conten... | 6,506,800,846,072,340,000 | Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
:raises ValueError: If the response body does not contain valid json. | src/oci/_vendor/requests/models.py | json | LaudateCorpus1/oci-python-sdk | python | def json(self, **kwargs):
'Returns the json-encoded content of a response, if any.\n\n :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n :raises ValueError: If the response body does not contain valid json.\n '
if ((not self.encoding) and self.content and (len(self.conten... |
@property
def links(self):
'Returns the parsed header links of the response, if any.'
header = self.headers.get('link')
l = {}
if header:
links = parse_header_links(header)
for link in links:
key = (link.get('rel') or link.get('url'))
l[key] = link
return l | 7,586,059,766,961,026,000 | Returns the parsed header links of the response, if any. | src/oci/_vendor/requests/models.py | links | LaudateCorpus1/oci-python-sdk | python | @property
def links(self):
header = self.headers.get('link')
l = {}
if header:
links = parse_header_links(header)
for link in links:
key = (link.get('rel') or link.get('url'))
l[key] = link
return l |
def raise_for_status(self):
'Raises :class:`HTTPError`, if one occurred.'
http_error_msg = ''
if isinstance(self.reason, bytes):
try:
reason = self.reason.decode('utf-8')
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
else:
reason = s... | 6,135,942,110,397,613,000 | Raises :class:`HTTPError`, if one occurred. | src/oci/_vendor/requests/models.py | raise_for_status | LaudateCorpus1/oci-python-sdk | python | def raise_for_status(self):
http_error_msg =
if isinstance(self.reason, bytes):
try:
reason = self.reason.decode('utf-8')
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
else:
reason = self.reason
if (400 <= self.status_code < 50... |
def close(self):
'Releases the connection back to the pool. Once this method has been\n called the underlying ``raw`` object must not be accessed again.\n\n *Note: Should not normally need to be called explicitly.*\n '
if (not self._content_consumed):
self.raw.close()
release_co... | 5,014,410,288,615,067,000 | Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.* | src/oci/_vendor/requests/models.py | close | LaudateCorpus1/oci-python-sdk | python | def close(self):
'Releases the connection back to the pool. Once this method has been\n called the underlying ``raw`` object must not be accessed again.\n\n *Note: Should not normally need to be called explicitly.*\n '
if (not self._content_consumed):
self.raw.close()
release_co... |
def update_init_info(module, init_info):
'Update the `_params_init_info` in the module if the value of parameters\n are changed.\n\n Args:\n module (obj:`nn.Module`): The module of PyTorch with a user-defined\n attribute `_params_init_info` which records the initialization\n infor... | -2,051,522,352,694,961,400 | Update the `_params_init_info` in the module if the value of parameters
are changed.
Args:
module (obj:`nn.Module`): The module of PyTorch with a user-defined
attribute `_params_init_info` which records the initialization
information.
init_info (str): The string that describes the initializatio... | deep3dmap/core/utils/weight_init.py | update_init_info | achao2013/DeepRecon | python | def update_init_info(module, init_info):
'Update the `_params_init_info` in the module if the value of parameters\n are changed.\n\n Args:\n module (obj:`nn.Module`): The module of PyTorch with a user-defined\n attribute `_params_init_info` which records the initialization\n infor... |
def bias_init_with_prob(prior_prob):
'initialize conv/fc bias value according to a given probability value.'
bias_init = float((- np.log(((1 - prior_prob) / prior_prob))))
return bias_init | 4,357,258,245,550,052,400 | initialize conv/fc bias value according to a given probability value. | deep3dmap/core/utils/weight_init.py | bias_init_with_prob | achao2013/DeepRecon | python | def bias_init_with_prob(prior_prob):
bias_init = float((- np.log(((1 - prior_prob) / prior_prob))))
return bias_init |
def initialize(module, init_cfg):
'Initialize a module.\n\n Args:\n module (``torch.nn.Module``): the module will be initialized.\n init_cfg (dict | list[dict]): initialization configuration dict to\n define initializer. OpenMMLab has implemented 6 initializers\n including ``C... | -8,268,513,196,977,106,000 | Initialize a module.
Args:
module (``torch.nn.Module``): the module will be initialized.
init_cfg (dict | list[dict]): initialization configuration dict to
define initializer. OpenMMLab has implemented 6 initializers
including ``Constant``, ``Xavier``, ``Normal``, ``Uniform``,
``Kaiming... | deep3dmap/core/utils/weight_init.py | initialize | achao2013/DeepRecon | python | def initialize(module, init_cfg):
'Initialize a module.\n\n Args:\n module (``torch.nn.Module``): the module will be initialized.\n init_cfg (dict | list[dict]): initialization configuration dict to\n define initializer. OpenMMLab has implemented 6 initializers\n including ``C... |
def trunc_normal_(tensor: Tensor, mean: float=0.0, std: float=1.0, a: float=(- 2.0), b: float=2.0) -> Tensor:
'Fills the input Tensor with values drawn from a truncated\n normal distribution. The values are effectively drawn from the\n normal distribution :math:`\\mathcal{N}(\\text{mean}, \\text{std}^2)`\n ... | -7,831,877,177,259,050,000 | Fills the input Tensor with values drawn from a truncated
normal distribution. The values are effectively drawn from the
normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
with values outside :math:`[a, b]` redrawn until they are within
the bounds. The method used for generating the random values works
... | deep3dmap/core/utils/weight_init.py | trunc_normal_ | achao2013/DeepRecon | python | def trunc_normal_(tensor: Tensor, mean: float=0.0, std: float=1.0, a: float=(- 2.0), b: float=2.0) -> Tensor:
'Fills the input Tensor with values drawn from a truncated\n normal distribution. The values are effectively drawn from the\n normal distribution :math:`\\mathcal{N}(\\text{mean}, \\text{std}^2)`\n ... |
def _parse_inputs(self):
'A number of the command line options expect precisely one or two files.\n '
nr_input_files = len(self.inputs.input_files)
for n in self.input_spec.bool_or_const_traits:
t = self.inputs.__getattribute__(n)
if isdefined(t):
if isinstance(t, bool):
... | -7,755,718,070,246,585,000 | A number of the command line options expect precisely one or two files. | nipype/interfaces/minc/minc.py | _parse_inputs | Inria-Visages/nipype | python | def _parse_inputs(self):
'\n '
nr_input_files = len(self.inputs.input_files)
for n in self.input_spec.bool_or_const_traits:
t = self.inputs.__getattribute__(n)
if isdefined(t):
if isinstance(t, bool):
if (nr_input_files != 2):
raise Valu... |
def patch_settings():
'Merge settings with global cms settings, so all required attributes\n will exist. Never override, just append non existing settings.\n \n Also check for setting inconsistencies if settings.DEBUG\n '
if patch_settings.ALREADY_PATCHED:
return
patch_settings.ALREADY_P... | -1,568,719,852,966,767,000 | Merge settings with global cms settings, so all required attributes
will exist. Never override, just append non existing settings.
Also check for setting inconsistencies if settings.DEBUG | cms/conf/__init__.py | patch_settings | tonatos/django-cms | python | def patch_settings():
'Merge settings with global cms settings, so all required attributes\n will exist. Never override, just append non existing settings.\n \n Also check for setting inconsistencies if settings.DEBUG\n '
if patch_settings.ALREADY_PATCHED:
return
patch_settings.ALREADY_P... |
def list_database_account_keys(account_name: Optional[str]=None, resource_group_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableListDatabaseAccountKeysResult:
'\n The access keys for the given database account.\n\n\n :param str account_name: Cosmos DB database account name.\n ... | -3,061,702,169,182,575,600 | The access keys for the given database account.
:param str account_name: Cosmos DB database account name.
:param str resource_group_name: Name of an Azure resource group. | sdk/python/pulumi_azure_native/documentdb/v20191212/list_database_account_keys.py | list_database_account_keys | polivbr/pulumi-azure-native | python | def list_database_account_keys(account_name: Optional[str]=None, resource_group_name: Optional[str]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableListDatabaseAccountKeysResult:
'\n The access keys for the given database account.\n\n\n :param str account_name: Cosmos DB database account name.\n ... |
@property
@pulumi.getter(name='primaryMasterKey')
def primary_master_key(self) -> str:
'\n Base 64 encoded value of the primary read-write key.\n '
return pulumi.get(self, 'primary_master_key') | -6,444,721,121,725,809,000 | Base 64 encoded value of the primary read-write key. | sdk/python/pulumi_azure_native/documentdb/v20191212/list_database_account_keys.py | primary_master_key | polivbr/pulumi-azure-native | python | @property
@pulumi.getter(name='primaryMasterKey')
def primary_master_key(self) -> str:
'\n \n '
return pulumi.get(self, 'primary_master_key') |
@property
@pulumi.getter(name='primaryReadonlyMasterKey')
def primary_readonly_master_key(self) -> str:
'\n Base 64 encoded value of the primary read-only key.\n '
return pulumi.get(self, 'primary_readonly_master_key') | 2,857,989,781,514,118,000 | Base 64 encoded value of the primary read-only key. | sdk/python/pulumi_azure_native/documentdb/v20191212/list_database_account_keys.py | primary_readonly_master_key | polivbr/pulumi-azure-native | python | @property
@pulumi.getter(name='primaryReadonlyMasterKey')
def primary_readonly_master_key(self) -> str:
'\n \n '
return pulumi.get(self, 'primary_readonly_master_key') |
@property
@pulumi.getter(name='secondaryMasterKey')
def secondary_master_key(self) -> str:
'\n Base 64 encoded value of the secondary read-write key.\n '
return pulumi.get(self, 'secondary_master_key') | 4,442,451,844,350,200,000 | Base 64 encoded value of the secondary read-write key. | sdk/python/pulumi_azure_native/documentdb/v20191212/list_database_account_keys.py | secondary_master_key | polivbr/pulumi-azure-native | python | @property
@pulumi.getter(name='secondaryMasterKey')
def secondary_master_key(self) -> str:
'\n \n '
return pulumi.get(self, 'secondary_master_key') |
@property
@pulumi.getter(name='secondaryReadonlyMasterKey')
def secondary_readonly_master_key(self) -> str:
'\n Base 64 encoded value of the secondary read-only key.\n '
return pulumi.get(self, 'secondary_readonly_master_key') | 1,901,077,849,702,143,000 | Base 64 encoded value of the secondary read-only key. | sdk/python/pulumi_azure_native/documentdb/v20191212/list_database_account_keys.py | secondary_readonly_master_key | polivbr/pulumi-azure-native | python | @property
@pulumi.getter(name='secondaryReadonlyMasterKey')
def secondary_readonly_master_key(self) -> str:
'\n \n '
return pulumi.get(self, 'secondary_readonly_master_key') |
def inference_data():
'\n Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF\n '
(X, Y) = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)
(x, y) = (X[0], Y[0])
n_states = x.shape[(- 1)]
edge_list = make_grid_edges(x, 4, return_lists=True)
edges = np.vstac... | 3,998,788,590,160,578,600 | Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF | pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py | inference_data | LemonLison/pystruct | python | def inference_data():
'\n \n '
(X, Y) = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)
(x, y) = (X[0], Y[0])
n_states = x.shape[(- 1)]
edge_list = make_grid_edges(x, 4, return_lists=True)
edges = np.vstack(edge_list)
pw_horz = ((- 1) * np.eye(n_states))
(xx, yy) = np.ind... |
def test_joint_feature_discrete():
'\n Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF\n '
(X, Y) = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)
(x, y) = (X[0], Y[0])
edge_list = make_grid_edges(x, 4, return_lists=True)
edges = np.vstack(edge_list)
... | -6,468,331,002,279,117,000 | Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF | pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py | test_joint_feature_discrete | LemonLison/pystruct | python | def test_joint_feature_discrete():
'\n \n '
(X, Y) = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)
(x, y) = (X[0], Y[0])
edge_list = make_grid_edges(x, 4, return_lists=True)
edges = np.vstack(edge_list)
edge_features = edge_list_to_features(edge_list)
x = ([x.reshape((- 1),... |
def test_joint_feature_continuous():
'\n Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF\n '
(X, Y) = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)
(x, y) = (X[0], Y[0])
n_states = x.shape[(- 1)]
edge_list = make_grid_edges(x, 4, return_lists=True)
e... | 52,569,035,070,579,250 | Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF | pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py | test_joint_feature_continuous | LemonLison/pystruct | python | def test_joint_feature_continuous():
'\n \n '
(X, Y) = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)
(x, y) = (X[0], Y[0])
n_states = x.shape[(- 1)]
edge_list = make_grid_edges(x, 4, return_lists=True)
edges = np.vstack(edge_list)
edge_features = edge_list_to_features(edge_... |
def run_recipe(recipe, args, config):
'Given a recipe, calls the appropriate query and returns the result.\n\n The provided recipe name is used to make a call to the modules.\n\n :param str recipe: name of the recipe to be run.\n :param list args: remainder arguments that were unparsed.\n :param Configu... | -761,608,809,952,332,300 | Given a recipe, calls the appropriate query and returns the result.
The provided recipe name is used to make a call to the modules.
:param str recipe: name of the recipe to be run.
:param list args: remainder arguments that were unparsed.
:param Configuration config: config object.
:returns: string | adr/recipe.py | run_recipe | gmierz/active-data-recipes | python | def run_recipe(recipe, args, config):
'Given a recipe, calls the appropriate query and returns the result.\n\n The provided recipe name is used to make a call to the modules.\n\n :param str recipe: name of the recipe to be run.\n :param list args: remainder arguments that were unparsed.\n :param Configu... |
def get_chromsizes(bwpath):
'\n TODO: replace this with negspy\n\n Also, return NaNs from any missing chromosomes in bbi.fetch\n\n '
chromsizes = bbi.chromsizes(bwpath)
chromosomes = natsorted(chromsizes.keys())
chrom_series = pd.Series(chromsizes)[chromosomes]
return chrom_series | 5,693,233,413,802,413,000 | TODO: replace this with negspy
Also, return NaNs from any missing chromosomes in bbi.fetch | clodius/tiles/bigwig.py | get_chromsizes | 4dn-dcic/clodius | python | def get_chromsizes(bwpath):
'\n TODO: replace this with negspy\n\n Also, return NaNs from any missing chromosomes in bbi.fetch\n\n '
chromsizes = bbi.chromsizes(bwpath)
chromosomes = natsorted(chromsizes.keys())
chrom_series = pd.Series(chromsizes)[chromosomes]
return chrom_series |
def tileset_info(bwpath, chromsizes=None):
"\n Get the tileset info for a bigWig file\n\n Parameters\n ----------\n bwpath: string\n The path to the bigwig file from which to retrieve data\n chromsizes: [[chrom, size],...]\n A list of chromosome sizes associated with this tileset.\n ... | 6,060,560,380,858,904,000 | Get the tileset info for a bigWig file
Parameters
----------
bwpath: string
The path to the bigwig file from which to retrieve data
chromsizes: [[chrom, size],...]
A list of chromosome sizes associated with this tileset.
Typically passed in to specify in what order data from
the bigwig should be return... | clodius/tiles/bigwig.py | tileset_info | 4dn-dcic/clodius | python | def tileset_info(bwpath, chromsizes=None):
"\n Get the tileset info for a bigWig file\n\n Parameters\n ----------\n bwpath: string\n The path to the bigwig file from which to retrieve data\n chromsizes: [[chrom, size],...]\n A list of chromosome sizes associated with this tileset.\n ... |
def tiles(bwpath, tile_ids, chromsizes_map={}, chromsizes=None):
'\n Generate tiles from a bigwig file.\n\n Parameters\n ----------\n tileset: tilesets.models.Tileset object\n The tileset that the tile ids should be retrieved from\n tile_ids: [str,...]\n A list of tile_ids (e.g. xyx.0.0... | -4,122,499,748,940,527,000 | Generate tiles from a bigwig file.
Parameters
----------
tileset: tilesets.models.Tileset object
The tileset that the tile ids should be retrieved from
tile_ids: [str,...]
A list of tile_ids (e.g. xyx.0.0) identifying the tiles
to be retrieved
chromsizes_map: {uid: []}
A set of chromsizes listings corr... | clodius/tiles/bigwig.py | tiles | 4dn-dcic/clodius | python | def tiles(bwpath, tile_ids, chromsizes_map={}, chromsizes=None):
'\n Generate tiles from a bigwig file.\n\n Parameters\n ----------\n tileset: tilesets.models.Tileset object\n The tileset that the tile ids should be retrieved from\n tile_ids: [str,...]\n A list of tile_ids (e.g. xyx.0.0... |
def chromsizes(filename):
'\n Get a list of chromosome sizes from this [presumably] bigwig\n file.\n\n Parameters:\n -----------\n filename: string\n The filename of the bigwig file\n\n Returns\n -------\n chromsizes: [(name:string, size:int), ...]\n An ordered list of chromoso... | 2,550,086,058,640,435,700 | Get a list of chromosome sizes from this [presumably] bigwig
file.
Parameters:
-----------
filename: string
The filename of the bigwig file
Returns
-------
chromsizes: [(name:string, size:int), ...]
An ordered list of chromosome names and sizes | clodius/tiles/bigwig.py | chromsizes | 4dn-dcic/clodius | python | def chromsizes(filename):
'\n Get a list of chromosome sizes from this [presumably] bigwig\n file.\n\n Parameters:\n -----------\n filename: string\n The filename of the bigwig file\n\n Returns\n -------\n chromsizes: [(name:string, size:int), ...]\n An ordered list of chromoso... |
def read_args():
'Reads command line arguments.\n\n Returns: Parsed arguments.'
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=str, help='path to .csv file', default='orbit.csv')
parser.add_argument('-u', '--units', type=str, help='units of distance (m or km)', default... | 6,337,914,842,948,013,000 | Reads command line arguments.
Returns: Parsed arguments. | orbitdeterminator/kep_determination/ellipse_fit.py | read_args | Alexandros23Kazantzidis/orbitdeterminator | python | def read_args():
'Reads command line arguments.\n\n Returns: Parsed arguments.'
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=str, help='path to .csv file', default='orbit.csv')
parser.add_argument('-u', '--units', type=str, help='units of distance (m or km)', default... |
def plane_err(data, coeffs):
'Calculates the total squared error of the data wrt a plane.\n\n The data should be a list of points. coeffs is an array of\n 3 elements - the coefficients a,b,c in the plane equation\n ax+by+c = 0.\n\n Arguments:\n data: A numpy array of points.\n co... | -5,432,732,931,796,351,000 | Calculates the total squared error of the data wrt a plane.
The data should be a list of points. coeffs is an array of
3 elements - the coefficients a,b,c in the plane equation
ax+by+c = 0.
Arguments:
data: A numpy array of points.
coeffs: The coefficients of the plane ax+by+c=0.
Returns: The total squared error wrt... | orbitdeterminator/kep_determination/ellipse_fit.py | plane_err | Alexandros23Kazantzidis/orbitdeterminator | python | def plane_err(data, coeffs):
'Calculates the total squared error of the data wrt a plane.\n\n The data should be a list of points. coeffs is an array of\n 3 elements - the coefficients a,b,c in the plane equation\n ax+by+c = 0.\n\n Arguments:\n data: A numpy array of points.\n co... |
def project_to_plane(points, coeffs):
'Projects points onto a plane.\n\n Projects a list of points onto the plane ax+by+c=0,\n where a,b,c are elements of coeffs.\n\n Arguments:\n coeffs: The coefficients of the plane ax+by+c=0.\n points: A numpy array of points.\n\n Returns:\n ... | 7,388,186,402,707,117,000 | Projects points onto a plane.
Projects a list of points onto the plane ax+by+c=0,
where a,b,c are elements of coeffs.
Arguments:
coeffs: The coefficients of the plane ax+by+c=0.
points: A numpy array of points.
Returns:
A list of projected points. | orbitdeterminator/kep_determination/ellipse_fit.py | project_to_plane | Alexandros23Kazantzidis/orbitdeterminator | python | def project_to_plane(points, coeffs):
'Projects points onto a plane.\n\n Projects a list of points onto the plane ax+by+c=0,\n where a,b,c are elements of coeffs.\n\n Arguments:\n coeffs: The coefficients of the plane ax+by+c=0.\n points: A numpy array of points.\n\n Returns:\n ... |
def conv_to_2D(points, x, y):
'Finds coordinates of points in a plane wrt a basis.\n\n Given a list of points in a plane, and a basis of the plane,\n this function returns the coordinates of those points\n wrt this basis.\n\n Arguments:\n points: A numpy array of points.\n x: One... | -1,297,365,435,381,717,800 | Finds coordinates of points in a plane wrt a basis.
Given a list of points in a plane, and a basis of the plane,
this function returns the coordinates of those points
wrt this basis.
Arguments:
points: A numpy array of points.
x: One vector of the basis.
y: Another vector of the basis.
Returns:
Coordinates of the po... | orbitdeterminator/kep_determination/ellipse_fit.py | conv_to_2D | Alexandros23Kazantzidis/orbitdeterminator | python | def conv_to_2D(points, x, y):
'Finds coordinates of points in a plane wrt a basis.\n\n Given a list of points in a plane, and a basis of the plane,\n this function returns the coordinates of those points\n wrt this basis.\n\n Arguments:\n points: A numpy array of points.\n x: One... |
def cart_to_pol(points):
'Converts a list of cartesian coordinates into polar ones.\n\n Arguments:\n points: The list of points in the format [x,y].\n\n Returns:\n A list of polar coordinates in the format [radius,angle].'
pol = np.empty(points.shape)
pol[:, 0] = np.sqrt(((points[:, ... | -8,661,686,831,716,060,000 | Converts a list of cartesian coordinates into polar ones.
Arguments:
points: The list of points in the format [x,y].
Returns:
A list of polar coordinates in the format [radius,angle]. | orbitdeterminator/kep_determination/ellipse_fit.py | cart_to_pol | Alexandros23Kazantzidis/orbitdeterminator | python | def cart_to_pol(points):
'Converts a list of cartesian coordinates into polar ones.\n\n Arguments:\n points: The list of points in the format [x,y].\n\n Returns:\n A list of polar coordinates in the format [radius,angle].'
pol = np.empty(points.shape)
pol[:, 0] = np.sqrt(((points[:, ... |
def ellipse_err(polar_coords, params):
'Calculates the total squared error of the data wrt an ellipse.\n\n params is a 3 element array used to define an ellipse.\n It contains 3 elements a,e, and t0.\n\n a is the semi-major axis\n e is the eccentricity\n t0 is the angle of the major ax... | -2,029,023,196,265,276,000 | Calculates the total squared error of the data wrt an ellipse.
params is a 3 element array used to define an ellipse.
It contains 3 elements a,e, and t0.
a is the semi-major axis
e is the eccentricity
t0 is the angle of the major axis wrt the x-axis.
These 3 elements define an ellipse with one focus at origin.
Equat... | orbitdeterminator/kep_determination/ellipse_fit.py | ellipse_err | Alexandros23Kazantzidis/orbitdeterminator | python | def ellipse_err(polar_coords, params):
'Calculates the total squared error of the data wrt an ellipse.\n\n params is a 3 element array used to define an ellipse.\n It contains 3 elements a,e, and t0.\n\n a is the semi-major axis\n e is the eccentricity\n t0 is the angle of the major ax... |
def configure_app(app):
'Multiple app configurations'
Compress(app) | -8,213,292,863,896,477,000 | Multiple app configurations | config.py | configure_app | Rwothoromo/Flask-Okta | python | def configure_app(app):
Compress(app) |
def _param_check():
' 受信パラメータチェック '
msg = ''
if (not HachiUtil.LocalAddress().is_localaddress(RecvParams.ip.get())):
msg += '・指定した待受IPアドレスがインターフェースにありません。\n'
if (not (0 <= RecvParams.port.get() <= 65535)):
msg += '・ポート番号は 0~65535 の範囲で指定してください。\n'
return msg | -3,071,456,578,103,253,500 | 受信パラメータチェック | controller/RxController.py | _param_check | kinformation/hachi | python | def _param_check():
' '
msg =
if (not HachiUtil.LocalAddress().is_localaddress(RecvParams.ip.get())):
msg += '・指定した待受IPアドレスがインターフェースにありません。\n'
if (not (0 <= RecvParams.port.get() <= 65535)):
msg += '・ポート番号は 0~65535 の範囲で指定してください。\n'
return msg |
def recv_tcp_start(self):
' TCPパケット送信スレッド '
self.th_recv = RecvTcpThread.RecvTcpThread(RecvParams(), self.shareObj)
self.th_recv.setDaemon(True)
self.th_recv.start() | -1,761,130,429,100,993,800 | TCPパケット送信スレッド | controller/RxController.py | recv_tcp_start | kinformation/hachi | python | def recv_tcp_start(self):
' '
self.th_recv = RecvTcpThread.RecvTcpThread(RecvParams(), self.shareObj)
self.th_recv.setDaemon(True)
self.th_recv.start() |
def recv_udp_start(self):
' UDPパケット受信スレッド '
self.th_recv = RecvUdpThread.RecvUdpThread(RecvParams(), self.shareObj)
self.th_recv.setDaemon(True)
self.th_recv.start() | 8,602,522,311,085,771,000 | UDPパケット受信スレッド | controller/RxController.py | recv_udp_start | kinformation/hachi | python | def recv_udp_start(self):
' '
self.th_recv = RecvUdpThread.RecvUdpThread(RecvParams(), self.shareObj)
self.th_recv.setDaemon(True)
self.th_recv.start() |
def monitor_start(self):
' パケット受信監視スレッド '
self.th_monitor = RecvMonitorThread.RecvMonitorThread(MonitorParams(), self.shareObj)
self.th_monitor.setDaemon(True)
self.th_monitor.start() | -5,020,833,981,410,120,000 | パケット受信監視スレッド | controller/RxController.py | monitor_start | kinformation/hachi | python | def monitor_start(self):
' '
self.th_monitor = RecvMonitorThread.RecvMonitorThread(MonitorParams(), self.shareObj)
self.th_monitor.setDaemon(True)
self.th_monitor.start() |
@pytest.fixture(scope='module', autouse=True)
def create_kmc_db():
'\n Set up tests and clean up after.\n '
kmer_len = 17
memory = 2
cutoff_min = 1
sig_len = 9
reads_src = 'input.fastq'
reads = ('GGCATTGCATGCAGTNNCAGTCATGCAGTCAGGCAGTCATGGCATGCAACGACGATCAGTCATGGTCGAG', 'GGCATTGCATGCAGTN... | 1,694,867,008,165,371,600 | Set up tests and clean up after. | tests/py_kmc_api/test_py_kmc_file.py | create_kmc_db | refresh-bio/KMC | python | @pytest.fixture(scope='module', autouse=True)
def create_kmc_db():
'\n \n '
kmer_len = 17
memory = 2
cutoff_min = 1
sig_len = 9
reads_src = 'input.fastq'
reads = ('GGCATTGCATGCAGTNNCAGTCATGCAGTCAGGCAGTCATGGCATGCAACGACGATCAGTCATGGTCGAG', 'GGCATTGCATGCAGTNNCAGTCATGCAGTCAGGCAGTCATGGCATGCA... |
def _cout_kmers(reads, kmer_len):
' Simple k-mer counting routine. '
kmers = {}
for read in reads:
for start in range(0, ((len(read) - kmer_len) + 1)):
kmer = read[start:(start + kmer_len)]
if ('N' in kmer):
continue
rev = kmer_utils.rev_comp(kmer)... | 292,329,010,136,147,000 | Simple k-mer counting routine. | tests/py_kmc_api/test_py_kmc_file.py | _cout_kmers | refresh-bio/KMC | python | def _cout_kmers(reads, kmer_len):
' '
kmers = {}
for read in reads:
for start in range(0, ((len(read) - kmer_len) + 1)):
kmer = read[start:(start + kmer_len)]
if ('N' in kmer):
continue
rev = kmer_utils.rev_comp(kmer)
if (rev < kmer):
... |
def _save_reads_as_fastq(reads, file_name):
' Save reads from input to file named file_name. '
file = open(file_name, 'w')
for read in reads:
file.write('@TEST\n')
file.write((read + '\n'))
file.write('+TEST\n')
file.write((('I' * len(read)) + '\n'))
file.close() | 7,954,480,761,115,530,000 | Save reads from input to file named file_name. | tests/py_kmc_api/test_py_kmc_file.py | _save_reads_as_fastq | refresh-bio/KMC | python | def _save_reads_as_fastq(reads, file_name):
' '
file = open(file_name, 'w')
for read in reads:
file.write('@TEST\n')
file.write((read + '\n'))
file.write('+TEST\n')
file.write((('I' * len(read)) + '\n'))
file.close() |
def _generate_not_existing_kmers(kmers, kmer_len):
' Generate k-mers that are not present in the database.\n\n :kmers: existing k-mers\n :kmer_len: length of k-mers\n\n '
def increment_kmer(kmer, start):
' Increments k-mer to next lexographical.\n\n Start from pos :start: (from ... | -3,914,537,680,329,714,700 | Generate k-mers that are not present in the database.
:kmers: existing k-mers
:kmer_len: length of k-mers | tests/py_kmc_api/test_py_kmc_file.py | _generate_not_existing_kmers | refresh-bio/KMC | python | def _generate_not_existing_kmers(kmers, kmer_len):
' Generate k-mers that are not present in the database.\n\n :kmers: existing k-mers\n :kmer_len: length of k-mers\n\n '
def increment_kmer(kmer, start):
' Increments k-mer to next lexographical.\n\n Start from pos :start: (from ... |
def _run_kmc(cutoff_min, kmer_len, memory, sig_len, reads_src):
' Runs kmc. '
if (init_sys_path.is_linux() or init_sys_path.is_mac()):
kmc_path = os.path.join(os.path.dirname(__file__), '../../bin/kmc')
elif init_sys_path.is_windows():
kmc_path = os.path.join(os.path.dirname(__file__), '../.... | 6,122,891,625,812,580,000 | Runs kmc. | tests/py_kmc_api/test_py_kmc_file.py | _run_kmc | refresh-bio/KMC | python | def _run_kmc(cutoff_min, kmer_len, memory, sig_len, reads_src):
' '
if (init_sys_path.is_linux() or init_sys_path.is_mac()):
kmc_path = os.path.join(os.path.dirname(__file__), '../../bin/kmc')
elif init_sys_path.is_windows():
kmc_path = os.path.join(os.path.dirname(__file__), '../../x64/Rel... |
def _open_for_listing():
' Open kmc database for listing and check if opened sucessfully. '
kmc_file = pka.KMCFile()
assert kmc_file.OpenForListing('kmc_db')
return kmc_file | 3,280,609,107,479,147,500 | Open kmc database for listing and check if opened sucessfully. | tests/py_kmc_api/test_py_kmc_file.py | _open_for_listing | refresh-bio/KMC | python | def _open_for_listing():
' '
kmc_file = pka.KMCFile()
assert kmc_file.OpenForListing('kmc_db')
return kmc_file |
def _open_for_ra():
' Open kmc database for random access and check if opened sucessfully. '
kmc_file = pka.KMCFile()
assert kmc_file.OpenForRA('kmc_db')
return kmc_file | 7,697,411,584,319,123,000 | Open kmc database for random access and check if opened sucessfully. | tests/py_kmc_api/test_py_kmc_file.py | _open_for_ra | refresh-bio/KMC | python | def _open_for_ra():
' '
kmc_file = pka.KMCFile()
assert kmc_file.OpenForRA('kmc_db')
return kmc_file |
def test_info(create_kmc_db):
'\n Test if some fields in object returned from Info are set properly.\n\n '
pattern = create_kmc_db
kmc_file = _open_for_listing()
info = kmc_file.Info()
assert (info.kmer_length == pattern['kmer_len'])
assert (info.mode == 0)
assert (info.counter_size ==... | -3,972,196,797,885,729,000 | Test if some fields in object returned from Info are set properly. | tests/py_kmc_api/test_py_kmc_file.py | test_info | refresh-bio/KMC | python | def test_info(create_kmc_db):
'\n \n\n '
pattern = create_kmc_db
kmc_file = _open_for_listing()
info = kmc_file.Info()
assert (info.kmer_length == pattern['kmer_len'])
assert (info.mode == 0)
assert (info.counter_size == 1)
assert (info.signature_len == pattern['sig_len'])
asse... |
def test_kmc_file_next_kmer(create_kmc_db):
' Test if all counted k-mers are returned by KMC API using NextKmer method. '
pattern = create_kmc_db['kmers']
kmc_file = _open_for_listing()
counter = pka.Count()
kmer = pka.KmerAPI(create_kmc_db['kmer_len'])
res = {}
while kmc_file.ReadNextKmer(k... | -5,991,943,377,933,929,000 | Test if all counted k-mers are returned by KMC API using NextKmer method. | tests/py_kmc_api/test_py_kmc_file.py | test_kmc_file_next_kmer | refresh-bio/KMC | python | def test_kmc_file_next_kmer(create_kmc_db):
' '
pattern = create_kmc_db['kmers']
kmc_file = _open_for_listing()
counter = pka.Count()
kmer = pka.KmerAPI(create_kmc_db['kmer_len'])
res = {}
while kmc_file.ReadNextKmer(kmer, counter):
res[str(kmer)] = counter.value
assert (res == ... |
def test_get_counters_for_read(create_kmc_db):
' Test case for GetCountersForRead method of KMCFile. '
kmers = create_kmc_db['kmers']
read = 'GGCATTGCATGCAGTNNCAGTCATGCAGTCAGGCAGTCATGGCATGCGTAAACGACGATCAGTCATGGTCGAG'
pattern = []
kmer_len = create_kmc_db['kmer_len']
for i in range(0, ((len(read)... | -1,974,169,297,877,745,200 | Test case for GetCountersForRead method of KMCFile. | tests/py_kmc_api/test_py_kmc_file.py | test_get_counters_for_read | refresh-bio/KMC | python | def test_get_counters_for_read(create_kmc_db):
' '
kmers = create_kmc_db['kmers']
read = 'GGCATTGCATGCAGTNNCAGTCATGCAGTCAGGCAGTCATGGCATGCGTAAACGACGATCAGTCATGGTCGAG'
pattern = []
kmer_len = create_kmc_db['kmer_len']
for i in range(0, ((len(read) - kmer_len) + 1)):
kmer = read[i:(i + kmer... |
def test_check_kmer(create_kmc_db):
'\n Test case for CheckKmer method.\n\n Check if are k-mers from input are present in the database and\n if some not present in the input are absent in the output.\n '
kmers = create_kmc_db['kmers']
kmer_len = create_kmc_db['kmer_len']
kmer = pka.KmerAPI(k... | -785,399,526,982,835,100 | Test case for CheckKmer method.
Check if are k-mers from input are present in the database and
if some not present in the input are absent in the output. | tests/py_kmc_api/test_py_kmc_file.py | test_check_kmer | refresh-bio/KMC | python | def test_check_kmer(create_kmc_db):
'\n Test case for CheckKmer method.\n\n Check if are k-mers from input are present in the database and\n if some not present in the input are absent in the output.\n '
kmers = create_kmc_db['kmers']
kmer_len = create_kmc_db['kmer_len']
kmer = pka.KmerAPI(k... |
def increment_kmer(kmer, start):
' Increments k-mer to next lexographical.\n\n Start from pos :start: (from end, i.e. start = 0 means last k-mer symbol). '
def replace_char(string, pos, new_char):
' Create new string with character at :pos: changed to :new_char:. '
if (pos < 0):
... | -6,267,665,744,541,755,000 | Increments k-mer to next lexographical.
Start from pos :start: (from end, i.e. start = 0 means last k-mer symbol). | tests/py_kmc_api/test_py_kmc_file.py | increment_kmer | refresh-bio/KMC | python | def increment_kmer(kmer, start):
' Increments k-mer to next lexographical.\n\n Start from pos :start: (from end, i.e. start = 0 means last k-mer symbol). '
def replace_char(string, pos, new_char):
' Create new string with character at :pos: changed to :new_char:. '
if (pos < 0):
... |
def replace_char(string, pos, new_char):
' Create new string with character at :pos: changed to :new_char:. '
if (pos < 0):
pos = (len(string) + pos)
return ((string[:pos] + new_char) + string[(pos + 1):]) | -4,285,610,178,083,164,000 | Create new string with character at :pos: changed to :new_char:. | tests/py_kmc_api/test_py_kmc_file.py | replace_char | refresh-bio/KMC | python | def replace_char(string, pos, new_char):
' '
if (pos < 0):
pos = (len(string) + pos)
return ((string[:pos] + new_char) + string[(pos + 1):]) |
def leakyrelu(x, leak=0.01):
'\n leakyrelu激活函数\n Args:\n x (Tensor): input\n leak (int): x<0时的斜率\n\n Returns:\n Tensor\n '
f1 = (0.5 * (1 + leak))
f2 = (0.5 * (1 - leak))
return ((f1 * x) + (f2 * tf.abs(x))) | 6,906,050,861,386,286,000 | leakyrelu激活函数
Args:
x (Tensor): input
leak (int): x<0时的斜率
Returns:
Tensor | algorithm/BST/leakyrelu.py | leakyrelu | tangxyw/RecAlgorithm | python | def leakyrelu(x, leak=0.01):
'\n leakyrelu激活函数\n Args:\n x (Tensor): input\n leak (int): x<0时的斜率\n\n Returns:\n Tensor\n '
f1 = (0.5 * (1 + leak))
f2 = (0.5 * (1 - leak))
return ((f1 * x) + (f2 * tf.abs(x))) |
def read_novel_info(self):
'Get novel title, autor, cover etc'
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup((self.novel_url + '?waring=1'))
self.novel_title = soup.find('div', {'class': 'manga-detail'}).find('h1').text
logger.info('Novel title: %s', self.novel_title)
self.nov... | -1,875,111,746,532,289,300 | Get novel title, autor, cover etc | sources/novelall.py | read_novel_info | BorgSquared/lightnovel-crawler | python | def read_novel_info(self):
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup((self.novel_url + '?waring=1'))
self.novel_title = soup.find('div', {'class': 'manga-detail'}).find('h1').text
logger.info('Novel title: %s', self.novel_title)
self.novel_cover = self.absolute_url(soup.f... |
def download_chapter_body(self, chapter):
'Download body of a single chapter and return as clean html format.'
logger.info('Downloading %s', chapter['url'])
soup = self.get_soup(chapter['url'])
contents = soup.find('div', {'class': 'reading-box'})
self.clean_contents(contents)
return str(content... | 2,756,602,651,324,911,000 | Download body of a single chapter and return as clean html format. | sources/novelall.py | download_chapter_body | BorgSquared/lightnovel-crawler | python | def download_chapter_body(self, chapter):
logger.info('Downloading %s', chapter['url'])
soup = self.get_soup(chapter['url'])
contents = soup.find('div', {'class': 'reading-box'})
self.clean_contents(contents)
return str(contents) |
def create_url_search(self, parameters):
'Creates the search url, combining the standard url and various\n search parameters.'
url = self.standard
url += parameters[0]
for i in parameters[1:]:
url += '&{}'.format(i)
url += '&apikey={}'.format(self.key_api)
return url | -7,296,441,941,738,629,000 | Creates the search url, combining the standard url and various
search parameters. | src/arcas/IEEE/main.py | create_url_search | ArcasProject/Arcas | python | def create_url_search(self, parameters):
'Creates the search url, combining the standard url and various\n search parameters.'
url = self.standard
url += parameters[0]
for i in parameters[1:]:
url += '&{}'.format(i)
url += '&apikey={}'.format(self.key_api)
return url |
@staticmethod
@ratelimit.rate_limited(3)
def make_request(url):
'Request from an API and returns response.'
response = requests.get(url, stream=True, verify=False)
if (response.status_code != 200):
raise APIError(response.status_code)
return response | 2,011,241,343,862,152,700 | Request from an API and returns response. | src/arcas/IEEE/main.py | make_request | ArcasProject/Arcas | python | @staticmethod
@ratelimit.rate_limited(3)
def make_request(url):
response = requests.get(url, stream=True, verify=False)
if (response.status_code != 200):
raise APIError(response.status_code)
return response |
def to_dataframe(self, raw_article):
'A function which takes a dictionary with structure of the IEEE\n results and transform it to a standardized format.\n '
raw_article['url'] = raw_article.get('html_url', None)
try:
raw_article['author'] = [author['full_name'] for author in raw_artic... | -7,890,503,207,656,345,000 | A function which takes a dictionary with structure of the IEEE
results and transform it to a standardized format. | src/arcas/IEEE/main.py | to_dataframe | ArcasProject/Arcas | python | def to_dataframe(self, raw_article):
'A function which takes a dictionary with structure of the IEEE\n results and transform it to a standardized format.\n '
raw_article['url'] = raw_article.get('html_url', None)
try:
raw_article['author'] = [author['full_name'] for author in raw_artic... |
def parse(self, root):
'Parsing the xml file'
if (root['total_records'] == 0):
return False
return root['articles'] | 7,165,902,714,162,163,000 | Parsing the xml file | src/arcas/IEEE/main.py | parse | ArcasProject/Arcas | python | def parse(self, root):
if (root['total_records'] == 0):
return False
return root['articles'] |
def parse_args():
'\n Parse input arguments\n '
parser = argparse.ArgumentParser(description='Generate txt result file')
parser.add_argument('--dir', dest='base_dir', help='result base dir', default='/home/hezheqi/data/frame/result', type=str)
parser.add_argument('--gt', dest='gt_dir', help='gt base d... | -3,541,902,435,000,393,000 | Parse input arguments | tools/eval_frame.py | parse_args | lz20061213/quadrilateral | python | def parse_args():
'\n \n '
parser = argparse.ArgumentParser(description='Generate txt result file')
parser.add_argument('--dir', dest='base_dir', help='result base dir', default='/home/hezheqi/data/frame/result', type=str)
parser.add_argument('--gt', dest='gt_dir', help='gt base dir', default='/data/h... |
def eval_one(results, gts, point_dis=False, rect_label=None):
'\n :param results:\n :param gts:\n :param point_dis:\n :param rect_label: use rectangle or not\n :return right_num, error_num, mid_num\n '
m = len(gts)
is_used = ([False] * m)
right_num = 0
err_num = 0
mid_num = 0
for res i... | 1,268,701,586,528,160,300 | :param results:
:param gts:
:param point_dis:
:param rect_label: use rectangle or not
:return right_num, error_num, mid_num | tools/eval_frame.py | eval_one | lz20061213/quadrilateral | python | def eval_one(results, gts, point_dis=False, rect_label=None):
'\n :param results:\n :param gts:\n :param point_dis:\n :param rect_label: use rectangle or not\n :return right_num, error_num, mid_num\n '
m = len(gts)
is_used = ([False] * m)
right_num = 0
err_num = 0
mid_num = 0
for res i... |
@property
def chat(self):
"\n Returns the :tl:`User`, :tl:`Chat` or :tl:`Channel` where this object\n belongs to. It may be ``None`` if Telegram didn't send the chat.\n\n If you're using `telethon.events`, use `get_chat` instead.\n "
return self._chat | -3,510,885,467,875,371,000 | Returns the :tl:`User`, :tl:`Chat` or :tl:`Channel` where this object
belongs to. It may be ``None`` if Telegram didn't send the chat.
If you're using `telethon.events`, use `get_chat` instead. | telethon/tl/custom/chatgetter.py | chat | bb010g/Telethon | python | @property
def chat(self):
"\n Returns the :tl:`User`, :tl:`Chat` or :tl:`Channel` where this object\n belongs to. It may be ``None`` if Telegram didn't send the chat.\n\n If you're using `telethon.events`, use `get_chat` instead.\n "
return self._chat |
async def get_chat(self):
"\n Returns `chat`, but will make an API call to find the\n chat unless it's already cached.\n "
if (((self._chat is None) or getattr(self._chat, 'min', None)) and (await self.get_input_chat())):
try:
self._chat = (await self._client.get_entity(... | 7,656,971,415,182,909,000 | Returns `chat`, but will make an API call to find the
chat unless it's already cached. | telethon/tl/custom/chatgetter.py | get_chat | bb010g/Telethon | python | async def get_chat(self):
"\n Returns `chat`, but will make an API call to find the\n chat unless it's already cached.\n "
if (((self._chat is None) or getattr(self._chat, 'min', None)) and (await self.get_input_chat())):
try:
self._chat = (await self._client.get_entity(... |
@property
def input_chat(self):
"\n This :tl:`InputPeer` is the input version of the chat where the\n message was sent. Similarly to `input_sender`, this doesn't have\n things like username or similar, but still useful in some cases.\n\n Note that this might not be available if the libra... | -8,939,400,300,496,340,000 | This :tl:`InputPeer` is the input version of the chat where the
message was sent. Similarly to `input_sender`, this doesn't have
things like username or similar, but still useful in some cases.
Note that this might not be available if the library doesn't
have enough information available. | telethon/tl/custom/chatgetter.py | input_chat | bb010g/Telethon | python | @property
def input_chat(self):
"\n This :tl:`InputPeer` is the input version of the chat where the\n message was sent. Similarly to `input_sender`, this doesn't have\n things like username or similar, but still useful in some cases.\n\n Note that this might not be available if the libra... |
async def get_input_chat(self):
"\n Returns `input_chat`, but will make an API call to find the\n input chat unless it's already cached.\n "
if ((self.input_chat is None) and self.chat_id and self._client):
try:
target = self.chat_id
async for d in self._clie... | -3,886,584,894,192,146,400 | Returns `input_chat`, but will make an API call to find the
input chat unless it's already cached. | telethon/tl/custom/chatgetter.py | get_input_chat | bb010g/Telethon | python | async def get_input_chat(self):
"\n Returns `input_chat`, but will make an API call to find the\n input chat unless it's already cached.\n "
if ((self.input_chat is None) and self.chat_id and self._client):
try:
target = self.chat_id
async for d in self._clie... |
@property
def chat_id(self):
'\n Returns the marked chat integer ID. Note that this value **will\n be different** from `to_id` for incoming private messages, since\n the chat *to* which the messages go is to your own person, but\n the *chat* itself is with the one who sent the message.\n... | 1,561,789,777,970,038,000 | Returns the marked chat integer ID. Note that this value **will
be different** from `to_id` for incoming private messages, since
the chat *to* which the messages go is to your own person, but
the *chat* itself is with the one who sent the message.
TL;DR; this gets the ID that you expect. | telethon/tl/custom/chatgetter.py | chat_id | bb010g/Telethon | python | @property
def chat_id(self):
'\n Returns the marked chat integer ID. Note that this value **will\n be different** from `to_id` for incoming private messages, since\n the chat *to* which the messages go is to your own person, but\n the *chat* itself is with the one who sent the message.\n... |
@property
def is_private(self):
'True if the message was sent as a private message.'
return isinstance(self._chat_peer, types.PeerUser) | 2,072,770,881,503,792,600 | True if the message was sent as a private message. | telethon/tl/custom/chatgetter.py | is_private | bb010g/Telethon | python | @property
def is_private(self):
return isinstance(self._chat_peer, types.PeerUser) |
@property
def is_group(self):
'True if the message was sent on a group or megagroup.'
if ((self._broadcast is None) and self.chat):
self._broadcast = getattr(self.chat, 'broadcast', None)
return (isinstance(self._chat_peer, (types.PeerChat, types.PeerChannel)) and (not self._broadcast)) | 8,039,516,671,244,592,000 | True if the message was sent on a group or megagroup. | telethon/tl/custom/chatgetter.py | is_group | bb010g/Telethon | python | @property
def is_group(self):
if ((self._broadcast is None) and self.chat):
self._broadcast = getattr(self.chat, 'broadcast', None)
return (isinstance(self._chat_peer, (types.PeerChat, types.PeerChannel)) and (not self._broadcast)) |
@property
def is_channel(self):
'True if the message was sent on a megagroup or channel.'
return isinstance(self._chat_peer, types.PeerChannel) | 2,578,293,180,495,241,700 | True if the message was sent on a megagroup or channel. | telethon/tl/custom/chatgetter.py | is_channel | bb010g/Telethon | python | @property
def is_channel(self):
return isinstance(self._chat_peer, types.PeerChannel) |
async def _refetch_chat(self):
'\n Re-fetches chat information through other means.\n ' | 4,903,209,581,249,528,000 | Re-fetches chat information through other means. | telethon/tl/custom/chatgetter.py | _refetch_chat | bb010g/Telethon | python | async def _refetch_chat(self):
'\n \n ' |
def est_fpos_rate(token, trace=None, stats=None):
"\n Estimate false positive rate of a single-token signature.\n \n Estimates using the 'tokensplit' and trace-modeling methods,\n and returns the higher (most pessimistic of the two). Note that both\n of these estimates are strictly equal to or higher... | -4,091,892,719,482,200,600 | Estimate false positive rate of a single-token signature.
Estimates using the 'tokensplit' and trace-modeling methods,
and returns the higher (most pessimistic of the two). Note that both
of these estimates are strictly equal to or higher than the actual
fraction of streams that 'token' occurs in within the trace. | polygraph/sig_gen/sig_gen.py | est_fpos_rate | hadisfr/Polygraph | python | def est_fpos_rate(token, trace=None, stats=None):
"\n Estimate false positive rate of a single-token signature.\n \n Estimates using the 'tokensplit' and trace-modeling methods,\n and returns the higher (most pessimistic of the two). Note that both\n of these estimates are strictly equal to or higher... |
def train(self, pos_samples):
'\n Generate one or more signatures from pos_samples (suspicious pool).\n Returns a sequence of Sig objects.\n '
raise NotImplementedError | 4,773,307,708,365,914,000 | Generate one or more signatures from pos_samples (suspicious pool).
Returns a sequence of Sig objects. | polygraph/sig_gen/sig_gen.py | train | hadisfr/Polygraph | python | def train(self, pos_samples):
'\n Generate one or more signatures from pos_samples (suspicious pool).\n Returns a sequence of Sig objects.\n '
raise NotImplementedError |
def match(self, sample):
'Return whether current signature matches the sample'
raise NotImplementedError | -4,908,549,882,155,932,000 | Return whether current signature matches the sample | polygraph/sig_gen/sig_gen.py | match | hadisfr/Polygraph | python | def match(self, sample):
raise NotImplementedError |
def runTest(self):
'This function will fetch added table under schema node.'
table_response = tables_utils.verify_table(self.server, self.db_name, self.table_id)
if (not table_response):
raise Exception('Could not find the table to update.')
if self.is_partition:
data = {'id': self.table... | -8,427,420,854,452,124,000 | This function will fetch added table under schema node. | pgAdmin4/pgAdmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/tests/test_table_put.py | runTest | Anillab/One-Minute-Pitch | python | def runTest(self):
table_response = tables_utils.verify_table(self.server, self.db_name, self.table_id)
if (not table_response):
raise Exception('Could not find the table to update.')
if self.is_partition:
data = {'id': self.table_id}
tables_utils.set_partition_data(self.server,... |
def dataset_parser(self, value):
'Parse an ImageNet record from a serialized string Tensor.'
keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, ''), 'image/format': tf.FixedLenFeature((), tf.string, 'jpeg'), 'image/class/label': tf.FixedLenFeature([], tf.int64, (- 1)), 'image/class/text': tf... | -2,487,874,934,583,650,000 | Parse an ImageNet record from a serialized string Tensor. | models/experimental/distribution_strategy/imagenet_input_keras.py | dataset_parser | aidangomez/tpu | python | def dataset_parser(self, value):
keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, ), 'image/format': tf.FixedLenFeature((), tf.string, 'jpeg'), 'image/class/label': tf.FixedLenFeature([], tf.int64, (- 1)), 'image/class/text': tf.FixedLenFeature([], tf.string, ), 'image/object/bbox/xmin': ... |
def input_fn(self):
'Input function which provides a single batch for train or eval.\n\n Returns:\n A `tf.data.Dataset` object.\n '
if (self.data_dir is None):
tf.logging.info('Using fake input.')
return self.input_fn_null()
file_pattern = os.path.join(self.data_dir, ('train-*' if... | -7,626,540,773,962,126,000 | Input function which provides a single batch for train or eval.
Returns:
A `tf.data.Dataset` object. | models/experimental/distribution_strategy/imagenet_input_keras.py | input_fn | aidangomez/tpu | python | def input_fn(self):
'Input function which provides a single batch for train or eval.\n\n Returns:\n A `tf.data.Dataset` object.\n '
if (self.data_dir is None):
tf.logging.info('Using fake input.')
return self.input_fn_null()
file_pattern = os.path.join(self.data_dir, ('train-*' if... |
def input_fn_null(self):
'Input function which provides null (black) images.'
dataset = tf.data.Dataset.range(1).repeat().map(self._get_null_input)
dataset = dataset.prefetch(self.batch_size)
dataset = dataset.batch(self.batch_size, drop_remainder=True)
dataset = dataset.prefetch(32)
tf.logging.... | -9,042,925,970,187,984,000 | Input function which provides null (black) images. | models/experimental/distribution_strategy/imagenet_input_keras.py | input_fn_null | aidangomez/tpu | python | def input_fn_null(self):
dataset = tf.data.Dataset.range(1).repeat().map(self._get_null_input)
dataset = dataset.prefetch(self.batch_size)
dataset = dataset.batch(self.batch_size, drop_remainder=True)
dataset = dataset.prefetch(32)
tf.logging.info('Input dataset: %s', str(dataset))
return d... |
def retrieval_fall_out(preds: Tensor, target: Tensor, k: Optional[int]=None) -> Tensor:
'Computes the Fall-out (for information retrieval), as explained in `IR Fall-out`_ Fall-out is the fraction\n of non-relevant documents retrieved among all the non-relevant documents.\n\n ``preds`` and ``target`` should be... | 6,820,039,520,958,153,000 | Computes the Fall-out (for information retrieval), as explained in `IR Fall-out`_ Fall-out is the fraction
of non-relevant documents retrieved among all the non-relevant documents.
``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``,
``0`` is returned. ``targe... | torchmetrics/functional/retrieval/fall_out.py | retrieval_fall_out | Abdelrhman-Hosny/metrics | python | def retrieval_fall_out(preds: Tensor, target: Tensor, k: Optional[int]=None) -> Tensor:
'Computes the Fall-out (for information retrieval), as explained in `IR Fall-out`_ Fall-out is the fraction\n of non-relevant documents retrieved among all the non-relevant documents.\n\n ``preds`` and ``target`` should be... |
def index(request):
'\n Return landing page\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Rendered home (index) page\n '
return render(request, 'webservice/index.html', {'demo_input_repo_name': DEMO_REPO_INPUT_NAME, 'supported_languages': sorted([lang.capitalize() for lang... | 2,300,159,280,462,162,700 | Return landing page
arguments:
:request: GET HTTP request
returns:
Rendered home (index) page | webserver/pkgpkr/webservice/views.py | index | pkgpkr/Package-Picker | python | def index(request):
'\n Return landing page\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Rendered home (index) page\n '
return render(request, 'webservice/index.html', {'demo_input_repo_name': DEMO_REPO_INPUT_NAME, 'supported_languages': sorted([lang.capitalize() for lang... |
def about(request):
'\n Return about info\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Rendered about page\n '
return render(request, 'webservice/about.html') | 1,604,955,779,372,363,300 | Return about info
arguments:
:request: GET HTTP request
returns:
Rendered about page | webserver/pkgpkr/webservice/views.py | about | pkgpkr/Package-Picker | python | def about(request):
'\n Return about info\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Rendered about page\n '
return render(request, 'webservice/about.html') |
def login(request):
' Log user in using GitHub OAuth\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Redirects to index\n '
if (not request.session.get('github_token')):
request.session['github_token'] = None
request.session['github_info'] = None
if (os.envi... | 1,179,897,966,924,708,600 | Log user in using GitHub OAuth
arguments:
:request: GET HTTP request
returns:
Redirects to index | webserver/pkgpkr/webservice/views.py | login | pkgpkr/Package-Picker | python | def login(request):
' Log user in using GitHub OAuth\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Redirects to index\n '
if (not request.session.get('github_token')):
request.session['github_token'] = None
request.session['github_info'] = None
if (os.envi... |
def callback(request):
'\n GitHub redirect here, then retrieves token for API\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Redirects to index\n '
code = request.GET.get('code')
payload = {'client_id': GITHUB_CLIENT_ID, 'client_secret': GITHUB_CLIENT_SECRET, 'code': co... | -6,453,799,905,267,306,000 | GitHub redirect here, then retrieves token for API
arguments:
:request: GET HTTP request
returns:
Redirects to index | webserver/pkgpkr/webservice/views.py | callback | pkgpkr/Package-Picker | python | def callback(request):
'\n GitHub redirect here, then retrieves token for API\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Redirects to index\n '
code = request.GET.get('code')
payload = {'client_id': GITHUB_CLIENT_ID, 'client_secret': GITHUB_CLIENT_SECRET, 'code': co... |
def logout(request):
'\n Logs user out but keep authorization ot OAuth GitHub\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Redirects to index\n '
request.session['github_token'] = None
request.session['github_info'] = None
return HttpResponseRedirect(reverse('inde... | -1,557,519,377,283,205,400 | Logs user out but keep authorization ot OAuth GitHub
arguments:
:request: GET HTTP request
returns:
Redirects to index | webserver/pkgpkr/webservice/views.py | logout | pkgpkr/Package-Picker | python | def logout(request):
'\n Logs user out but keep authorization ot OAuth GitHub\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Redirects to index\n '
request.session['github_token'] = None
request.session['github_info'] = None
return HttpResponseRedirect(reverse('inde... |
def repositories(request):
'\n Get full list (up to 100) for the current user\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Rendered repositories page\n '
if (not request.session.get('github_token')):
return HttpResponseRedirect(reverse('index'))
repos_per_lang... | 4,976,217,205,767,315,000 | Get full list (up to 100) for the current user
arguments:
:request: GET HTTP request
returns:
Rendered repositories page | webserver/pkgpkr/webservice/views.py | repositories | pkgpkr/Package-Picker | python | def repositories(request):
'\n Get full list (up to 100) for the current user\n\n arguments:\n :request: GET HTTP request\n\n returns:\n Rendered repositories page\n '
if (not request.session.get('github_token')):
return HttpResponseRedirect(reverse('index'))
repos_per_lang... |
def recommendations(request, name):
'\n Get recommended packages for the repo\n\n arguments:\n :request: GET/POST HTTP request\n :name: repo name\n\n returns:\n Rendered recommendation page\n '
repo_name = urllib.parse.unquote_plus(name)
if (request.method == 'POST'):
... | -4,413,514,821,107,826,700 | Get recommended packages for the repo
arguments:
:request: GET/POST HTTP request
:name: repo name
returns:
Rendered recommendation page | webserver/pkgpkr/webservice/views.py | recommendations | pkgpkr/Package-Picker | python | def recommendations(request, name):
'\n Get recommended packages for the repo\n\n arguments:\n :request: GET/POST HTTP request\n :name: repo name\n\n returns:\n Rendered recommendation page\n '
repo_name = urllib.parse.unquote_plus(name)
if (request.method == 'POST'):
... |
def recommendations_json(request, name):
'\n Get recommended packages for the repo in JSON format\n\n arguments:\n :request: GET HTTP request\n :name: repo name\n\n returns:\n JSON object with recommendations\n '
repo_name = urllib.parse.unquote_plus(name)
if (name == DEMO_R... | 2,116,296,651,441,857,800 | Get recommended packages for the repo in JSON format
arguments:
:request: GET HTTP request
:name: repo name
returns:
JSON object with recommendations | webserver/pkgpkr/webservice/views.py | recommendations_json | pkgpkr/Package-Picker | python | def recommendations_json(request, name):
'\n Get recommended packages for the repo in JSON format\n\n arguments:\n :request: GET HTTP request\n :name: repo name\n\n returns:\n JSON object with recommendations\n '
repo_name = urllib.parse.unquote_plus(name)
if (name == DEMO_R... |
@csrf_exempt
def recommendations_service_api(request):
'\n Returns package recommendations for API POST call without authentication\n\n arguments:\n :request: POST request of application/json type\n\n returns:\n list of package recommendations\n '
if (request.method == 'POST'):
... | 6,866,179,884,337,457,000 | Returns package recommendations for API POST call without authentication
arguments:
:request: POST request of application/json type
returns:
list of package recommendations | webserver/pkgpkr/webservice/views.py | recommendations_service_api | pkgpkr/Package-Picker | python | @csrf_exempt
def recommendations_service_api(request):
'\n Returns package recommendations for API POST call without authentication\n\n arguments:\n :request: POST request of application/json type\n\n returns:\n list of package recommendations\n '
if (request.method == 'POST'):
... |
def _get_modifiable_indices(self, current_text):
' \n Returns the word indices in ``current_text`` which are able to be modified.\n '
non_stopword_indices = set()
for (i, word) in enumerate(current_text.words):
if (word not in self.stopwords):
non_stopword_indices.add(i)
... | -7,270,054,439,923,210,000 | Returns the word indices in ``current_text`` which are able to be modified. | textattack/constraints/pre_transformation/stopword_modification.py | _get_modifiable_indices | fighting41love/TextAttack | python | def _get_modifiable_indices(self, current_text):
' \n \n '
non_stopword_indices = set()
for (i, word) in enumerate(current_text.words):
if (word not in self.stopwords):
non_stopword_indices.add(i)
return non_stopword_indices |
def check_compatibility(self, transformation):
' \n The stopword constraint only is concerned with word swaps since paraphrasing phrases\n containing stopwords is OK.\n\n Args:\n transformation: The ``Transformation`` to check compatibility with.\n '
return transformation_... | -5,874,091,402,889,851,000 | The stopword constraint only is concerned with word swaps since paraphrasing phrases
containing stopwords is OK.
Args:
transformation: The ``Transformation`` to check compatibility with. | textattack/constraints/pre_transformation/stopword_modification.py | check_compatibility | fighting41love/TextAttack | python | def check_compatibility(self, transformation):
' \n The stopword constraint only is concerned with word swaps since paraphrasing phrases\n containing stopwords is OK.\n\n Args:\n transformation: The ``Transformation`` to check compatibility with.\n '
return transformation_... |
def link_iterable_by_fields(unlinked, other=None, fields=None, kind=None, internal=False, relink=False):
'Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``.\n\n The database to be linked must have uniqueness for each object for the given ``fields``.\n\n If ``kind... | 2,774,126,575,220,764,000 | Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``.
The database to be linked must have uniqueness for each object for the given ``fields``.
If ``kind``, limit objects in ``unlinked`` of type ``kind``.
If ``relink``, link to objects which already have an ``input``. Other... | bw2io/strategies/generic.py | link_iterable_by_fields | pjamesjoyce/brightway2-io | python | def link_iterable_by_fields(unlinked, other=None, fields=None, kind=None, internal=False, relink=False):
'Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``.\n\n The database to be linked must have uniqueness for each object for the given ``fields``.\n\n If ``kind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.