uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3af766bde89a2fb8ba51b127 | train | class | class ModelBasedEvaluator(BaseEvaluator):
def __init__(self, params_file, finetunee_script, options_str=""):
super(ModelBasedEvaluator, self).__init__(
params_file, finetunee_script, options_str=options_str)
self.half_best_model_path = []
self.run_count = 0
def run(self, *ar... | class ModelBasedEvaluator(BaseEvaluator):
| def __init__(self, params_file, finetunee_script, options_str=""):
super(ModelBasedEvaluator, self).__init__(
params_file, finetunee_script, options_str=options_str)
self.half_best_model_path = []
self.run_count = 0
def run(self, *args):
params = args[0][0]
n... | export CUDA_VISIBLE_DEVICES=%s; python -u %s --saved_params_dir=%s %s %s >%s 2>&1" % \
(num_cuda, self.finetunee_script, saved_params_dir, param_str, self.options_str, log_file)
try:
os.system(run_cmd)
with open(log_file, "r") as f:
lines = f.readline... | 249 | 249 | 833 | 7 | 241 | MRXLT/PaddleHub | paddlehub/autofinetune/evaluator.py | Python | ModelBasedEvaluator | ModelBasedEvaluator | 160 | 234 | 160 | 160 | 5ebb39214b1272ae7bf4b3aec59c5ab9b83881d0 | bigcode/the-stack | train |
eef7e67b551f020dfcae7afd | train | class | class FullTrailEvaluator(BaseEvaluator):
def __init__(self, params_file, finetunee_script, options_str=""):
super(FullTrailEvaluator, self).__init__(
params_file, finetunee_script, options_str=options_str)
def run(self, *args):
params = args[0][0]
num_cuda = args[0][1]
... | class FullTrailEvaluator(BaseEvaluator):
| def __init__(self, params_file, finetunee_script, options_str=""):
super(FullTrailEvaluator, self).__init__(
params_file, finetunee_script, options_str=options_str)
def run(self, *args):
params = args[0][0]
num_cuda = args[0][1]
saved_params_dir = args[0][2]
... |
if cparams[i] >= 1.0:
cparams[i] = 1.0
return cparams
def format_params_str(self, params):
param_str = "--%s=%s" % (self.params["param_list"][0]["name"],
params[0])
for i in range(1, len(self.params["param_list"])):
p... | 148 | 148 | 494 | 7 | 140 | MRXLT/PaddleHub | paddlehub/autofinetune/evaluator.py | Python | FullTrailEvaluator | FullTrailEvaluator | 111 | 157 | 111 | 111 | 31b6ea8b8ebd7a655c80d691f78c3086e6946227 | bigcode/the-stack | train |
02766d67a9111d929ef488e3 | train | class | class OWSProviderCheck(ProviderCheck):
"""
Implementation of ProviderCheck for OWS (WMS, WMTS, WFS, WCS) providers.
"""
def __init__(self, *args, **kwargs):
"""
Initialize this OWSProviderCheck object with a service URL and layer.
:param service_url: URL of provider, if applicab... | class OWSProviderCheck(ProviderCheck):
| """
Implementation of ProviderCheck for OWS (WMS, WMTS, WFS, WCS) providers.
"""
def __init__(self, *args, **kwargs):
"""
Initialize this OWSProviderCheck object with a service URL and layer.
:param service_url: URL of provider, if applicable. Query string parameters are ignored... | (CheckResult.NOT_FOUND)
if not response.ok:
raise ProviderCheckError(CheckResult.UNAVAILABLE, status=response.status_code)
return response
except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout) as ex:
logger.error("Provider check timed... | 212 | 212 | 709 | 9 | 203 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | OWSProviderCheck | OWSProviderCheck | 357 | 430 | 357 | 357 | bfc6b5fca3abede53fe97e07327078e8a2ba27f9 | bigcode/the-stack | train |
b19939c204c2ce001cf0712f | train | class | class WCSProviderCheck(OWSProviderCheck):
"""
Implementation of OWSProviderCheck for WCS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WCS"
def find_layer(self, root) -> Union[CheckResult, List[str]... | class WCSProviderCheck(OWSProviderCheck):
| """
Implementation of OWSProviderCheck for WCS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WCS"
def find_layer(self, root) -> Union[CheckResult, List[str]]:
"""
:param root: Name o... | ^]]*\])?>", xml)
if doctype is not None:
doctype_pos = doctype.end()
xmll = xml[:doctype_pos] + xml[doctype_pos + 1 :].lower()
xmll = xmll.replace("![cdata[", "![CDATA[")
# Strip namespaces from tags (from http://bugs.python.org/issue18304)
... | 225 | 225 | 752 | 11 | 214 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | WCSProviderCheck | WCSProviderCheck | 433 | 511 | 433 | 433 | af1113057be27f73a936f643acafadb582c453a0 | bigcode/the-stack | train |
c89129cdf95cdbfb3974e912 | train | class | class CheckResult(Enum):
"""
Enum describing possible results of the provider check. Returns are in JSON format, with a status field
containing an error code, and a message field containing more detailed information. Status may be one of:
TIMEOUT - The connection timed out (requests.get raised Conne... | class CheckResult(Enum):
| """
Enum describing possible results of the provider check. Returns are in JSON format, with a status field
containing an error code, and a message field containing more detailed information. Status may be one of:
TIMEOUT - The connection timed out (requests.get raised ConnectionTimeout)
CON... | # -*- coding: utf-8 -*-
import base64
import json
import logging
import re
import xml.etree.ElementTree as ET
from enum import Enum
from io import StringIO
from typing import Type, Union, Optional, List
import requests
import yaml
from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry, Polyg... | 165 | 253 | 844 | 5 | 159 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | CheckResult | CheckResult | 29 | 124 | 29 | 29 | 1c94703ca63096ef998e92e31357e9058d7bb039 | bigcode/the-stack | train |
bfefe419f7a9f673f2f8fab5 | train | class | class WMSProviderCheck(OWSProviderCheck):
"""
Implementation of OWSProviderCheck for WMS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WMS"
# 1.3.0 will work as well, if that's returned. 1.0.0 i... | class WMSProviderCheck(OWSProviderCheck):
| """
Implementation of OWSProviderCheck for WMS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WMS"
# 1.3.0 will work as well, if that's returned. 1.0.0 isn't widely supported.
self.query[... |
feature_names = [(ft, ft.find("name")) for ft in feature_types]
logger.debug("WFS layers offered: {}".format([name.text for feature, name in feature_names if name]))
features = [feature for feature, name in feature_names if name is not None and self.layer == name.text]
if not features:... | 179 | 179 | 597 | 11 | 167 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | WMSProviderCheck | WMSProviderCheck | 556 | 626 | 556 | 556 | 400f6e1ab50147b947b692b80c59e22bbcc56383 | bigcode/the-stack | train |
aa5f01c68735d0e9a56ae1e4 | train | class | class FileProviderCheck(ProviderCheck):
"""
Implementation of ProviderCheck for geospatial file providers.
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def get_provider_response(self) -> requests.Response:
"""
Sends a HEAD r... | class FileProviderCheck(ProviderCheck):
| """
Implementation of ProviderCheck for geospatial file providers.
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def get_provider_response(self) -> requests.Response:
"""
Sends a HEAD request to the provided service URL retur... | _ERROR)
if layer_name is None:
raise ProviderCheckError(CheckResult.LAYER_NOT_AVAILABLE)
layer_name = layer_name.lower()
return layer_name
class TMSProviderCheck(ProviderCheck):
def __init__(self, service_url, *args, **kwargs):
super(TMSProviderCheck, self).__init__(s... | 108 | 108 | 360 | 8 | 100 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | FileProviderCheck | FileProviderCheck | 704 | 747 | 704 | 704 | 6c7ea0d6aa356e741fb7e6ee36576595ecb871b6 | bigcode/the-stack | train |
8e95d66605938b9f4ace7aea | train | function | def perform_provider_check(provider: DataProvider, geojson: dict) -> dict:
try:
provider_type = str(provider.export_provider_type)
url = str(provider.url)
if url == "" and "osm" in provider_type:
url = settings.OVERPASS_API_URL
provider_checker = get_provider_checker(pr... | def perform_provider_check(provider: DataProvider, geojson: dict) -> dict:
| try:
provider_type = str(provider.export_provider_type)
url = str(provider.url)
if url == "" and "osm" in provider_type:
url = settings.OVERPASS_API_URL
provider_checker = get_provider_checker(provider_type)
conf = yaml.safe_load(provider.config) or dict()
... | type.
:param type_slug: String describing provider type
:return: Checker for given provider type
"""
try:
return PROVIDER_CHECK_MAP[type_slug]
except KeyError:
return ProviderCheck
def perform_provider_check(provider: DataProvider, geojson: dict) -> dict:
| 64 | 64 | 203 | 17 | 46 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | perform_provider_check | perform_provider_check | 827 | 854 | 827 | 827 | 7697a546271e6e4eec32f554cbe7ffc17cfb4e78 | bigcode/the-stack | train |
71de41b741bfee54fa68649a | train | class | class WMTSProviderCheck(OWSProviderCheck):
"""
Implementation of OWSProviderCheck for WMS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WMTS"
def find_layer(self, root):
"""
:param r... | class WMTSProviderCheck(OWSProviderCheck):
| """
Implementation of OWSProviderCheck for WMS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WMTS"
def find_layer(self, root):
"""
:param root: Name of layer to find
:return:... | .findtext(point)) for point in points]
return bbox
def get_layer_name(self):
try:
layer_name = (
self.config.get("sources", {})
.get("default", {})
.get("req", {})
.get("layers") # TODO: Can there be more than one lay... | 152 | 152 | 509 | 11 | 140 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | WMTSProviderCheck | WMTSProviderCheck | 629 | 695 | 629 | 629 | b9f6a818ddb0f9b4967b66b6d08194d35c14509d | bigcode/the-stack | train |
ff4f9d49b705de414322e913 | train | class | class ProviderCheckError(Exception):
def __init__(self, check_result: CheckResult = None, *args, **kwargs):
if check_result:
self.status_result = ProviderCheck.get_status_result(check_result=check_result, **kwargs)
self.message = self.status_result["message"]
super().__init__... | class ProviderCheckError(Exception):
| def __init__(self, check_result: CheckResult = None, *args, **kwargs):
if check_result:
self.status_result = ProviderCheck.get_status_result(check_result=check_result, **kwargs)
self.message = self.status_result["message"]
super().__init__(*args, **kwargs)
| )
response = ProviderCheck.get_status_result(CheckResult.UNKNOWN_ERROR)
if provider:
logger.info(f"An exception occurred while checking the {provider.name} provider: {e}")
logger.info(f"Status of provider '{provider.name}': {response}")
return response
class ProviderCheckErr... | 64 | 64 | 71 | 6 | 57 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | ProviderCheckError | ProviderCheckError | 857 | 862 | 857 | 857 | 2d2dd62fae4c2b1070d48ae71a201c35aa7df6e4 | bigcode/the-stack | train |
8e4ff3055da70a1a750275ff | train | class | class OGCProviderCheck(ProviderCheck):
"""
Implementation of ProviderCheck for geospatial file providers.
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def get_provider_response(self):
"""
Sends a HEAD request to the provided... | class OGCProviderCheck(ProviderCheck):
| """
Implementation of ProviderCheck for geospatial file providers.
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def get_provider_response(self):
"""
Sends a HEAD request to the provided service URL returns its response if th... | {}".format(self.service_url, str(ex)))
raise ProviderCheckError(CheckResult.SSL_EXCEPTION)
except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema) as ex:
logger.error("Provider check failed for URL {}: {}".format(self.service_url, str(ex)))
raise Pro... | 114 | 114 | 383 | 9 | 105 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | OGCProviderCheck | OGCProviderCheck | 750 | 795 | 750 | 750 | 31171f546a854a750792bcee2f28d773d15e8d4c | bigcode/the-stack | train |
78686ffdbab9e9ff13590c81 | train | class | class OverpassProviderCheck(ProviderCheck):
"""
Implementation of ProviderCheck for Overpass providers.
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def get_provider_response(self) -> requests.Response:
"""
Sends a POST requ... | class OverpassProviderCheck(ProviderCheck):
| """
Implementation of ProviderCheck for Overpass providers.
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def get_provider_response(self) -> requests.Response:
"""
Sends a POST request for metadata to Overpass URL and returns... | cache.get_or_set(
self.get_cache_key(), lambda: self.get_provider_response(), timeout=DEFAULT_CACHE_TIMEOUT
)
if not self.validate_response(response):
raise ProviderCheckError(CheckResult.UNKNOWN_ERROR)
cache.set(status_check_cache_key, status, time... | 125 | 125 | 419 | 9 | 115 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | OverpassProviderCheck | OverpassProviderCheck | 304 | 354 | 304 | 304 | a018c3b2855103f68b4a1205b583ad0cef3e4d38 | bigcode/the-stack | train |
eb7f94aae3fc02fb9eb3c1a9 | train | class | class ProviderCheck(object):
"""
During the second stage of creating a datapack, each available data provider is pinged to apprise the user
of its availability. This class and its subclasses contain methods to ping OWS and Overpass servers, and determine:
* Whether they are online
* Whether ... | class ProviderCheck(object):
| """
During the second stage of creating a datapack, each available data provider is pinged to apprise the user
of its availability. This class and its subclasses contain methods to ping OWS and Overpass servers, and determine:
* Whether they are online
* Whether authorization is required
... | may occur when creating the DataPack."
),
}
LAYER_NOT_AVAILABLE = {
"status": "WARN",
"type": "LAYER_NOT_AVAILABLE",
"message": _("This data provider does not offer the requested layer."),
}
NO_INTERSECT = {
"status": "WARN",
"type": "NO_INTERSECT",
... | 256 | 256 | 1,444 | 5 | 251 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | ProviderCheck | ProviderCheck | 127 | 301 | 127 | 127 | 490339780df2332ed0d6c59a47829eacc6b8ac83 | bigcode/the-stack | train |
63af88245893483818cce94e | train | function | def get_provider_checker(type_slug) -> Type[ProviderCheck]:
"""
Given a string describing a provider type, return a reference to the class appropriate for checking the status
of a provider of that type.
:param type_slug: String describing provider type
:return: Checker for given provider type
""... | def get_provider_checker(type_slug) -> Type[ProviderCheck]:
| """
Given a string describing a provider type, return a reference to the class appropriate for checking the status
of a provider of that type.
:param type_slug: String describing provider type
:return: Checker for given provider type
"""
try:
return PROVIDER_CHECK_MAP[type_slug]
... | "arcgis-feature": ProviderCheck,
"tms": TMSProviderCheck,
"vector-file": FileProviderCheck,
"raster-file": FileProviderCheck,
"ogcapi-process": OGCProviderCheck,
}
def get_provider_checker(type_slug) -> Type[ProviderCheck]:
| 64 | 64 | 89 | 13 | 51 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | get_provider_checker | get_provider_checker | 814 | 824 | 814 | 814 | 2acfb916b18c6b36fe3f0e53204d43429176383b | bigcode/the-stack | train |
fd1eec533ba2472dea071558 | train | class | class TMSProviderCheck(ProviderCheck):
def __init__(self, service_url, *args, **kwargs):
super(TMSProviderCheck, self).__init__(service_url, *args, **kwargs)
self.service_url = self.service_url.format(z="0", y="0", x="0")
| class TMSProviderCheck(ProviderCheck):
| def __init__(self, service_url, *args, **kwargs):
super(TMSProviderCheck, self).__init__(service_url, *args, **kwargs)
self.service_url = self.service_url.format(z="0", y="0", x="0")
| logger.error("Unable to get layer name from provider configuration.")
raise ProviderCheckError(CheckResult.UNKNOWN_ERROR)
if layer_name is None:
raise ProviderCheckError(CheckResult.LAYER_NOT_AVAILABLE)
layer_name = layer_name.lower()
return layer_name
class... | 64 | 64 | 66 | 9 | 54 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | TMSProviderCheck | TMSProviderCheck | 698 | 701 | 698 | 698 | 16c2ce4603a210551c7a9046dd08fc5c02cb62bd | bigcode/the-stack | train |
a01473e1d89a9d651882e30d | train | class | class WFSProviderCheck(OWSProviderCheck):
"""
Implementation of OWSProviderCheck for WFS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WFS"
def find_layer(self, root):
"""
:param roo... | class WFSProviderCheck(OWSProviderCheck):
| """
Implementation of OWSProviderCheck for WFS providers
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.query["SERVICE"] = "WFS"
def find_layer(self, root):
"""
:param root: Name of layer to find
:return: ... | , miny, maxx, maxy] = {}".format(str(box)))
minx, miny, maxx, maxy = box
bbox = Polygon.from_bbox((minx, miny, maxx, maxy))
if not (self.aoi is not None and not self.aoi.intersects(bbox)):
return
raise ProviderCheckError(CheckResult.NO_INTERSECT)
class WFSPr... | 96 | 96 | 321 | 11 | 85 | sandhillgeo/eventkit-cloud | eventkit_cloud/utils/provider_check.py | Python | WFSProviderCheck | WFSProviderCheck | 514 | 553 | 514 | 514 | 34d90aae39fd2191144ba114ece6fa4d358abd73 | bigcode/the-stack | train |
38ba53f93d8376e8bb4fbb8c | train | class | class DigMontage(object):
"""Montage for digitized electrode and headshape position data.
.. warning:: Montages are typically loaded from a file using
:func:`read_dig_montage` instead of instantiating
this class.
Parameters
----------
hsp : array, shape (n_points,... | class DigMontage(object):
| """Montage for digitized electrode and headshape position data.
.. warning:: Montages are typically loaded from a file using
:func:`read_dig_montage` instead of instantiating
this class.
Parameters
----------
hsp : array, shape (n_points, 3)
The positions ... | coordinate "
"system. Either add the points, or read the "
"montage with transform=False. " % missing)
nasion = pos[names_lower.index(fids[0])]
lpa = pos[names_lower.index(fids[1])]
rpa = pos[names_lower.index(fids[2])]
neuromag... | 256 | 256 | 1,612 | 6 | 250 | mvdoc/mne-python | mne/channels/montage.py | Python | DigMontage | DigMontage | 338 | 498 | 338 | 338 | 1ffc944d6e4fa9f33945157a0ea5172c5ee0a7b9 | bigcode/the-stack | train |
e3378e2275350d3210671b96 | train | function | def _check_frame(d, frame_str):
"""Helper to check coordinate frames."""
if d['coord_frame'] != _str_to_frame[frame_str]:
raise RuntimeError('dig point must be in %s coordinate frame, got %s'
% (frame_str, _frame_to_str[d['coord_frame']]))
| def _check_frame(d, frame_str):
| """Helper to check coordinate frames."""
if d['coord_frame'] != _str_to_frame[frame_str]:
raise RuntimeError('dig point must be in %s coordinate frame, got %s'
% (frame_str, _frame_to_str[d['coord_frame']]))
| ._get_dig())
_cardinal_ident_mapping = {
FIFF.FIFFV_POINT_NASION: 'nasion',
FIFF.FIFFV_POINT_LPA: 'lpa',
FIFF.FIFFV_POINT_RPA: 'rpa',
}
def _check_frame(d, frame_str):
| 64 | 64 | 68 | 9 | 55 | mvdoc/mne-python | mne/channels/montage.py | Python | _check_frame | _check_frame | 508 | 512 | 508 | 508 | 39d15f5a95dd8ea6c49b7dba2338471d28c3bc4f | bigcode/the-stack | train |
379e0ebe65afec0757a1c98a | train | function | def read_dig_montage(hsp=None, hpi=None, elp=None, point_names=None,
unit='auto', fif=None, transform=True, dev_head_t=False):
r"""Read subject-specific digitization montage from a file.
Parameters
----------
hsp : None | str | array, shape (n_points, 3)
If str, this corres... | def read_dig_montage(hsp=None, hpi=None, elp=None, point_names=None,
unit='auto', fif=None, transform=True, dev_head_t=False):
| r"""Read subject-specific digitization montage from a file.
Parameters
----------
hsp : None | str | array, shape (n_points, 3)
If str, this corresponds to the filename of the headshape points.
This is typically used with the Polhemus FastSCAN system.
If numpy.array, this corres... | .hsp, dig_ch_pos=self.dig_ch_pos)
def save(self, fname):
"""Save digitization points to FIF.
Parameters
----------
fname : str
The filename to use. Should end in .fif or .fif.gz.
"""
if self.coord_frame != 'head':
raise RuntimeError('Can only... | 255 | 256 | 1,679 | 39 | 216 | mvdoc/mne-python | mne/channels/montage.py | Python | read_dig_montage | read_dig_montage | 515 | 668 | 515 | 516 | c73bf8f5e322af8e6585d9634eafaece67d31a33 | bigcode/the-stack | train |
953b6cc857a88d2a92520376 | train | function | def _set_montage(info, montage, update_ch_names=False):
"""Apply montage to data.
With a Montage, this function will replace the EEG channel names and
locations with the values specified for the particular montage.
With a DigMontage, this function will replace the digitizer info with
the values sp... | def _set_montage(info, montage, update_ch_names=False):
| """Apply montage to data.
With a Montage, this function will replace the EEG channel names and
locations with the values specified for the particular montage.
With a DigMontage, this function will replace the digitizer info with
the values specified for the particular montage.
Usually, a mont... | m')
elif ext in ('.sqd', '.mrk'):
from ..io.kit import read_mrk
hpi = read_mrk(hpi)
else:
raise ValueError('HPI file with extension *%s is not '
'supported. Only *.txt, *.sqd and *.mrk are '
... | 256 | 256 | 954 | 15 | 240 | mvdoc/mne-python | mne/channels/montage.py | Python | _set_montage | _set_montage | 671 | 761 | 671 | 671 | 09a35aba3b364dd54e49d0f1e57e841955aef1df | bigcode/the-stack | train |
47645e440cea9768e94d1d52 | train | class | class Montage(object):
"""Montage for standard EEG electrode locations.
.. warning:: Montages should typically be loaded from a file using
:func:`mne.channels.read_montage` instead of
instantiating this class directly.
Parameters
----------
pos : array, shape (n_c... | class Montage(object):
| """Montage for standard EEG electrode locations.
.. warning:: Montages should typically be loaded from a file using
:func:`mne.channels.read_montage` instead of
instantiating this class directly.
Parameters
----------
pos : array, shape (n_channels, 3)
The... | _to_str)
from ..io.meas_info import (_make_dig_points, _read_dig_points, _read_dig_fif,
write_dig)
from ..io.pick import pick_types
from ..io.open import fiff_open
from ..io.constants import FIFF
from ..utils import _check_fname, warn, copy_function_doc_to_method_doc
from ..externals.six im... | 100 | 100 | 335 | 4 | 95 | mvdoc/mne-python | mne/channels/montage.py | Python | Montage | Montage | 33 | 77 | 33 | 33 | 26fe5b5e0ea371fa67a09bdf46fa9f883945e718 | bigcode/the-stack | train |
025721f8ad271cedcc730f58 | train | function | def read_montage(kind, ch_names=None, path=None, unit='m', transform=False):
"""Read a generic (built-in) montage.
Individualized (digitized) electrode positions should be
read in using :func:`read_dig_montage`.
In most cases, you should only need the `kind` parameter to load one of
the built-in m... | def read_montage(kind, ch_names=None, path=None, unit='m', transform=False):
| """Read a generic (built-in) montage.
Individualized (digitized) electrode positions should be
read in using :func:`read_dig_montage`.
In most cases, you should only need the `kind` parameter to load one of
the built-in montages (see Notes).
Parameters
----------
kind : str
Th... | of montage (e.g. 'standard_1005').
selection : array of int
The indices of the selected channels in the montage file.
See Also
--------
DigMontage
read_montage
read_dig_montage
Notes
-----
.. versionadded:: 0.9.0
"""
def __init__(self, pos, ch_names, kind, selecti... | 256 | 256 | 2,758 | 21 | 235 | mvdoc/mne-python | mne/channels/montage.py | Python | read_montage | read_montage | 80 | 335 | 80 | 80 | a894ba0724a0b79561b2c8c353fa4d4fac3c98e0 | bigcode/the-stack | train |
badac1aaa1fb3133800468dd | train | class | class AudioLanguageShallowMultiModel(AudioLanguageModel):
def __init__(self, model_cfg:AudioLanguageShallowMultiConfig, ad_cfg:AudioFeatureConfig, lm_cfg:LanguageFeatureConfig, label_cfg:LabelPreprocessConfig):
super(AudioLanguageShallowMultiModel, self).__init__(model_cfg, ad_cfg, lm_cfg, label_cfg)
... | class AudioLanguageShallowMultiModel(AudioLanguageModel):
| def __init__(self, model_cfg:AudioLanguageShallowMultiConfig, ad_cfg:AudioFeatureConfig, lm_cfg:LanguageFeatureConfig, label_cfg:LabelPreprocessConfig):
super(AudioLanguageShallowMultiModel, self).__init__(model_cfg, ad_cfg, lm_cfg, label_cfg)
## am type
self.am_concat_proj = model_cfg.am_c... | torch
from torch import nn
from dataclasses import _MISSING_TYPE, dataclass, field
from .ad_lm_model import AudioLanguageModel, AudioLanguageModelConfig
from src.dataset.audio_dataset import AudioFeatureConfig
from src.dataset.language_dataset import LanguageFeatureConfig
from src.process.label_preprocess import Label... | 256 | 256 | 2,097 | 11 | 244 | JoungheeKim/emotion_recognition | src/model/audio_lm_shallow_multi.py | Python | AudioLanguageShallowMultiModel | AudioLanguageShallowMultiModel | 32 | 234 | 32 | 32 | 40d4c54a2b1fd2a9287347420d7854699609050e | bigcode/the-stack | train |
ee3db77079052f2f11d3d25e | train | class | @dataclass
class AudioLanguageShallowMultiConfig(AudioLanguageModelConfig):
name:str = 'shallow_fusion_multi'
am_kernel_size: int = 3
lm_kernel_size: int = 3
hidden_dim: int = 20
final_dropout: float = 0.1
am_concat_proj:str=''
lm_concat_proj:str=''
am_last_hidden: bool = False
lm_la... | @dataclass
class AudioLanguageShallowMultiConfig(AudioLanguageModelConfig):
| name:str = 'shallow_fusion_multi'
am_kernel_size: int = 3
lm_kernel_size: int = 3
hidden_dim: int = 20
final_dropout: float = 0.1
am_concat_proj:str=''
lm_concat_proj:str=''
am_last_hidden: bool = False
lm_last_hidden: bool = False
multitune_start_step: int = 0
multitune_end_... | AudioLanguageModel, AudioLanguageModelConfig
from src.dataset.audio_dataset import AudioFeatureConfig
from src.dataset.language_dataset import LanguageFeatureConfig
from src.process.label_preprocess import LabelPreprocessConfig
from torch.nn import functional as F
@dataclass
class AudioLanguageShallowMultiConfig(Audio... | 64 | 64 | 168 | 15 | 48 | JoungheeKim/emotion_recognition | src/model/audio_lm_shallow_multi.py | Python | AudioLanguageShallowMultiConfig | AudioLanguageShallowMultiConfig | 13 | 29 | 13 | 14 | d3d391de1b04db1f4c8019a1e1fc6aeda3d7fa76 | bigcode/the-stack | train |
9b834ef5ef7db140bf094673 | train | function | def get_matrix(regions_filename, seq_files_data, end, repeat_amounts, threads):
# Make the matrices
with multiprocessing.Pool(threads) as pool:
args = []
for dataset in seq_files_data:
args.append(
[regions_filename, dataset, end, repeat_amounts]
)
... | def get_matrix(regions_filename, seq_files_data, end, repeat_amounts, threads):
# Make the matrices
| with multiprocessing.Pool(threads) as pool:
args = []
for dataset in seq_files_data:
args.append(
[regions_filename, dataset, end, repeat_amounts]
)
individual_matrices = pool.starmap(get_individual_matrix, args)
# Combine the matrices
combi... | _parameters, offset=1)
else:
ticks = None
generate_heatmap(matrix_filename, 'gray', output_filename, gamma, min_value, max_value, ticks=ticks)
def get_matrix(regions_filename, seq_files_data, end, repeat_amounts, threads):
# Make the matrices
| 64 | 64 | 114 | 25 | 39 | GeoffSCollins/PolTools | PolTools/main_programs/region_heatmap.py | Python | get_matrix | get_matrix | 86 | 103 | 86 | 87 | cce9b6d5b01ac343ace23bbe9be55ce8bc50b5c1 | bigcode/the-stack | train |
62499c43654fd420ac98728c | train | function | def get_original_matrix(regions_filename, sequencing_file, norm_factor, end):
# 1. Load the five_prime_dict
counts_dict = build_counts_dict(sequencing_file, end)
matrix = []
with open(regions_filename) as file:
for line in file:
if line.rstrip():
chromosome, left, r... | def get_original_matrix(regions_filename, sequencing_file, norm_factor, end):
# 1. Load the five_prime_dict
| counts_dict = build_counts_dict(sequencing_file, end)
matrix = []
with open(regions_filename) as file:
for line in file:
if line.rstrip():
chromosome, left, right, gene_name, _, strand = line.split()
left, right = int(left), int(right)
... | generate_heatmap, Ticks
from PolTools.utils.heatmap_utils.average_matrix import average_matrix
from PolTools.utils.heatmap_utils.add_matrices import add_matrices
def get_original_matrix(regions_filename, sequencing_file, norm_factor, end):
# 1. Load the five_prime_dict
| 64 | 64 | 175 | 27 | 36 | GeoffSCollins/PolTools | PolTools/main_programs/region_heatmap.py | Python | get_original_matrix | get_original_matrix | 17 | 39 | 17 | 18 | ac30a5c7079fd455bd454f18a8fb2fe8ef227639 | bigcode/the-stack | train |
f7a25d85ddd740777f548564 | train | function | def make_heatmap(matrix_filename, output_prefix, heatmap_parameters, tick_parameters):
max_value, gamma = heatmap_parameters
# Now make the heatmap
min_value = None
output_filename = output_prefix + "_max_" + str(max_value) + "_gamma_" + str(gamma) + "_region_heatmap.tiff"
if tick_parameters != (N... | def make_heatmap(matrix_filename, output_prefix, heatmap_parameters, tick_parameters):
| max_value, gamma = heatmap_parameters
# Now make the heatmap
min_value = None
output_filename = output_prefix + "_max_" + str(max_value) + "_gamma_" + str(gamma) + "_region_heatmap.tiff"
if tick_parameters != (None, None):
ticks = Ticks(*tick_parameters, offset=1)
else:
ticks =... | "\t".join(output_list) + "\n"
)
# Do the vertical averaging
heatmap_matrix = average_matrix(matrix_filename, vertical_averaging)
remove_files(matrix_filename)
return heatmap_matrix
def make_heatmap(matrix_filename, output_prefix, heatmap_parameters, tick_parameters):
| 64 | 64 | 129 | 17 | 46 | GeoffSCollins/PolTools | PolTools/main_programs/region_heatmap.py | Python | make_heatmap | make_heatmap | 71 | 83 | 71 | 71 | 5351cf3554dc2933de95da5fb7314de72860c0c8 | bigcode/the-stack | train |
297f9d421e3b31b18abbfbe0 | train | function | def run_region_heatmap(args):
end, filenames, seq_files_data, heatmap_parameters, repeat_amounts, tick_parameters, threads = parse_input(args)
regions_filename, output_prefix = filenames
combined_matrix = get_matrix(regions_filename, seq_files_data, end, repeat_amounts, threads)
make_heatmap(combined_... | def run_region_heatmap(args):
| end, filenames, seq_files_data, heatmap_parameters, repeat_amounts, tick_parameters, threads = parse_input(args)
regions_filename, output_prefix = filenames
combined_matrix = get_matrix(regions_filename, seq_files_data, end, repeat_amounts, threads)
make_heatmap(combined_matrix, output_prefix, heatmap... | dataset, end, repeat_amounts]
)
individual_matrices = pool.starmap(get_individual_matrix, args)
# Combine the matrices
combined_matrix = add_matrices(individual_matrices)
remove_files(individual_matrices)
return combined_matrix
def run_region_heatmap(args):
| 64 | 64 | 89 | 7 | 56 | GeoffSCollins/PolTools | PolTools/main_programs/region_heatmap.py | Python | run_region_heatmap | run_region_heatmap | 106 | 114 | 106 | 106 | b551c414d0dce7c882a4286947db232881aefde2 | bigcode/the-stack | train |
bfd0fa7953320098e4bb006b | train | function | def get_individual_matrix(regions_filename, seq_file_data, end, repeat_amounts):
repeat_amount, vertical_averaging = repeat_amounts
seq_file, norm_factor = seq_file_data
# 2. Load 2D list containing the data to be outputted
original_matrix = get_original_matrix(regions_filename, seq_file, norm_factor, ... | def get_individual_matrix(regions_filename, seq_file_data, end, repeat_amounts):
| repeat_amount, vertical_averaging = repeat_amounts
seq_file, norm_factor = seq_file_data
# 2. Load 2D list containing the data to be outputted
original_matrix = get_original_matrix(regions_filename, seq_file, norm_factor, end)
# Expand the matrix using the repeat amounts and write it to a file
... | we need to reverse the list
if strand == "-":
curr_gene_counts = curr_gene_counts[::-1]
# Now we loop through the region left to right
matrix.append(curr_gene_counts)
return matrix
def get_individual_matrix(regions_filename, seq_file_data, end, ... | 66 | 66 | 220 | 19 | 46 | GeoffSCollins/PolTools | PolTools/main_programs/region_heatmap.py | Python | get_individual_matrix | get_individual_matrix | 42 | 68 | 42 | 42 | d44057f3083665da0c94a2cd824820c25ac19ff7 | bigcode/the-stack | train |
ecb24a1a8906e6aba4432d78 | train | function | def parse_input(args):
def positive_float(num):
try:
val = float(num)
if val <= 0:
raise Exception("Go to the except")
except:
raise argparse.ArgumentTypeError(num + " must be positive")
return val
def positive_int(num):
try:... | def parse_input(args):
| def positive_float(num):
try:
val = float(num)
if val <= 0:
raise Exception("Go to the except")
except:
raise argparse.ArgumentTypeError(num + " must be positive")
return val
def positive_int(num):
try:
val = int(n... | (*tick_parameters, offset=1)
else:
ticks = None
generate_heatmap(matrix_filename, 'gray', output_filename, gamma, min_value, max_value, ticks=ticks)
def get_matrix(regions_filename, seq_files_data, end, repeat_amounts, threads):
# Make the matrices
with multiprocessing.Pool(threads) as pool:
... | 249 | 249 | 832 | 5 | 244 | GeoffSCollins/PolTools | PolTools/main_programs/region_heatmap.py | Python | parse_input | parse_input | 117 | 205 | 117 | 118 | 7dae7fe9a60babda6049db8a920a6751b88f6fbe | bigcode/the-stack | train |
a7c92249adb89f0110a5acef | train | function | def load_image(infilename):
img = Image.open(infilename)
img = img.resize((_IMAGE_SIZE, _IMAGE_SIZE))
img.load()
data = np.asarray(img, dtype=np.float32)
data = standardize(data)
return data
| def load_image(infilename):
| img = Image.open(infilename)
img = img.resize((_IMAGE_SIZE, _IMAGE_SIZE))
img.load()
data = np.asarray(img, dtype=np.float32)
data = standardize(data)
return data
| 'hentai', 2: 'neutral', 3: 'porn', 4: 'sexy'}
def standardize(img):
mean = np.mean(img)
std = np.std(img)
img = (img - mean) / std
return img
def load_image(infilename):
| 64 | 64 | 54 | 6 | 57 | PotatoDrug/Sitemon | main/actions.py | Python | load_image | load_image | 187 | 193 | 187 | 187 | af447092720ff57d40439d043d778d9ed0708c1e | bigcode/the-stack | train |
4a1629e230cfc6e55d629a21 | train | class | class ActionStatus(Action):
""" action_status class """
def name(self):
return "action_status"
def run(self, dispatcher, tracker, domain):
username = tracker.sender_id
sites = get_urls_by_user(username)
if sites:
msg = 'Current watch list\n'
for ind... | class ActionStatus(Action):
| """ action_status class """
def name(self):
return "action_status"
def run(self, dispatcher, tracker, domain):
username = tracker.sender_id
sites = get_urls_by_user(username)
if sites:
msg = 'Current watch list\n'
for index, url in enumerate(sites):... | {} to watch list\n'.format(p_site)
# logging.info('Sites: {}'.format(sites))
if msg == '':
msg = 'You have not entered an url or an url that is already in your watch list.'
dispatcher.utter_message(msg)
return []
class ActionStatus(Action):
| 63 | 64 | 113 | 5 | 58 | PotatoDrug/Sitemon | main/actions.py | Python | ActionStatus | ActionStatus | 285 | 304 | 285 | 285 | 71026aa6eae8531f7f816c4a76e4b1579903ceb3 | bigcode/the-stack | train |
1f00535d5ae15e381bf05913 | train | function | def remove_url(username, url):
"""
Remove an url from the database
:param username: username of the user that wants to remove the url
:param url: the url to remove
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('DELETE FROM watchlist WHERE username=? and url=?',
... | def remove_url(username, url):
| """
Remove an url from the database
:param username: username of the user that wants to remove the url
:param url: the url to remove
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('DELETE FROM watchlist WHERE username=? and url=?',
(username, url))... | cur = conn.cursor()
cur.execute('''INSERT INTO watchlist VALUES (?,?,?,DATETIME('now','localtime'),'false',?)''',
(username, response.url, sitehash, response.status_code))
conn.commit()
conn.close()
return True
def remove_url(username, url):
| 64 | 64 | 88 | 7 | 56 | PotatoDrug/Sitemon | main/actions.py | Python | remove_url | remove_url | 124 | 136 | 124 | 124 | 98409cf6dd294be9d08dc116b2d31946972185d7 | bigcode/the-stack | train |
14333d467591e64f3700d80e | train | function | def get_urls_by_user(username):
"""
Finds all the urls watched by the user
:param username: username of the target user
:return: a list of all the urls watched by the user
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('SELECT url FROM watchlist WHERE username=?',... | def get_urls_by_user(username):
| """
Finds all the urls watched by the user
:param username: username of the target user
:return: a list of all the urls watched by the user
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('SELECT url FROM watchlist WHERE username=?', (username,))
urls = cur.fet... | append http:// to it.
:param url: the url to be processed
:return: the processed url
"""
if not url.startswith('http://') and not url.startswith('https://'):
url = 'http://' + url
return url
def get_urls_by_user(username):
| 64 | 64 | 91 | 7 | 56 | PotatoDrug/Sitemon | main/actions.py | Python | get_urls_by_user | get_urls_by_user | 62 | 74 | 62 | 62 | e1ff9f7f48310ab1a4e5312d0b914ef491931dee | bigcode/the-stack | train |
21d66a444086e14524f25b18 | train | function | def clear_watchlist(username):
"""
Remove all the urls added by the user
:param username: username of the user that wants to remove all the urls
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('DELETE FROM watchlist WHERE username=?', (username,))
conn.commit()
... | def clear_watchlist(username):
| """
Remove all the urls added by the user
:param username: username of the user that wants to remove all the urls
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('DELETE FROM watchlist WHERE username=?', (username,))
conn.commit()
conn.close()
| the url
:param url: the url to remove
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('DELETE FROM watchlist WHERE username=? and url=?',
(username, url))
conn.commit()
conn.close()
def clear_watchlist(username):
| 64 | 64 | 74 | 6 | 58 | PotatoDrug/Sitemon | main/actions.py | Python | clear_watchlist | clear_watchlist | 139 | 149 | 139 | 139 | 333fc959ec7a384819393527592ec7f9639fe509 | bigcode/the-stack | train |
0a3594b748333d35a099c754 | train | function | def getsitehash(url):
"""
Gets the perceptual hash of a site
:param url: the url of the site
:return: The perceptual hash of the fullpage screen shot of the site or None if it failed
"""
tempname = '/tmp/{}.jpg'.format(str(uuid.uuid4()))
os.system('utils/screenshot.js -u \'{}\' -o {}'.forma... | def getsitehash(url):
| """
Gets the perceptual hash of a site
:param url: the url of the site
:return: The perceptual hash of the fullpage screen shot of the site or None if it failed
"""
tempname = '/tmp/{}.jpg'.format(str(uuid.uuid4()))
os.system('utils/screenshot.js -u \'{}\' -o {}'.format(url, tempname))
... | : a list of all the urls watched by the user
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('SELECT url FROM watchlist WHERE username=?', (username,))
urls = cur.fetchall()
conn.close()
return urls
def getsitehash(url):
| 64 | 64 | 139 | 6 | 57 | PotatoDrug/Sitemon | main/actions.py | Python | getsitehash | getsitehash | 77 | 92 | 77 | 77 | 590bcf6a15e69d713688178c1a268ec07341d146 | bigcode/the-stack | train |
6da549124daaa36bf0612782 | train | function | def geturls(text):
"""
Finds all the urls in the string
:param text: the string to search in
:return: set of urls found in the string
"""
urlregex = re.compile(
r'(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?')
... | def geturls(text):
| """
Finds all the urls in the string
:param text: the string to search in
:return: set of urls found in the string
"""
urlregex = re.compile(
r'(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?')
urls = set()
f... | the user
:param username: username of the user that wants to remove all the urls
"""
conn = create_connection(DB_FILE)
cur = conn.cursor()
cur.execute('DELETE FROM watchlist WHERE username=?', (username,))
conn.commit()
conn.close()
def geturls(text):
| 64 | 64 | 147 | 5 | 59 | PotatoDrug/Sitemon | main/actions.py | Python | geturls | geturls | 152 | 168 | 152 | 152 | 82bca67ee83e414646c28ee85e38c5566903e7d3 | bigcode/the-stack | train |
cd298e3ef48afa75064fa219 | train | class | class ActionMonitorSite(Action):
""" action_monitor_site class """
def name(self):
# type: () -> Text
return "action_monitor_site"
def run(self, dispatcher, tracker, domain):
username = tracker.sender_id
logging.info('Sender_id: {}'.format(username))
sites = get_url... | class ActionMonitorSite(Action):
| """ action_monitor_site class """
def name(self):
# type: () -> Text
return "action_monitor_site"
def run(self, dispatcher, tracker, domain):
username = tracker.sender_id
logging.info('Sender_id: {}'.format(username))
sites = get_urls_by_user(username)
new_... | {}'.format(site, tempname))
if not os.path.isfile(tempname):
msg += 'An error occured when checking {}\n'.format(site)
continue
categorydict = predict(tempname)
msg += '{} belongs to {} the category\n'.format(
s... | 86 | 87 | 290 | 6 | 80 | PotatoDrug/Sitemon | main/actions.py | Python | ActionMonitorSite | ActionMonitorSite | 245 | 282 | 245 | 245 | 1408dec7d3fcfbbd318e4294c3503e5a8804b5fe | bigcode/the-stack | train |
db7767acf48b9e0f96e64693 | train | function | def insert_url(username, url):
"""
Insert new url to watch into database, the url
inserted will be the one after following redirects
:param username: username of the user that wants to watch the url
:param url: the url to watch
:return: True if successful, False if failed
"""
try:
... | def insert_url(username, url):
| """
Insert new url to watch into database, the url
inserted will be the one after following redirects
:param username: username of the user that wants to watch the url
:param url: the url to watch
:return: True if successful, False if failed
"""
try:
response = requests.get(url)... | \' -o {}'.format(url, tempname))
try:
sitehash = str(imagehash.phash(Image.open(tempname)))
except FileNotFoundError:
return None
if os.path.isfile(tempname):
os.remove(tempname)
return sitehash
def insert_url(username, url):
| 64 | 64 | 215 | 7 | 56 | PotatoDrug/Sitemon | main/actions.py | Python | insert_url | insert_url | 95 | 121 | 95 | 95 | 82f8517ad19ac38497ab7aaf00345a34ffea17d5 | bigcode/the-stack | train |
31d625a0d3d0d46883391266 | train | function | def create_connection(db_file):
"""
Create a database connection to the SQLite database specified by the file name
:param fname: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as err:
print(err)
... | def create_connection(db_file):
| """
Create a database connection to the SQLite database specified by the file name
:param fname: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as err:
print(err)
return None
| = 'database.db'
logging.basicConfig(level=LOG_LEVEL,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename=LOG_FILE,
filemode='a')
def create_connection(db_file):
| 64 | 64 | 72 | 6 | 58 | PotatoDrug/Sitemon | main/actions.py | Python | create_connection | create_connection | 34 | 47 | 34 | 34 | 56968ad5172f21d6fcab0838ba12053671773157 | bigcode/the-stack | train |
16996d0be5f8d31876bd0c6a | train | function | def process_url(url):
"""
If the url does not start with http:// or https://, append http:// to it.
:param url: the url to be processed
:return: the processed url
"""
if not url.startswith('http://') and not url.startswith('https://'):
url = 'http://' + url
return url
| def process_url(url):
| """
If the url does not start with http:// or https://, append http:// to it.
:param url: the url to be processed
:return: the processed url
"""
if not url.startswith('http://') and not url.startswith('https://'):
url = 'http://' + url
return url
| to the SQLite database specified by the file name
:param fname: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as err:
print(err)
return None
def process_url(url):
| 64 | 64 | 78 | 5 | 58 | PotatoDrug/Sitemon | main/actions.py | Python | process_url | process_url | 50 | 59 | 50 | 50 | a5f30c7ec4dcc6f9c0fb009906d3d7e2bf3473a7 | bigcode/the-stack | train |
6ca0096569dc0acce3e67cd4 | train | class | class ActionRemoveAllSites(Action):
""" action_remove_all_sites class """
def name(self):
return "action_remove_all_sites"
def run(self, dispatcher, tracker, domain):
# dispatcher.utter_template('utter_confirm_clearwatchlist', tracker)
clear_watchlist(tracker.sender_id)
ret... | class ActionRemoveAllSites(Action):
| """ action_remove_all_sites class """
def name(self):
return "action_remove_all_sites"
def run(self, dispatcher, tracker, domain):
# dispatcher.utter_template('utter_confirm_clearwatchlist', tracker)
clear_watchlist(tracker.sender_id)
return []
| ))
if (p_site,) in sites:
remove_url(username, p_site)
msg += 'Removed {} from watch list\n'.format(p_site)
if msg == '':
msg = 'No sites removed'
dispatcher.utter_message(msg)
return []
class ActionRemoveAllSites(Action):
| 63 | 64 | 66 | 7 | 56 | PotatoDrug/Sitemon | main/actions.py | Python | ActionRemoveAllSites | ActionRemoveAllSites | 337 | 346 | 337 | 337 | fdea900c9f9e6a8618675bdd7c8cf2c7eb8684b5 | bigcode/the-stack | train |
b3a4a6323d40813ada8e1a37 | train | function | def standardize(img):
mean = np.mean(img)
std = np.std(img)
img = (img - mean) / std
return img
| def standardize(img):
| mean = np.mean(img)
std = np.std(img)
img = (img - mean) / std
return img
| .path.dirname(__file__)), 'saved_model')
_IMAGE_SIZE = 64
_BATCH_SIZE = 128
_LABEL_MAP = {0: 'drawings', 1: 'hentai', 2: 'neutral', 3: 'porn', 4: 'sexy'}
def standardize(img):
| 63 | 64 | 34 | 5 | 58 | PotatoDrug/Sitemon | main/actions.py | Python | standardize | standardize | 180 | 184 | 180 | 180 | bbcfecc78ea8781c4a78461b1b208549535ab30e | bigcode/the-stack | train |
7d865260dd8e3cb590a640f0 | train | class | class ActionRemoveSite(Action):
""" action_remove_site class """
def name(self):
return "action_remove_site"
def run(self, dispatcher, tracker, domain):
username = tracker.sender_id
sites = get_urls_by_user(username)
logging.info('Sites: {}'.format(sites))
remove_si... | class ActionRemoveSite(Action):
| """ action_remove_site class """
def name(self):
return "action_remove_site"
def run(self, dispatcher, tracker, domain):
username = tracker.sender_id
sites = get_urls_by_user(username)
logging.info('Sites: {}'.format(sites))
remove_sites = set(tracker.get_latest_ent... | 'Current watch list\n'
for index, url in enumerate(sites):
msg += '{}. {}\n'.format(index+1, url[0])
dispatcher.utter_message(msg)
else:
dispatcher.utter_message('Not watching any sites')
return []
class ActionRemoveSite(Action):
| 63 | 64 | 185 | 6 | 57 | PotatoDrug/Sitemon | main/actions.py | Python | ActionRemoveSite | ActionRemoveSite | 307 | 334 | 307 | 307 | b5d4e46f5f35c33fb85ae9a7121d12d993ee48ef | bigcode/the-stack | train |
f48dc5ada8b5feacda4ffd8b | train | class | class ActionNsfwCheck(Action):
""" action_nsfw_check class """
def name(self):
return "action_nsfw_check"
def run(self, dispatcher, tracker, domain):
new_sites = set(tracker.get_latest_entity_values('url'))
new_sites = new_sites.union(geturls(tracker.latest_message['text']))
... | class ActionNsfwCheck(Action):
| """ action_nsfw_check class """
def name(self):
return "action_nsfw_check"
def run(self, dispatcher, tracker, domain):
new_sites = set(tracker.get_latest_entity_values('url'))
new_sites = new_sites.union(geturls(tracker.latest_message['text']))
p_sites = list(map(process_ur... | ATCH_SIZE})
probabilities_dict = {_LABEL_MAP.get(
i): l for i, l in enumerate(probabilities[0])}
pre_label = _LABEL_MAP.get(class_index[0])
result = {"class": pre_label, "probability": probabilities_dict}
return result
class ActionNsfwCheck(Action):
| 69 | 69 | 231 | 8 | 60 | PotatoDrug/Sitemon | main/actions.py | Python | ActionNsfwCheck | ActionNsfwCheck | 216 | 242 | 216 | 216 | c0837613bf02c46d1deeec47c1f19a009b2bdb34 | bigcode/the-stack | train |
bf91e05449402d66fc849320 | train | function | def predict(image_path):
with tf.Session() as sess:
graph = tf.get_default_graph()
tf.saved_model.loader.load(
sess, [tf.saved_model.tag_constants.SERVING], _MODEL_DIR)
inputs = graph.get_tensor_by_name("input_tensor:0")
probabilities_op = graph.get_tensor_by_name('softma... | def predict(image_path):
| with tf.Session() as sess:
graph = tf.get_default_graph()
tf.saved_model.loader.load(
sess, [tf.saved_model.tag_constants.SERVING], _MODEL_DIR)
inputs = graph.get_tensor_by_name("input_tensor:0")
probabilities_op = graph.get_tensor_by_name('softmax_tensor:0')
clas... |
return img
def load_image(infilename):
img = Image.open(infilename)
img = img.resize((_IMAGE_SIZE, _IMAGE_SIZE))
img.load()
data = np.asarray(img, dtype=np.float32)
data = standardize(data)
return data
def predict(image_path):
| 64 | 64 | 191 | 5 | 58 | PotatoDrug/Sitemon | main/actions.py | Python | predict | predict | 196 | 213 | 196 | 196 | 9a958ee82714ff80b05d80d78ff4904cfb73606c | bigcode/the-stack | train |
a697efa6ab720862ee09f333 | train | function | def run_before(*phases):
"""Registers a method of a package to be run before a given phase"""
return PackageMeta.register_callback('run_before', *phases)
| def run_before(*phases):
| """Registers a method of a package to be run before a given phase"""
return PackageMeta.register_callback('run_before', *phases)
| the containing module names.
"""
if self._name is None:
self._name = self.module.__name__
if '.' in self._name:
self._name = self._name[self._name.rindex('.') + 1:]
return self._name
def run_before(*phases):
| 64 | 64 | 37 | 7 | 56 | healther/spack | lib/spack/spack/package.py | Python | run_before | run_before | 370 | 372 | 370 | 370 | dac764763e5e65895d420852de2f572541e3b3d9 | bigcode/the-stack | train |
394198b5f5992ca3dde78dae | train | function | def install_dependency_symlinks(pkg, spec, prefix):
"""
Execute a dummy install and flatten dependencies.
This routine can be used in a ``package.py`` definition by setting
``install = install_dependency_symlinks``.
This feature comes in handy for creating a common location for the
the install... | def install_dependency_symlinks(pkg, spec, prefix):
| """
Execute a dummy install and flatten dependencies.
This routine can be used in a ``package.py`` definition by setting
``install = install_dependency_symlinks``.
This feature comes in handy for creating a common location for the
the installation of third-party libraries.
"""
flatten_... |
#: build-system class we are using
build_system_class = 'Package'
# This will be used as a registration decorator in user
# packages, if need be
run_after('install')(PackageBase.sanity_check_prefix)
def install_dependency_symlinks(pkg, spec, prefix):
| 64 | 64 | 80 | 12 | 52 | healther/spack | lib/spack/spack/package.py | Python | install_dependency_symlinks | install_dependency_symlinks | 2,617 | 2,627 | 2,617 | 2,617 | 9b92e7e039f1f0f5ee340cd2d389057b60b053e1 | bigcode/the-stack | train |
b9a8416f7356e018eb5ae106 | train | class | class PackageMeta(
DetectablePackageMeta,
spack.directives.DirectiveMeta,
spack.mixins.PackageMixinsMeta,
spack.multimethod.MultiMethodMeta
):
"""
Package metaclass for supporting directives (e.g., depends_on) and phases
"""
phase_fmt = '_InstallPhase_{0}'
_InstallPhase_run_before =... | class PackageMeta(
DetectablePackageMeta,
spack.directives.DirectiveMeta,
spack.mixins.PackageMixinsMeta,
spack.multimethod.MultiMethodMeta
):
| """
Package metaclass for supporting directives (e.g., depends_on) and phases
"""
phase_fmt = '_InstallPhase_{0}'
_InstallPhase_run_before = {}
_InstallPhase_run_after = {}
def __new__(cls, name, bases, attr_dict):
"""
Instance creation is preceded by phase attribute transf... | )))
else:
specs.append(spack.spec.Spec.from_detection(
spec, extra_attributes=extra_attributes
))
return sorted(specs)
@classmethod
def determine_variants(cls, exes, ... | 256 | 256 | 973 | 40 | 216 | healther/spack | lib/spack/spack/package.py | Python | PackageMeta | PackageMeta | 245 | 367 | 245 | 250 | 731abd52cc8a4a66d50088836b19a55f7e38262b | bigcode/the-stack | train |
2eba0347c1a5e220d21309b3 | train | function | def flatten_dependencies(spec, flat_dir):
"""Make each dependency of spec present in dir via symlink."""
for dep in spec.traverse(root=False):
name = dep.name
dep_path = spack.store.layout.path_for_spec(dep)
dep_files = LinkTree(dep_path)
os.mkdir(flat_dir + '/' + name)
... | def flatten_dependencies(spec, flat_dir):
| """Make each dependency of spec present in dir via symlink."""
for dep in spec.traverse(root=False):
name = dep.name
dep_path = spack.store.layout.path_for_spec(dep)
dep_files = LinkTree(dep_path)
os.mkdir(flat_dir + '/' + name)
conflict = dep_files.find_conflict(flat_... | """Compiler names for builds that rely on cray compiler names."""
os.environ['CC'] = 'cc'
os.environ['CXX'] = 'CC'
os.environ['FC'] = 'ftn'
os.environ['F77'] = 'ftn'
def flatten_dependencies(spec, flat_dir):
| 64 | 64 | 108 | 8 | 56 | healther/spack | lib/spack/spack/package.py | Python | flatten_dependencies | flatten_dependencies | 2,638 | 2,652 | 2,638 | 2,638 | b5e211024461619eca2a84703888b3c66a4c87e3 | bigcode/the-stack | train |
44002b7004f6cb556886ccb7 | train | function | def test_process(pkg, kwargs):
with tty.log.log_output(pkg.test_log_file) as logger:
with logger.force_echo():
tty.msg('Testing package {0}'
.format(pkg.test_suite.test_pkg_id(pkg.spec)))
# use debug print levels for log file to record commands
old_debug = tt... | def test_process(pkg, kwargs):
| with tty.log.log_output(pkg.test_log_file) as logger:
with logger.force_echo():
tty.msg('Testing package {0}'
.format(pkg.test_suite.test_pkg_id(pkg.spec)))
# use debug print levels for log file to record commands
old_debug = tty.is_debug()
tty.set_de... | _package_attributes(run_tests=True)
def _run_default_install_time_test_callbacks(self):
"""Tries to call all the methods that are listed in the attribute
``install_time_test_callbacks`` if ``self.run_tests is True``.
If ``install_time_test_callbacks is None`` returns immediately.
""... | 154 | 154 | 515 | 7 | 147 | healther/spack | lib/spack/spack/package.py | Python | test_process | test_process | 2,520 | 2,582 | 2,520 | 2,520 | cb7d3be3629bb74b6d4fdfb612e76209c0030217 | bigcode/the-stack | train |
d1ed4fa1b13d1fe4b4690ae9 | train | class | class ActivationError(ExtensionError):
"""Raised when there are problems activating an extension."""
def __init__(self, msg, long_msg=None):
super(ActivationError, self).__init__(msg, long_msg)
| class ActivationError(ExtensionError):
| """Raised when there are problems activating an extension."""
def __init__(self, msg, long_msg=None):
super(ActivationError, self).__init__(msg, long_msg)
| has no version with a URL." % cls.__name__)
class InvalidPackageOpError(PackageError):
"""Raised when someone tries perform an invalid operation on a package."""
class ExtensionError(PackageError):
"""Superclass for all errors having to do with extension packages."""
class ActivationError(ExtensionError):
| 63 | 64 | 46 | 7 | 56 | healther/spack | lib/spack/spack/package.py | Python | ActivationError | ActivationError | 2,731 | 2,734 | 2,731 | 2,731 | 67f092fde170b53bbe02011d117b76f3b5944986 | bigcode/the-stack | train |
013a7667a8aa02654d0576b1 | train | function | def run_after(*phases):
"""Registers a method of a package to be run after a given phase"""
return PackageMeta.register_callback('run_after', *phases)
| def run_after(*phases):
| """Registers a method of a package to be run after a given phase"""
return PackageMeta.register_callback('run_after', *phases)
| = self._name[self._name.rindex('.') + 1:]
return self._name
def run_before(*phases):
"""Registers a method of a package to be run before a given phase"""
return PackageMeta.register_callback('run_before', *phases)
def run_after(*phases):
| 64 | 64 | 37 | 7 | 57 | healther/spack | lib/spack/spack/package.py | Python | run_after | run_after | 375 | 377 | 375 | 375 | 5e8ce8fe062ea08fb0f2c9b957d4f3ff5bc88dc7 | bigcode/the-stack | train |
b602465a799dc07dc0b7b974 | train | class | class DetectablePackageMeta(object):
"""Check if a package is detectable and add default implementations
for the detection function.
"""
def __init__(cls, name, bases, attr_dict):
# If a package has the executables attribute then it's
# assumed to be detectable
if hasattr(cls, 'e... | class DetectablePackageMeta(object):
| """Check if a package is detectable and add default implementations
for the detection function.
"""
def __init__(cls, name, bases, attr_dict):
# If a package has the executables attribute then it's
# assumed to be detectable
if hasattr(cls, 'executables'):
@classmetho... | spack.build_environment import StopPhase
raise StopPhase('Stopping before \'{0}\' phase'.format(self.name))
def _on_phase_exit(self, instance):
# If a phase has a matching last_phase attribute,
# stop the installation process raising a StopPhase
if getattr(instance, 'last_phase... | 222 | 222 | 743 | 7 | 215 | healther/spack | lib/spack/spack/package.py | Python | DetectablePackageMeta | DetectablePackageMeta | 149 | 242 | 149 | 149 | c6e2cd31d3e426bbdd94b49409c071a97d9b6307 | bigcode/the-stack | train |
cbcf884e291e16e872fba8be | train | class | class InstallPhase(object):
"""Manages a single phase of the installation.
This descriptor stores at creation time the name of the method it should
search for execution. The method is retrieved at __get__ time, so that
it can be overridden by subclasses of whatever class declared the phases.
It al... | class InstallPhase(object):
| """Manages a single phase of the installation.
This descriptor stores at creation time the name of the method it should
search for execution. The method is retrieved at __get__ time, so that
it can be overridden by subclasses of whatever class declared the phases.
It also provides hooks to execute... |
from spack.util.executable import which, ProcessError
from spack.util.prefix import Prefix
from spack.stage import stage_prefix, Stage, ResourceStage, StageComposite
from spack.util.package_hash import package_hash
from spack.version import Version
"""Allowed URL schemes for spack packages."""
_ALLOWED_URL_SCHEMES = ... | 163 | 163 | 545 | 5 | 158 | healther/spack | lib/spack/spack/package.py | Python | InstallPhase | InstallPhase | 76 | 141 | 76 | 76 | d71208372d71cd136e8144011dfe21acbfa4d3f2 | bigcode/the-stack | train |
59d7d34a8af935f5a4f2e25c | train | class | class PackageError(spack.error.SpackError):
"""Raised when something is wrong with a package definition."""
def __init__(self, message, long_msg=None):
super(PackageError, self).__init__(message, long_msg)
| class PackageError(spack.error.SpackError):
| """Raised when something is wrong with a package definition."""
def __init__(self, message, long_msg=None):
super(PackageError, self).__init__(message, long_msg)
| needed by another on uninstall."""
def __init__(self, spec, dependents):
super(PackageStillNeededError, self).__init__("Cannot uninstall %s" %
spec)
self.spec = spec
self.dependents = dependents
class PackageError(spack.error.SpackError)... | 64 | 64 | 50 | 10 | 53 | healther/spack | lib/spack/spack/package.py | Python | PackageError | PackageError | 2,701 | 2,704 | 2,701 | 2,701 | ebb665bb4a44bc0d11f29904a956b955dbb448fc | bigcode/the-stack | train |
4744efa5d2d395c573c58a67 | train | class | class NoURLError(PackageError):
"""Raised when someone tries to build a URL for a package with no URLs."""
def __init__(self, cls):
super(NoURLError, self).__init__(
"Package %s has no version with a URL." % cls.__name__)
| class NoURLError(PackageError):
| """Raised when someone tries to build a URL for a package with no URLs."""
def __init__(self, cls):
super(NoURLError, self).__init__(
"Package %s has no version with a URL." % cls.__name__)
| cannot automatically be determined."""
def __init__(self, version):
super(PackageVersionError, self).__init__(
"Cannot determine a URL automatically for version %s" % version,
"Please provide a url for this version in the package.py file.")
class NoURLError(PackageError):
| 63 | 64 | 61 | 8 | 55 | healther/spack | lib/spack/spack/package.py | Python | NoURLError | NoURLError | 2,715 | 2,720 | 2,715 | 2,715 | 32c137d9e7e29da5c1c1da07f131f936b1f905c4 | bigcode/the-stack | train |
11715dc8850d6f92557ae2fb | train | function | def on_package_attributes(**attr_dict):
"""Decorator: executes instance function only if object has attr valuses.
Executes the decorated method only if at the moment of calling the
instance has attributes that are equal to certain values.
Args:
attr_dict (dict): dictionary mapping attribute na... | def on_package_attributes(**attr_dict):
| """Decorator: executes instance function only if object has attr valuses.
Executes the decorated method only if at the moment of calling the
instance has attributes that are equal to certain values.
Args:
attr_dict (dict): dictionary mapping attribute names to their
required values... | before a given phase"""
return PackageMeta.register_callback('run_before', *phases)
def run_after(*phases):
"""Registers a method of a package to be run after a given phase"""
return PackageMeta.register_callback('run_after', *phases)
def on_package_attributes(**attr_dict):
| 64 | 64 | 211 | 8 | 56 | healther/spack | lib/spack/spack/package.py | Python | on_package_attributes | on_package_attributes | 380 | 406 | 380 | 380 | 407add25ac88f6e486c8535ba97be2abed8be3f5 | bigcode/the-stack | train |
7d17191b20d7921991174607 | train | function | def possible_dependencies(*pkg_or_spec, **kwargs):
"""Get the possible dependencies of a number of packages.
See ``PackageBase.possible_dependencies`` for details.
"""
packages = []
for pos in pkg_or_spec:
if isinstance(pos, PackageMeta):
packages.append(pos)
continu... | def possible_dependencies(*pkg_or_spec, **kwargs):
| """Get the possible dependencies of a number of packages.
See ``PackageBase.possible_dependencies`` for details.
"""
packages = []
for pos in pkg_or_spec:
if isinstance(pos, PackageMeta):
packages.append(pos)
continue
if not isinstance(pos, spack.spec.Spec):... | LinkTree(dep_path)
os.mkdir(flat_dir + '/' + name)
conflict = dep_files.find_conflict(flat_dir + '/' + name)
if conflict:
raise DependencyConflictError(conflict)
dep_files.merge(flat_dir + '/' + name)
def possible_dependencies(*pkg_or_spec, **kwargs):
| 64 | 64 | 160 | 11 | 53 | healther/spack | lib/spack/spack/package.py | Python | possible_dependencies | possible_dependencies | 2,655 | 2,682 | 2,655 | 2,655 | 86b639ab7441e0d3fbc24cd1132e4c307bf05da3 | bigcode/the-stack | train |
fd7d500010f0b55182827b5d | train | class | class DependencyConflictError(spack.error.SpackError):
"""Raised when the dependencies cannot be flattened as asked for."""
def __init__(self, conflict):
super(DependencyConflictError, self).__init__(
"%s conflicts with another file in the flattened directory." % (
conflict))... | class DependencyConflictError(spack.error.SpackError):
| """Raised when the dependencies cannot be flattened as asked for."""
def __init__(self, conflict):
super(DependencyConflictError, self).__init__(
"%s conflicts with another file in the flattened directory." % (
conflict))
| to do with extension packages."""
class ActivationError(ExtensionError):
"""Raised when there are problems activating an extension."""
def __init__(self, msg, long_msg=None):
super(ActivationError, self).__init__(msg, long_msg)
class DependencyConflictError(spack.error.SpackError):
| 64 | 64 | 61 | 11 | 53 | healther/spack | lib/spack/spack/package.py | Python | DependencyConflictError | DependencyConflictError | 2,737 | 2,742 | 2,737 | 2,737 | 413a2af0a67b554a90e6b0714291c466d1003cbb | bigcode/the-stack | train |
cb601f961d53317678375213 | train | class | class PackageViewMixin(object):
"""This collects all functionality related to adding installed Spack
package to views. Packages can customize how they are added to views by
overriding these functions.
"""
def view_source(self):
"""The source root directory that will be added to the view: fil... | class PackageViewMixin(object):
| """This collects all functionality related to adding installed Spack
package to views. Packages can customize how they are added to views by
overriding these functions.
"""
def view_source(self):
"""The source root directory that will be added to the view: files are
added such that t... | , *args, **kwargs):
# If all the attributes have the value we require, then execute
has_all_attributes = all(
[hasattr(instance, key) for key in attr_dict]
)
if has_all_attributes:
has_the_right_values = all(
[getattr(in... | 125 | 125 | 419 | 6 | 118 | healther/spack | lib/spack/spack/package.py | Python | PackageViewMixin | PackageViewMixin | 409 | 453 | 409 | 409 | dec4cf22195add080a3682bcf83a787cdd229701 | bigcode/the-stack | train |
b03de42a0e958c9cf2f632cd | train | class | class InvalidPackageOpError(PackageError):
"""Raised when someone tries perform an invalid operation on a package."""
| class InvalidPackageOpError(PackageError):
| """Raised when someone tries perform an invalid operation on a package."""
| Error):
"""Raised when someone tries to build a URL for a package with no URLs."""
def __init__(self, cls):
super(NoURLError, self).__init__(
"Package %s has no version with a URL." % cls.__name__)
class InvalidPackageOpError(PackageError):
| 64 | 64 | 23 | 9 | 55 | healther/spack | lib/spack/spack/package.py | Python | InvalidPackageOpError | InvalidPackageOpError | 2,723 | 2,724 | 2,723 | 2,723 | 8a03488962e91c373796a1a2963e12d102150922 | bigcode/the-stack | train |
297fc4c5d332ed353ddf71dd | train | function | def use_cray_compiler_names():
"""Compiler names for builds that rely on cray compiler names."""
os.environ['CC'] = 'cc'
os.environ['CXX'] = 'CC'
os.environ['FC'] = 'ftn'
os.environ['F77'] = 'ftn'
| def use_cray_compiler_names():
| """Compiler names for builds that rely on cray compiler names."""
os.environ['CC'] = 'cc'
os.environ['CXX'] = 'CC'
os.environ['FC'] = 'ftn'
os.environ['F77'] = 'ftn'
| This routine can be used in a ``package.py`` definition by setting
``install = install_dependency_symlinks``.
This feature comes in handy for creating a common location for the
the installation of third-party libraries.
"""
flatten_dependencies(spec, prefix)
def use_cray_compiler_names():
| 64 | 64 | 65 | 8 | 56 | healther/spack | lib/spack/spack/package.py | Python | use_cray_compiler_names | use_cray_compiler_names | 2,630 | 2,635 | 2,630 | 2,630 | 55cfc54500715c58d890b428cf22d97be947b5ae | bigcode/the-stack | train |
a395f513a4c19e3e12790d9b | train | class | class FetchError(spack.error.SpackError):
"""Raised when something goes wrong during fetch."""
def __init__(self, message, long_msg=None):
super(FetchError, self).__init__(message, long_msg)
| class FetchError(spack.error.SpackError):
| """Raised when something goes wrong during fetch."""
def __init__(self, message, long_msg=None):
super(FetchError, self).__init__(message, long_msg)
| for p in spack.repo.path.providers_for(pos.name)
)
continue
else:
packages.append(pos.package_class)
visited = {}
for pkg in packages:
pkg.possible_dependencies(visited=visited, **kwargs)
return visited
class FetchError(spack.error.SpackError):
| 64 | 64 | 48 | 10 | 53 | healther/spack | lib/spack/spack/package.py | Python | FetchError | FetchError | 2,685 | 2,689 | 2,685 | 2,685 | eb803c5ea4413e8d5f284d508b470a4ced2124e9 | bigcode/the-stack | train |
d90928fcc6812e23381f3e69 | train | class | class BundlePackage(PackageBase):
"""General purpose bundle, or no-code, package class."""
#: There are no phases by default but the property is required to support
#: post-install hooks (e.g., for module generation).
phases = []
#: This attribute is used in UI queries that require to know which
... | class BundlePackage(PackageBase):
| """General purpose bundle, or no-code, package class."""
#: There are no phases by default but the property is required to support
#: post-install hooks (e.g., for module generation).
phases = []
#: This attribute is used in UI queries that require to know which
#: build-system class we are usin... | if pkg.test_failures:
raise TestFailure(pkg.test_failures)
finally:
# reset debug level
tty.set_debug(old_debug)
inject_flags = PackageBase.inject_flags
env_flags = PackageBase.env_flags
build_system_flags = PackageBase.build_system_flags
class BundlePackage(PackageBa... | 64 | 64 | 105 | 7 | 56 | healther/spack | lib/spack/spack/package.py | Python | BundlePackage | BundlePackage | 2,590 | 2,600 | 2,590 | 2,590 | 75bc9c057c6b49cb84ec6f3c5be8e2b7cc65fb23 | bigcode/the-stack | train |
92ef1eeef1b07e1ca7e9c335 | train | class | class PackageStillNeededError(InstallError):
"""Raised when package is still needed by another on uninstall."""
def __init__(self, spec, dependents):
super(PackageStillNeededError, self).__init__("Cannot uninstall %s" %
spec)
self.spec = spec... | class PackageStillNeededError(InstallError):
| """Raised when package is still needed by another on uninstall."""
def __init__(self, spec, dependents):
super(PackageStillNeededError, self).__init__("Cannot uninstall %s" %
spec)
self.spec = spec
self.dependents = dependents
| **kwargs)
return visited
class FetchError(spack.error.SpackError):
"""Raised when something goes wrong during fetch."""
def __init__(self, message, long_msg=None):
super(FetchError, self).__init__(message, long_msg)
class PackageStillNeededError(InstallError):
| 64 | 64 | 70 | 9 | 55 | healther/spack | lib/spack/spack/package.py | Python | PackageStillNeededError | PackageStillNeededError | 2,692 | 2,698 | 2,692 | 2,692 | 2b00cd3cae9343c6cb4c8dfb3b57ee573d30b468 | bigcode/the-stack | train |
844482ab35da254581ef0880 | train | class | class Package(PackageBase):
"""General purpose class with a single ``install``
phase that needs to be coded by packagers.
"""
#: The one and only phase
phases = ['install']
#: This attribute is used in UI queries that require to know which
#: build-system class we are using
build_system_... | class Package(PackageBase):
| """General purpose class with a single ``install``
phase that needs to be coded by packagers.
"""
#: The one and only phase
phases = ['install']
#: This attribute is used in UI queries that require to know which
#: build-system class we are using
build_system_class = 'Package'
# This... | generation).
phases = []
#: This attribute is used in UI queries that require to know which
#: build-system class we are using
build_system_class = 'BundlePackage'
#: Bundle packages do not have associated source or binary code.
has_code = False
class Package(PackageBase):
| 64 | 64 | 111 | 6 | 57 | healther/spack | lib/spack/spack/package.py | Python | Package | Package | 2,603 | 2,614 | 2,603 | 2,603 | 958fec9cf346892da95568eab3f3f9a645d21ecf | bigcode/the-stack | train |
f7f7f59e73ac50d24794048f | train | class | class PackageVersionError(PackageError):
"""Raised when a version URL cannot automatically be determined."""
def __init__(self, version):
super(PackageVersionError, self).__init__(
"Cannot determine a URL automatically for version %s" % version,
"Please provide a url for this ver... | class PackageVersionError(PackageError):
| """Raised when a version URL cannot automatically be determined."""
def __init__(self, version):
super(PackageVersionError, self).__init__(
"Cannot determine a URL automatically for version %s" % version,
"Please provide a url for this version in the package.py file.")
| pendents = dependents
class PackageError(spack.error.SpackError):
"""Raised when something is wrong with a package definition."""
def __init__(self, message, long_msg=None):
super(PackageError, self).__init__(message, long_msg)
class PackageVersionError(PackageError):
| 64 | 64 | 70 | 8 | 56 | healther/spack | lib/spack/spack/package.py | Python | PackageVersionError | PackageVersionError | 2,707 | 2,712 | 2,707 | 2,707 | 008c8fd7ae7ec773b92b7b8d5328f0047c61d11a | bigcode/the-stack | train |
8969440645e1725f5037a204 | train | class | class PackageBase(six.with_metaclass(PackageMeta, PackageViewMixin, object)):
"""This is the superclass for all spack packages.
***The Package class***
At its core, a package consists of a set of software to be installed.
A package may focus on a piece of software and its associated software
depen... | class PackageBase(six.with_metaclass(PackageMeta, PackageViewMixin, object)):
| """This is the superclass for all spack packages.
***The Package class***
At its core, a package consists of a set of software to be installed.
A package may focus on a piece of software and its associated software
dependencies or it may simply be a set, or bundle, of software. The
former req... | for example if other packages
linked into the view already include the file.
"""
for src, dst in merge_map.items():
if not os.path.exists(dst):
view.link(src, dst, spec=self.spec)
def remove_files_from_view(self, view, merge_map):
"""Given a map of packa... | 255 | 256 | 16,763 | 18 | 237 | healther/spack | lib/spack/spack/package.py | Python | PackageBase | PackageBase | 470 | 2,517 | 470 | 470 | 25e8794cd69f19b85f32d80f3f7a6864d4e57e60 | bigcode/the-stack | train |
dd30fc873881049566438353 | train | class | class ExtensionError(PackageError):
"""Superclass for all errors having to do with extension packages."""
| class ExtensionError(PackageError):
| """Superclass for all errors having to do with extension packages."""
| init__(self, cls):
super(NoURLError, self).__init__(
"Package %s has no version with a URL." % cls.__name__)
class InvalidPackageOpError(PackageError):
"""Raised when someone tries perform an invalid operation on a package."""
class ExtensionError(PackageError):
| 63 | 64 | 20 | 7 | 56 | healther/spack | lib/spack/spack/package.py | Python | ExtensionError | ExtensionError | 2,727 | 2,728 | 2,727 | 2,727 | e7a0b39219d19ba615b6a2765ba209dc63440d5e | bigcode/the-stack | train |
2d9d8446ad1dbe1da3c7d094 | train | function | def test_log_pathname(test_stage, spec):
"""Build the pathname of the test log file
Args:
test_stage (str): path to the test stage directory
spec (Spec): instance of the spec under test
Returns:
(str): the pathname of the test log file
"""
return os.path.join(test_stage,
... | def test_log_pathname(test_stage, spec):
| """Build the pathname of the test log file
Args:
test_stage (str): path to the test stage directory
spec (Spec): instance of the spec under test
Returns:
(str): the pathname of the test log file
"""
return os.path.join(test_stage,
'test-{0}-out.txt'.... | . Alternative implementations may not remove all files. For
example if two packages include the same file, it should only be
removed when both packages are removed.
"""
for src, dst in merge_map.items():
view.remove_file(src, dst)
def test_log_pathname(test_stage, spec):
| 64 | 64 | 91 | 10 | 54 | healther/spack | lib/spack/spack/package.py | Python | test_log_pathname | test_log_pathname | 456 | 467 | 456 | 456 | f3d41dc0fccdbf45238aabea85e0625c3776c674 | bigcode/the-stack | train |
fdd3209d218ac5aae8c6909b | train | class | class ObsoletePatches(AbstractStep):
@classmethod
def options(cls):
return AbstractStep.options() + [
Options.obsolete_patches,
]
def run(self, state):
if not self._options.obsolete_patches:
return
bug_id = state["bug_id"]
patches = self._tool... | class ObsoletePatches(AbstractStep):
@classmethod
| def options(cls):
return AbstractStep.options() + [
Options.obsolete_patches,
]
def run(self, state):
if not self._options.obsolete_patches:
return
bug_id = state["bug_id"]
patches = self._tool.bugs.fetch_bug(bug_id).patches()
if not patch... | OF THE POSSIBILITY OF SUCH DAMAGE.
from webkitpy.tool.grammar import pluralize
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
from webkitpy.common.system.deprecated_logging import log
class ObsoletePatches(AbstractStep):
@classmethod
| 64 | 64 | 136 | 12 | 51 | nizovn/luna-sysmgr | hooks/webkitpy/tool/steps/obsoletepatches.py | Python | ObsoletePatches | ObsoletePatches | 35 | 51 | 35 | 36 | 5d43e0464c4b238f4ac14e3cd06f6f6d3a55da12 | bigcode/the-stack | train |
e7f1b606fde97bbd9e9d4777 | train | class | class DjangoRealtimeConfig(AppConfig):
name = 'django_realtime'
| class DjangoRealtimeConfig(AppConfig):
| name = 'django_realtime'
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class DjangoRealtimeConfig(AppConfig):
| 30 | 64 | 15 | 7 | 22 | keepexploring/smartbiogas | django_realtime/apps.py | Python | DjangoRealtimeConfig | DjangoRealtimeConfig | 7 | 8 | 7 | 7 | e8860193391dbb44198828859b1c1bb7d2f11f64 | bigcode/the-stack | train |
8e60275d1faa5c08204c307f | train | function | def get_snapshot(account_name: Optional[str] = None,
pool_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
snapshot_name: Optional[str] = None,
volume_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOption... | def get_snapshot(account_name: Optional[str] = None,
pool_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
snapshot_name: Optional[str] = None,
volume_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOption... | """
Snapshot of a Volume
:param str account_name: The name of the NetApp account
:param str pool_name: The name of the capacity pool
:param str resource_group_name: The name of the resource group.
:param str snapshot_name: The name of the mount target
:param str volume_name: The name of th... | id=self.id,
location=self.location,
name=self.name,
provisioning_state=self.provisioning_state,
snapshot_id=self.snapshot_id,
type=self.type)
def get_snapshot(account_name: Optional[str] = None,
pool_name: Optional[str] = None,
... | 108 | 108 | 360 | 73 | 35 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/netapp/v20200801/get_snapshot.py | Python | get_snapshot | get_snapshot | 117 | 152 | 117 | 122 | c1eb102f3121beb0eb52247ae801109b045deec2 | bigcode/the-stack | train |
3f44d07f659c12fec9c74da9 | train | class | class AwaitableGetSnapshotResult(GetSnapshotResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetSnapshotResult(
created=self.created,
id=self.id,
location=self.location,
name=self.name,
... | class AwaitableGetSnapshotResult(GetSnapshotResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetSnapshotResult(
created=self.created,
id=self.id,
location=self.location,
name=self.name,
provisioning_state=self.provisioning_state,
snapshot_id=self.snapshot_id,
... | (self, "snapshot_id")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type
"""
return pulumi.get(self, "type")
class AwaitableGetSnapshotResult(GetSnapshotResult):
# pylint: disable=using-constant-test
| 64 | 64 | 83 | 21 | 43 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/netapp/v20200801/get_snapshot.py | Python | AwaitableGetSnapshotResult | AwaitableGetSnapshotResult | 102 | 114 | 102 | 103 | 87e52e9498081f00e8e1e322cb68aaa9b638d818 | bigcode/the-stack | train |
75876234944ddfe9afa4637d | train | class | @pulumi.output_type
class GetSnapshotResult:
"""
Snapshot of a Volume
"""
def __init__(__self__, created=None, id=None, location=None, name=None, provisioning_state=None, snapshot_id=None, type=None):
if created and not isinstance(created, str):
raise TypeError("Expected argument 'cr... | @pulumi.output_type
class GetSnapshotResult:
| """
Snapshot of a Volume
"""
def __init__(__self__, created=None, id=None, location=None, name=None, provisioning_state=None, snapshot_id=None, type=None):
if created and not isinstance(created, str):
raise TypeError("Expected argument 'created' to be a str")
pulumi.set(__sel... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... | 110 | 183 | 613 | 11 | 99 | sebtelko/pulumi-azure-native | sdk/python/pulumi_azure_native/netapp/v20200801/get_snapshot.py | Python | GetSnapshotResult | GetSnapshotResult | 17 | 99 | 17 | 18 | e376bd2ac4790b454af0921c95e7bc212ef3a7f1 | bigcode/the-stack | train |
1c7a5fac783284a85d88470e | train | class | class Transaction(object):
state = _STATE_NOT_STARTED
id = None
start_time = None
_locals = threading.local()
logger = logging.getLogger("Transaction")
thread_id = None
def __init__(self, client, connection, timeout, durability, transaction_type):
self.connection = connection
... | class Transaction(object):
| state = _STATE_NOT_STARTED
id = None
start_time = None
_locals = threading.local()
logger = logging.getLogger("Transaction")
thread_id = None
def __init__(self, client, connection, timeout, durability, transaction_type):
self.connection = connection
self.timeout = timeout
... |
is no prepare of the transactions, so conflicts are not detected. If there is a conflict, then when the transaction
commits the changes, some of the changes are written and others are not; leaving the system in a potentially permanent
inconsistent state.
"""
ONE_PHASE = 2
RETRY_COUNT = 20
class TransactionManager(o... | 245 | 245 | 817 | 4 | 241 | LifeDJIK/S.H.I.V.A. | containers/shiva/hazelcast/transaction.py | Python | Transaction | Transaction | 63 | 168 | 63 | 63 | af135e720dcd470ff8b33e67345f428cd738c738 | bigcode/the-stack | train |
96b24a38b0d1879cd64f2525 | train | class | class TransactionManager(object):
logger = logging.getLogger("TransactionManager")
def __init__(self, client):
self._client = client
def _connect(self):
for count in xrange(0, RETRY_COUNT):
try:
address = self._client.load_balancer.next_address()
... | class TransactionManager(object):
| logger = logging.getLogger("TransactionManager")
def __init__(self, client):
self._client = client
def _connect(self):
for count in xrange(0, RETRY_COUNT):
try:
address = self._client.load_balancer.next_address()
return self._client.connection_ma... | so conflicts are not detected. If there is a conflict, then when the transaction
commits the changes, some of the changes are written and others are not; leaving the system in a potentially permanent
inconsistent state.
"""
ONE_PHASE = 2
RETRY_COUNT = 20
class TransactionManager(object):
| 64 | 64 | 174 | 5 | 58 | LifeDJIK/S.H.I.V.A. | containers/shiva/hazelcast/transaction.py | Python | TransactionManager | TransactionManager | 40 | 60 | 40 | 40 | a6cc88cce3c9c0bd7a40395724a0e879b73b87c3 | bigcode/the-stack | train |
21ea387bf3f13009f60a1633 | train | class | class Escape(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle(self.trUtf8('Переопределение события'))
self.resize(250, 150)
self.connect(self, QtCore.SIGNAL('closeEmitApp()'), QtCore.SLOT('close()'))
def keyPressEvent(s... | class Escape(QtGui.QWidget):
| def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle(self.trUtf8('Переопределение события'))
self.resize(250, 150)
self.connect(self, QtCore.SIGNAL('closeEmitApp()'), QtCore.SLOT('close()'))
def keyPressEvent(self, event):
if event... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Escape(QtGui.QWidget):
| 35 | 64 | 106 | 7 | 27 | janusnic/21v-pyqt | unit_02/slot2.py | Python | Escape | Escape | 7 | 17 | 7 | 7 | 91dc9b3ebe40930acd7b783377092336f5ee6675 | bigcode/the-stack | train |
20845ee54090fe792f0685f3 | train | class | class Autogen(AutotoolsPackage):
"""AutoGen is a tool designed to simplify the creation and maintenance of
programs that contain large amounts of repetitious text. It is especially
valuable in programs that have several blocks of text that must be kept
synchronized."""
homepage = "https://www.gnu.o... | class Autogen(AutotoolsPackage):
| """AutoGen is a tool designed to simplify the creation and maintenance of
programs that contain large amounts of repetitious text. It is especially
valuable in programs that have several blocks of text that must be kept
synchronized."""
homepage = "https://www.gnu.org/software/autogen/index.html"
... | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Autogen(AutotoolsPackage):
| 63 | 94 | 315 | 9 | 54 | adrianjhpc/spack | var/spack/repos/builtin/packages/autogen/package.py | Python | Autogen | Autogen | 9 | 43 | 9 | 9 | 5e12c3a1565bdf74cd10ecb9ed622c1023b3e633 | bigcode/the-stack | train |
df1d9b33a390122c032b517b | train | function | def do_html(name, choice):
if name == '1':
with open("txt.txt", "r", encoding='utf-8') as tt: # gb18030
txt = tt.readlines()
else:
with open("%s%s记录.txt" % (name, choice), "r", encoding='utf-8') as tt:#gb18030
txt = tt.readlines()
if not txt:
raise ... | def do_html(name, choice):
| if name == '1':
with open("txt.txt", "r", encoding='utf-8') as tt: # gb18030
txt = tt.readlines()
else:
with open("%s%s记录.txt" % (name, choice), "r", encoding='utf-8') as tt:#gb18030
txt = tt.readlines()
if not txt:
raise IndexError
counts = []
... | def do_html(name, choice):
| 7 | 118 | 396 | 7 | 0 | ChenFengYese/ChenFengYese.github.io | python_demo/test2.py | Python | do_html | do_html | 1 | 36 | 1 | 1 | 8ebc724396edd17943adf5d1cee311eae7f45bbe | bigcode/the-stack | train |
23a914a7ae0186c8884ceccf | train | function | def makebeam(xpixels,ypixels,st_dev,rot=0,cent=0):
if not cent: cent=[xpixels/2.,ypixels/2]
st_dev=st_dev[::-1]
st_dev=np.array(st_dev)/2.355
if np.tan(np.radians(rot)) == 0:
dirfac=1
else:
dirfac=np.sign(np.tan(np.radians(rot)))
x,y=np.indices((int(xpixels),int(ypixels)),dtyp... | def makebeam(xpixels,ypixels,st_dev,rot=0,cent=0):
| if not cent: cent=[xpixels/2.,ypixels/2]
st_dev=st_dev[::-1]
st_dev=np.array(st_dev)/2.355
if np.tan(np.radians(rot)) == 0:
dirfac=1
else:
dirfac=np.sign(np.tan(np.radians(rot)))
x,y=np.indices((int(xpixels),int(ypixels)),dtype='float')
x -=cent[0]
y -=cent[1] ... | # coding: utf-8
import numpy as np
def makebeam(xpixels,ypixels,st_dev,rot=0,cent=0):
| 32 | 98 | 329 | 20 | 11 | r-xue/KinMSpy | makebeam.py | Python | makebeam | makebeam | 4 | 19 | 4 | 4 | bbe63be809a0f2c1a80df0183192c784e8fa9f45 | bigcode/the-stack | train |
4b0616b9b7d8113eea683514 | train | function | def _try_get_item(x):
try:
return x.item()
except AttributeError:
return x
| def _try_get_item(x):
| try:
return x.item()
except AttributeError:
return x
| __ = ['Index']
_unsortable_types = frozenset(('mixed', 'mixed-integer'))
_index_doc_kwargs = dict(klass='Index', inplace='',
target_klass='Index',
unique='Index', duplicated='np.ndarray')
_index_shared_docs = dict()
def _try_get_item(x):
| 64 | 64 | 24 | 7 | 57 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _try_get_item | _try_get_item | 80 | 84 | 80 | 80 | 60de52641382e86a0b91295ec6b7947221e77ef5 | bigcode/the-stack | train |
37e7f1a2f6c41509e9b81385 | train | class | class Index(IndexOpsMixin, PandasObject):
"""
Immutable ndarray implementing an ordered, sliceable set. The basic object
storing axis labels for all pandas objects
Parameters
----------
data : array-like (1-dimensional)
dtype : NumPy dtype (default: object)
copy : bool
Make a co... | class Index(IndexOpsMixin, PandasObject):
| """
Immutable ndarray implementing an ordered, sliceable set. The basic object
storing axis labels for all pandas objects
Parameters
----------
data : array-like (1-dimensional)
dtype : NumPy dtype (default: object)
copy : bool
Make a copy of input ndarray
name : object
... | other)
result = missing.dispatch_missing(op, values, other, result)
attrs = self._get_attributes_dict()
attrs = self._maybe_update_attributes(attrs)
if op is divmod:
result = (Index(result[0], **attrs), Index(result[1], **attrs))
else:
result = Index(re... | 256 | 256 | 33,904 | 10 | 246 | Imanflow/pandas | pandas/core/indexes/base.py | Python | Index | Index | 175 | 4,709 | 175 | 175 | 09ba40bd600a73586737b6bf515d0828e8900721 | bigcode/the-stack | train |
8f43728c098deaf6fe1cbfe8 | train | function | def _make_arithmetic_op(op, cls):
def index_arithmetic_method(self, other):
if isinstance(other, (ABCSeries, ABCDataFrame)):
return NotImplemented
elif isinstance(other, ABCTimedeltaIndex):
# Defer to subclass implementation
return NotImplemented
other = ... | def _make_arithmetic_op(op, cls):
| def index_arithmetic_method(self, other):
if isinstance(other, (ABCSeries, ABCDataFrame)):
return NotImplemented
elif isinstance(other, ABCTimedeltaIndex):
# Defer to subclass implementation
return NotImplemented
other = self._validate_for_numeric_binop(o... | just return the indexing array directly
if is_bool_dtype(result):
return result
try:
return Index(result)
except TypeError:
return result
name = '__{name}__'.format(name=op.__name__)
# TODO: docstring?
return set_function_name(cmp_method, name, c... | 81 | 81 | 271 | 10 | 71 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _make_arithmetic_op | _make_arithmetic_op | 120 | 152 | 120 | 120 | 0a17d6c3d7d8128a09cbd2fa22a2d7dcc8e8fd2b | bigcode/the-stack | train |
e5b4677b439d521064b73c16 | train | function | def _make_comparison_op(op, cls):
def cmp_method(self, other):
if isinstance(other, (np.ndarray, Index, ABCSeries)):
if other.ndim > 0 and len(self) != len(other):
raise ValueError('Lengths must match to compare')
# we may need to directly compare underlying
# re... | def _make_comparison_op(op, cls):
| def cmp_method(self, other):
if isinstance(other, (np.ndarray, Index, ABCSeries)):
if other.ndim > 0 and len(self) != len(other):
raise ValueError('Lengths must match to compare')
# we may need to directly compare underlying
# representations
if needs_i8_... | ', 'mixed-integer'))
_index_doc_kwargs = dict(klass='Index', inplace='',
target_klass='Index',
unique='Index', duplicated='np.ndarray')
_index_shared_docs = dict()
def _try_get_item(x):
try:
return x.item()
except AttributeError:
return x
def ... | 76 | 76 | 254 | 10 | 65 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _make_comparison_op | _make_comparison_op | 87 | 117 | 87 | 87 | dd403dc0d75c1bfac53cb049b51272baee717587 | bigcode/the-stack | train |
bfc9d40d41e53dc564e12be3 | train | function | def _ensure_has_len(seq):
"""If seq is an iterator, put its values into a list."""
try:
len(seq)
except TypeError:
return list(seq)
else:
return seq
| def _ensure_has_len(seq):
| """If seq is an iterator, put its values into a list."""
try:
len(seq)
except TypeError:
return list(seq)
else:
return seq
| index_like = converted
else:
# clean_index_list does the equivalent of copying
# so only need to do this if not list instance
if copy:
from copy import copy
index_like = copy(index_like)
return Index(index_like)
def _ensure_has_len(seq):
| 64 | 64 | 46 | 7 | 57 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _ensure_has_len | _ensure_has_len | 4,817 | 4,824 | 4,817 | 4,817 | 5355d75af951e6fdcf157e343d9ee477e6ec2ba7 | bigcode/the-stack | train |
a7bb0c57d179838d73e0e764 | train | function | def _ensure_index_from_sequences(sequences, names=None):
"""Construct an index from sequences of data.
A single sequence returns an Index. Many sequences returns a
MultiIndex.
Parameters
----------
sequences : sequence of sequences
names : sequence of str
Returns
-------
index... | def _ensure_index_from_sequences(sequences, names=None):
| """Construct an index from sequences of data.
A single sequence returns an Index. Many sequences returns a
MultiIndex.
Parameters
----------
sequences : sequence of sequences
names : sequence of str
Returns
-------
index : Index or MultiIndex
Examples
--------
>>>... | .any)
@classmethod
def _add_logical_methods_disabled(cls):
""" add in logical methods to disable """
cls.all = make_invalid_op('all')
cls.any = make_invalid_op('any')
Index._add_numeric_methods_disabled()
Index._add_logical_methods()
Index._add_comparison_methods()
def _ensure_index_f... | 78 | 78 | 262 | 12 | 66 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _ensure_index_from_sequences | _ensure_index_from_sequences | 4,717 | 4,754 | 4,717 | 4,717 | 5879995cbcff273b2644e7ab3beab09af45eccb1 | bigcode/the-stack | train |
7be6a8914357a0dea05581d7 | train | function | def _validate_join_method(method):
if method not in ['left', 'right', 'inner', 'outer']:
raise ValueError('do not recognize join method %s' % method)
| def _validate_join_method(method):
| if method not in ['left', 'right', 'inner', 'outer']:
raise ValueError('do not recognize join method %s' % method)
| ):
"""
Trims zeros and decimal points
"""
trimmed = strings
while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):
trimmed = [x[1:] for x in trimmed]
return trimmed
def _validate_join_method(method):
| 64 | 64 | 40 | 7 | 56 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _validate_join_method | _validate_join_method | 4,837 | 4,839 | 4,837 | 4,837 | 45d44a33f3896f17b42c64af5ac3cbf9c5094a71 | bigcode/the-stack | train |
26452acd1e8935c86ddfca10 | train | class | class InvalidIndexError(Exception):
pass
| class InvalidIndexError(Exception):
| pass
| 1], **attrs))
else:
result = Index(result, **attrs)
return result
name = '__{name}__'.format(name=op.__name__)
# TODO: docstring?
return set_function_name(index_arithmetic_method, name, cls)
class InvalidIndexError(Exception):
| 64 | 64 | 9 | 6 | 58 | Imanflow/pandas | pandas/core/indexes/base.py | Python | InvalidIndexError | InvalidIndexError | 155 | 156 | 155 | 155 | 015a5dcf6abb8e89a7ce8afdc6f7c27ae6ec9af3 | bigcode/the-stack | train |
773224f53c85918976066eda | train | function | def _ensure_index(index_like, copy=False):
"""
Ensure that we have an index from some index-like object
Parameters
----------
index : sequence
An Index or other sequence
copy : bool
Returns
-------
index : Index or MultiIndex
Examples
--------
>>> _ensure_index... | def _ensure_index(index_like, copy=False):
| """
Ensure that we have an index from some index-like object
Parameters
----------
index : sequence
An Index or other sequence
copy : bool
Returns
-------
index : Index or MultiIndex
Examples
--------
>>> _ensure_index(['a', 'b'])
Index(['a', 'b'], dtype='o... | ['a'], ['a', 'b']],
labels=[[0, 0], [0, 1]],
names=['L1', 'L2'])
See Also
--------
_ensure_index
"""
from .multi import MultiIndex
if len(sequences) == 1:
if names is not None:
names = names[0]
return Index(sequences[0], name=names)
... | 117 | 117 | 391 | 10 | 107 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _ensure_index | _ensure_index | 4,757 | 4,814 | 4,757 | 4,757 | a14577783150012630e1befdf83cc8f56f5bc1f8 | bigcode/the-stack | train |
fe0fe0ba324459deb7fa0063 | train | function | def _trim_front(strings):
"""
Trims zeros and decimal points
"""
trimmed = strings
while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):
trimmed = [x[1:] for x in trimmed]
return trimmed
| def _trim_front(strings):
| """
Trims zeros and decimal points
"""
trimmed = strings
while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):
trimmed = [x[1:] for x in trimmed]
return trimmed
| _like = copy(index_like)
return Index(index_like)
def _ensure_has_len(seq):
"""If seq is an iterator, put its values into a list."""
try:
len(seq)
except TypeError:
return list(seq)
else:
return seq
def _trim_front(strings):
| 64 | 64 | 62 | 6 | 57 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _trim_front | _trim_front | 4,827 | 4,834 | 4,827 | 4,827 | efe6284e51a431b9250cd0e1a40e74b5ccc7fb39 | bigcode/the-stack | train |
4304631d9d9984299dfe94db | train | function | def _new_Index(cls, d):
""" This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__
"""
# required for backward compat, because PI can't be instantiated with
# ordinals through __new__ GH #13277
if issubclass(cls, ABCPeriodIndex):
from pand... | def _new_Index(cls, d):
| """ This is called upon unpickling, rather than the default which doesn't
have arguments and breaks __new__
"""
# required for backward compat, because PI can't be instantiated with
# ordinals through __new__ GH #13277
if issubclass(cls, ABCPeriodIndex):
from pandas.core.indexes.period i... | = '__{name}__'.format(name=op.__name__)
# TODO: docstring?
return set_function_name(index_arithmetic_method, name, cls)
class InvalidIndexError(Exception):
pass
_o_dtype = np.dtype(object)
_Identity = object
def _new_Index(cls, d):
| 64 | 64 | 110 | 8 | 55 | Imanflow/pandas | pandas/core/indexes/base.py | Python | _new_Index | _new_Index | 163 | 172 | 163 | 163 | d166721298a73f458b43689bd66641153c4145bf | bigcode/the-stack | train |
6f83e7dc7dba98592ac701a1 | train | function | def chooseLoadLevel(load):
if load <= 0.25:
return 1
elif 0.25 < load <= 0.5:
return 2
elif 0.5 < load <= 0.75:
return 3
elif 0.75 < load <= 1:
return 4
elif 1 < load <= 1.25:
return 5
elif load > 1.25:
return 6
| def chooseLoadLevel(load):
| if load <= 0.25:
return 1
elif 0.25 < load <= 0.5:
return 2
elif 0.5 < load <= 0.75:
return 3
elif 0.75 < load <= 1:
return 4
elif 1 < load <= 1.25:
return 5
elif load > 1.25:
return 6
| #! /usr/bin/env python3
from gpiozero import *
from os import getloadavg
from time import sleep
import mypins
leds = []
for x in mypins.pins6:
leds.append(LED(x))
def chooseLoadLevel(load):
| 55 | 64 | 106 | 6 | 49 | steelcowboy/pi-gpiozero | loadLEDS.py | Python | chooseLoadLevel | chooseLoadLevel | 13 | 25 | 13 | 13 | 21c357b88fd35734b5409adb92d54b74886cc30c | bigcode/the-stack | train |
071111bbaad144276a33abe5 | train | class | class PretreatmentEntity:
binaryzation: object = -1
concat_frames: object = -1
blend_frames: object = -1
replace_transparent: bool = True
horizontal_stitching: bool = False
exec_map: dict = {}
| class PretreatmentEntity:
| binaryzation: object = -1
concat_frames: object = -1
blend_frames: object = -1
replace_transparent: bool = True
horizontal_stitching: bool = False
exec_map: dict = {}
|
hue: bool = False
gamma: bool = False
channel_swap: bool = False
random_blank: int = -1
random_transition: int = -1
random_captcha: dict = {"Enable": False, "FontPath": ""}
class PretreatmentEntity:
| 63 | 64 | 59 | 5 | 59 | mycodemylife/captcha_trainer | config.py | Python | PretreatmentEntity | PretreatmentEntity | 133 | 139 | 133 | 133 | a36d0a1d92bd01baf90ae3d14f1fa5c9ab4dd060 | bigcode/the-stack | train |
f9c60d3af537e23f8aea6de8 | train | class | class DataAugmentationEntity:
binaryzation: object = -1
median_blur: int = -1
gaussian_blur: int = -1
equalize_hist: bool = False
laplace: bool = False
warp_perspective: bool = False
rotate: int = -1
sp_noise: float = -1.0
brightness: bool = False
saturation: bool = False
hue... | class DataAugmentationEntity:
| binaryzation: object = -1
median_blur: int = -1
gaussian_blur: int = -1
equalize_hist: bool = False
laplace: bool = False
warp_perspective: bool = False
rotate: int = -1
sp_noise: float = -1.0
brightness: bool = False
saturation: bool = False
hue: bool = False
gamma: bool... | ],
CNNNetwork.ResNetTiny: [16, 1024],
CNNNetwork.ResNet50: [16, 2048],
CNNNetwork.DenseNet: [32, 2048],
CNNNetwork.MobileNetV2: [32, 1200]
}
class DataAugmentationEntity:
| 64 | 64 | 153 | 6 | 58 | mycodemylife/captcha_trainer | config.py | Python | DataAugmentationEntity | DataAugmentationEntity | 114 | 130 | 114 | 114 | 4a91532cc465ed9316d29405abd25bf46b7dfe32 | bigcode/the-stack | train |
a101648aa5defe4695bee3d0 | train | class | class ModelConfig:
"""MODEL"""
model_root: dict
model_name: str
model_tag: str
model_field_param: str
model_scene_param: str
"""SYSTEM"""
system_root: dict
memory_usage: float
save_model: str
save_checkpoint: str
"""FIELD PARAM - IMAGE"""
field_root: dict
catego... | class ModelConfig:
| """MODEL"""
model_root: dict
model_name: str
model_tag: str
model_field_param: str
model_scene_param: str
"""SYSTEM"""
system_root: dict
memory_usage: float
save_model: str
save_checkpoint: str
"""FIELD PARAM - IMAGE"""
field_root: dict
category_param: list or s... | 50: [16, 2048],
CNNNetwork.DenseNet: [32, 2048],
CNNNetwork.MobileNetV2: [32, 1200]
}
class DataAugmentationEntity:
binaryzation: object = -1
median_blur: int = -1
gaussian_blur: int = -1
equalize_hist: bool = False
laplace: bool = False
warp_perspective: bool = False
rotate: int =... | 255 | 256 | 5,173 | 4 | 251 | mycodemylife/captcha_trainer | config.py | Python | ModelConfig | ModelConfig | 142 | 676 | 142 | 142 | 4e31dd800900725ab0f2613720ad4e5feeb3c15a | bigcode/the-stack | train |
375f5c3c20b2f21b600c91a1 | train | function | @pytest.fixture
def mock_device():
"""Mock a Dynalite device."""
return create_mock_device("switch", DynalitePresetSwitchDevice)
| @pytest.fixture
def mock_device():
| """Mock a Dynalite device."""
return create_mock_device("switch", DynalitePresetSwitchDevice)
| from dynalite_devices_lib.switch import DynalitePresetSwitchDevice
import pytest
from homeassistant.const import ATTR_FRIENDLY_NAME
from .common import (
ATTR_METHOD,
ATTR_SERVICE,
create_entity_from_device,
create_mock_device,
run_service_tests,
)
@pytest.fixture
def mock_device():
| 64 | 64 | 29 | 7 | 57 | tbarbette/core | tests/components/dynalite/test_switch.py | Python | mock_device | mock_device | 17 | 20 | 17 | 18 | 4905ce87eb0d6c89d817bc335e1d4de561b24fb2 | bigcode/the-stack | train |
1c71aa2fc8b6bc7ede6568e0 | train | function | async def test_switch_setup(hass, mock_device):
"""Test a successful setup."""
await create_entity_from_device(hass, mock_device)
entity_state = hass.states.get("switch.name")
assert entity_state.attributes[ATTR_FRIENDLY_NAME] == mock_device.name
await run_service_tests(
hass,
mock_d... | async def test_switch_setup(hass, mock_device):
| """Test a successful setup."""
await create_entity_from_device(hass, mock_device)
entity_state = hass.states.get("switch.name")
assert entity_state.attributes[ATTR_FRIENDLY_NAME] == mock_device.name
await run_service_tests(
hass,
mock_device,
"switch",
[
{... | ATTR_METHOD,
ATTR_SERVICE,
create_entity_from_device,
create_mock_device,
run_service_tests,
)
@pytest.fixture
def mock_device():
"""Mock a Dynalite device."""
return create_mock_device("switch", DynalitePresetSwitchDevice)
async def test_switch_setup(hass, mock_device):
| 64 | 64 | 115 | 11 | 53 | tbarbette/core | tests/components/dynalite/test_switch.py | Python | test_switch_setup | test_switch_setup | 23 | 36 | 23 | 23 | b70a96a81565da43c3d304d04e009b743cf33200 | bigcode/the-stack | train |
ba652dd33da525896d5905ff | train | function | def test_post_example(mock_client: TestClient):
"""Asserts ping endpoint returns pong"""
response = mock_client.post(f"{EXAMPLE_API_PREFIX}/", json={"a": 2, "b": 4})
assert response.status_code == HTTPStatus.OK.value
assert response.json()["result"] == 8
| def test_post_example(mock_client: TestClient):
| """Asserts ping endpoint returns pong"""
response = mock_client.post(f"{EXAMPLE_API_PREFIX}/", json={"a": 2, "b": 4})
assert response.status_code == HTTPStatus.OK.value
assert response.json()["result"] == 8
| _get_example(mock_client: TestClient):
"""Asserts ping endpoint returns pong"""
response = mock_client.get(f"{EXAMPLE_API_PREFIX}/")
assert response.status_code == HTTPStatus.OK.value
assert "Hello" in response.json()["msg"]
def test_post_example(mock_client: TestClient):
| 63 | 64 | 68 | 10 | 53 | gbourniq/lambda-restapi | sam-application/lambda_restapi/api/endpoints/v1/tests/test_example.py | Python | test_post_example | test_post_example | 23 | 29 | 23 | 23 | 1066bab2cd4d65e28fc06ac7fc0b6a3c0af63bfe | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.