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
a082de45a515393416a710ca
train
class
class VideoDirectoryImporter(UnlabeledVideoDatasetImporter): """Importer for a directory of videos stored on disk. See :ref:`this page <VideoDirectory-import>` for format details. Args: dataset_dir: the dataset directory recursive (True): whether to recursively traverse subdirectories ...
class VideoDirectoryImporter(UnlabeledVideoDatasetImporter):
"""Importer for a directory of videos stored on disk. See :ref:`this page <VideoDirectory-import>` for format details. Args: dataset_dir: the dataset directory recursive (True): whether to recursively traverse subdirectories compute_metadata (False): whether to produce ...
return self.compute_metadata def setup(self): filepaths = etau.list_files( self.dataset_dir, abs_paths=True, recursive=self.recursive ) filepaths = [p for p in filepaths if etai.is_image_mime_type(p)] self._filepaths = self._preprocess_list(filepaths) se...
156
156
520
11
145
pixta-dev/fiftyone
fiftyone/utils/data/importers.py
Python
VideoDirectoryImporter
VideoDirectoryImporter
1,742
1,820
1,742
1,742
22cc78fd4187d5a2116f42cfb358b8673624b906
bigcode/the-stack
train
b7091ce8b59be0d14b7b5edd
train
class
class ImageClassificationDirectoryTreeImporter(LabeledImageDatasetImporter): """Importer for an image classification directory tree stored on disk. See :ref:`this page <ImageClassificationDirectoryTree-import>` for format details. Args: dataset_dir: the dataset directory compute_metada...
class ImageClassificationDirectoryTreeImporter(LabeledImageDatasetImporter):
"""Importer for an image classification directory tree stored on disk. See :ref:`this page <ImageClassificationDirectoryTree-import>` for format details. Args: dataset_dir: the dataset directory compute_metadata (False): whether to produce :class:`fiftyone.core.metadata.Ima...
= labels.get("classes", None) self._sample_parser.classes = self._classes self._labels_map = labels.get("labels", {}) uuids = sorted(self._labels_map.keys()) self._uuids = self._preprocess_list(uuids) self._num_samples = len(self._uuids) def get_dataset_info(self): ...
206
206
687
12
194
pixta-dev/fiftyone
fiftyone/utils/data/importers.py
Python
ImageClassificationDirectoryTreeImporter
ImageClassificationDirectoryTreeImporter
1,991
2,104
1,991
1,991
a3af0c545b68a4cd4257e85b82a704f3edeea100
bigcode/the-stack
train
3fce7bb99278d6ec8d6c5221
train
class
class FiftyOneImageDetectionDatasetImporter( LabeledImageDatasetImporter, ImportPathsMixin ): """Importer for image detection datasets stored on disk in a simple JSON format. See :ref:`this page <FiftyOneImageDetectionDataset-import>` for format details. Args: dataset_dir (None): the d...
class FiftyOneImageDetectionDatasetImporter( LabeledImageDatasetImporter, ImportPathsMixin ):
"""Importer for image detection datasets stored on disk in a simple JSON format. See :ref:`this page <FiftyOneImageDetectionDataset-import>` for format details. Args: dataset_dir (None): the dataset directory. If omitted, ``data_path`` and/or ``labels_path`` must be provided ...
classes = set() for class_dir in etau.list_subdirs(self.dataset_dir, abs_paths=True): label = os.path.basename(class_dir) if label.startswith("."): continue if label == self.unlabeled: label = None else: cla...
256
256
1,256
20
235
pixta-dev/fiftyone
fiftyone/utils/data/importers.py
Python
FiftyOneImageDetectionDatasetImporter
FiftyOneImageDetectionDatasetImporter
2,227
2,395
2,227
2,229
720a66c0ed34ee849a34d61900eb5508c6be6c9a
bigcode/the-stack
train
863814654e1f679e292e0136
train
class
class BatchDatasetImporter(DatasetImporter): """Base interface for importers that load all of their samples in a single call to :meth:`import_samples`. This interface allows for greater efficiency for import formats that handle aggregating over the samples themselves. Typically, dataset importers ...
class BatchDatasetImporter(DatasetImporter):
"""Base interface for importers that load all of their samples in a single call to :meth:`import_samples`. This interface allows for greater efficiency for import formats that handle aggregating over the samples themselves. Typically, dataset importers should implement the parameters documented on...
`` parameters of the importer. Args: l: a list Returns: a processed copy of the list """ if self.shuffle: if self.seed is not None: random.seed(self.seed) l = copy(l) random.shuffle(l) if self...
90
90
301
8
81
pixta-dev/fiftyone
fiftyone/utils/data/importers.py
Python
BatchDatasetImporter
BatchDatasetImporter
818
858
818
818
395fe9afba2af8874c691ded2b77494de4845ef9
bigcode/the-stack
train
780400e7768d401655533493
train
class
class NetworkInterface(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, dns_settings: Optional[pulumi.Input[pulumi.InputType['NetworkInterfaceDnsSettingsArgs']]] = None, enable_accele...
class NetworkInterface(pulumi.CustomResource):
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, dns_settings: Optional[pulumi.Input[pulumi.InputType['NetworkInterfaceDnsSettingsArgs']]] = None, enable_accelerated_networking: Optional[pulumi.Input[bool]] ...
# 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 from ... import _utilities, _tables from...
110
256
2,960
9
101
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/network/v20191101/network_interface.py
Python
NetworkInterface
NetworkInterface
17
264
17
17
3395ed7dffb39f3dfb81a9a8f0c19c8f4492dc7f
bigcode/the-stack
train
a0dca8ebb67b3bb7c4f200e2
train
function
def read_version(txtpath): with open(txtpath, 'r') as f: version = f.readline().strip() return version
def read_version(txtpath):
with open(txtpath, 'r') as f: version = f.readline().strip() return version
ilation.html#compiler-directives ''' ext.cython_directives = { 'embedsignature':True, 'boundscheck':False, 'nonecheck':False, 'wraparound':False, 'cdivision':True} return ext def read_version(txtpath):
64
64
30
6
57
spata0818/prediction-constrained-topic-models
setup.py
Python
read_version
read_version
48
51
48
48
7fa18f6a1e768d0a7a2783e0e21fce6b51914c13
bigcode/the-stack
train
1c1b9bbf39ffef2d92f053c2
train
function
def add_directives_to_cython_ext(ext): ''' Improve speed of cython code extensions References ---------- http://docs.cython.org/src/reference/compilation.html#compiler-directives ''' ext.cython_directives = { 'embedsignature':True, 'boundscheck':False, 'nonecheck':False,...
def add_directives_to_cython_ext(ext):
''' Improve speed of cython code extensions References ---------- http://docs.cython.org/src/reference/compilation.html#compiler-directives ''' ext.cython_directives = { 'embedsignature':True, 'boundscheck':False, 'nonecheck':False, 'wraparound':False, 'c...
prerequisites are not specified. Returns ------- ext_list : list of extension objects ''' ext_list = list() if HAS_CYTHON: ext_list.append(make_cython_extension__nef_map_pi_d_K()) return ext_list def add_directives_to_cython_ext(ext):
64
64
94
10
53
spata0818/prediction-constrained-topic-models
setup.py
Python
add_directives_to_cython_ext
add_directives_to_cython_ext
33
46
33
33
04689d1c007847c28bf1b1ea7a4bfd4b092f26c6
bigcode/the-stack
train
155c446c700a6f4639b7154c
train
function
def make_extensions(): ''' Assemble C++/Cython extension objects for compilation. Warns user if required prerequisites are not specified. Returns ------- ext_list : list of extension objects ''' ext_list = list() if HAS_CYTHON: ext_list.append(make_cython_extension__nef_map_pi_...
def make_extensions():
''' Assemble C++/Cython extension objects for compilation. Warns user if required prerequisites are not specified. Returns ------- ext_list : list of extension objects ''' ext_list = list() if HAS_CYTHON: ext_list.append(make_cython_extension__nef_map_pi_d_K()) return ext_l...
pc_toolbox/model_slda/est_local_params__single_doc_map/calc_nef_map_pi_d_K__cython.pyx"], libraries=["m"], extra_compile_args = ["-O3", "-ffast-math"]) return add_directives_to_cython_ext(ext) def make_extensions():
64
64
77
4
60
spata0818/prediction-constrained-topic-models
setup.py
Python
make_extensions
make_extensions
19
31
19
19
1a12a73718d0039c584998a3613fffe458d690d5
bigcode/the-stack
train
e5eabf9f4a0d96970a0760f5
train
function
def make_cython_extension__nef_map_pi_d_K(): ext = Extension( "pc_toolbox.model_slda.est_local_params__single_doc_map.calc_nef_map_pi_d_K__cython", ["pc_toolbox/model_slda/est_local_params__single_doc_map/calc_nef_map_pi_d_K__cython.pyx"], libraries=["m"], extra_compile_args = ["-O3"...
def make_cython_extension__nef_map_pi_d_K():
ext = Extension( "pc_toolbox.model_slda.est_local_params__single_doc_map.calc_nef_map_pi_d_K__cython", ["pc_toolbox/model_slda/est_local_params__single_doc_map/calc_nef_map_pi_d_K__cython.pyx"], libraries=["m"], extra_compile_args = ["-O3", "-ffast-math"]) return add_directives_t...
from distutils.extension import Extension try: from Cython.Distutils import build_ext HAS_CYTHON = True except ImportError: from distutils.command.build_ext import build_ext HAS_CYTHON = False def make_cython_extension__nef_map_pi_d_K():
64
64
105
12
51
spata0818/prediction-constrained-topic-models
setup.py
Python
make_cython_extension__nef_map_pi_d_K
make_cython_extension__nef_map_pi_d_K
11
17
11
11
c1f679980bded00b3ca98525b4b1ef0167c93d61
bigcode/the-stack
train
e493680a7ddb1ae932cfdea1
train
class
class PeoplePOM(Serializable): def __init__(self): super().__init__() self.__people = OrderedDict() self.__annotated_frame = None self.__raw_frame = None def set_annotated_frame(self, frame): self.__annotated_frame = frame def set_raw_frame(self, frame): ...
class PeoplePOM(Serializable):
def __init__(self): super().__init__() self.__people = OrderedDict() self.__annotated_frame = None self.__raw_frame = None def set_annotated_frame(self, frame): self.__annotated_frame = frame def set_raw_frame(self, frame): self.__raw_frame = frame ...
# pylint: skip-file from collections import OrderedDict from darcyai.serializable import Serializable class PeoplePOM(Serializable):
28
256
1,162
7
20
edgeworx/darcyai
src/darcyai/perceptor/coral/people_perceptor_pom.py
Python
PeoplePOM
PeoplePOM
6
188
6
6
eaac253cec031e328666531ac5145a74136450a1
bigcode/the-stack
train
a1d2bd74e993345126f875ce
train
function
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" _LOGGER.debug("__init__ async_unload_entry") unload_ok = all( await asyncio.gather( *( hass.config_entries.async_forward_entry_unload(entry, component) ...
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" _LOGGER.debug("__init__ async_unload_entry") unload_ok = all( await asyncio.gather( *( hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ) ) ) if unload_ok...
coordinator, CONF_API: energy_api, } for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
64
64
133
20
43
DCSBL/ha-homewizard-energy
custom_components/homewizard_energy/__init__.py
Python
async_unload_entry
async_unload_entry
78
97
78
78
f91d09324b063a5cc050dfffe41b15f306d916f0
bigcode/the-stack
train
13c66e0901791cbc8c234ba1
train
function
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Homewizard Energy from a config entry.""" _LOGGER.debug("__init__ async_setup_entry") # Get api and do a initialization energy_api = aiohwenergy.HomeWizardEnergy(entry.data.get("host")) # Validate connection ...
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Homewizard Energy from a config entry.""" _LOGGER.debug("__init__ async_setup_entry") # Get api and do a initialization energy_api = aiohwenergy.HomeWizardEnergy(entry.data.get("host")) # Validate connection initialized = False try: with async_timeout.timeout(10): ...
"""The Homewizard Energy integration.""" import asyncio import logging import aiohwenergy import async_timeout from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from .const import CONF_API, COORDINATOR, DOMAIN, P...
110
114
382
19
91
DCSBL/ha-homewizard-energy
custom_components/homewizard_energy/__init__.py
Python
async_setup_entry
async_setup_entry
18
75
18
18
e16ee24dcb27965890d239814b8fb06a3ca96fb1
bigcode/the-stack
train
8856a8d4c256fd730f3de1e0
train
class
class VerificationFlowMethod(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute...
class VerificationFlowMethod(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
# coding: utf-8 """ Ory Kratos Welcome to the ORY Kratos HTTP API documentation! # noqa: E501 The version of the OpenAPI document: v0.5.4-alpha.1 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from ory_kratos_client.configuration import Configur...
96
256
904
6
89
UkonnRa/sdk
clients/kratos/python/ory_kratos_client/models/verification_flow_method.py
Python
VerificationFlowMethod
VerificationFlowMethod
21
150
21
21
ad836a085c5b6fcae019616a97f5b7206b1c674d
bigcode/the-stack
train
25fe9e60baafcaeb42493d68
train
class
class RegReader(object): def __init__(self, filename, image_scale = 4, verbose = False): # keep a record of the filename self.filename = filename self.verbose = verbose # regex for determining "source" and "target" (reference) image frame_re = re.compile(r'Source img: (...
class RegReader(object):
def __init__(self, filename, image_scale = 4, verbose = False): # keep a record of the filename self.filename = filename self.verbose = verbose # regex for determining "source" and "target" (reference) image frame_re = re.compile(r'Source img: ([\d]+) Target img: ([\d]+)') ...
#!/usr/bin/env python """ Class for reading ImageJ MultiStackReg Transformation files. This assumes that there is only one reference image and that all of the transforms are of the same type. Hazen 08/10 """ import math import numpy import os import re # The file reader class & helper functions def parseline(line,...
124
256
1,492
6
118
bintulab/storm-analysis
storm_analysis/sa_library/regfilereader.py
Python
RegReader
RegReader
25
204
25
26
25003e0c13b0a08dadcabbbec943e6843c498778
bigcode/the-stack
train
48ba7710dad373b7970d4603
train
function
def applyTransform(f_to_f_matrix, x, y): p = numpy.ones(x.shape[0]) input = numpy.concatenate((x[:,None], y[:,None], p[:,None]), axis = 1) result = numpy.dot(input, f_to_f_matrix) return [result[:,0], result[:,1]]
def applyTransform(f_to_f_matrix, x, y):
p = numpy.ones(x.shape[0]) input = numpy.concatenate((x[:,None], y[:,None], p[:,None]), axis = 1) result = numpy.dot(input, f_to_f_matrix) return [result[:,0], result[:,1]]
print("") def getTransformMatrix(self, index): if self.verbose: print("") print(index) print(self.f_to_f_matrix[index]) print("") return self.f_to_f_matrix[index] # Utility functions def applyTransform(f_to_f_ma...
64
64
70
12
51
bintulab/storm-analysis
storm_analysis/sa_library/regfilereader.py
Python
applyTransform
applyTransform
208
214
208
208
00422d384b268948c41b2b3ae00579f9693c42d8
bigcode/the-stack
train
b6aab6bb82fd947d2e12d41f
train
function
def applyTransformNoTranslation(f_to_f_matrix, x, y): p = numpy.zeros(x.shape[0]) input = numpy.concatenate((x[:,None], y[:,None], p[:,None]), axis = 1) result = numpy.dot(input, f_to_f_matrix) return [result[:,0], result[:,1]]
def applyTransformNoTranslation(f_to_f_matrix, x, y):
p = numpy.zeros(x.shape[0]) input = numpy.concatenate((x[:,None], y[:,None], p[:,None]), axis = 1) result = numpy.dot(input, f_to_f_matrix) return [result[:,0], result[:,1]]
0]) input = numpy.concatenate((x[:,None], y[:,None], p[:,None]), axis = 1) result = numpy.dot(input, f_to_f_matrix) return [result[:,0], result[:,1]] def applyTransformNoTranslation(f_to_f_matrix, x, y):
64
64
72
14
50
bintulab/storm-analysis
storm_analysis/sa_library/regfilereader.py
Python
applyTransformNoTranslation
applyTransformNoTranslation
216
222
216
216
3305eaaeb53f65946e9b2e6ec5455359d55556f2
bigcode/the-stack
train
08cfc1b764606c412f1dae1f
train
function
def parseline(line, scale): try: [x, y] = line.split("\t") return [float(x)/float(scale), float(y)/float(scale)] except: print("Error parsing:", line)
def parseline(line, scale):
try: [x, y] = line.split("\t") return [float(x)/float(scale), float(y)/float(scale)] except: print("Error parsing:", line)
StackReg Transformation files. This assumes that there is only one reference image and that all of the transforms are of the same type. Hazen 08/10 """ import math import numpy import os import re # The file reader class & helper functions def parseline(line, scale):
64
64
49
8
55
bintulab/storm-analysis
storm_analysis/sa_library/regfilereader.py
Python
parseline
parseline
18
23
18
18
70595b1a0dac4c2b87af9a7e5f5da0aa5b04d5cf
bigcode/the-stack
train
bbb2bf6996f58f89bec34c76
train
class
class WeVoteAPIsV1TestsVoterBallotItemsRetrieve(TestCase): def setUp(self): self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView") self.organization_count_url = reverse("apis_v1:organizationCountView") self.voter_create_url = reverse("apis_v1:voterCreateView") s...
class WeVoteAPIsV1TestsVoterBallotItemsRetrieve(TestCase):
def setUp(self): self.generate_voter_device_id_url = reverse("apis_v1:deviceIdGenerateView") self.organization_count_url = reverse("apis_v1:organizationCountView") self.voter_create_url = reverse("apis_v1:voterCreateView") self.voter_ballot_items_retrieve_url = reverse("apis_v1:voter...
# apis_v1/test_views_voter_ballot_items_retrieve.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.core.urlresolvers import reverse from django.test import TestCase import json class WeVoteAPIsV1TestsVoterBallotItemsRetrieve(TestCase):
72
256
1,143
17
54
mattare2/WeVoteServer
apis_v1/tests/test_views_voter_ballot_items_retrieve.py
Python
WeVoteAPIsV1TestsVoterBallotItemsRetrieve
WeVoteAPIsV1TestsVoterBallotItemsRetrieve
10
100
10
11
00a955adafc1a2712ebcc87aca93f9ebfb766a7c
bigcode/the-stack
train
477ea6434c92e5d01a0c8034
train
function
def check_for_license(main): if (os.path.isfile("license") or os.path.isfile("LICENSE") or os.path.isfile("license.md") or os.path.isfile("LICENSE.md")): main.output_result_check(passed=True, title="Recipe license") return True main.output_result_check(passed=False, title="Recipe lic...
def check_for_license(main):
if (os.path.isfile("license") or os.path.isfile("LICENSE") or os.path.isfile("license.md") or os.path.isfile("LICENSE.md")): main.output_result_check(passed=True, title="Recipe license") return True main.output_result_check(passed=False, title="Recipe license", ...
import os def check_for_license(main):
9
64
94
6
2
bincrafters/bincrafters-conventions
bincrafters_conventions/actions/check_for_license.py
Python
check_for_license
check_for_license
4
11
4
4
86bf61de06cf680a1278ec5693859d31e92398dd
bigcode/the-stack
train
ccb781e715c655ff25471eec
train
class
class Config: def __init__(self): # test params try: opts, _ = getopt.getopt( sys.argv[1:], "i:o:s:t:hvV", [ "input=", "output=", "sleep=", "strategy=", ...
class Config:
def __init__(self): # test params try: opts, _ = getopt.getopt( sys.argv[1:], "i:o:s:t:hvV", [ "input=", "output=", "sleep=", "strategy=", "...
import getopt import os import os.path import sys from dateutil import tz from datetime import datetime VERSION = "1.1.0" FAKE_SENSOR = "/tmp/fake-devices" INPUT = "/dev/video0" DEFAULT_SLEEP_MODE = "lux" DEFAULT_SLEEP_TIME = 30 DEFAULT_STRATEGY = "webcam" GPS = {"latitude": "48.8566969", "longitude": "2.3514616"} W...
136
228
763
3
133
cyrinux/wluma-als-emulator
wluma_als_emulator/core/config.py
Python
Config
Config
23
125
23
23
55282cb20c62d0c5bd8e30479b8ed0ae4454cda1
bigcode/the-stack
train
6147836936e08ed223e2602d
train
function
def list_incidents(profile): ''' List services belonging to this account CLI Example: pagerduty.list_incidents my-pagerduty-account ''' pager = _get_pager(profile) ret = {} for incident in pager.incidents.list(): ret[incident.id] = { 'status': incident.status, ...
def list_incidents(profile):
''' List services belonging to this account CLI Example: pagerduty.list_incidents my-pagerduty-account ''' pager = _get_pager(profile) ret = {} for incident in pager.incidents.list(): ret[incident.id] = { 'status': incident.status, 'service': { ...
'email_incident_creation': service.email_incident_creation, 'id': service.id, 'incident_counts': { 'acknowledged': service.incident_counts.acknowledged, 'resolved': service.incident_counts.resolved, 'total': service.incident_counts.tota...
140
140
469
6
133
skrobul/salt
salt/modules/pagerduty.py
Python
list_incidents
list_incidents
90
146
90
90
9256ff87e3315ccab858c9a63ca275e8750837c5
bigcode/the-stack
train
34a5f8172121c7f7e472b15f
train
function
def list_services(profile): ''' List services belonging to this account CLI Example: pagerduty.list_services my-pagerduty-account ''' pager = _get_pager(profile) ret = {} for service in pager.services.list(): ret[service.name] = { 'acknowledgement_timeout': serv...
def list_services(profile):
''' List services belonging to this account CLI Example: pagerduty.list_services my-pagerduty-account ''' pager = _get_pager(profile) ret = {} for service in pager.services.list(): ret[service.name] = { 'acknowledgement_timeout': service.acknowledgement_timeout,...
return False def _get_pager(profile): ''' Return the pagerduty connection ''' creds = __salt__['config.option'](profile) pager = pygerduty.PagerDuty( creds.get('pagerduty.subdomain'), creds.get('pagerduty.api_key'), ) return pager def list_services(profile):
78
78
262
5
72
skrobul/salt
salt/modules/pagerduty.py
Python
list_services
list_services
54
87
54
54
a0322bb4c5abffc05c5189c6a656aa82dfdcedd7
bigcode/the-stack
train
3a3658b807968c06034fd85d
train
function
def create_event(service_key, description, details, incident_key=None, profile=None): ''' Create an event in PagerDuty. Designed for use in states. CLI Example: pagerduty.create_event <service_key> <description> <details> \ profile=my-pagerduty-account The followi...
def create_event(service_key, description, details, incident_key=None, profile=None):
''' Create an event in PagerDuty. Designed for use in states. CLI Example: pagerduty.create_event <service_key> <description> <details> \ profile=my-pagerduty-account The following parameters are required: service_key This key can be found by using pagerduty.list_serv...
_status_change_by.id, 'name': incident.last_status_change_by.name, 'html_url': incident.last_status_change_by.html_url, 'email': incident.last_status_change_by.email, } return ret def create_event(service_key, description, details, incident_key=None, ...
64
64
198
18
45
skrobul/salt
salt/modules/pagerduty.py
Python
create_event
create_event
149
182
149
150
ce39848026f66420ef38113d6691acf78a5d19c3
bigcode/the-stack
train
1d19820ae8fe3fa51b038bd4
train
function
def _get_pager(profile): ''' Return the pagerduty connection ''' creds = __salt__['config.option'](profile) pager = pygerduty.PagerDuty( creds.get('pagerduty.subdomain'), creds.get('pagerduty.api_key'), ) return pager
def _get_pager(profile):
''' Return the pagerduty connection ''' creds = __salt__['config.option'](profile) pager = pygerduty.PagerDuty( creds.get('pagerduty.subdomain'), creds.get('pagerduty.api_key'), ) return pager
Error: pass __virtualname__ = 'pagerduty' def __virtual__(): ''' Only load this module if pygerduty is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return False def _get_pager(profile):
64
64
69
7
56
skrobul/salt
salt/modules/pagerduty.py
Python
_get_pager
_get_pager
40
51
40
40
c50b78018c8358d458214c082ccd2fb43167d1e9
bigcode/the-stack
train
99904270fd5351a30dee51e7
train
function
def __virtual__(): ''' Only load this module if pygerduty is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return False
def __virtual__():
''' Only load this module if pygerduty is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return False
ve43rfFWf2214 pagerduty.subdomain: mysubdomain ''' HAS_LIBS = False try: import pygerduty HAS_LIBS = True except ImportError: pass __virtualname__ = 'pagerduty' def __virtual__():
64
64
42
5
59
skrobul/salt
salt/modules/pagerduty.py
Python
__virtual__
__virtual__
31
37
31
31
fdeb6549f25eb7a442a372a4f6cbc2e7bb7fe50a
bigcode/the-stack
train
9676ac366a3b64bf37314d11
train
function
def main(): """Run the server.""" return create_app()
def main():
"""Run the server.""" return create_app()
an instance of the flask application. :return: Instance of flask application. """ app = Flask(__name__) @app.route("/health") def health(): """ Get information about whether service is running """ return jsonify({"online": True}) return app def main():
64
64
14
3
60
zamj/selected-tests
src/selectedtests/app/app.py
Python
main
main
28
30
28
28
484fb1fd8267d21bcef4f2c6e4805e9336cad635
bigcode/the-stack
train
193961769b8b86b536be0948
train
function
def create_app() -> Flask: """ Create an instance of the flask application. :return: Instance of flask application. """ app = Flask(__name__) @app.route("/health") def health(): """ Get information about whether service is running """ return jsonify({"online...
def create_app() -> Flask:
""" Create an instance of the flask application. :return: Instance of flask application. """ app = Flask(__name__) @app.route("/health") def health(): """ Get information about whether service is running """ return jsonify({"online": True}) return app
""" Application to serve API of selected-tests service. """ from flask import Flask, jsonify DEFAULT_PORT = 8080 def create_app() -> Flask:
32
64
72
7
24
zamj/selected-tests
src/selectedtests/app/app.py
Python
create_app
create_app
10
25
10
10
04b30a5c274b8dffe2c1432efbd2931e545cdaee
bigcode/the-stack
train
3e971d6b7aa3239c372d97ad
train
class
class FormTests(TestCase): def setUp(self): self.account = Account.objects.create(name="first account") self.personal = Account.objects.create(name="personal account") def test_TransferForm(self): data = { 'title': 'transfer', 'source_account': self.account.pk, ...
class FormTests(TestCase):
def setUp(self): self.account = Account.objects.create(name="first account") self.personal = Account.objects.create(name="personal account") def test_TransferForm(self): data = { 'title': 'transfer', 'source_account': self.account.pk, 'destination_acc...
from django.db import models from django.test import TestCase from silverstrike.forms import DepositForm, TransferForm, WithdrawForm from silverstrike.models import Account, Split, Transaction class FormTests(TestCase):
44
256
1,209
6
37
luisfmelo/silverstrike
silverstrike/tests/test_forms.py
Python
FormTests
FormTests
8
146
8
8
35dd61580e4f12743252a0e8856b47a7681f85f2
bigcode/the-stack
train
83c5db291158cfbdce9ba7da
train
function
@s.PermissionWebhookAPI.post(schema=s.PermissionWebhook_POST_RequestSchema, tags=[s.WebhooksTag], response_schemas=s.PermissionWebhook_POST_responses) @view_config(route_name=s.PermissionWebhookAPI.name, request_method="POST") def post_permission_webhook_view(request): """ Permissio...
@s.PermissionWebhookAPI.post(schema=s.PermissionWebhook_POST_RequestSchema, tags=[s.WebhooksTag], response_schemas=s.PermissionWebhook_POST_responses) @view_config(route_name=s.PermissionWebhookAPI.name, request_method="POST") def post_permission_webhook_view(request):
""" Permission webhook used for created or removed permission events. """ event = ar.get_multiformat_body(request, "event") ax.verify_param(event, param_name="event", param_compare=ValidOperations.values(), is_in=True, http_error=HTTPBadReq...
: LOGGER.warning("Cannot complete the Magpie callback url request to [%s] : [%s]", callback_url, exc) else: LOGGER.warning("Exception occurs while dispatching event") # TODO: return something else than 200 return ax.valid_http(HTTPOk, detail=s.UserWebhook_POST_OkResponseS...
128
128
429
55
73
Ouranosinc/cowbird
cowbird/api/webhooks/views.py
Python
post_permission_webhook_view
post_permission_webhook_view
75
117
75
78
c2a2f3cb835fa582800ca151dd2e3d104a1f5d58
bigcode/the-stack
train
611291d80cd6a5963485df8a
train
function
@s.UserWebhookAPI.post(schema=s.UserWebhook_POST_RequestSchema, tags=[s.WebhooksTag], response_schemas=s.UserWebhook_POST_responses) @view_config(route_name=s.UserWebhookAPI.name, request_method="POST") def post_user_webhook_view(request): """ User webhook used for created or removed user...
@s.UserWebhookAPI.post(schema=s.UserWebhook_POST_RequestSchema, tags=[s.WebhooksTag], response_schemas=s.UserWebhook_POST_responses) @view_config(route_name=s.UserWebhookAPI.name, request_method="POST") def post_user_webhook_view(request):
""" User webhook used for created or removed user events. """ event = ar.get_multiformat_body(request, "event") ax.verify_param(event, param_name="event", param_compare=ValidOperations.values(), is_in=True, http_error=HTTPBadRequest, ...
) svc_fct(svc) except Exception as exception: # noqa exceptions.append(exception) LOGGER.error("Exception raised while handling event [%s] for service [%s] : [%r]", event_name, svc.name, exception) if exceptions: raise Exception(exception...
118
118
395
55
63
Ouranosinc/cowbird
cowbird/api/webhooks/views.py
Python
post_user_webhook_view
post_user_webhook_view
34
72
34
37
e02ea6676c0c253a4d3df87038d0be7f0bb672f6
bigcode/the-stack
train
af2ca8ba3e1f14446f3c0223
train
function
def dispatch(svc_fct): exceptions = [] event_name = inspect.getsource(svc_fct).split(":")[1].strip() for svc in ServiceFactory().get_active_services(): # Allow every service to be notified even if one of them throw an error try: LOGGER.info("Dispatching event [%s] for service [%s...
def dispatch(svc_fct):
exceptions = [] event_name = inspect.getsource(svc_fct).split(":")[1].strip() for svc in ServiceFactory().get_active_services(): # Allow every service to be notified even if one of them throw an error try: LOGGER.info("Dispatching event [%s] for service [%s]", event_name, svc.nam...
from cowbird.api import schemas as s from cowbird.api.schemas import ValidOperations from cowbird.permissions_synchronizer import Permission from cowbird.services.service_factory import ServiceFactory from cowbird.utils import get_logger, get_ssl_verify LOGGER = get_logger(__name__) def dispatch(svc_fct):
64
64
144
7
57
Ouranosinc/cowbird
cowbird/api/webhooks/views.py
Python
dispatch
dispatch
18
31
18
18
133ecc35b971dea88ecba9cedba1db5c0c66f4df
bigcode/the-stack
train
b547d893450d072b01c4d11f
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Game', fields=[ ('uid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('cre...
class Migration(migrations.Migration):
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Game', fields=[ ('uid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('created_at', models.DateTimeField(auto_now_...
# Generated by Django 2.2.3 on 2019-08-01 18:24 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration):
48
117
392
7
40
SolarLiner/django-serverside
ssr_test/migrations/0001_initial.py
Python
Migration
Migration
8
59
8
9
68e02845888d61dc170bbad9aa223f446e0322e0
bigcode/the-stack
train
bc18d1a612848237f94576ab
train
function
def main(): """ Advbox demo which demonstrate how to use advbox. """ TOTAL_NUM = 500 IMG_NAME = 'img' LABEL_NAME = 'label' img = fluid.layers.data(name=IMG_NAME, shape=[1, 28, 28], dtype='float32') # gradient should flow img.stop_gradient = False label = fluid.layers.data(name=L...
def main():
""" Advbox demo which demonstrate how to use advbox. """ TOTAL_NUM = 500 IMG_NAME = 'img' LABEL_NAME = 'label' img = fluid.layers.data(name=IMG_NAME, shape=[1, 28, 28], dtype='float32') # gradient should flow img.stop_gradient = False label = fluid.layers.data(name=LABEL_NAME, s...
# Copyright 2017 - 2018 Baidu Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
234
256
906
3
230
jayxio/AdvBox
tutorials/mnist_tutorial_lbfgs.py
Python
main
main
31
139
31
31
c6221cdfef165bae74f2e4e80a18fee90d910d08
bigcode/the-stack
train
03f2117be5251cc7f1afa99a
train
class
class Sweeper(object): plotOptions = None monitorOptions = None def __init__(self): self.data = None self.savefile = None self.plotOptions = dict() self.monitorOptions = dict() def gather(self): print('gather method must be overloaded in subclass') def save...
class Sweeper(object):
plotOptions = None monitorOptions = None def __init__(self): self.data = None self.savefile = None self.plotOptions = dict() self.monitorOptions = dict() def gather(self): print('gather method must be overloaded in subclass') def save(self, savefile=None): ...
''' Generalized sweep classes ''' import matplotlib.pyplot as plt import numpy as np import time from IPython import display import matplotlib.cm from collections import OrderedDict from lightlab.util.data import argFlatten, rms from lightlab.util.plot import plotCovEllipse import lightlab.util.io as io from lightlab...
77
168
561
5
71
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
Sweeper
Sweeper
17
104
17
17
bfb117dab4370ea957a69d19b1049e41e8d3891f
bigcode/the-stack
train
0cd919da005f9cbdf93a91c4
train
class
class NdSweeper(Sweeper): ''' Generic sweeper. Here's the difference between measure and parse: measure is a call to something, usually an instrument and some simpe post processing, like peak finding. * It is stored in data * When subsuming, only unique measureme...
class NdSweeper(Sweeper):
''' Generic sweeper. Here's the difference between measure and parse: measure is a call to something, usually an instrument and some simpe post processing, like peak finding. * It is stored in data * When subsuming, only unique measurements are kept ...
self.plotOptions[k] = v return self.plotOptions def setMonitorOptions(self, **kwargs): ''' Valid options for NdSweeper * livePlot * plotEvery * stdoutPrint * runServer Valid options for CommandControlSweeper ...
256
256
5,798
8
247
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
NdSweeper
NdSweeper
118
717
118
118
73d4e6de43990f37db474a89490f69a70b96cbd6
bigcode/the-stack
train
ad684573f016f58df696e086
train
function
def plotCmdCtrl(sweepData, index=None, ax=None, interactive=False): ''' sweepData should have ALL the command weights specified Args: sweepData (tuple): cmdWeights, measWeights, monitWeights (optional) measWeights has shape (nTrials, len(swp1), len(sp2) or 1, len(sweepingChannel...
def plotCmdCtrl(sweepData, index=None, ax=None, interactive=False):
''' sweepData should have ALL the command weights specified Args: sweepData (tuple): cmdWeights, measWeights, monitWeights (optional) measWeights has shape (nTrials, len(swp1), len(sp2) or 1, len(sweepingChannels)) index (tuple): tells which parts of measured weights...
VsWeight = rms(measWeights - meanVsWeight, axis=0) # Statistics normed over channels at every grid point # netErrRmsVsWeight = rms(errRmsVsWeight, axis=-1) netErrMeanVsWeight = rms(errMeanVsWeight, axis=-1) netErrStddevVsWeight = rms(errStddevVsWeight, axis=-1) # Take the worst...
256
256
1,334
17
238
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
plotCmdCtrl
plotCmdCtrl
970
1,093
970
970
b3ee58b08434b0f189e510c8c8b41e6b36b7a588
bigcode/the-stack
train
213acd91adf0d33d7031b10b
train
function
def assertValidPlotType(plType, dims=None, swpClass=None): if plType not in availablePlots(dims, swpClass): errStr = ['Invalid plot type.'] errStr.append(f'This sweep is a {dims}-dimensional {swpClass.__name__}.') if plType not in availablePlots(): errStr.append(f'{plType} is not...
def assertValidPlotType(plType, dims=None, swpClass=None):
if plType not in availablePlots(dims, swpClass): errStr = ['Invalid plot type.'] errStr.append(f'This sweep is a {dims}-dimensional {swpClass.__name__}.') if plType not in availablePlots(): errStr.append(f'{plType} is not a valid plot type at all.') else: errS...
or type(swpType) is type and swpType.__name__ in v[1] \ or type(swpType) is str and swpType in v[1]: avail.append(k) return avail def assertValidPlotType(plType, dims=None, swpClass=None):
64
64
157
16
47
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
assertValidPlotType
assertValidPlotType
1,123
1,133
1,123
1,123
a7bebdebf0ebb6c2eba090e5cbc4bfbc62366883
bigcode/the-stack
train
c24f372c3ef286875c5ad938
train
class
class CommandControlSweeper(Sweeper): ''' Generic command-control sweep for evaluating a controller. The command function called at each point takes one argument that is an array (length M) and returns an array **of equal length**. The sweep is N (<= M) dimensional. * The user specifie...
class CommandControlSweeper(Sweeper):
''' Generic command-control sweep for evaluating a controller. The command function called at each point takes one argument that is an array (length M) and returns an array **of equal length**. The sweep is N (<= M) dimensional. * The user specifies the mapping between the sweep domain...
return newObj def load(self, savefile=None): super().load(savefile) self._recalcSwpShape() def simpleSweep(actuate, domain, measure=None): ''' Basic sweep in one dimension, without function keys, parsing, or plotting. Args: actuate (function): a procedure or function of ...
256
256
2,244
9
247
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
CommandControlSweeper
CommandControlSweeper
743
961
743
743
d4107803928a26b49316a272a252c5350e075e8d
bigcode/the-stack
train
65824ef31aafabcf7f89b3ff
train
function
def availablePlots(dims=None, swpType=None): ''' Filter by dims and swpType If the argument is none, do not filter by that ''' avail = [] for k, v in pTypes.items(): if dims is None or dims in v[0]: if swpType is None \ or type(swpType) is type and swpTyp...
def availablePlots(dims=None, swpType=None):
''' Filter by dims and swpType If the argument is none, do not filter by that ''' avail = [] for k, v in pTypes.items(): if dims is None or dims in v[0]: if swpType is None \ or type(swpType) is type and swpType.__name__ in v[1] \ or t...
Sweeper.__name__, CommandControlSweeper.__name__}) pTypes['surf'] = ({2}, {NdSweeper.__name__}) pTypes['cmdErr'] = ({1, 2}, {CommandControlSweeper.__name__}) def availablePlots(dims=None, swpType=None):
64
64
120
12
52
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
availablePlots
availablePlots
1,108
1,120
1,108
1,108
8d6ac23a260e630e334f3ea1a8652c50b757a5c0
bigcode/the-stack
train
1682e39443f2b0e4c82f1042
train
class
class Actuation(object): function = None domain = None doOnEveryPoint = None def __init__(self, function=None, domain=None, doOnEveryPoint=False): self.function = function self.domain = domain self.doOnEveryPoint = doOnEveryPoint
class Actuation(object):
function = None domain = None doOnEveryPoint = None def __init__(self, function=None, domain=None, doOnEveryPoint=False): self.function = function self.domain = domain self.doOnEveryPoint = doOnEveryPoint
logger.warning('Valid ones are %s', self.monitorOptions.keys()) else: self.monitorOptions[k] = v return self.monitorOptions @classmethod def fromFile(cls, filename): new = cls() new.load(filename) return new class Actuation(object):
64
64
66
5
58
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
Actuation
Actuation
107
115
107
107
b15bd186a4d69e26c7b9a0260fb5a485faa983bd
bigcode/the-stack
train
03dbb64e041f7d2544e58a0a
train
function
def simpleSweep(actuate, domain, measure=None): ''' Basic sweep in one dimension, without function keys, parsing, or plotting. Args: actuate (function): a procedure or function of one argument called at every point domain (ndarray): elements passed as an argument to actuate for each...
def simpleSweep(actuate, domain, measure=None):
''' Basic sweep in one dimension, without function keys, parsing, or plotting. Args: actuate (function): a procedure or function of one argument called at every point domain (ndarray): elements passed as an argument to actuate for each point measure (function, None): a f...
newObj.parse = functionSource.parse # Restore measurements functions newObj.measure = functionSource.measure return newObj def load(self, savefile=None): super().load(savefile) self._recalcSwpShape() def simpleSweep(actuate, domain, measure=None):
65
65
218
11
54
Kaixuangithub/lightlab
lightlab/util/sweep.py
Python
simpleSweep
simpleSweep
720
740
720
720
93eb89193a7c6d8bc22fd28068bb3991b32f4d31
bigcode/the-stack
train
ea68e77cfa9c9d56d2498e7a
train
class
class EnasMutator(Mutator): def __init__(self, model, lstm_size=64, lstm_num_layers=1, tanh_constant=1.5, cell_exit_extra_step=False, skip_target=0.4, temperature=None, branch_bias=0.25, ...
class EnasMutator(Mutator):
def __init__(self, model, lstm_size=64, lstm_num_layers=1, tanh_constant=1.5, cell_exit_extra_step=False, skip_target=0.4, temperature=None, branch_bias=0.25, entropy_reduction='su...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import tensorflow as tf from tensorflow.keras.layers import Dense, Embedding, LSTMCell, RNN from tensorflow.keras.losses import SparseCategoricalCrossentropy, Reduction from nni.nas.tensorflow.mutator import Mutator from nni.nas.tensorflow.mutab...
94
256
1,614
9
84
PeterouZh/nni
src/sdk/pynni/nni/nas/tensorflow/enas/mutator.py
Python
EnasMutator
EnasMutator
12
160
12
12
ea3d961b04ff9f6c8d109d9f1b9bd426840bb689
bigcode/the-stack
train
c07ae2d8e94b821b9ecd6211
train
class
class UnfiledImages(DummyFolder): name = _("unfiled files") is_root = True _icon = "unfiled_folder" def _files(self): return File.objects.filter(folder__isnull=True) files = property(_files) def get_admin_directory_listing_url_path(self): return urlresolvers.reverse('admin:filer-...
class UnfiledImages(DummyFolder):
name = _("unfiled files") is_root = True _icon = "unfiled_folder" def _files(self): return File.objects.filter(folder__isnull=True) files = property(_files) def get_admin_directory_listing_url_path(self): return urlresolvers.reverse('admin:filer-directory_listing-unfiled_images')...
(id__in=[0]) # empty queryset @property def files(self): return File.objects.filter(id__in=[0]) # empty queryset parent_url = None @property def image_files(self): return self.files class UnfiledImages(DummyFolder):
64
64
85
9
54
digi604/django-filer
filer/models/virtualitems.py
Python
UnfiledImages
UnfiledImages
29
37
29
29
ba0366f134579db981114ea65350b86bb795dbd4
bigcode/the-stack
train
6128ea0d59bd8fb389fdf8ed
train
class
class ImagesWithMissingData(DummyFolder): name = _("files with missing metadata") is_root = True _icon = "incomplete_metadata_folder" @property def files(self): return File.objects.filter(has_all_mandatory_data=False) def get_admin_directory_listing_url_path(self): return urlreso...
class ImagesWithMissingData(DummyFolder):
name = _("files with missing metadata") is_root = True _icon = "incomplete_metadata_folder" @property def files(self): return File.objects.filter(has_all_mandatory_data=False) def get_admin_directory_listing_url_path(self): return urlresolvers.reverse('admin:filer-directory_listi...
d_folder" def _files(self): return File.objects.filter(folder__isnull=True) files = property(_files) def get_admin_directory_listing_url_path(self): return urlresolvers.reverse('admin:filer-directory_listing-unfiled_images') class ImagesWithMissingData(DummyFolder):
63
64
83
9
54
digi604/django-filer
filer/models/virtualitems.py
Python
ImagesWithMissingData
ImagesWithMissingData
39
47
39
39
11db7936219721141c49d13bb55d5b40c4581721
bigcode/the-stack
train
750dfdd8d7b089727e119898
train
class
class DummyFolder(mixins.IconsMixin): name = "Dummy Folder" is_root = True is_smart_folder = True can_have_subfolders = False parent = None _icon = "plainfolder" @property def virtual_folders(self): return [] @property def children(self): return Folder.objects.fil...
class DummyFolder(mixins.IconsMixin):
name = "Dummy Folder" is_root = True is_smart_folder = True can_have_subfolders = False parent = None _icon = "plainfolder" @property def virtual_folders(self): return [] @property def children(self): return Folder.objects.filter(id__in=[0]) # empty queryset @...
from django.utils.translation import ugettext_lazy as _ from filer.models.filemodels import File from filer.models.foldermodels import Folder from filer.models import mixins from django.core import urlresolvers class DummyFolder(mixins.IconsMixin):
51
64
135
10
40
digi604/django-filer
filer/models/virtualitems.py
Python
DummyFolder
DummyFolder
7
26
7
7
d751504642b53a205057eb18a660025a92769f23
bigcode/the-stack
train
cd702ae40ea9551d1db4f1a4
train
class
class FolderRoot(DummyFolder): name = 'Root' is_root = True is_smart_folder = False can_have_subfolders = True @property def virtual_folders(self): return [UnfiledImages(), ]# ImagesWithMissingData()] @property def children(self): return Folder.objects.filter(parent__isnu...
class FolderRoot(DummyFolder):
name = 'Root' is_root = True is_smart_folder = False can_have_subfolders = True @property def virtual_folders(self): return [UnfiledImages(), ]# ImagesWithMissingData()] @property def children(self): return Folder.objects.filter(parent__isnull=True) parent_url = None...
icon = "incomplete_metadata_folder" @property def files(self): return File.objects.filter(has_all_mandatory_data=False) def get_admin_directory_listing_url_path(self): return urlresolvers.reverse('admin:filer-directory_listing-images_with_missing_data') class FolderRoot(DummyFolder):
64
64
112
7
57
digi604/django-filer
filer/models/virtualitems.py
Python
FolderRoot
FolderRoot
49
62
49
49
a35ce3cc55c54f77c96292424a456fa803f2c715
bigcode/the-stack
train
ca9ebb31dca0b7e2e8cfff72
train
function
def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.SWAP.on(input_q...
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=5 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=19 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode def make_circuit(n: int, input_qubit):
101
115
386
12
88
UCLA-SEAL/QDiff
data/cirq_new/cirq_program/startCirq_noisy438.py
Python
make_circuit
make_circuit
17
40
17
17
96128200511d7c3a1143559f4f1fdac0ac3bb6ea
bigcode/the-stack
train
7a7aebdafdb0965abc0a097e
train
function
def bitstring(bits): return ''.join(str(int(b)) for b in bits)
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
bit[0])) # number=17 c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=18 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits):
64
64
18
5
58
UCLA-SEAL/QDiff
data/cirq_new/cirq_program/startCirq_noisy438.py
Python
bitstring
bitstring
42
43
42
42
d8906cddcb2bd582e6d3ac5751986873fa7d631d
bigcode/the-stack
train
928217ac1919d768a746b2c0
train
class
class DsspRecord(object) : """Representation of DSSP output.""" __slots__ = ['pdbid', 'residues', '_res_dict'] def __init__(self, dssp_file) : """Construct a DsspRecord from a DSSP output file. args: - dssp_file : An open file handle attributes : ...
class DsspRecord(object) :
"""Representation of DSSP output.""" __slots__ = ['pdbid', 'residues', '_res_dict'] def __init__(self, dssp_file) : """Construct a DsspRecord from a DSSP output file. args: - dssp_file : An open file handle attributes : - pdbid : The PDB id....
. """ args = [self.command, '--'] try : p = Popen(args, stdin= pdb_file, stdout=PIPE) (out,err) = p.communicate() except OSError : raise RuntimeError("Cannot communicate with DSSP.") return out def record(self, pdb_file) : "...
137
138
461
7
129
go-bears/Final-Project
weblogo-3.4_rd/corebio/secstruc/dssp.py
Python
DsspRecord
DsspRecord
95
153
95
95
1717aba5ec85deca080f199dc6761b08445f1863
bigcode/the-stack
train
233a4dfe8f95afb92d04711f
train
class
class RunDssp(object) : """Run a locally installed DSSP executable.""" def __init__(self, path=None) : command = find_command('dsspcmbi', path=path) self.command = command def version(self) : args = [self.command, '-V'] try : p = Popen(args, stdout=PIPE) ...
class RunDssp(object) :
"""Run a locally installed DSSP executable.""" def __init__(self, path=None) : command = find_command('dsspcmbi', path=path) self.command = command def version(self) : args = [self.command, '-V'] try : p = Popen(args, stdout=PIPE) (out,err) = p.c...
'I' : '5 helix (pi helix)', 'T' : 'hydrogen bonded turn', 'S' : 'bend', ' ' : 'loop or irregular', } _dssp_header = "==== Secondary Structure Definition by the program DSSP, updated CMBI version by ElmK / April 1,2000" class RunDssp(object) :
82
82
276
7
75
go-bears/Final-Project
weblogo-3.4_rd/corebio/secstruc/dssp.py
Python
RunDssp
RunDssp
58
90
58
58
0607124b7cbd56a1bd6120ed36a3831d1f057902
bigcode/the-stack
train
96dec1d0ddb764519b1258f1
train
class
class DsspResidue(object): """Structural information for a single protein residue derived from a DSSP output file. Attributes : - num Sequential residue number - chainid - resid - aa one letter amino acid code, - secstruc compromise summary of secondary stru...
class DsspResidue(object):
"""Structural information for a single protein residue derived from a DSSP output file. Attributes : - num Sequential residue number - chainid - resid - aa one letter amino acid code, - secstruc compromise summary of secondary structure, intended to approxim...
[13] != '!': res.append( DsspResidue(line) ) self.residues = res def total_area(self) : """Return the total solvent accessible area """ area = 0 for r in self.residues : area += r.solvent_acc_area return area def pri...
256
256
861
7
248
go-bears/Final-Project
weblogo-3.4_rd/corebio/secstruc/dssp.py
Python
DsspResidue
DsspResidue
158
240
158
158
f7b7efdea1f0143d5495fd2fe46e922b4626d478
bigcode/the-stack
train
79a733555553abf301096bd7
train
function
def _generateTempFile(infile): ''' Generate a temporary file with fixed dictionary keys. inputs: infile: file name (string) ''' with open(infile) as f: data = json.load(f) _keyNameFix(data, basename(infile)) with open('temp', 'w') as f: json.dump(data, f,...
def _generateTempFile(infile):
''' Generate a temporary file with fixed dictionary keys. inputs: infile: file name (string) ''' with open(infile) as f: data = json.load(f) _keyNameFix(data, basename(infile)) with open('temp', 'w') as f: json.dump(data, f, indent=2)
) and (filename not in key): # 'os.path.splitext(filename)[0]' will remove extension from name new_key = os.path.splitext(filename)[0] + '_' + key changed.append(new_key) dictionary[new_key] = dictionary.pop(key) def _generateTempFile(infile):
64
64
83
8
56
namanUIUC/drl_deepair
event_parsing/single_episode/utils/json_flatter.py
Python
_generateTempFile
_generateTempFile
43
54
43
43
39c6f25eedebce3a44921a7d05c41be93cafabe6
bigcode/the-stack
train
b448a8997f0731f866a28b56
train
function
def flat_json(output_filename, input_filenames): ''' Generates one file from multiple json files : output_filename: file name for output file (string) input_filenames: list of names to merge (list) ''' with open(output_filename, "w") as outfile: first = True f...
def flat_json(output_filename, input_filenames):
''' Generates one file from multiple json files : output_filename: file name for output file (string) input_filenames: list of names to merge (list) ''' with open(output_filename, "w") as outfile: first = True for infile_name in input_filenames: _g...
string) ''' with open(infile) as f: data = json.load(f) _keyNameFix(data, basename(infile)) with open('temp', 'w') as f: json.dump(data, f, indent=2) def flat_json(output_filename, input_filenames):
64
64
134
10
54
namanUIUC/drl_deepair
event_parsing/single_episode/utils/json_flatter.py
Python
flat_json
flat_json
57
75
57
57
f6ef75f5110d3788cf9f5b284bd8167001835804
bigcode/the-stack
train
d5fa7716cc016e441f09d891
train
function
def _mangle(s): return s.strip()[1:-1]
def _mangle(s):
return s.strip()[1:-1]
AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Parser to generate flat json file""" import json import os from os.path import basename def _mangle(s):
64
64
15
6
57
namanUIUC/drl_deepair
event_parsing/single_episode/utils/json_flatter.py
Python
_mangle
_mangle
22
23
22
22
22fd78eb8c75fd18f7be389bdcb83f905d675675
bigcode/the-stack
train
c8c13b67933ba597b16fe4a2
train
function
def _keyNameFix(dictionary, filename): ''' Rename all the first level keys in the dictionary to filename_dictionary. inputs: dictionary: a python dict() filename: basepath of a file (string) ''' changed = [] for key in dictionary.keys(): if (key no...
def _keyNameFix(dictionary, filename):
''' Rename all the first level keys in the dictionary to filename_dictionary. inputs: dictionary: a python dict() filename: basepath of a file (string) ''' changed = [] for key in dictionary.keys(): if (key not in changed) and (filename not in key)...
implied. # See the License for the specific language governing permissions and # limitations under the License. """Parser to generate flat json file""" import json import os from os.path import basename def _mangle(s): return s.strip()[1:-1] def _keyNameFix(dictionary, filename):
64
64
124
9
55
namanUIUC/drl_deepair
event_parsing/single_episode/utils/json_flatter.py
Python
_keyNameFix
_keyNameFix
26
40
26
26
fbb1953ebfa2c6290745b42245a825ca418f1032
bigcode/the-stack
train
5db4f5bbc9eb3768f13543d6
train
function
def CDF(path, cdf_spec=None, delete=False, validate=None, string_encoding='ascii', s3_flag=1): """ A wrapper function for cdfread and cdfwrite modules. If you specify a file that exists, it returns a CDF reading class. If you specify a file that does not yet exist, one will be created and this ...
def CDF(path, cdf_spec=None, delete=False, validate=None, string_encoding='ascii', s3_flag=1):
""" A wrapper function for cdfread and cdfwrite modules. If you specify a file that exists, it returns a CDF reading class. If you specify a file that does not yet exist, one will be created and this function will return a CDF writing class. Parameters ---------- path : str The...
from pathlib import Path from . import cdfread, cdfwrite from .epochs import CDFepoch as cdfepoch # noqa: F401 # This function determines if we are reading or writing a file def CDF(path, cdf_spec=None, delete=False, validate=None, string_encoding='ascii', s3_flag=1):
75
155
517
28
46
sandyfreelance/cdflib
cdflib/cdf_factory.py
Python
CDF
CDF
8
62
8
9
7742c17d62e9283bbb62232715c8dedb207b2626
bigcode/the-stack
train
6b4c627ad59da32ec0078e85
train
class
class Migration(migrations.Migration): dependencies = [ ('profiles_api', '0002_auto_20210515_2339'), ] operations = [ migrations.CreateModel( name='ProfileFeedItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=Fals...
class Migration(migrations.Migration):
dependencies = [ ('profiles_api', '0002_auto_20210515_2339'), ] operations = [ migrations.CreateModel( name='ProfileFeedItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
# Generated by Django 2.2 on 2021-05-16 15:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
49
64
129
7
41
pricemou/profiles-rests-api
profiles_api/migrations/0003_profilefeeditem.py
Python
Migration
Migration
8
24
8
9
cd99f6c5195079cc5b898cf18f4177010a9e1fd8
bigcode/the-stack
train
df494d2a859f1c0c497843da
train
class
class FeedImageField(serializers.HyperlinkedRelatedField): read_only = True hash_field = 'image_hash' def get_url(self, obj, view_name, request, format): if getattr(obj, self.hash_field, None): # Always prefix with STATIC_URL to return images from our CDN. prefix = settings....
class FeedImageField(serializers.HyperlinkedRelatedField):
read_only = True hash_field = 'image_hash' def get_url(self, obj, view_name, request, format): if getattr(obj, self.hash_field, None): # Always prefix with STATIC_URL to return images from our CDN. prefix = settings.STATIC_URL.strip('/') # Always append image_has...
not expensive. """ app_field = AppESHomeField(many=True) app_field.context = self.context return app_field.to_native(obj._app_ids) def get_app_count(self, obj): return len(self.get_apps(obj)) class FeedImageField(serializers.HyperlinkedRelatedField):
64
64
148
11
53
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedImageField
FeedImageField
89
103
89
89
800b88e3acbed9d285dce72b7f4b8cfab0626a50
bigcode/the-stack
train
6aac4b544d61620200290c57
train
class
class BaseFeedCollectionSerializer(ValidateSlugMixin, URLSerializerMixin, serializers.ModelSerializer): """ Base serializer for subclasses of BaseFeedCollection. """ apps = FeedCollectionMembershipField(many=True, source='apps') slug = serializers.CharField(require...
class BaseFeedCollectionSerializer(ValidateSlugMixin, URLSerializerMixin, serializers.ModelSerializer):
""" Base serializer for subclasses of BaseFeedCollection. """ apps = FeedCollectionMembershipField(many=True, source='apps') slug = serializers.CharField(required=False) # Search-specific. app_count = serializers.SerializerMethodField('get_app_count') preview_icon = serializers.Serializ...
ugs, coerce them into something safer. """ def validate_slug(self, attrs, source): if source in attrs: attrs[source] = slugify(unicode(attrs[source])) return attrs class BaseFeedCollectionSerializer(ValidateSlugMixin, URLSerializerMixin, serial...
64
64
149
19
44
clouserw/zamboni
mkt/feed/serializers.py
Python
BaseFeedCollectionSerializer
BaseFeedCollectionSerializer
42
62
42
43
6e587455565064db227dd9c6154f4cae66a9c5ac
bigcode/the-stack
train
875d590d6152a00e80fc5024
train
class
class FeedBrandESSerializer(BaseFeedCollectionESSerializer, FeedBrandSerializer): """ A serializer for the FeedBrand class for ES representation. """ apps = AppESField(source='_app_ids', many=True) def fake_object(self, data): brand = self._attach_fields(FeedBran...
class FeedBrandESSerializer(BaseFeedCollectionESSerializer, FeedBrandSerializer):
""" A serializer for the FeedBrand class for ES representation. """ apps = AppESField(source='_app_ids', many=True) def fake_object(self, data): brand = self._attach_fields(FeedBrand(), data, ( 'id', 'layout', 'slug', 'type' )) brand._app_ids = data.get('apps') ...
required=True) class Meta: fields = ('app_count', 'apps', 'id', 'layout', 'slug', 'type', 'url') model = FeedBrand url_basename = 'feedbrands' class FeedBrandESSerializer(BaseFeedCollectionESSerializer, FeedBrandSerializer):
64
64
98
16
48
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedBrandESSerializer
FeedBrandESSerializer
182
194
182
183
c7c63a27fb5fa91ee8b69213b759d7ade4ed5608
bigcode/the-stack
train
b2d3a8053a7d24a710c6f5d0
train
class
class FeedItemSerializer(URLSerializerMixin, serializers.ModelSerializer): """ A serializer for the FeedItem class, which wraps all items that live on the feed. """ carrier = SlugChoiceField(required=False, choices_dict=mkt.carriers.CARRIER_MAP) region = SlugChoiceF...
class FeedItemSerializer(URLSerializerMixin, serializers.ModelSerializer):
""" A serializer for the FeedItem class, which wraps all items that live on the feed. """ carrier = SlugChoiceField(required=False, choices_dict=mkt.carriers.CARRIER_MAP) region = SlugChoiceField(required=False, choices_dict=mkt.regions....
= self._attach_fields(FeedShelf(), data, ( 'id', 'carrier', 'image_hash', 'image_landing_hash', 'region', 'slug' )) shelf = self._attach_translations(shelf, data, ( 'description', 'name' )) shelf._app_ids = data.get('apps') # Attach groups. ...
177
177
592
12
165
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedItemSerializer
FeedItemSerializer
380
449
380
380
3506fec0ddf75b798304311350d786a5947cf4c9
bigcode/the-stack
train
93c63d8ccd95e2e6c5f8f20a
train
class
class FeedLandingImageField(FeedImageField): read_only = True hash_field = 'image_landing_hash'
class FeedLandingImageField(FeedImageField):
read_only = True hash_field = 'image_landing_hash'
%s' % getattr(obj, self.hash_field) url = reverse(view_name, kwargs={'pk': obj.pk}, request=request, format=format) return '%s%s%s' % (prefix, url, suffix) else: return None class FeedLandingImageField(FeedImageField):
63
64
26
10
52
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedLandingImageField
FeedLandingImageField
106
108
106
106
d27ec1182af6e35e354633474b6f34a8e11039b5
bigcode/the-stack
train
f10f4afb063d4db9e87197d7
train
class
class FeedCollectionESSerializer(BaseFeedCollectionESSerializer, FeedCollectionSerializer): """ A serializer for the FeedCollection class for ES representation. """ apps = AppESField(source='_app_ids', many=True) description = ESTranslationSerializerField(required=Fa...
class FeedCollectionESSerializer(BaseFeedCollectionESSerializer, FeedCollectionSerializer):
""" A serializer for the FeedCollection class for ES representation. """ apps = AppESField(source='_app_ids', many=True) description = ESTranslationSerializerField(required=False) name = ESTranslationSerializerField(required=False) def fake_object(self, data): collection = self._att...
= self.context for member in memberships: data = AppSerializer(member.app, context=self.context).data data['group'] = field.field_to_native(member, 'group') ret.append(data) return ret class FeedCollectionESSerializer(BaseFeedCollectionESSerializer, ...
64
64
183
16
47
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedCollectionESSerializer
FeedCollectionESSerializer
258
281
258
259
ccc7abac3b07486fc43a97f765d53f5d9e6e0c7f
bigcode/the-stack
train
64f7674c6267481fdeb38d97
train
class
class FeedShelfESSerializer(BaseFeedCollectionESSerializer, FeedShelfSerializer): """A serializer for the FeedShelf class for ES representation.""" apps = AppESField(source='_app_ids', many=True) description = ESTranslationSerializerField(required=False) name = ESTranslationS...
class FeedShelfESSerializer(BaseFeedCollectionESSerializer, FeedShelfSerializer):
"""A serializer for the FeedShelf class for ES representation.""" apps = AppESField(source='_app_ids', many=True) description = ESTranslationSerializerField(required=False) name = ESTranslationSerializerField(required=False) class Meta(FeedShelfSerializer.Meta): fields = filter(lambda field...
= self.context for member in memberships: data = AppSerializer(member.app, context=self.context).data data['group'] = field.field_to_native(member, 'group') ret.append(data) return ret class FeedShelfESSerializer(BaseFeedCollectionESSerializer, ...
64
64
214
16
47
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedShelfESSerializer
FeedShelfESSerializer
345
371
345
346
4278ee0a04553662bff97433cf9e14a04157a0dd
bigcode/the-stack
train
7619fec0cc73916afe598f3a
train
class
class FeedCollectionESHomeSerializer(FeedCollectionESSerializer): """Stripped down FeedCollectionESSerializer targeted for the homepage.""" apps = serializers.SerializerMethodField('get_apps') def get_apps(self, obj): if obj.type == feed.COLLECTION_PROMO: # Need app icons if not backgro...
class FeedCollectionESHomeSerializer(FeedCollectionESSerializer):
"""Stripped down FeedCollectionESSerializer targeted for the homepage.""" apps = serializers.SerializerMethodField('get_apps') def get_apps(self, obj): if obj.type == feed.COLLECTION_PROMO: # Need app icons if not background image. app_field = AppESHomePromoCollectionField( ...
description' )) collection._app_ids = data.get('apps') # Attach groups. self.context['group_apps'] = data.get('group_apps') self.context['group_names'] = data.get('group_names') return collection class FeedCollectionESHomeSerializer(FeedCollectionESSerializer):
64
64
158
12
51
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedCollectionESHomeSerializer
FeedCollectionESHomeSerializer
284
300
284
284
84ea744487bcb2d1b46e7373abf4cce05b1d38bf
bigcode/the-stack
train
5a4aa89a032123a9f2fad1b1
train
class
class FeedBrandSerializer(BaseFeedCollectionSerializer): """ A serializer for the FeedBrand class, a type of collection that allows editors to quickly create content without involving localizers. """ layout = serializers.ChoiceField(choices=constants.BRAND_LAYOUT_CHOICES, ...
class FeedBrandSerializer(BaseFeedCollectionSerializer):
""" A serializer for the FeedBrand class, a type of collection that allows editors to quickly create content without involving localizers. """ layout = serializers.ChoiceField(choices=constants.BRAND_LAYOUT_CHOICES, required=True) type = serializers.ChoiceFie...
feed_app._app_id = data.get('app') return feed_app class FeedAppESHomeSerializer(FeedAppESSerializer): """Stripped down FeedAppESSerializer targeted for the homepage.""" app = AppESHomeField(source='_app_id') class FeedBrandSerializer(BaseFeedCollectionSerializer):
64
64
126
9
55
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedBrandSerializer
FeedBrandSerializer
166
179
166
166
b2ef15ab8b57336689aec190d26963e3a17ec0a3
bigcode/the-stack
train
19fad9ae73642744eb26dc04
train
class
class BaseFeedCollectionESSerializer(BaseESSerializer): """ Base serializer for subclasses of BaseFeedCollection that serializes ES representation. """ apps = AppESField(source='_app_ids', many=True) app_count = serializers.SerializerMethodField('get_app_count') def get_apps(self, obj): ...
class BaseFeedCollectionESSerializer(BaseESSerializer):
""" Base serializer for subclasses of BaseFeedCollection that serializes ES representation. """ apps = AppESField(source='_app_ids', many=True) app_count = serializers.SerializerMethodField('get_app_count') def get_apps(self, obj): """ Manually deserialize the app field, use...
obj): return obj.apps().count() def get_preview_icon(self, obj): if obj.apps().exists(): return obj.apps()[0].get_icon_url(48) class Meta: fields = ('apps', 'slug', 'url') class BaseFeedCollectionESSerializer(BaseESSerializer):
64
64
197
10
54
clouserw/zamboni
mkt/feed/serializers.py
Python
BaseFeedCollectionESSerializer
BaseFeedCollectionESSerializer
65
86
65
65
9797c9e012a17f52118998255a7b07dff6995c5f
bigcode/the-stack
train
9d359b584411ff793883301e
train
class
class ValidateSlugMixin(object): """ Rather than raise validation errors on slugs, coerce them into something safer. """ def validate_slug(self, attrs, source): if source in attrs: attrs[source] = slugify(unicode(attrs[source])) return attrs
class ValidateSlugMixin(object):
""" Rather than raise validation errors on slugs, coerce them into something safer. """ def validate_slug(self, attrs, source): if source in attrs: attrs[source] = slugify(unicode(attrs[source])) return attrs
from .fields import (AppESField, AppESHomeField, AppESHomePromoCollectionField, FeedCollectionMembershipField) from .models import (FeedApp, FeedBrand, FeedCollection, FeedCollectionMembership, FeedItem, FeedShelf, FeedShelfMembership) class ValidateSlugMi...
64
64
61
6
58
clouserw/zamboni
mkt/feed/serializers.py
Python
ValidateSlugMixin
ValidateSlugMixin
30
39
30
30
43f2a79c3ceb41ceae4b27eb5f62e6c7467151b5
bigcode/the-stack
train
95f10fdfc59d97d354ef1b17
train
class
class FeedShelfESHomeSerializer(FeedShelfESSerializer): """Stripped down FeedShelfESSerializer targeted for the homepage.""" apps = AppESHomePromoCollectionField(source='_app_ids', many=True, limit=feed.HOME_NUM_APPS_SHELF)
class FeedShelfESHomeSerializer(FeedShelfESSerializer):
"""Stripped down FeedShelfESSerializer targeted for the homepage.""" apps = AppESHomePromoCollectionField(source='_app_ids', many=True, limit=feed.HOME_NUM_APPS_SHELF)
name' )) shelf._app_ids = data.get('apps') # Attach groups. self.context['group_apps'] = data.get('group_apps') self.context['group_names'] = data.get('group_names') return shelf class FeedShelfESHomeSerializer(FeedShelfESSerializer):
64
64
56
12
51
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedShelfESHomeSerializer
FeedShelfESHomeSerializer
374
377
374
374
2d76dff4ca0a7164edff64a37a1f2f994bc41d6d
bigcode/the-stack
train
b3b3262e36845cce76403272
train
class
class FeedBrandESHomeSerializer(FeedBrandESSerializer): """ Stripped down FeedBrandESSerializer targeted for the homepage. Different from the other Feed*ESHomeSerializers because it uses its own app field. """ apps = AppESHomeField(source='_app_ids', many=True, limit=fe...
class FeedBrandESHomeSerializer(FeedBrandESSerializer):
""" Stripped down FeedBrandESSerializer targeted for the homepage. Different from the other Feed*ESHomeSerializers because it uses its own app field. """ apps = AppESHomeField(source='_app_ids', many=True, limit=feed.HOME_NUM_APPS_BRAND)
def fake_object(self, data): brand = self._attach_fields(FeedBrand(), data, ( 'id', 'layout', 'slug', 'type' )) brand._app_ids = data.get('apps') return brand class FeedBrandESHomeSerializer(FeedBrandESSerializer):
64
64
77
12
51
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedBrandESHomeSerializer
FeedBrandESHomeSerializer
197
204
197
197
d6a73c2fc426a7fd123cb523eedd5f566e9a29c7
bigcode/the-stack
train
10828397f63dd30d55a1209a
train
class
class FeedItemESSerializer(FeedItemSerializer, BaseESSerializer): """ A serializer for the FeedItem class from an ES object, which wraps all items that live on the feed. It will turn something like >> {'item_type': 'app', 'carrier': 1, 'region': 1, 'app': 140L, 'id': 229L} into a fully serial...
class FeedItemESSerializer(FeedItemSerializer, BaseESSerializer):
""" A serializer for the FeedItem class from an ES object, which wraps all items that live on the feed. It will turn something like >> {'item_type': 'app', 'carrier': 1, 'region': 1, 'app': 140L, 'id': 229L} into a fully serialized FeedItem. self.context['app_map'] -- mapping of app IDs ...
_CHOICE_DICT[shelf.carrier] if attrs.get('carrier') != carrier.slug: raise serializers.ValidationError( 'Feed item carrier does not match operator shelf carrier.') region = REGIONS_CHOICES_ID_DICT[shelf.region] if attrs.get('region') != region.slu...
97
97
326
14
82
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedItemESSerializer
FeedItemESSerializer
452
487
452
452
f20f3a88744bb754079a3627f2a9269d83ae90c6
bigcode/the-stack
train
6dd75b3313c5492a6b1ceaca
train
class
class FeedAppESSerializer(FeedAppSerializer, BaseESSerializer): """ A serializer for the FeedApp class that serializes ES representation. """ app = AppESField(source='_app_id') background_image = FeedImageField( source='*', view_name='api-v2:feed-app-image-detail', format='png') descript...
class FeedAppESSerializer(FeedAppSerializer, BaseESSerializer):
""" A serializer for the FeedApp class that serializes ES representation. """ app = AppESField(source='_app_id') background_image = FeedImageField( source='*', view_name='api-v2:feed-app-image-detail', format='png') description = ESTranslationSerializerField(required=False) preview =...
'description', 'id', 'preview', 'pullquote_attribution', 'pullquote_rating', 'pullquote_text', 'slug', 'type', 'url') model = FeedApp url_basename = 'feedapps' class FeedAppESSerializer(FeedAppSerializer, BaseESSerializer):
65
65
219
14
51
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedAppESSerializer
FeedAppESSerializer
136
158
136
136
5a0a0316eac5718922dcf3150d52c2a82cac8e0e
bigcode/the-stack
train
60bc7cfee508d15a30f3230c
train
class
class FeedShelfSerializer(BaseFeedCollectionSerializer): """ A serializer for the FeedBrand class, a type of collection that allows editors to quickly create content without involving localizers. """ apps = serializers.SerializerMethodField('get_apps') background_image = FeedImageField( ...
class FeedShelfSerializer(BaseFeedCollectionSerializer):
""" A serializer for the FeedBrand class, a type of collection that allows editors to quickly create content without involving localizers. """ apps = serializers.SerializerMethodField('get_apps') background_image = FeedImageField( source='*', view_name='api-v2:feed-shelf-image-detail', f...
# Need app icons if not background image. app_field = AppESHomePromoCollectionField( many=True, limit=feed.HOME_NUM_APPS_PROMO_COLL) elif obj.type == feed.COLLECTION_LISTING: # Needs minimal app serialization like FeedBrand. app_field = AppESHomeF...
111
111
371
9
102
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedShelfSerializer
FeedShelfSerializer
303
342
303
303
7f1f18f4045f13fc8350530d264c83144c8be1b8
bigcode/the-stack
train
fe5c5da1cb071ac71473c4bc
train
class
class FeedAppESHomeSerializer(FeedAppESSerializer): """Stripped down FeedAppESSerializer targeted for the homepage.""" app = AppESHomeField(source='_app_id')
class FeedAppESHomeSerializer(FeedAppESSerializer):
"""Stripped down FeedAppESSerializer targeted for the homepage.""" app = AppESHomeField(source='_app_id')
_app._preview = data.get('preview') feed_app = self._attach_translations(feed_app, data, ( 'description', 'pullquote_text' )) feed_app._app_id = data.get('app') return feed_app class FeedAppESHomeSerializer(FeedAppESSerializer):
64
64
38
12
51
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedAppESHomeSerializer
FeedAppESHomeSerializer
161
163
161
161
1e3adb37ca70a63c34d7c58cd727654c196e5ef7
bigcode/the-stack
train
77079b33627b57466e17c54a
train
class
class FeedCollectionSerializer(BaseFeedCollectionSerializer): """ A serializer for the FeedCollection class. """ type = serializers.ChoiceField(choices=constants.COLLECTION_TYPE_CHOICES) background_image = FeedImageField( source='*', view_name='api-v2:feed-collection-image-detail', f...
class FeedCollectionSerializer(BaseFeedCollectionSerializer):
""" A serializer for the FeedCollection class. """ type = serializers.ChoiceField(choices=constants.COLLECTION_TYPE_CHOICES) background_image = FeedImageField( source='*', view_name='api-v2:feed-collection-image-detail', format='png') color = serializers.CharField(max_length=20, ...
(), data, ( 'id', 'layout', 'slug', 'type' )) brand._app_ids = data.get('apps') return brand class FeedBrandESHomeSerializer(FeedBrandESSerializer): """ Stripped down FeedBrandESSerializer targeted for the homepage. Different from the other Feed*ESHomeSerializers becaus...
120
120
400
9
111
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedCollectionSerializer
FeedCollectionSerializer
207
255
207
207
38457ee38dff741f0f6495fe07b3fe55a55c682b
bigcode/the-stack
train
548a65f5825bdcdefeca0e7a
train
class
class FeedAppSerializer(ValidateSlugMixin, URLSerializerMixin, serializers.ModelSerializer): """ A serializer for the FeedApp class, which highlights a single app and some additional metadata (e.g. a review or a screenshot). """ app = SplitField(relations.PrimaryKeyRelatedFie...
class FeedAppSerializer(ValidateSlugMixin, URLSerializerMixin, serializers.ModelSerializer):
""" A serializer for the FeedApp class, which highlights a single app and some additional metadata (e.g. a review or a screenshot). """ app = SplitField(relations.PrimaryKeyRelatedField(required=True), AppSerializer()) background_image = FeedImageField( source='*', v...
) return '%s%s%s' % (prefix, url, suffix) else: return None class FeedLandingImageField(FeedImageField): read_only = True hash_field = 'image_landing_hash' class FeedAppSerializer(ValidateSlugMixin, URLSerializerMixin, serializers.ModelSerializer):
67
67
226
18
49
clouserw/zamboni
mkt/feed/serializers.py
Python
FeedAppSerializer
FeedAppSerializer
111
133
111
112
847e4b95cb1c257c227d961ad8ff0ca90993d8bf
bigcode/the-stack
train
bd71ce10a052f4731325a155
train
class
class AwaitableListMediaServiceEdgePoliciesResult(ListMediaServiceEdgePoliciesResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListMediaServiceEdgePoliciesResult( usage_data_collection_policy=self.usage_data_collection_policy...
class AwaitableListMediaServiceEdgePoliciesResult(ListMediaServiceEdgePoliciesResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return ListMediaServiceEdgePoliciesResult( usage_data_collection_policy=self.usage_data_collection_policy)
usageDataCollectionPolicy") def usage_data_collection_policy(self) -> Optional['outputs.EdgeUsageDataCollectionPolicyResponse']: return pulumi.get(self, "usage_data_collection_policy") class AwaitableListMediaServiceEdgePoliciesResult(ListMediaServiceEdgePoliciesResult): # pylint: disable=using-constant...
64
64
63
27
37
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/media/list_media_service_edge_policies.py
Python
AwaitableListMediaServiceEdgePoliciesResult
AwaitableListMediaServiceEdgePoliciesResult
31
37
31
32
8fb8efa4df8ef5d7b4056617135c5dac259f9a1b
bigcode/the-stack
train
e222a976bb9ccd55260b5dbe
train
class
@pulumi.output_type class ListMediaServiceEdgePoliciesResult: def __init__(__self__, usage_data_collection_policy=None): if usage_data_collection_policy and not isinstance(usage_data_collection_policy, dict): raise TypeError("Expected argument 'usage_data_collection_policy' to be a dict") ...
@pulumi.output_type class ListMediaServiceEdgePoliciesResult:
def __init__(__self__, usage_data_collection_policy=None): if usage_data_collection_policy and not isinstance(usage_data_collection_policy, dict): raise TypeError("Expected argument 'usage_data_collection_policy' to be a dict") pulumi.set(__self__, "usage_data_collection_policy", usage_d...
Union, overload from .. import _utilities from . import outputs __all__ = [ 'ListMediaServiceEdgePoliciesResult', 'AwaitableListMediaServiceEdgePoliciesResult', 'list_media_service_edge_policies', ] @pulumi.output_type class ListMediaServiceEdgePoliciesResult:
64
64
130
14
50
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/media/list_media_service_edge_policies.py
Python
ListMediaServiceEdgePoliciesResult
ListMediaServiceEdgePoliciesResult
18
28
18
19
4566bfc972b1aa8ce318093d1d1516bbdc48f3a2
bigcode/the-stack
train
cc26b751b9ab03e303ff61eb
train
function
def list_media_service_edge_policies(account_name: Optional[str] = None, device_id: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableLis...
def list_media_service_edge_policies(account_name: Optional[str] = None, device_id: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableLis...
""" API Version: 2020-05-01. :param str account_name: The Media Services account name. :param str device_id: Unique identifier of the edge device. :param str resource_group_name: The name of the resource group within the Azure subscription. """ __args__ = dict() __args__['accountName']...
MediaServiceEdgePoliciesResult( usage_data_collection_policy=self.usage_data_collection_policy) def list_media_service_edge_policies(account_name: Optional[str] = None, device_id: Optional[str] = None, resource_group_name: Optional[st...
78
78
260
60
18
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/media/list_media_service_edge_policies.py
Python
list_media_service_edge_policies
list_media_service_edge_policies
40
63
40
43
18d41e3632acebd43faf29592972c26567003870
bigcode/the-stack
train
dfab889ac59d49db9c745810
train
class
class Song: def __init__(self): self.player = vlc.MediaPlayer() def play_song(self, stream_url): self.player = vlc.MediaPlayer(stream_url) self.player.play() def play_mp3(file_name): dir_path = os.path.dirname(os.path.realpath(__file__)) p = vlc.MediaPla...
class Song:
def __init__(self): self.player = vlc.MediaPlayer() def play_song(self, stream_url): self.player = vlc.MediaPlayer(stream_url) self.player.play() def play_mp3(file_name): dir_path = os.path.dirname(os.path.realpath(__file__)) p = vlc.MediaPlayer(dir_path + ...
import time import os if os.name == 'nt': os.add_dll_directory(r'C:\\Program Files (x86)\\VideoLAN\\VLC') import vlc class Song:
42
64
108
3
38
kyoushi/dj_jack
playVLC.py
Python
Song
Song
9
27
9
10
da40c70993023db0234c5ac1b4ce38596d4eb29f
bigcode/the-stack
train
d961d115852cee598c8bb5ee
train
function
def make_data(): """Make data.""" n_epochs, n_chan, n_time = 50, 32, 10 X = np.random.rand(n_epochs, n_chan, n_time) y = np.arange(n_epochs) % 2 for ii in range(n_time): coef = np.random.randn(n_chan) X[y == 0, :, ii] += coef X[y == 1, :, ii] -= coef return X, y
def make_data():
"""Make data.""" n_epochs, n_chan, n_time = 50, 32, 10 X = np.random.rand(n_epochs, n_chan, n_time) y = np.arange(n_epochs) % 2 for ii in range(n_time): coef = np.random.randn(n_chan) X[y == 0, :, ii] += coef X[y == 1, :, ii] -= coef return X, y
: BSD (3-clause) import numpy as np from numpy.testing import assert_array_equal, assert_equal import pytest from mne.utils import requires_version from mne.decoding.search_light import SlidingEstimator, GeneralizingEstimator from mne.decoding.transformer import Vectorizer def make_data():
64
64
104
4
59
fmamashli/mne-python
mne/decoding/tests/test_search_light.py
Python
make_data
make_data
14
23
14
14
4fe2ace1ccd76320b60d1cf1003ca483ea9d2815
bigcode/the-stack
train
979c891a496f924ba6c91355
train
function
@requires_version('sklearn', '0.17') def test_search_light(): """Test SlidingEstimator.""" from sklearn.linear_model import Ridge, LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.metrics import roc_auc_score, make_scorer with pytest.warns(None): # NumPy module import ...
@requires_version('sklearn', '0.17') def test_search_light():
"""Test SlidingEstimator.""" from sklearn.linear_model import Ridge, LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.metrics import roc_auc_score, make_scorer with pytest.warns(None): # NumPy module import from sklearn.ensemble import BaggingClassifier from sk...
# Author: Jean-Remi King, <jeanremi.king@gmail.com> # # License: BSD (3-clause) import numpy as np from numpy.testing import assert_array_equal, assert_equal import pytest from mne.utils import requires_version from mne.decoding.search_light import SlidingEstimator, GeneralizingEstimator from mne.decoding.transformer...
202
256
1,320
17
184
fmamashli/mne-python
mne/decoding/tests/test_search_light.py
Python
test_search_light
test_search_light
26
161
26
27
2119568f3aedf842fd80b589ed4e110967e25e38
bigcode/the-stack
train
1a3f253419e8c0273923f9c6
train
function
@requires_version('sklearn', '0.17') def test_generalization_light(): """Test GeneralizingEstimator.""" from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score logreg = LogisticRegression(solver='liblinear', multi_clas...
@requires_version('sklearn', '0.17') def test_generalization_light():
"""Test GeneralizingEstimator.""" from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score logreg = LogisticRegression(solver='liblinear', multi_class='ovr', random_state=0) X, y = m...
idingEstimator(_LogRegTransformer()), logreg) pipe.fit(X, y) pipe.predict(X) # n-dimensional feature space X = np.random.rand(10, 3, 4, 2) y = np.arange(10) % 2 y_preds = list() for n_jobs in [1, 2]: pipe = SlidingEstimator( make_pipeline(Vectori...
256
256
866
18
238
fmamashli/mne-python
mne/decoding/tests/test_search_light.py
Python
test_generalization_light
test_generalization_light
164
248
164
165
c106b2818576c4fa8be0f86f75c5f557746b9f7c
bigcode/the-stack
train
ff94ae8e33b6e7e5b067a7ba
train
function
@requires_version('sklearn', '0.19') # 0.18 does not raise when it should def test_cross_val_predict(): """Test cross_val_predict with predict_proba.""" from sklearn.linear_model import LinearRegression from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.base import BaseEs...
@requires_version('sklearn', '0.19') # 0.18 does not raise when it should def test_cross_val_predict():
"""Test cross_val_predict with predict_proba.""" from sklearn.linear_model import LinearRegression from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.base import BaseEstimator, clone from sklearn.model_selection import cross_val_predict rng = np.random.RandomState(...
_jobs) y_preds.append(pipe.fit(X, y).predict(X)) features_shape = pipe.estimators_[0].steps[0][1].features_shape_ assert_array_equal(features_shape, [3, 4]) assert_array_equal(y_preds[0], y_preds[1]) @requires_version('sklearn', '0.19') # 0.18 does not raise when it should def test_cross_va...
93
93
311
31
62
fmamashli/mne-python
mne/decoding/tests/test_search_light.py
Python
test_cross_val_predict
test_cross_val_predict
251
283
251
252
ee9e8e1152f4f7b3fba436e3f0d4f1959ea49cf2
bigcode/the-stack
train
57d445914f9e7df0fbb2911d
train
class
class JenkinsInvoke(object): """ JenkinsInvoke object implements class to call from command line """ @classmethod def mkparser(cls): parser = optparse.OptionParser() DEFAULT_BASEURL = os.environ.get( "JENKINS_URL", "http://localhost/jenkins") parser.help_text = ...
class JenkinsInvoke(object):
""" JenkinsInvoke object implements class to call from command line """ @classmethod def mkparser(cls): parser = optparse.OptionParser() DEFAULT_BASEURL = os.environ.get( "JENKINS_URL", "http://localhost/jenkins") parser.help_text = "Execute a number of jenkins j...
""" jenkinsapi class for invoking Jenkins """ import os import sys import logging import optparse from jenkinsapi import jenkins log = logging.getLogger(__name__) class JenkinsInvoke(object):
44
158
528
5
39
pkocandr/jenkinsapi
jenkinsapi/command_line/jenkins_invoke.py
Python
JenkinsInvoke
JenkinsInvoke
14
72
14
15
4d9e1c0c24b3f24ec8c0a326b55855ac4f9aa699
bigcode/the-stack
train
6b4cdcaafbee514cd0c4b486
train
function
def main(): logging.basicConfig() logging.getLogger("").setLevel(logging.INFO) JenkinsInvoke.main()
def main():
logging.basicConfig() logging.getLogger("").setLevel(logging.INFO) JenkinsInvoke.main()
job(self, jobname, block, token): assert type(block) == bool assert type(jobname) == str assert token is None or isinstance(token, str) job = self.api.get_job(jobname) job.invoke(securitytoken=token, block=block) def main():
64
64
23
3
61
pkocandr/jenkinsapi
jenkinsapi/command_line/jenkins_invoke.py
Python
main
main
75
78
75
75
6368052aef1abf254886f204e1d77283be5c16f8
bigcode/the-stack
train
26e8384bb49d6f77c03051dc
train
function
def parse_spec(s, defaultport): match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) elif s.count(':') > 1: # ipv6, no port host = s port = '' else: (host,_,port) = s.partition(':') if not port...
def parse_spec(s, defaultport):
match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s) if match: # ipv6 host = match.group(1) port = match.group(2) elif s.count(':') > 1: # ipv6, no port host = s port = '' else: (host,_,port) = s.partition(':') if not port: port = defaultport ...
]) elif addr.startswith('0x'): # IPv4-in-little-endian return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:]))) else: raise ValueError('Could not parse address %s' % addr) def parse_spec(s, defaultport):
64
64
141
8
56
thomascvitale/herbsters
herbsters/contrib/seeds/generate-seeds.py
Python
parse_spec
parse_spec
75
93
75
75
dd000d35b717ae4c4e4581d24307f0f33a3c07dc
bigcode/the-stack
train
b07f9bc27c301c2fde7404d4
train
function
def main(): if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef herbsters_CHAINPARAMSSEEDS_H\n') g.write('#define herbsters_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * ...
def main():
if len(sys.argv)<2: print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr) exit(1) g = sys.stdout indir = sys.argv[1] g.write('#ifndef herbsters_CHAINPARAMSSEEDS_H\n') g.write('#define herbsters_CHAINPARAMSSEEDS_H\n') g.write('/**\n') g.write(' * List of fixe...
if not first: g.write(',\n') first = False (host,port) = parse_spec(line, defaultport) hoststr = ','.join(('0x%02x' % b) for b in host) g.write(' {{%s}, %i}' % (hoststr, port)) g.write('\n};\n') def main():
85
85
284
3
82
thomascvitale/herbsters
herbsters/contrib/seeds/generate-seeds.py
Python
main
main
114
134
114
114
52e9650c83ba28af7d3083aa16ee0e45c5c08e08
bigcode/the-stack
train
9df587beb67dfc5376295b75
train
function
def process_nodes(g, f, structname, defaultport): g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not...
def process_nodes(g, f, structname, defaultport):
g.write('static SeedSpec6 %s[] = {\n' % structname) first = True for line in f: comment = line.find('#') if comment != -1: line = line[0:comment] line = line.strip() if not line: continue if not first: g.write(',\n') first =...
else: (host,_,port) = s.partition(':') if not port: port = defaultport else: port = int(port) host = name_to_ipv6(host) return (host,port) def process_nodes(g, f, structname, defaultport):
64
64
161
13
51
thomascvitale/herbsters
herbsters/contrib/seeds/generate-seeds.py
Python
process_nodes
process_nodes
95
112
95
95
3dbce44502830f85f28bc4c7456018b89dd95fb8
bigcode/the-stack
train
18a4d037c113e36f523a2c90
train
function
def name_to_ipv6(addr): if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray(...
def name_to_ipv6(addr):
if len(addr)>6 and addr.endswith('.onion'): vchAddr = b32decode(addr[0:-6], True) if len(vchAddr) != 16-len(pchOnionCat): raise ValueError('Invalid onion %s' % s) return pchOnionCat + vchAddr elif '.' in addr: # IPv4 return pchIPv4 + bytearray((int(x) for x in addr.sp...
import sys, os import re # ipv4 in ipv6 prefix pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]) # tor-specific ipv6 prefix pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43]) def name_to_ipv6(addr):
108
108
363
7
101
thomascvitale/herbsters
herbsters/contrib/seeds/generate-seeds.py
Python
name_to_ipv6
name_to_ipv6
45
73
45
45
2e80f2c9f04d5ed5acb45ee10216dfdff6b1eba7
bigcode/the-stack
train
01e6b7316aa61488ce2fd027
train
function
def expand( urls_to_expand, chunksize=1280, n_workers=1, cache_file=None, random_seed=303, verbose=0, filter_function=None, **kwargs, ): """Calls expand with multiple (``n_workers``) threads to unshorten a list of urls. Unshortens all urls by default, unless one sets a ``filter_funct...
def expand( urls_to_expand, chunksize=1280, n_workers=1, cache_file=None, random_seed=303, verbose=0, filter_function=None, **kwargs, ):
"""Calls expand with multiple (``n_workers``) threads to unshorten a list of urls. Unshortens all urls by default, unless one sets a ``filter_function``. :param chunksize: chunks urls_to_expand, which makes computation quicker with larger inputs (Default value = 1280) :type chunksize: int :param n_work...
, headers=_pick_headers(url), **kwargs, ) r.raise_for_status() url_long = r.url domain = url_utils.get_domain(url_long) if verbose: print("First expansion OK") except requests.exceptions.RequestException as exc: if verbose: ...
256
256
915
47
209
wlmwng/urlExpander
urlexpander/core/api.py
Python
expand
expand
241
344
241
250
20d28d21d2e7fa5db8d80358b725f9bbf693792f
bigcode/the-stack
train
3726ff05b573313bd1c1c654
train
function
def _parse_error(error, verbose=False): """Parse error messages from the server response, to try to figure out what website the bit-link was intended to re-direct to. Although some redirects no longer work, we can still use the response from the error to figure out where it would have gone. :param erro...
def _parse_error(error, verbose=False):
"""Parse error messages from the server response, to try to figure out what website the bit-link was intended to re-direct to. Although some redirects no longer work, we can still use the response from the error to figure out where it would have gone. :param error: error response from expand() or expan...
chunks(lst, chunksize): """Yield successive n-sized chunks from lst. Taken from https://stackoverflow.com/a/312464/5094480 :param lst: the list to break up into smaller chunks :type lst: list :param chunksize: the number of items to include in each chunk :type chunksize: int """ for i ...
112
112
375
9
103
wlmwng/urlExpander
urlexpander/core/api.py
Python
_parse_error
_parse_error
59
96
59
59
743fee33f0a15ea891bbc759d0c6151bb2d1388a
bigcode/the-stack
train
7f37051d1113418fe538ab96
train
function
def _pick_headers(url): """workaround for expanding t.co links. See constants.py for details. :param url: URL :type url: str :returns: headers-> headers used in HTTP request :rtype: dict """ domain = url_utils.get_domain(url) if domain == "t.co": headers = constants.headers_tw ...
def _pick_headers(url):
"""workaround for expanding t.co links. See constants.py for details. :param url: URL :type url: str :returns: headers-> headers used in HTTP request :rtype: dict """ domain = url_utils.get_domain(url) if domain == "t.co": headers = constants.headers_tw else: header...
from random import randint import numpy as np import pandas as pd import requests import unshortenit from newsplease.crawler import response_decoder from tqdm import tqdm from urlexpander.core import constants, url_utils LOGGER = logging.getLogger(__name__) def _pick_headers(url):
64
64
93
6
58
wlmwng/urlExpander
urlexpander/core/api.py
Python
_pick_headers
_pick_headers
27
42
27
27
ab05c7da3a9c9adb5ad978386473099853085311
bigcode/the-stack
train
e160cbbc302637a1557a14c1
train
function
def _chunks(lst, chunksize): """Yield successive n-sized chunks from lst. Taken from https://stackoverflow.com/a/312464/5094480 :param lst: the list to break up into smaller chunks :type lst: list :param chunksize: the number of items to include in each chunk :type chunksize: int """ f...
def _chunks(lst, chunksize):
"""Yield successive n-sized chunks from lst. Taken from https://stackoverflow.com/a/312464/5094480 :param lst: the list to break up into smaller chunks :type lst: list :param chunksize: the number of items to include in each chunk :type chunksize: int """ for i in range(0, len(lst), ch...
:returns: headers-> headers used in HTTP request :rtype: dict """ domain = url_utils.get_domain(url) if domain == "t.co": headers = constants.headers_tw else: headers = constants.headers return headers def _chunks(lst, chunksize):
64
64
105
8
55
wlmwng/urlExpander
urlexpander/core/api.py
Python
_chunks
_chunks
45
56
45
45
3bae63461fc482887ae26d578370bb695a8d195b
bigcode/the-stack
train
35db1a41482d3ffe86f347bc
train
function
def expand_with_content(url, timeout=10): """Wrapper for _expand_with_content :param url: URL :type url: str :param timeout: number of seconds to wait for a reseponse (Default value = 10) :type timeout: int :returns: url_content-> see _expand_with_content() :rtype: dict """ url_con...
def expand_with_content(url, timeout=10):
"""Wrapper for _expand_with_content :param url: URL :type url: str :param timeout: number of seconds to wait for a reseponse (Default value = 10) :type timeout: int :returns: url_content-> see _expand_with_content() :rtype: dict """ url_content = _expand_with_content(url=url, timeo...
"resolved URL: {url_long}") return dict( original_url=url, response_url=response_url, resolved_url=url_long, resolved_domain=domain, response_code=status_code, response_reason=reason, resolved_text=text, ) def expand_with_content(url, timeout=10):
64
64
102
10
54
wlmwng/urlExpander
urlexpander/core/api.py
Python
expand_with_content
expand_with_content
164
177
164
164
5481c545923ee35afa0d6a18ef8874ce81a2dd96
bigcode/the-stack
train
4d8baaaa02aa091eeaccb7a0
train
function
def _expand_with_content(url, timeout=10): """Expands a URL and retrieves the HTML and status info from the server response. :param url: URL :type url: str :param timeout: number of seconds to wait for a reseponse (Default value = 10) :type timeout: int :rtype: a dictionary containing the follo...
def _expand_with_content(url, timeout=10):
"""Expands a URL and retrieves the HTML and status info from the server response. :param url: URL :type url: str :param timeout: number of seconds to wait for a reseponse (Default value = 10) :type timeout: int :rtype: a dictionary containing the following keys - original_url (str): the ...
NECTIONPOOL_ERROR__: {error}") elif "Client Error: " in error or "Server Error" in error: if verbose: print("ConnectionError or Server Error") url_endpoint = error.split(" for url: ")[-1] domain = url_utils.get_domain(url_endpoint) url_endpoint = os.path.join("http://", ...
150
150
501
11
138
wlmwng/urlExpander
urlexpander/core/api.py
Python
_expand_with_content
_expand_with_content
99
161
99
99
8df06c2f9e4082ca4dd555add10b2221ed3ac09b
bigcode/the-stack
train
3489920fc7365f545ea69ed7
train
function
def _expand(url, timeout=10, verbose=False, use_head=True, **kwargs): """Expands a URL, while taking into consideration: special URL shortener or analytics platforms that either need a sophisticated redirect(st.sh), or parsing of the url (ln.is) :param url: URL to expand :type url: str :param timeo...
def _expand(url, timeout=10, verbose=False, use_head=True, **kwargs):
"""Expands a URL, while taking into consideration: special URL shortener or analytics platforms that either need a sophisticated redirect(st.sh), or parsing of the url (ln.is) :param url: URL to expand :type url: str :param timeout: number of seconds to wait for a response (Default value = 10) ...
domain, response_code=status_code, response_reason=reason, resolved_text=text, ) def expand_with_content(url, timeout=10): """Wrapper for _expand_with_content :param url: URL :type url: str :param timeout: number of seconds to wait for a reseponse (Default value = 10) ...
142
142
476
19
122
wlmwng/urlExpander
urlexpander/core/api.py
Python
_expand
_expand
180
238
180
180
e3b4be7f204ef5c47f2f983b0a8492eb32edc929
bigcode/the-stack
train
28f26f45e9dc8ff2db48f2a2
train
function
def multithread_function( urls_to_expand, function, cache_col, chunksize=1280, n_workers=64, cache_file=None, random_seed=303, verbose=0, **kwargs, ): """Calls 'function' with multiple (n_workers) threads. :param urls_to_expand: a list of URLs (str) to unshorten :type ur...
def multithread_function( urls_to_expand, function, cache_col, chunksize=1280, n_workers=64, cache_file=None, random_seed=303, verbose=0, **kwargs, ):
"""Calls 'function' with multiple (n_workers) threads. :param urls_to_expand: a list of URLs (str) to unshorten :type urls_to_expand: list :param function: :param chunksize: chunks urls_to_expand, which makes computation quicker with larger inputs (Default value = 1280) :type chunksize: int ...
}) if verbose == 2: print( "{} failed to resolve due to error: {}".format( chunk[i], str(type(exc)) ) ) finally: ...
196
197
658
52
144
wlmwng/urlExpander
urlexpander/core/api.py
Python
multithread_function
multithread_function
347
424
347
357
6ebb05bf3c706b6c0e10599afb9e193d3e2fd763
bigcode/the-stack
train
cbb0aeed5e7c1db84d7095d0
train
function
def main(): a = int(input()) print(-15 < a <= 12 or 14 < a < 17 or 19 <= a)
def main():
a = int(input()) print(-15 < a <= 12 or 14 < a < 17 or 19 <= a)
int(input()) # if -15 < a <= 12: # print(True) # elif 14 < a < 17: # print(True) # elif a >= 19: # print(True) # else: # print(False) # Good example: def main():
64
64
32
3
61
fedusia/python
stepik/Programming_on_Python/part1/1.2.interval.py
Python
main
main
18
20
18
18
3e35464748b6eda6a008d7fd96fef7a54775661d
bigcode/the-stack
train
03d0e47b7508c0c98d603794
train
class
class IrCron(osv.osv): _inherit = 'ir.cron' def executer_manuellement(self, cr, uid, ids, context=None): for cron in self.browse(cr, uid, ids): requete = 'self.pool.get("' + cron.model + '").' + cron.function + '(cr, uid, context)' _logger.info("Requete manuelle de : " + requete...
class IrCron(osv.osv):
_inherit = 'ir.cron' def executer_manuellement(self, cr, uid, ids, context=None): for cron in self.browse(cr, uid, ids): requete = 'self.pool.get("' + cron.model + '").' + cron.function + '(cr, uid, context)' _logger.info("Requete manuelle de : " + requete) exec(requ...
US) from sirius_lib.Metro.Models.drop_shipping.flux_rupture import * from openerp.osv import fields, osv from openerp import SUPERUSER_ID import logging import netsvc from ftplib import FTP _logger = logging.getLogger(__name__) class IrCron(osv.osv):
64
64
99
8
56
Sirfanas/manual_execute_ir_cron
manual_execute_ir_cron/models/ir_cron.py
Python
IrCron
IrCron
19
27
19
19
6ba93af12f2ee541509b57f462dfb459f974168e
bigcode/the-stack
train