blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b470f22ba047330f5444cd81237126d1f687d950 | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nd, n = data.shape\nif n < 2:\n raise ValueError('data must contain multiple data points')\nself.mean, self.cov = self.mean_cov(data)",
"d, n = X.shape\nmean = np.expand_dims(np.mean(X, axis=1)... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = data.shape
if n < 2:
raise ValueError('data must contain multiple data points')
self.mean, self.cov = self.mean_cov(data)
<|end_... | MultiNormal class Attriburte: data (numpy.ndarray): Of shape (d, n) containing the data set where n is the number of data points, and d is the number of dimensions. Raises: TypeError: If data is not a 2D numpy.ndarray. ValueError: If n is less than 2 | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""MultiNormal class Attriburte: data (numpy.ndarray): Of shape (d, n) containing the data set where n is the number of data points, and d is the number of dimensions. Raises: TypeError: If data is not a 2D numpy.ndarray. ValueError: If n is less than 2"""
def __init__(self, dat... | stack_v2_sparse_classes_36k_train_003700 | 2,291 | no_license | [
{
"docstring": "Consturctor",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Calculates the mean and covariance of data set Args: X (np.ndarray): of shape (n, d) containing the data set where n is the number of data point, and d is the number of dimension. Returns... | 3 | null | Implement the Python class `MultiNormal` described below.
Class description:
MultiNormal class Attriburte: data (numpy.ndarray): Of shape (d, n) containing the data set where n is the number of data points, and d is the number of dimensions. Raises: TypeError: If data is not a 2D numpy.ndarray. ValueError: If n is les... | Implement the Python class `MultiNormal` described below.
Class description:
MultiNormal class Attriburte: data (numpy.ndarray): Of shape (d, n) containing the data set where n is the number of data points, and d is the number of dimensions. Raises: TypeError: If data is not a 2D numpy.ndarray. ValueError: If n is les... | 2ddae38cc25d914488451b8c30e1234f1fa55ebe | <|skeleton|>
class MultiNormal:
"""MultiNormal class Attriburte: data (numpy.ndarray): Of shape (d, n) containing the data set where n is the number of data points, and d is the number of dimensions. Raises: TypeError: If data is not a 2D numpy.ndarray. ValueError: If n is less than 2"""
def __init__(self, dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""MultiNormal class Attriburte: data (numpy.ndarray): Of shape (d, n) containing the data set where n is the number of data points, and d is the number of dimensions. Raises: TypeError: If data is not a 2D numpy.ndarray. ValueError: If n is less than 2"""
def __init__(self, data):
"... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | KoeusIss/holbertonschool-machine_learning | train | 0 |
09ff35c7a52d235f4cc3e7356379c929f2be0567 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AuditLogRoot()",
"from .directory_audit import DirectoryAudit\nfrom .entity import Entity\nfrom .provisioning_object_summary import ProvisioningObjectSummary\nfrom .sign_in import SignIn\nfrom .directory_audit import DirectoryAudit\nfr... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AuditLogRoot()
<|end_body_0|>
<|body_start_1|>
from .directory_audit import DirectoryAudit
from .entity import Entity
from .provisioning_object_summary import ProvisioningObjectS... | AuditLogRoot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditLogRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k_train_003701 | 3,089 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AuditLogRoot",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | null | Implement the Python class `AuditLogRoot` described below.
Class description:
Implement the AuditLogRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `AuditLogRoot` described below.
Class description:
Implement the AuditLogRoot class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AuditLogRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuditLogRoot:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AuditLogRoot:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AuditLogRoot""... | the_stack_v2_python_sparse | msgraph/generated/models/audit_log_root.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
dd71e51390519c515ed9914888f22e9accb0602c | [
"if self.physical_element in ['UH', 'UR'] and self.num_value is not None:\n return self.num_value * 10\nif self.unit_convention == 'E' or self.num_value is None:\n return self.num_value\nename = shef_english_units.get(self.physical_element)\nsname = shef_standard_units.get(self.physical_element)\nif ename is ... | <|body_start_0|>
if self.physical_element in ['UH', 'UR'] and self.num_value is not None:
return self.num_value * 10
if self.unit_convention == 'E' or self.num_value is None:
return self.num_value
ename = shef_english_units.get(self.physical_element)
sname = shef_... | A PEDTSEP Element. | SHEFElement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SHEFElement:
"""A PEDTSEP Element."""
def to_english(self) -> float:
"""Return an English value representation. Implementation Note: In the case of wind direction (UH, UR), this returns the un-scaled value."""
<|body_0|>
def varname(self) -> str:
"""Return the Fu... | stack_v2_sparse_classes_36k_train_003702 | 4,398 | permissive | [
{
"docstring": "Return an English value representation. Implementation Note: In the case of wind direction (UH, UR), this returns the un-scaled value.",
"name": "to_english",
"signature": "def to_english(self) -> float"
},
{
"docstring": "Return the Full SHEF Code.",
"name": "varname",
"... | 4 | null | Implement the Python class `SHEFElement` described below.
Class description:
A PEDTSEP Element.
Method signatures and docstrings:
- def to_english(self) -> float: Return an English value representation. Implementation Note: In the case of wind direction (UH, UR), this returns the un-scaled value.
- def varname(self) ... | Implement the Python class `SHEFElement` described below.
Class description:
A PEDTSEP Element.
Method signatures and docstrings:
- def to_english(self) -> float: Return an English value representation. Implementation Note: In the case of wind direction (UH, UR), this returns the un-scaled value.
- def varname(self) ... | 460f44394be05e1b655111595a3d7de3f7e47757 | <|skeleton|>
class SHEFElement:
"""A PEDTSEP Element."""
def to_english(self) -> float:
"""Return an English value representation. Implementation Note: In the case of wind direction (UH, UR), this returns the un-scaled value."""
<|body_0|>
def varname(self) -> str:
"""Return the Fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SHEFElement:
"""A PEDTSEP Element."""
def to_english(self) -> float:
"""Return an English value representation. Implementation Note: In the case of wind direction (UH, UR), this returns the un-scaled value."""
if self.physical_element in ['UH', 'UR'] and self.num_value is not None:
... | the_stack_v2_python_sparse | src/pyiem/models/shef.py | akrherz/pyIEM | train | 38 |
08dbdbabc7f3d86e78704da64e02ddd164c4e4bb | [
"if self._context.get('op_fees_ids', []):\n illness_id = self.env['hospital.treatment'].resolve_2many_commands('op_fees_ids', self._context.get('op_fees_ids', []))\n args.append(('id', 'not in', [isinstance(d['illness_id'], tuple) and d['illness_id'][0] or d['illness_id'] for d in illness_id]))\nreturn super(... | <|body_start_0|>
if self._context.get('op_fees_ids', []):
illness_id = self.env['hospital.treatment'].resolve_2many_commands('op_fees_ids', self._context.get('op_fees_ids', []))
args.append(('id', 'not in', [isinstance(d['illness_id'], tuple) and d['illness_id'][0] or d['illness_id'] for... | Zakat_illness | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Zakat_illness:
def name_search(self, name='', args=None, operator='ilike', limit=100):
"""show only illness that is not selected :return: list of ids"""
<|body_0|>
def fields_check(self):
"""Check if name field contain an invalid value :raise exception"""
<|b... | stack_v2_sparse_classes_36k_train_003703 | 47,323 | no_license | [
{
"docstring": "show only illness that is not selected :return: list of ids",
"name": "name_search",
"signature": "def name_search(self, name='', args=None, operator='ilike', limit=100)"
},
{
"docstring": "Check if name field contain an invalid value :raise exception",
"name": "fields_check"... | 2 | null | Implement the Python class `Zakat_illness` described below.
Class description:
Implement the Zakat_illness class.
Method signatures and docstrings:
- def name_search(self, name='', args=None, operator='ilike', limit=100): show only illness that is not selected :return: list of ids
- def fields_check(self): Check if n... | Implement the Python class `Zakat_illness` described below.
Class description:
Implement the Zakat_illness class.
Method signatures and docstrings:
- def name_search(self, name='', args=None, operator='ilike', limit=100): show only illness that is not selected :return: list of ids
- def fields_check(self): Check if n... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class Zakat_illness:
def name_search(self, name='', args=None, operator='ilike', limit=100):
"""show only illness that is not selected :return: list of ids"""
<|body_0|>
def fields_check(self):
"""Check if name field contain an invalid value :raise exception"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Zakat_illness:
def name_search(self, name='', args=None, operator='ilike', limit=100):
"""show only illness that is not selected :return: list of ids"""
if self._context.get('op_fees_ids', []):
illness_id = self.env['hospital.treatment'].resolve_2many_commands('op_fees_ids', self._... | the_stack_v2_python_sparse | v_11/zakat-project/branches/dzc_1/models/dzc_1_config.py | musabahmed/baba | train | 0 | |
75865bf85a74c9cab76934b4b73596c13092c7a4 | [
"try:\n self.f = lambda x: eval(function)\nexcept:\n print('Function was not understood.')\n self.f = lambda x: 0\nwhile True:\n colour = (random.randint(0, 5) * 51, random.randint(0, 5) * 51, random.randint(0, 5) * 51)\n if self.colour_check(colour):\n self.plotter = PygameTools.Sprite(Pygame... | <|body_start_0|>
try:
self.f = lambda x: eval(function)
except:
print('Function was not understood.')
self.f = lambda x: 0
while True:
colour = (random.randint(0, 5) * 51, random.randint(0, 5) * 51, random.randint(0, 5) * 51)
if self.co... | Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variable (a list) that will update as colours... | FunctionOfX | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionOfX:
"""Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variab... | stack_v2_sparse_classes_36k_train_003704 | 5,748 | no_license | [
{
"docstring": "Create the function object with an original plotter.",
"name": "__init__",
"signature": "def __init__(self, function)"
},
{
"docstring": "Plots the function to the surface.",
"name": "plot",
"signature": "def plot(self, surface)"
},
{
"docstring": "Return True and... | 3 | stack_v2_sparse_classes_30k_train_008343 | Implement the Python class `FunctionOfX` described below.
Class description:
Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours ... | Implement the Python class `FunctionOfX` described below.
Class description:
Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours ... | e7bbc0f7cfab13a2e16baa4c931d3a412c86277c | <|skeleton|>
class FunctionOfX:
"""Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionOfX:
"""Class for the functions to be plotted. A function will be of x and any other symbols must have been predefined (like e or pi). Each function will have a plotter that is a uniquely coloured sprite (from PygameTools.Sprite). The unique colours are maintained by having a class variable (a list) t... | the_stack_v2_python_sparse | Plot2.py | Chig00/Python | train | 1 |
ed918d08b202d6a9c6ce64ee5a113d05b336c722 | [
"gh_client = graphql.GraphQLClient()\nresult = github_util.get_issue(url, gh_client)\nprint(json.dumps(result, indent=4, sort_keys=True))",
"publisher = pubsub.PublisherClient()\nrepo_owner, repo_name, issue_num = util.parse_issue_spec(issue)\nif not repo_owner:\n raise ValueError(f\"issue={issue} didn't match... | <|body_start_0|>
gh_client = graphql.GraphQLClient()
result = github_util.get_issue(url, gh_client)
print(json.dumps(result, indent=4, sort_keys=True))
<|end_body_0|>
<|body_start_1|>
publisher = pubsub.PublisherClient()
repo_owner, repo_name, issue_num = util.parse_issue_spec(i... | Cli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cli:
def get_issue(url):
"""Get the data for a specific issue. Args: url: URL of the issue"""
<|body_0|>
def label_issue(issue, pubsub_topic=DEFAULT_TOPIC):
"""Label a specific issue. Args: issue: The issue in the form {owner}/{repo}#{issue} pubsub_topic: (Optional) ... | stack_v2_sparse_classes_36k_train_003705 | 2,503 | permissive | [
{
"docstring": "Get the data for a specific issue. Args: url: URL of the issue",
"name": "get_issue",
"signature": "def get_issue(url)"
},
{
"docstring": "Label a specific issue. Args: issue: The issue in the form {owner}/{repo}#{issue} pubsub_topic: (Optional) the pubsub topic to publish to. Th... | 3 | stack_v2_sparse_classes_30k_train_001872 | Implement the Python class `Cli` described below.
Class description:
Implement the Cli class.
Method signatures and docstrings:
- def get_issue(url): Get the data for a specific issue. Args: url: URL of the issue
- def label_issue(issue, pubsub_topic=DEFAULT_TOPIC): Label a specific issue. Args: issue: The issue in t... | Implement the Python class `Cli` described below.
Class description:
Implement the Cli class.
Method signatures and docstrings:
- def get_issue(url): Get the data for a specific issue. Args: url: URL of the issue
- def label_issue(issue, pubsub_topic=DEFAULT_TOPIC): Label a specific issue. Args: issue: The issue in t... | 5889168299f9112d1b5f6f0af46452ad50c44993 | <|skeleton|>
class Cli:
def get_issue(url):
"""Get the data for a specific issue. Args: url: URL of the issue"""
<|body_0|>
def label_issue(issue, pubsub_topic=DEFAULT_TOPIC):
"""Label a specific issue. Args: issue: The issue in the form {owner}/{repo}#{issue} pubsub_topic: (Optional) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cli:
def get_issue(url):
"""Get the data for a specific issue. Args: url: URL of the issue"""
gh_client = graphql.GraphQLClient()
result = github_util.get_issue(url, gh_client)
print(json.dumps(result, indent=4, sort_keys=True))
def label_issue(issue, pubsub_topic=DEFAULT_... | the_stack_v2_python_sparse | py/label_microservice/cli.py | kubeflow/code-intelligence | train | 56 | |
20da6f9129cef93a93d48fb518d53250a1d35b77 | [
"super(CrossEntropyLoss, self).__init__()\nself.num_classes = num_classes\nself.weights = weights\nself.device = device",
"target_oh = torch.eye(self.num_classes)[target.squeeze(1)]\ntarget_oh = target_oh.permute(0, 4, 1, 2, 3).float()\nprobs = softmax(pred, dim=1)\ntarget_oh = target_oh.type(pred.type())\ndims =... | <|body_start_0|>
super(CrossEntropyLoss, self).__init__()
self.num_classes = num_classes
self.weights = weights
self.device = device
<|end_body_0|>
<|body_start_1|>
target_oh = torch.eye(self.num_classes)[target.squeeze(1)]
target_oh = target_oh.permute(0, 4, 1, 2, 3).fl... | CrossEntropyLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossEntropyLoss:
def __init__(self, num_classes, weights, device):
"""A wrapper Module for a custom loss function"""
<|body_0|>
def tversky_loss(self, pred, target, alpha=0.7, beta=0.3):
"""Calculate the Tversky loss for the input batches :param pred: predicted batc... | stack_v2_sparse_classes_36k_train_003706 | 2,932 | permissive | [
{
"docstring": "A wrapper Module for a custom loss function",
"name": "__init__",
"signature": "def __init__(self, num_classes, weights, device)"
},
{
"docstring": "Calculate the Tversky loss for the input batches :param pred: predicted batch from model :param target: target batch from input :pa... | 4 | null | Implement the Python class `CrossEntropyLoss` described below.
Class description:
Implement the CrossEntropyLoss class.
Method signatures and docstrings:
- def __init__(self, num_classes, weights, device): A wrapper Module for a custom loss function
- def tversky_loss(self, pred, target, alpha=0.7, beta=0.3): Calcula... | Implement the Python class `CrossEntropyLoss` described below.
Class description:
Implement the CrossEntropyLoss class.
Method signatures and docstrings:
- def __init__(self, num_classes, weights, device): A wrapper Module for a custom loss function
- def tversky_loss(self, pred, target, alpha=0.7, beta=0.3): Calcula... | a30e907e83fa5bbfb934d951b7c663b622104fcc | <|skeleton|>
class CrossEntropyLoss:
def __init__(self, num_classes, weights, device):
"""A wrapper Module for a custom loss function"""
<|body_0|>
def tversky_loss(self, pred, target, alpha=0.7, beta=0.3):
"""Calculate the Tversky loss for the input batches :param pred: predicted batc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossEntropyLoss:
def __init__(self, num_classes, weights, device):
"""A wrapper Module for a custom loss function"""
super(CrossEntropyLoss, self).__init__()
self.num_classes = num_classes
self.weights = weights
self.device = device
def tversky_loss(self, pred, ta... | the_stack_v2_python_sparse | em/deep_segmentation/extreme_points/CrossEntropyLoss.py | tecdatalab/biostructure | train | 0 | |
50f446d66ec1f67b19221f85e9f089c91162981d | [
"self.bed_dict = {}\nwith open(fileagp) as fh:\n for line in fh:\n this_chr, this_start, this_end, this_name, this_strand = [''] * 5\n mylist = line.rstrip('\\n').split()\n this_score = '.'\n if mylist[4] == 'U':\n this_chr, this_start, this_end = mylist[0:3]\n t... | <|body_start_0|>
self.bed_dict = {}
with open(fileagp) as fh:
for line in fh:
this_chr, this_start, this_end, this_name, this_strand = [''] * 5
mylist = line.rstrip('\n').split()
this_score = '.'
if mylist[4] == 'U':
... | AGPIO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AGPIO:
def __init__(self, fileagp):
"""Read AGP file into BedIO object ==> groups.agp <== Hic.fastq.gz.counts_GATC.20g1 1 79244 1 W tig00005006|arrow_np1212 1 79244 + Hic.fastq.gz.counts_GATC.20g1 79245 79344 2 U 100 contig yes map Hic.fastq.gz.counts_GATC.20g1 79345 123128 3 W tig000050... | stack_v2_sparse_classes_36k_train_003707 | 10,695 | no_license | [
{
"docstring": "Read AGP file into BedIO object ==> groups.agp <== Hic.fastq.gz.counts_GATC.20g1 1 79244 1 W tig00005006|arrow_np1212 1 79244 + Hic.fastq.gz.counts_GATC.20g1 79245 79344 2 U 100 contig yes map Hic.fastq.gz.counts_GATC.20g1 79345 123128 3 W tig00005007|arrow_np1212 1 43784 -",
"name": "__init... | 2 | null | Implement the Python class `AGPIO` described below.
Class description:
Implement the AGPIO class.
Method signatures and docstrings:
- def __init__(self, fileagp): Read AGP file into BedIO object ==> groups.agp <== Hic.fastq.gz.counts_GATC.20g1 1 79244 1 W tig00005006|arrow_np1212 1 79244 + Hic.fastq.gz.counts_GATC.20... | Implement the Python class `AGPIO` described below.
Class description:
Implement the AGPIO class.
Method signatures and docstrings:
- def __init__(self, fileagp): Read AGP file into BedIO object ==> groups.agp <== Hic.fastq.gz.counts_GATC.20g1 1 79244 1 W tig00005006|arrow_np1212 1 79244 + Hic.fastq.gz.counts_GATC.20... | e31c8f2f65260ceff110d07b530b67e465e41800 | <|skeleton|>
class AGPIO:
def __init__(self, fileagp):
"""Read AGP file into BedIO object ==> groups.agp <== Hic.fastq.gz.counts_GATC.20g1 1 79244 1 W tig00005006|arrow_np1212 1 79244 + Hic.fastq.gz.counts_GATC.20g1 79245 79344 2 U 100 contig yes map Hic.fastq.gz.counts_GATC.20g1 79345 123128 3 W tig000050... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AGPIO:
def __init__(self, fileagp):
"""Read AGP file into BedIO object ==> groups.agp <== Hic.fastq.gz.counts_GATC.20g1 1 79244 1 W tig00005006|arrow_np1212 1 79244 + Hic.fastq.gz.counts_GATC.20g1 79245 79344 2 U 100 contig yes map Hic.fastq.gz.counts_GATC.20g1 79345 123128 3 W tig00005007|arrow_np121... | the_stack_v2_python_sparse | lh_bin/assembly_agp2bedpe.py | lhui2010/bundle | train | 6 | |
08feff8ded758a44575a959bc56bbd3ea17d3ebb | [
"super(Worker, self).__init__(name='Worker-%d' % next(self._counter))\nself._queue = jobs_queue\nself._job = None",
"logger.debug('%s started.', self.name)\nwhile True:\n self._job = self._queue.get()\n logger.info('%s picked up %s', self.name, self._job)\n try:\n if self._job == KILL_WORKER:\n ... | <|body_start_0|>
super(Worker, self).__init__(name='Worker-%d' % next(self._counter))
self._queue = jobs_queue
self._job = None
<|end_body_0|>
<|body_start_1|>
logger.debug('%s started.', self.name)
while True:
self._job = self._queue.get()
logger.info('%... | Worker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
def __init__(self, jobs_queue):
""":param jobs_queue: queue with the jobs to execute :type jobs_queue: queue.Queue[LocalCommand]"""
<|body_0|>
def run(self):
"""Runs Worker thread which polls queue for commands and starts them."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_003708 | 21,767 | no_license | [
{
"docstring": ":param jobs_queue: queue with the jobs to execute :type jobs_queue: queue.Queue[LocalCommand]",
"name": "__init__",
"signature": "def __init__(self, jobs_queue)"
},
{
"docstring": "Runs Worker thread which polls queue for commands and starts them.",
"name": "run",
"signat... | 2 | stack_v2_sparse_classes_30k_train_021334 | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, jobs_queue): :param jobs_queue: queue with the jobs to execute :type jobs_queue: queue.Queue[LocalCommand]
- def run(self): Runs Worker thread which polls queue fo... | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def __init__(self, jobs_queue): :param jobs_queue: queue with the jobs to execute :type jobs_queue: queue.Queue[LocalCommand]
- def run(self): Runs Worker thread which polls queue fo... | 20bcc179792c4f975eeeb0924a9f234599453090 | <|skeleton|>
class Worker:
def __init__(self, jobs_queue):
""":param jobs_queue: queue with the jobs to execute :type jobs_queue: queue.Queue[LocalCommand]"""
<|body_0|>
def run(self):
"""Runs Worker thread which polls queue for commands and starts them."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Worker:
def __init__(self, jobs_queue):
""":param jobs_queue: queue with the jobs to execute :type jobs_queue: queue.Queue[LocalCommand]"""
super(Worker, self).__init__(name='Worker-%d' % next(self._counter))
self._queue = jobs_queue
self._job = None
def run(self):
... | the_stack_v2_python_sparse | slivka/scheduler/task_queue.py | stuartmac/Slivka | train | 0 | |
088ac256a3cf15785085c494bc69912280c63774 | [
"client = mock_client(mocker)\nargs = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com'}}\nmocker.patch.object(client, 'get_user', return_value=None)\nmocker.patch.object(IAMUserProfile, 'map_object', return_value={})\nmocker.patch.object(client, 'create_user', return_value=USER_APP_DATA)\nuser_profile... | <|body_start_0|>
client = mock_client(mocker)
args = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com'}}
mocker.patch.object(client, 'get_user', return_value=None)
mocker.patch.object(IAMUserProfile, 'map_object', return_value={})
mocker.patch.object(client, 'create_... | Class to group the create user commands test | TestCreateUserCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreateUserCommand:
"""Class to group the create user commands test"""
def test_create_user_command__success(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_u... | stack_v2_sparse_classes_36k_train_003709 | 13,964 | permissive | [
{
"docstring": "Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_user_command Then: - Ensure a User Profile object with the user data is returned",
"name": "test_create_user_command__success",
"signat... | 2 | stack_v2_sparse_classes_30k_test_000436 | Implement the Python class `TestCreateUserCommand` described below.
Class description:
Class to group the create user commands test
Method signatures and docstrings:
- def test_create_user_command__success(self, mocker): Given: - An app client object - A user-profile argument that contains an email of a non-existing ... | Implement the Python class `TestCreateUserCommand` described below.
Class description:
Class to group the create user commands test
Method signatures and docstrings:
- def test_create_user_command__success(self, mocker): Given: - An app client object - A user-profile argument that contains an email of a non-existing ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestCreateUserCommand:
"""Class to group the create user commands test"""
def test_create_user_command__success(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCreateUserCommand:
"""Class to group the create user commands test"""
def test_create_user_command__success(self, mocker):
"""Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_user_command T... | the_stack_v2_python_sparse | Packs/PrismaCloud/Integrations/PrismaCloudIAM/PrismaCloudIAM_test.py | demisto/content | train | 1,023 |
a0ca8a4f4d1f0ecbd62fdaa3635f7b7135b48449 | [
"group_claim = Config.get_OIDC_group_claim()\nself._assert_required_token_parameters([group_claim])\nreturn self.token[group_claim]",
"from ..security import assert_authorized_group\nassert_authorized_group(groups, self.token)\nreturn"
] | <|body_start_0|>
group_claim = Config.get_OIDC_group_claim()
self._assert_required_token_parameters([group_claim])
return self.token[group_claim]
<|end_body_0|>
<|body_start_1|>
from ..security import assert_authorized_group
assert_authorized_group(groups, self.token)
re... | Mixin: add a token_group attribute, based on group claim set in DSS config. Includes verification methods. | TokenGroupMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenGroupMixin:
"""Mixin: add a token_group attribute, based on group claim set in DSS config. Includes verification methods."""
def token_group(self):
"""Property for the user's JWT group claim"""
<|body_0|>
def _assert_authorized_group(self, groups):
"""Verify... | stack_v2_sparse_classes_36k_train_003710 | 4,756 | permissive | [
{
"docstring": "Property for the user's JWT group claim",
"name": "token_group",
"signature": "def token_group(self)"
},
{
"docstring": "Verify user JWT token group matches specified groups",
"name": "_assert_authorized_group",
"signature": "def _assert_authorized_group(self, groups)"
... | 2 | stack_v2_sparse_classes_30k_train_021043 | Implement the Python class `TokenGroupMixin` described below.
Class description:
Mixin: add a token_group attribute, based on group claim set in DSS config. Includes verification methods.
Method signatures and docstrings:
- def token_group(self): Property for the user's JWT group claim
- def _assert_authorized_group(... | Implement the Python class `TokenGroupMixin` described below.
Class description:
Mixin: add a token_group attribute, based on group claim set in DSS config. Includes verification methods.
Method signatures and docstrings:
- def token_group(self): Property for the user's JWT group claim
- def _assert_authorized_group(... | fa96624a09c7ac1595fcd6fbabd31e551382b757 | <|skeleton|>
class TokenGroupMixin:
"""Mixin: add a token_group attribute, based on group claim set in DSS config. Includes verification methods."""
def token_group(self):
"""Property for the user's JWT group claim"""
<|body_0|>
def _assert_authorized_group(self, groups):
"""Verify... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenGroupMixin:
"""Mixin: add a token_group attribute, based on group claim set in DSS config. Includes verification methods."""
def token_group(self):
"""Property for the user's JWT group claim"""
group_claim = Config.get_OIDC_group_claim()
self._assert_required_token_parameters... | the_stack_v2_python_sparse | dss/util/auth/authorize.py | charlesreid1acom/data-store | train | 0 |
67c0ed03c8f71a462b43ce90fd9c89502261f5d4 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.targetedManagedAppConfiguration'.casefold()... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | Configuration used to deliver a set of custom settings as-is to apps for users to whom the configuration is scoped | ManagedAppConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagedAppConfiguration:
"""Configuration used to deliver a set of custom settings as-is to apps for users to whom the configuration is scoped"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppConfiguration:
"""Creates a new instance of the app... | stack_v2_sparse_classes_36k_train_003711 | 3,291 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ManagedAppConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimin... | 3 | stack_v2_sparse_classes_30k_train_013698 | Implement the Python class `ManagedAppConfiguration` described below.
Class description:
Configuration used to deliver a set of custom settings as-is to apps for users to whom the configuration is scoped
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> M... | Implement the Python class `ManagedAppConfiguration` described below.
Class description:
Configuration used to deliver a set of custom settings as-is to apps for users to whom the configuration is scoped
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> M... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ManagedAppConfiguration:
"""Configuration used to deliver a set of custom settings as-is to apps for users to whom the configuration is scoped"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppConfiguration:
"""Creates a new instance of the app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManagedAppConfiguration:
"""Configuration used to deliver a set of custom settings as-is to apps for users to whom the configuration is scoped"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedAppConfiguration:
"""Creates a new instance of the appropriate clas... | the_stack_v2_python_sparse | msgraph/generated/models/managed_app_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
7e09de1c5dc520c79c269c897db4b3fe602bd1f3 | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nlinks = LinkExtractor(restrict_xpaths='//div[@class=\"forumbg\"]//a[contains(@class,\"topictitle\")]').extract_links(response)\nfor link in links:\n yield scrapy.Request(link.url, callback=self.pages_in_thread, dont_filter=True)",
"assert is... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
links = LinkExtractor(restrict_xpaths='//div[@class="forumbg"]//a[contains(@class,"topictitle")]').extract_links(response)
for link in links:
yield scrapy.Request(link.url, callback=self.pages_in_thr... | scrape images from angling addicts forum | SeaAnglingIrelandSpeciesHuntImageSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeaAnglingIrelandSpeciesHuntImageSpider:
"""scrape images from angling addicts forum"""
def parse(self, response):
"""get all thread links on a page"""
<|body_0|>
def pages_in_thread(self, response):
"""loop through a thread response in: http://www.sea-angling-ir... | stack_v2_sparse_classes_36k_train_003712 | 5,577 | no_license | [
{
"docstring": "get all thread links on a page",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "loop through a thread response in: http://www.sea-angling-ireland.org/forum/viewtopic.php?f=30&t=14430 yields: http://www.sea-angling-ireland.org/forum/viewtopic.php?f=30... | 3 | null | Implement the Python class `SeaAnglingIrelandSpeciesHuntImageSpider` described below.
Class description:
scrape images from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): get all thread links on a page
- def pages_in_thread(self, response): loop through a thread response in: http... | Implement the Python class `SeaAnglingIrelandSpeciesHuntImageSpider` described below.
Class description:
scrape images from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): get all thread links on a page
- def pages_in_thread(self, response): loop through a thread response in: http... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class SeaAnglingIrelandSpeciesHuntImageSpider:
"""scrape images from angling addicts forum"""
def parse(self, response):
"""get all thread links on a page"""
<|body_0|>
def pages_in_thread(self, response):
"""loop through a thread response in: http://www.sea-angling-ir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SeaAnglingIrelandSpeciesHuntImageSpider:
"""scrape images from angling addicts forum"""
def parse(self, response):
"""get all thread links on a page"""
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
links = LinkExtractor(restrict_xpaths='//div[@class="forumbg"... | the_stack_v2_python_sparse | imgscrape/spiders/seaanglingireland.py | gmonkman/python | train | 0 |
2183df1904056ec1719f5874a743a947446ed481 | [
"self.word_indices = defaultdict(list)\nfor index, word in enumerate(words):\n self.word_indices[word].append(index)",
"list1 = self.word_indices[word1]\nlist2 = self.word_indices[word2]\nptr1 = ptr2 = 0\nans = (1 << 31) - 1\nwhile ptr1 < len(list1) and ptr2 < len(list2):\n while ptr1 < len(list1) and list1... | <|body_start_0|>
self.word_indices = defaultdict(list)
for index, word in enumerate(words):
self.word_indices[word].append(index)
<|end_body_0|>
<|body_start_1|>
list1 = self.word_indices[word1]
list2 = self.word_indices[word2]
ptr1 = ptr2 = 0
ans = (1 << 31)... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.word_indices = defaultdict(list)... | stack_v2_sparse_classes_36k_train_003713 | 1,151 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 5e09a5d36ac55d782628a888ad57d48e234b61ac | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.word_indices = defaultdict(list)
for index, word in enumerate(words):
self.word_indices[word].append(index)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype:... | the_stack_v2_python_sparse | 244/244.py | sjzyjc/leetcode | train | 0 | |
02c4f92b4dd013cc5388f23e9fe2a1ca3c54767b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn HostComponent()",
"from .artifact import Artifact\nfrom .host import Host\nfrom .artifact import Artifact\nfrom .host import Host\nfields: Dict[str, Callable[[Any], None]] = {'category': lambda n: setattr(self, 'category', n.get_str_va... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return HostComponent()
<|end_body_0|>
<|body_start_1|>
from .artifact import Artifact
from .host import Host
from .artifact import Artifact
from .host import Host
fields... | HostComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostComponent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostComponent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k_train_003714 | 3,935 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: HostComponent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_005659 | Implement the Python class `HostComponent` described below.
Class description:
Implement the HostComponent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostComponent: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `HostComponent` described below.
Class description:
Implement the HostComponent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostComponent: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class HostComponent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostComponent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostComponent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostComponent:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: HostComponen... | the_stack_v2_python_sparse | msgraph/generated/models/security/host_component.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fb8278608e00a9762c37261d6e5d43f91f5995f1 | [
"if isinstance(rules, str):\n rules = re.split('\\\\s|,\\\\s*', rules)\npositive_rules = [rule for rule in rules if not rule.startswith('!') and (not rule.strip() == '')]\nnegative_rules = [rule[1:] for rule in rules if rule not in positive_rules]\nif len(positive_rules) == 0:\n positive_rules.append('*')\nma... | <|body_start_0|>
if isinstance(rules, str):
rules = re.split('\\s|,\\s*', rules)
positive_rules = [rule for rule in rules if not rule.startswith('!') and (not rule.strip() == '')]
negative_rules = [rule[1:] for rule in rules if rule not in positive_rules]
if len(positive_rule... | Device name matching against the devices specification in tuning profiles. The devices specification consists of multiple rules separated by spaces. The rules have a syntax of shell-style wildcards and are either positive or negative. The negative rules are prefixed with an exclamation mark. | DeviceMatcher | [
"GPL-2.0-or-later",
"CC-BY-SA-3.0",
"GPL-2.0-only",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceMatcher:
"""Device name matching against the devices specification in tuning profiles. The devices specification consists of multiple rules separated by spaces. The rules have a syntax of shell-style wildcards and are either positive or negative. The negative rules are prefixed with an excl... | stack_v2_sparse_classes_36k_train_003715 | 1,576 | permissive | [
{
"docstring": "Match a device against the specification in the profile. If there is no positive rule in the specification, implicit rule which matches all devices is added. The device matches if and only if it matches some positive rule, but no negative rule.",
"name": "match",
"signature": "def match(... | 2 | stack_v2_sparse_classes_30k_train_009967 | Implement the Python class `DeviceMatcher` described below.
Class description:
Device name matching against the devices specification in tuning profiles. The devices specification consists of multiple rules separated by spaces. The rules have a syntax of shell-style wildcards and are either positive or negative. The n... | Implement the Python class `DeviceMatcher` described below.
Class description:
Device name matching against the devices specification in tuning profiles. The devices specification consists of multiple rules separated by spaces. The rules have a syntax of shell-style wildcards and are either positive or negative. The n... | 6784795578ba558593cc9f620610bcf99fb26de5 | <|skeleton|>
class DeviceMatcher:
"""Device name matching against the devices specification in tuning profiles. The devices specification consists of multiple rules separated by spaces. The rules have a syntax of shell-style wildcards and are either positive or negative. The negative rules are prefixed with an excl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceMatcher:
"""Device name matching against the devices specification in tuning profiles. The devices specification consists of multiple rules separated by spaces. The rules have a syntax of shell-style wildcards and are either positive or negative. The negative rules are prefixed with an exclamation mark.... | the_stack_v2_python_sparse | assets/tuned/daemon/tuned/hardware/device_matcher.py | openshift/cluster-node-tuning-operator | train | 90 |
04b5d6c5ce8eb0f284aec334c410abc972ae4ac9 | [
"if root == None:\n return ''\nlevel = [root]\nres = str(root.val) + ' '\nwhile len(level) > 0:\n next_level = []\n for node in level:\n if node.left:\n next_level.append(node.left)\n res += str(node.left.val) + ' '\n else:\n res += 'n '\n if node.right... | <|body_start_0|>
if root == None:
return ''
level = [root]
res = str(root.val) + ' '
while len(level) > 0:
next_level = []
for node in level:
if node.left:
next_level.append(node.left)
res += str(... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003716 | 2,127 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_013644 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 47d48d261e15d567e4a6c0bb2ff5abcbf206fcb4 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return ''
level = [root]
res = str(root.val) + ' '
while len(level) > 0:
next_level = []
for node in level:
... | the_stack_v2_python_sparse | LeetCode/Binary Tree/Conclusion/Serialize and Deserialize Binary Tree.py | msaei/coding | train | 0 | |
aca3e5eed4e41cb4e57b26fc5b3d8f4e625c6f90 | [
"self.lg('%s STARTED' % self._testID)\nresponse = self.get_request_response(uri='/menus')\nself.lg('#. Get /menus, should succeed')\nself.assertEqual(response.status_code, 200)\nself.assertTrue(response.ok)\nself.lg('#. Check response headers, should succeed')\n[self.assertIn(header, response.headers.keys()) for he... | <|body_start_0|>
self.lg('%s STARTED' % self._testID)
response = self.get_request_response(uri='/menus')
self.lg('#. Get /menus, should succeed')
self.assertEqual(response.status_code, 200)
self.assertTrue(response.ok)
self.lg('#. Check response headers, should succeed')
... | TestMenus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMenus:
def test001_get_menus(self):
"""TestCase-17: Test case for test get /menus.* **Test Scenario:** #. Get /menus, should succeed #. Check response headers, should succeed #. Check response body, should succeed"""
<|body_0|>
def test002_get_menu(self):
"""Test... | stack_v2_sparse_classes_36k_train_003717 | 5,565 | no_license | [
{
"docstring": "TestCase-17: Test case for test get /menus.* **Test Scenario:** #. Get /menus, should succeed #. Check response headers, should succeed #. Check response body, should succeed",
"name": "test001_get_menus",
"signature": "def test001_get_menus(self)"
},
{
"docstring": "TestCase-18:... | 2 | stack_v2_sparse_classes_30k_train_000720 | Implement the Python class `TestMenus` described below.
Class description:
Implement the TestMenus class.
Method signatures and docstrings:
- def test001_get_menus(self): TestCase-17: Test case for test get /menus.* **Test Scenario:** #. Get /menus, should succeed #. Check response headers, should succeed #. Check re... | Implement the Python class `TestMenus` described below.
Class description:
Implement the TestMenus class.
Method signatures and docstrings:
- def test001_get_menus(self): TestCase-17: Test case for test get /menus.* **Test Scenario:** #. Get /menus, should succeed #. Check response headers, should succeed #. Check re... | 9b25ce55fd44976b1b8afc1fb638c1a1b4d3589d | <|skeleton|>
class TestMenus:
def test001_get_menus(self):
"""TestCase-17: Test case for test get /menus.* **Test Scenario:** #. Get /menus, should succeed #. Check response headers, should succeed #. Check response body, should succeed"""
<|body_0|>
def test002_get_menu(self):
"""Test... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMenus:
def test001_get_menus(self):
"""TestCase-17: Test case for test get /menus.* **Test Scenario:** #. Get /menus, should succeed #. Check response headers, should succeed #. Check response body, should succeed"""
self.lg('%s STARTED' % self._testID)
response = self.get_request_... | the_stack_v2_python_sparse | mobile_api_testing/testsuite/test_010_menus.py | simplymahmoud/sss-scripts | train | 0 | |
b502a3a0e6ba53d161946be8bb8a45b34c298549 | [
"self.c = capacity\nself.table = {}\nself.head = LinkList(0)\nself.tail = LinkList(0)\nself.head.next, self.tail.prev = (self.tail, self.head)",
"if key not in self.table:\n return -1\nvalue, node = self.table[key]\nnode.prev.next, node.next.prev = (node.next, node.prev)\nself.tail.prev.next, self.tail.prev, n... | <|body_start_0|>
self.c = capacity
self.table = {}
self.head = LinkList(0)
self.tail = LinkList(0)
self.head.next, self.tail.prev = (self.tail, self.head)
<|end_body_0|>
<|body_start_1|>
if key not in self.table:
return -1
value, node = self.table[key... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_003718 | 2,073 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_train_001561 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | a041962eeab9192799ad7f74b4bbd3e4f74933d0 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.c = capacity
self.table = {}
self.head = LinkList(0)
self.tail = LinkList(0)
self.head.next, self.tail.prev = (self.tail, self.head)
def get(self, key):
""":rtype: int"""
... | the_stack_v2_python_sparse | codes/146. LRU Cache.py | zcgu/leetcode | train | 1 | |
b5c64fff565bb10820b5416cb5d790edb3019cb2 | [
"if post_data is None:\n res = requests.get(url, headers=headers)\n html_tree = etree.HTML(res.text)\nelse:\n res = requests.post(url, headers=headers, post_data=post_data)\n html_tree = etree.HTML(res.text)\nreturn {'__VIEWSTATE': html_tree.xpath(view_state)[0], '__EVENTVALIDATION': html_tree.xpath(eve... | <|body_start_0|>
if post_data is None:
res = requests.get(url, headers=headers)
html_tree = etree.HTML(res.text)
else:
res = requests.post(url, headers=headers, post_data=post_data)
html_tree = etree.HTML(res.text)
return {'__VIEWSTATE': html_tree.... | Tool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tool:
def get_view_state(cls, url, view_state, event_validation, post_data=None, headers=None):
"""传入view_state,event_validation的xpath :param url: http://www.jscsfc.com/NewHouse/ :param view_state: //*[@id="__VIEWSTATE"]/@value :param event_validation: //*[@id="__EVENTVALIDATION"]/@value... | stack_v2_sparse_classes_36k_train_003719 | 1,777 | no_license | [
{
"docstring": "传入view_state,event_validation的xpath :param url: http://www.jscsfc.com/NewHouse/ :param view_state: //*[@id=\"__VIEWSTATE\"]/@value :param event_validation: //*[@id=\"__EVENTVALIDATION\"]/@value :return: {'__VIEWSTATE': html_tree.xpath(view_state), '__EVENTVALIDATION': html_tree.xpath(event_valid... | 2 | stack_v2_sparse_classes_30k_train_007966 | Implement the Python class `Tool` described below.
Class description:
Implement the Tool class.
Method signatures and docstrings:
- def get_view_state(cls, url, view_state, event_validation, post_data=None, headers=None): 传入view_state,event_validation的xpath :param url: http://www.jscsfc.com/NewHouse/ :param view_stat... | Implement the Python class `Tool` described below.
Class description:
Implement the Tool class.
Method signatures and docstrings:
- def get_view_state(cls, url, view_state, event_validation, post_data=None, headers=None): 传入view_state,event_validation的xpath :param url: http://www.jscsfc.com/NewHouse/ :param view_stat... | 808cb78fc3887f35bf838d77d62308fce9e6aa5d | <|skeleton|>
class Tool:
def get_view_state(cls, url, view_state, event_validation, post_data=None, headers=None):
"""传入view_state,event_validation的xpath :param url: http://www.jscsfc.com/NewHouse/ :param view_state: //*[@id="__VIEWSTATE"]/@value :param event_validation: //*[@id="__EVENTVALIDATION"]/@value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tool:
def get_view_state(cls, url, view_state, event_validation, post_data=None, headers=None):
"""传入view_state,event_validation的xpath :param url: http://www.jscsfc.com/NewHouse/ :param view_state: //*[@id="__VIEWSTATE"]/@value :param event_validation: //*[@id="__EVENTVALIDATION"]/@value :return: {'__... | the_stack_v2_python_sparse | hilder_gv/backup/tool.py | pjkui/githubproject | train | 0 | |
9abe9eecfb320f6d312aaaca915ccbd59a96ba47 | [
"try:\n if self.pool != self.pool.check_signaling():\n self.env.reset()\n self = self.env()[self._name]\n log_depth = None if _logger.isEnabledFor(logging.DEBUG) else 1\n odoo.netsvc.log(_logger, logging.DEBUG, 'cron.object.execute', (self._cr.dbname, self._uid, '*', cron_name, server_action_... | <|body_start_0|>
try:
if self.pool != self.pool.check_signaling():
self.env.reset()
self = self.env()[self._name]
log_depth = None if _logger.isEnabledFor(logging.DEBUG) else 1
odoo.netsvc.log(_logger, logging.DEBUG, 'cron.object.execute', (sel... | 扩展添加用户数据 | IrCronExtend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
... | stack_v2_sparse_classes_36k_train_003720 | 4,343 | no_license | [
{
"docstring": "Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method.",
"name": "_callback",
"signature": "def _callback(self, cron_name, server_action_id, job_id, job_data=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_001601 | Implement the Python class `IrCronExtend` described below.
Class description:
扩展添加用户数据
Method signatures and docstrings:
- def _callback(self, cron_name, server_action_id, job_id, job_data=None): Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the ... | Implement the Python class `IrCronExtend` described below.
Class description:
扩展添加用户数据
Method signatures and docstrings:
- def _callback(self, cron_name, server_action_id, job_id, job_data=None): Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the ... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
try:
... | the_stack_v2_python_sparse | mdias_addons/funenc_theme/models/funenc_extend_cron.py | rezaghanimi/main_mdias | train | 0 |
d244ece889197c6099474d8bcec2c02860ca2eb7 | [
"fileName = inspect.getsourcefile(self.parent._create_widgets)\nself.master = master\nself.title('Source Code: ' + fileName)\ntxtFrame = ttk.Frame(self)\ntxtFrame.pack(side=TOP, fill=BOTH)\ntext = tk.Text(txtFrame, height=24, width=100, wrap=WORD, setgrid=1, highlightthickness=0, pady=2, padx=3)\nyscroll = ttk.Scro... | <|body_start_0|>
fileName = inspect.getsourcefile(self.parent._create_widgets)
self.master = master
self.title('Source Code: ' + fileName)
txtFrame = ttk.Frame(self)
txtFrame.pack(side=TOP, fill=BOTH)
text = tk.Text(txtFrame, height=24, width=100, wrap=WORD, setgrid=1, hi... | Create a modal dialog to display a demo's source code file. | CodeDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeDialog:
"""Create a modal dialog to display a demo's source code file."""
def body(self, master: tk.Tk) -> None:
"""Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons."""
<|body_0|>
def buttonbox(self) -> None:... | stack_v2_sparse_classes_36k_train_003721 | 4,028 | permissive | [
{
"docstring": "Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons.",
"name": "body",
"signature": "def body(self, master: tk.Tk) -> None"
},
{
"docstring": "Overrides Dialog.buttonbox() to create custom buttons for this dialog.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_003225 | Implement the Python class `CodeDialog` described below.
Class description:
Create a modal dialog to display a demo's source code file.
Method signatures and docstrings:
- def body(self, master: tk.Tk) -> None: Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons... | Implement the Python class `CodeDialog` described below.
Class description:
Create a modal dialog to display a demo's source code file.
Method signatures and docstrings:
- def body(self, master: tk.Tk) -> None: Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons... | 4672c6a6faa3e8ed31f0bbc1d8c8fdee8b8f928a | <|skeleton|>
class CodeDialog:
"""Create a modal dialog to display a demo's source code file."""
def body(self, master: tk.Tk) -> None:
"""Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons."""
<|body_0|>
def buttonbox(self) -> None:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CodeDialog:
"""Create a modal dialog to display a demo's source code file."""
def body(self, master: tk.Tk) -> None:
"""Overrides Dialog.body() to populate the dialog window with a scrolled text window and custom dialog buttons."""
fileName = inspect.getsourcefile(self.parent._create_widg... | the_stack_v2_python_sparse | src/dmltk/panels.py | Yobmod/dmlmung | train | 0 |
1e354c99cfaae71fe77fed7d25d407945e3d5a19 | [
"request_dict = rest_utils.get_json_and_verify_params({'tenant_name': {'type': str}, 'username': {'type': str}, 'role': {'type': str}})\nrest_utils.validate_inputs(request_dict)\nrole_name = request_dict.get('role')\nif role_name:\n rest_utils.verify_role(role_name)\nelse:\n role_name = constants.DEFAULT_TENA... | <|body_start_0|>
request_dict = rest_utils.get_json_and_verify_params({'tenant_name': {'type': str}, 'username': {'type': str}, 'role': {'type': str}})
rest_utils.validate_inputs(request_dict)
role_name = request_dict.get('role')
if role_name:
rest_utils.verify_role(role_name... | TenantUsers | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenantUsers:
def put(self, multi_tenancy):
"""Add a user to a tenant"""
<|body_0|>
def patch(self, multi_tenancy):
"""Update role in user tenant association."""
<|body_1|>
def delete(self, multi_tenancy):
"""Remove a user from a tenant"""
... | stack_v2_sparse_classes_36k_train_003722 | 10,735 | permissive | [
{
"docstring": "Add a user to a tenant",
"name": "put",
"signature": "def put(self, multi_tenancy)"
},
{
"docstring": "Update role in user tenant association.",
"name": "patch",
"signature": "def patch(self, multi_tenancy)"
},
{
"docstring": "Remove a user from a tenant",
"na... | 3 | null | Implement the Python class `TenantUsers` described below.
Class description:
Implement the TenantUsers class.
Method signatures and docstrings:
- def put(self, multi_tenancy): Add a user to a tenant
- def patch(self, multi_tenancy): Update role in user tenant association.
- def delete(self, multi_tenancy): Remove a u... | Implement the Python class `TenantUsers` described below.
Class description:
Implement the TenantUsers class.
Method signatures and docstrings:
- def put(self, multi_tenancy): Add a user to a tenant
- def patch(self, multi_tenancy): Update role in user tenant association.
- def delete(self, multi_tenancy): Remove a u... | c0de6442e1d7653fad824d75e571802a74eee605 | <|skeleton|>
class TenantUsers:
def put(self, multi_tenancy):
"""Add a user to a tenant"""
<|body_0|>
def patch(self, multi_tenancy):
"""Update role in user tenant association."""
<|body_1|>
def delete(self, multi_tenancy):
"""Remove a user from a tenant"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TenantUsers:
def put(self, multi_tenancy):
"""Add a user to a tenant"""
request_dict = rest_utils.get_json_and_verify_params({'tenant_name': {'type': str}, 'username': {'type': str}, 'role': {'type': str}})
rest_utils.validate_inputs(request_dict)
role_name = request_dict.get('... | the_stack_v2_python_sparse | rest-service/manager_rest/rest/resources_v3/tenants.py | cloudify-cosmo/cloudify-manager | train | 146 | |
8a3a2ecbfe0cdb6bf92905d76864f31c11d7a830 | [
"if len(nums) == 0:\n return -1\nelif len(nums) == 1:\n if nums[0] == target:\n return 0\n else:\n return -1\nif nums[0] < nums[-1] and (target < nums[0] or target > nums[-1]):\n return -1\nelse:\n index = len(nums) // 2\n ans1 = self.search(nums[:index], target)\n ans2 = self.sea... | <|body_start_0|>
if len(nums) == 0:
return -1
elif len(nums) == 1:
if nums[0] == target:
return 0
else:
return -1
if nums[0] < nums[-1] and (target < nums[0] or target > nums[-1]):
return -1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if... | stack_v2_sparse_classes_36k_train_003723 | 2,123 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search1",
"signature": "def search1(self, nums, target)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search1(self, nums, target): :type nums: List[int] :type target: int :rtype: int
<|skel... | 5b55e35f15c7bf098203a6aabbb7aad6b14579fa | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search1(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
if len(nums) == 0:
return -1
elif len(nums) == 1:
if nums[0] == target:
return 0
else:
return -1
if nums[0] < ... | the_stack_v2_python_sparse | leetcode/33. Search in Rotated Sorted Array.py | queryor/algorithms | train | 0 | |
05b6c57fd058c86d07ec22963ae423e59fd24951 | [
"min, max = params.z_range\nself._absc = np.linspace(min, max, round((max - min) / resolution + 1), dtype=float)\nself._curve_x, self._curve_y = params.sigma_from_z(self._absc)",
"dw = (np.sqrt(data['size_x'].to_numpy()[:, np.newaxis]) - np.sqrt(self._curve_x[np.newaxis, :])) ** 2 + (np.sqrt(data['size_y'].to_num... | <|body_start_0|>
min, max = params.z_range
self._absc = np.linspace(min, max, round((max - min) / resolution + 1), dtype=float)
self._curve_x, self._curve_y = params.sigma_from_z(self._absc)
<|end_body_0|>
<|body_start_1|>
dw = (np.sqrt(data['size_x'].to_numpy()[:, np.newaxis]) - np.sqr... | Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See the `fitz` program in the `sa_util... | Fitter | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fitter:
"""Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See ... | stack_v2_sparse_classes_36k_train_003724 | 13,366 | permissive | [
{
"docstring": "Parameters ---------- params : Parameters Z fit parameters resolution : float, optional Resolution, i. e. smallest z change detectable. Defaults to 1e-3.",
"name": "__init__",
"signature": "def __init__(self, params, resolution=0.001)"
},
{
"docstring": "Fit the z position Takes ... | 2 | null | Implement the Python class `Fitter` described below.
Class description:
Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum... | Implement the Python class `Fitter` described below.
Class description:
Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum... | 2f953e553f32118c3ad1f244481e5a0ac6c533f0 | <|skeleton|>
class Fitter:
"""Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fitter:
"""Class for fitting the z position from the elipticity of PSFs This implements the Zhuang group's z fitting algorithm [*]_. The calibration curves for x and y are calculated from the parameters and the z position is determined by finding the minimum "distance" from the curve. .. [*] See the `fitz` pr... | the_stack_v2_python_sparse | sdt/loc/z_fit.py | schuetzgroup/sdt-python | train | 31 |
e51e7c0cbcc03e4a5f14fafb293ab8d3042eb203 | [
"self.available_options['always'] = True\nsuper().__init__(**kwargs)\nself.claims = claims\nself.exists_arg = ''.join((x for x in exists_arg.lower() if x in 'pqst'))\nself.cacheSources()\nif self.exists_arg:\n pywikibot.info(f\"'exists' argument set to '{self.exists_arg}'\")",
"for claim in self.claims:\n s... | <|body_start_0|>
self.available_options['always'] = True
super().__init__(**kwargs)
self.claims = claims
self.exists_arg = ''.join((x for x in exists_arg.lower() if x in 'pqst'))
self.cacheSources()
if self.exists_arg:
pywikibot.info(f"'exists' argument set to... | A bot to add Wikidata claims. | ClaimRobot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClaimRobot:
"""A bot to add Wikidata claims."""
def __init__(self, claims, exists_arg: str='', **kwargs) -> None:
"""Initializer. :param claims: A list of wikidata claims :type claims: list :param exists_arg: String specifying how to handle duplicate claims"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_003725 | 5,373 | permissive | [
{
"docstring": "Initializer. :param claims: A list of wikidata claims :type claims: list :param exists_arg: String specifying how to handle duplicate claims",
"name": "__init__",
"signature": "def __init__(self, claims, exists_arg: str='', **kwargs) -> None"
},
{
"docstring": "Treat each page. :... | 2 | null | Implement the Python class `ClaimRobot` described below.
Class description:
A bot to add Wikidata claims.
Method signatures and docstrings:
- def __init__(self, claims, exists_arg: str='', **kwargs) -> None: Initializer. :param claims: A list of wikidata claims :type claims: list :param exists_arg: String specifying ... | Implement the Python class `ClaimRobot` described below.
Class description:
A bot to add Wikidata claims.
Method signatures and docstrings:
- def __init__(self, claims, exists_arg: str='', **kwargs) -> None: Initializer. :param claims: A list of wikidata claims :type claims: list :param exists_arg: String specifying ... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class ClaimRobot:
"""A bot to add Wikidata claims."""
def __init__(self, claims, exists_arg: str='', **kwargs) -> None:
"""Initializer. :param claims: A list of wikidata claims :type claims: list :param exists_arg: String specifying how to handle duplicate claims"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClaimRobot:
"""A bot to add Wikidata claims."""
def __init__(self, claims, exists_arg: str='', **kwargs) -> None:
"""Initializer. :param claims: A list of wikidata claims :type claims: list :param exists_arg: String specifying how to handle duplicate claims"""
self.available_options['alwa... | the_stack_v2_python_sparse | scripts/claimit.py | wikimedia/pywikibot | train | 432 |
6bf32976c0f38a0704efe7837473718c24575e54 | [
"dict1 = {k: obj1.__dict__[k] for k in keys}\ndict2 = {k: obj2.__dict__[k] for k in keys}\nreturn dict1 == dict2",
"addressObjs = []\naddressObjs.append(Address(locality=request['permanentAdd']['locality'], city=request['permanentAdd']['city'], state=request['permanentAdd']['state'], country=request['permanentAdd... | <|body_start_0|>
dict1 = {k: obj1.__dict__[k] for k in keys}
dict2 = {k: obj2.__dict__[k] for k in keys}
return dict1 == dict2
<|end_body_0|>
<|body_start_1|>
addressObjs = []
addressObjs.append(Address(locality=request['permanentAdd']['locality'], city=request['permanentAdd']['... | AddressManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddressManager:
def __eq__(self, obj1, obj2, keys):
"""compares two objects on the basis of keys given"""
<|body_0|>
def addAddress(self, request):
"""add addresses in the database"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dict1 = {k: obj1.__d... | stack_v2_sparse_classes_36k_train_003726 | 7,824 | permissive | [
{
"docstring": "compares two objects on the basis of keys given",
"name": "__eq__",
"signature": "def __eq__(self, obj1, obj2, keys)"
},
{
"docstring": "add addresses in the database",
"name": "addAddress",
"signature": "def addAddress(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021191 | Implement the Python class `AddressManager` described below.
Class description:
Implement the AddressManager class.
Method signatures and docstrings:
- def __eq__(self, obj1, obj2, keys): compares two objects on the basis of keys given
- def addAddress(self, request): add addresses in the database | Implement the Python class `AddressManager` described below.
Class description:
Implement the AddressManager class.
Method signatures and docstrings:
- def __eq__(self, obj1, obj2, keys): compares two objects on the basis of keys given
- def addAddress(self, request): add addresses in the database
<|skeleton|>
class... | 9673bf8b6094560f0e5cb60efb536139deaa965e | <|skeleton|>
class AddressManager:
def __eq__(self, obj1, obj2, keys):
"""compares two objects on the basis of keys given"""
<|body_0|>
def addAddress(self, request):
"""add addresses in the database"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddressManager:
def __eq__(self, obj1, obj2, keys):
"""compares two objects on the basis of keys given"""
dict1 = {k: obj1.__dict__[k] for k in keys}
dict2 = {k: obj2.__dict__[k] for k in keys}
return dict1 == dict2
def addAddress(self, request):
"""add addresses i... | the_stack_v2_python_sparse | Profiler/models/Person.py | IEEEDTU/CMS | train | 5 | |
7bec960b0278f2ec0ca8b6e90ffca7a75eb058a6 | [
"self._day = day\nself._month = month\nself._year = year\nself._events = []",
"result = str(self._year) + ',' + self._month + ',' + str(self._day)\nresult += '\\n'\nself._events.sort()\nfor event in self._events:\n result += str(event)\n result += '\\n'\nreturn result",
"for event in self._events:\n if... | <|body_start_0|>
self._day = day
self._month = month
self._year = year
self._events = []
<|end_body_0|>
<|body_start_1|>
result = str(self._year) + ',' + self._month + ',' + str(self._day)
result += '\n'
self._events.sort()
for event in self._events:
... | A calendar day and its events. | Day | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Day:
"""A calendar day and its events."""
def __init__(self, day=1, month='January', year=2016):
"""(Day, int, str, int) -> NoneType Initialize this calendar day. REQ: 0 < day <= 31 REQ: day is an integer"""
<|body_0|>
def __str__(self):
"""(Day) -> str Return a ... | stack_v2_sparse_classes_36k_train_003727 | 3,603 | no_license | [
{
"docstring": "(Day, int, str, int) -> NoneType Initialize this calendar day. REQ: 0 < day <= 31 REQ: day is an integer",
"name": "__init__",
"signature": "def __init__(self, day=1, month='January', year=2016)"
},
{
"docstring": "(Day) -> str Return a string representation of this day.",
"n... | 3 | stack_v2_sparse_classes_30k_train_015869 | Implement the Python class `Day` described below.
Class description:
A calendar day and its events.
Method signatures and docstrings:
- def __init__(self, day=1, month='January', year=2016): (Day, int, str, int) -> NoneType Initialize this calendar day. REQ: 0 < day <= 31 REQ: day is an integer
- def __str__(self): (... | Implement the Python class `Day` described below.
Class description:
A calendar day and its events.
Method signatures and docstrings:
- def __init__(self, day=1, month='January', year=2016): (Day, int, str, int) -> NoneType Initialize this calendar day. REQ: 0 < day <= 31 REQ: day is an integer
- def __str__(self): (... | dffbef98cbf43eccc13fafb40df1aaada50850f4 | <|skeleton|>
class Day:
"""A calendar day and its events."""
def __init__(self, day=1, month='January', year=2016):
"""(Day, int, str, int) -> NoneType Initialize this calendar day. REQ: 0 < day <= 31 REQ: day is an integer"""
<|body_0|>
def __str__(self):
"""(Day) -> str Return a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Day:
"""A calendar day and its events."""
def __init__(self, day=1, month='January', year=2016):
"""(Day, int, str, int) -> NoneType Initialize this calendar day. REQ: 0 < day <= 31 REQ: day is an integer"""
self._day = day
self._month = month
self._year = year
sel... | the_stack_v2_python_sparse | Fall_2016_CSCA08_Intro_to_Computer_Science_I/Week_9_OOP/week9_calendar_complete.py | BoZhaoUT/Teaching | train | 0 |
3c69d82bf70110373a00967ffdbbbe65837f441f | [
"serializer = serializers_anio.CreateAnioSerializer(data=request.data)\ndata = {}\nif serializer.is_valid(raise_exception=True):\n try:\n instance = serializer.create()\n except ValidationError as e:\n return Response(data={'detail': e.message}, status=status.HTTP_400_BAD_REQUEST)\n data = {'... | <|body_start_0|>
serializer = serializers_anio.CreateAnioSerializer(data=request.data)
data = {}
if serializer.is_valid(raise_exception=True):
try:
instance = serializer.create()
except ValidationError as e:
return Response(data={'detail': ... | AnioViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnioViewSet:
def create(self, request):
"""Crear un anio con sus cursos (opcional)"""
<|body_0|>
def update(self, request, pk=None):
"""Editar un anio, sin afectar sus cursos (se editan aparte)"""
<|body_1|>
def destroy(self, request, pk=None):
"... | stack_v2_sparse_classes_36k_train_003728 | 9,416 | no_license | [
{
"docstring": "Crear un anio con sus cursos (opcional)",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Editar un anio, sin afectar sus cursos (se editan aparte)",
"name": "update",
"signature": "def update(self, request, pk=None)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_005547 | Implement the Python class `AnioViewSet` described below.
Class description:
Implement the AnioViewSet class.
Method signatures and docstrings:
- def create(self, request): Crear un anio con sus cursos (opcional)
- def update(self, request, pk=None): Editar un anio, sin afectar sus cursos (se editan aparte)
- def des... | Implement the Python class `AnioViewSet` described below.
Class description:
Implement the AnioViewSet class.
Method signatures and docstrings:
- def create(self, request): Crear un anio con sus cursos (opcional)
- def update(self, request, pk=None): Editar un anio, sin afectar sus cursos (se editan aparte)
- def des... | be80b2d15f84a8eeba898e753efee348de6ce998 | <|skeleton|>
class AnioViewSet:
def create(self, request):
"""Crear un anio con sus cursos (opcional)"""
<|body_0|>
def update(self, request, pk=None):
"""Editar un anio, sin afectar sus cursos (se editan aparte)"""
<|body_1|>
def destroy(self, request, pk=None):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnioViewSet:
def create(self, request):
"""Crear un anio con sus cursos (opcional)"""
serializer = serializers_anio.CreateAnioSerializer(data=request.data)
data = {}
if serializer.is_valid(raise_exception=True):
try:
instance = serializer.create()
... | the_stack_v2_python_sparse | curricula/api/views/anio.py | Clear-Education/ontrack_backend | train | 1 | |
9e4c9d3343448eacac22a93c90341d1b194cd362 | [
"self.min = np.array([np.nan])\nself.value = np.nan\nself.domain = np.array([[0.0, 1.0]])\nself.n = 1\nself.smooth = True\nself.info = [True, False, False]\nself.latex_name = 'Forrester Function'\nself.latex_type = 'Many Local Minima'\nself.latex_cost = '\\\\[ f(x) = (6x - 2)^2 \\\\sin(12x - 4) \\\\]'\nself.latex_d... | <|body_start_0|>
self.min = np.array([np.nan])
self.value = np.nan
self.domain = np.array([[0.0, 1.0]])
self.n = 1
self.smooth = True
self.info = [True, False, False]
self.latex_name = 'Forrester Function'
self.latex_type = 'Many Local Minima'
self... | Forrester Function. | Forrester | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Forrester:
"""Forrester Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.min = np.array([np.nan])
self.value = np.nan
self.do... | stack_v2_sparse_classes_36k_train_003729 | 903 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008517 | Implement the Python class `Forrester` described below.
Class description:
Forrester Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function. | Implement the Python class `Forrester` described below.
Class description:
Forrester Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
<|skeleton|>
class Forrester:
"""Forrester Function."""
def __init__(self):
"""Constructor."""
... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class Forrester:
"""Forrester Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Forrester:
"""Forrester Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([np.nan])
self.value = np.nan
self.domain = np.array([[0.0, 1.0]])
self.n = 1
self.smooth = True
self.info = [True, False, False]
self.latex_name... | the_stack_v2_python_sparse | ctf/functions1d/forrester.py | cntaylor/ctf | train | 1 |
1a2a4fc2807d1d9cbb2cf2b0d4c3eca9732331d0 | [
"self.place_data = json.loads(self.request.body)\nself.place_data['user'] = users.get_current_user()\nself.place_data['email'] = users.get_current_user().email()\nplace_key = placedlit.PlacedLit.create_from_dict(self.place_data)\nself.add_scene_to_user(scene_key=place_key)\nagent = self.request.headers['User-Agent'... | <|body_start_0|>
self.place_data = json.loads(self.request.body)
self.place_data['user'] = users.get_current_user()
self.place_data['email'] = users.get_current_user().email()
place_key = placedlit.PlacedLit.create_from_dict(self.place_data)
self.add_scene_to_user(scene_key=place... | adding a place from user interaction | AddPlacesHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddPlacesHandler:
"""adding a place from user interaction"""
def post(self):
"""add scene from user submission"""
<|body_0|>
def add_scene_to_user(self, scene_key=None):
"""update a users added and vistited scenes"""
<|body_1|>
def send_response(self... | stack_v2_sparse_classes_36k_train_003730 | 3,967 | no_license | [
{
"docstring": "add scene from user submission",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "update a users added and vistited scenes",
"name": "add_scene_to_user",
"signature": "def add_scene_to_user(self, scene_key=None)"
},
{
"docstring": "format user clie... | 3 | stack_v2_sparse_classes_30k_train_002684 | Implement the Python class `AddPlacesHandler` described below.
Class description:
adding a place from user interaction
Method signatures and docstrings:
- def post(self): add scene from user submission
- def add_scene_to_user(self, scene_key=None): update a users added and vistited scenes
- def send_response(self, sc... | Implement the Python class `AddPlacesHandler` described below.
Class description:
adding a place from user interaction
Method signatures and docstrings:
- def post(self): add scene from user submission
- def add_scene_to_user(self, scene_key=None): update a users added and vistited scenes
- def send_response(self, sc... | 5dc6e67ff8d10dfb95a6b0ca46b72cff9ba45d38 | <|skeleton|>
class AddPlacesHandler:
"""adding a place from user interaction"""
def post(self):
"""add scene from user submission"""
<|body_0|>
def add_scene_to_user(self, scene_key=None):
"""update a users added and vistited scenes"""
<|body_1|>
def send_response(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddPlacesHandler:
"""adding a place from user interaction"""
def post(self):
"""add scene from user submission"""
self.place_data = json.loads(self.request.body)
self.place_data['user'] = users.get_current_user()
self.place_data['email'] = users.get_current_user().email()
... | the_stack_v2_python_sparse | handlers/new_scene.py | stevenyoung/placinglit | train | 2 |
ddcb38246886062202b57eb45bb60e8a5de68486 | [
"hash_table = {}\nmax_len = 0\ncur = 0\nfor i, c in enumerate(s):\n if c in hash_table and cur <= hash_table[c]:\n cur = hash_table[c] + 1\n else:\n max_len = max(max_len, i - cur + 1)\n hash_table[c] = i\nreturn max_len",
"L, res, last = (-1, 0, {})\nfor R, char in enumerate(s):\n if ch... | <|body_start_0|>
hash_table = {}
max_len = 0
cur = 0
for i, c in enumerate(s):
if c in hash_table and cur <= hash_table[c]:
cur = hash_table[c] + 1
else:
max_len = max(max_len, i - cur + 1)
hash_table[c] = i
retu... | SolutionF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionF:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hash_table = {}
max_len = 0
... | stack_v2_sparse_classes_36k_train_003731 | 2,850 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring2",
"signature": "def lengthOfLongestSubstring2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002815 | Implement the Python class `SolutionF` described below.
Class description:
Implement the SolutionF class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int | Implement the Python class `SolutionF` described below.
Class description:
Implement the SolutionF class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring2(self, s): :type s: str :rtype: int
<|skeleton|>
class SolutionF:
def lengt... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class SolutionF:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolutionF:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
hash_table = {}
max_len = 0
cur = 0
for i, c in enumerate(s):
if c in hash_table and cur <= hash_table[c]:
cur = hash_table[c] + 1
else:
... | the_stack_v2_python_sparse | SlidingWindow/q003_longest_substring_without_repeating_characters.py | sevenhe716/LeetCode | train | 0 | |
2bc2f91c65f918e0cc9f711baf98910343997146 | [
"if not root:\n return 'None,'\nreturn '{},'.format(root.val) + self.serialize(root.left) + self.serialize(root.right)",
"def build_tree(data):\n if self.count >= len(data) or data[self.count] == 'None':\n self.count += 1\n return None\n node = TreeNode(int(data[self.count]))\n self.coun... | <|body_start_0|>
if not root:
return 'None,'
return '{},'.format(root.val) + self.serialize(root.left) + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
def build_tree(data):
if self.count >= len(data) or data[self.count] == 'None':
self.count ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003732 | 1,226 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 9126c2089e41d4d7fd3a204115eba2b5074076ad | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return 'None,'
return '{},'.format(root.val) + self.serialize(root.left) + self.serialize(root.right)
def deserialize(self, data):
"""Decode... | the_stack_v2_python_sparse | 297_Serialize and Deserialize Binary Tree.py | Shwan-Yu/Data_Structures_and_Algorithms | train | 0 | |
446f93db141f6f425732417fb84e211bbd69465d | [
"super().__init__()\nself.N = N\nself.dm = dm\nself.embedding = tf.keras.layers.Embedding(target_vocab, dm)\nself.positional_encoding = positional_encoding(max_seq_len, dm)\nself.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]\nself.dropout = tf.keras.layers.Dropout(drop_rate)",
"seq_len = tf.... | <|body_start_0|>
super().__init__()
self.N = N
self.dm = dm
self.embedding = tf.keras.layers.Embedding(target_vocab, dm)
self.positional_encoding = positional_encoding(max_seq_len, dm)
self.blocks = [DecoderBlock(dm, h, hidden, drop_rate) for _ in range(N)]
self.d... | class Decoder | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""class Decoder"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected laye... | stack_v2_sparse_classes_36k_train_003733 | 18,002 | no_license | [
{
"docstring": "* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * target_vocab - the size of the target vocabulary * max_seq_len - the maximum sequence length possible * drop_rate - the ... | 2 | stack_v2_sparse_classes_30k_train_016651 | Implement the Python class `Decoder` described below.
Class description:
class Decoder
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): * N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden... | Implement the Python class `Decoder` described below.
Class description:
class Decoder
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1): * N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class Decoder:
"""class Decoder"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected laye... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""class Decoder"""
def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1):
"""* N - the number of blocks in the encoder * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * target_vo... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
b652cd16ecd3e43b2865ffbc2505e7d68a8ca4ae | [
"self.total_count = total_count\nself.step = step\nself.cursor = 0",
"self.cursor += 1\nif self.cursor > 1 and eq(self.cursor % self.step, 0):\n print('%.1f%%' % (100.0 * self.cursor / self.total_count))"
] | <|body_start_0|>
self.total_count = total_count
self.step = step
self.cursor = 0
<|end_body_0|>
<|body_start_1|>
self.cursor += 1
if self.cursor > 1 and eq(self.cursor % self.step, 0):
print('%.1f%%' % (100.0 * self.cursor / self.total_count))
<|end_body_1|>
| ProcessPrint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessPrint:
def __init__(self, total_count, step=50):
""":param total_count: 总量 :param step: 步长 :return:"""
<|body_0|>
def forward(self):
"""前进 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.total_count = total_count
self.st... | stack_v2_sparse_classes_36k_train_003734 | 3,299 | permissive | [
{
"docstring": ":param total_count: 总量 :param step: 步长 :return:",
"name": "__init__",
"signature": "def __init__(self, total_count, step=50)"
},
{
"docstring": "前进 :return:",
"name": "forward",
"signature": "def forward(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012893 | Implement the Python class `ProcessPrint` described below.
Class description:
Implement the ProcessPrint class.
Method signatures and docstrings:
- def __init__(self, total_count, step=50): :param total_count: 总量 :param step: 步长 :return:
- def forward(self): 前进 :return: | Implement the Python class `ProcessPrint` described below.
Class description:
Implement the ProcessPrint class.
Method signatures and docstrings:
- def __init__(self, total_count, step=50): :param total_count: 总量 :param step: 步长 :return:
- def forward(self): 前进 :return:
<|skeleton|>
class ProcessPrint:
def __in... | a7c9567975b5372b2edabddb0fec8d73bc01c3dc | <|skeleton|>
class ProcessPrint:
def __init__(self, total_count, step=50):
""":param total_count: 总量 :param step: 步长 :return:"""
<|body_0|>
def forward(self):
"""前进 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessPrint:
def __init__(self, total_count, step=50):
""":param total_count: 总量 :param step: 步长 :return:"""
self.total_count = total_count
self.step = step
self.cursor = 0
def forward(self):
"""前进 :return:"""
self.cursor += 1
if self.cursor > 1 an... | the_stack_v2_python_sparse | Dispatcher/tools_lib/common_util/archived/utils.py | cash2one/Logistics | train | 0 | |
e7b347ad603ff2baca675f7b5c22c06d00aa1673 | [
"self.repo_path = repo_path\nself.logger = logger\nself.secret = secret",
"assert command and len(command)\ncommand = ['git'] + list(command)\nif self.logger:\n command_str = ' '.join(map(pipes.quote, command))\n if self.secret:\n command_str = command_str.replace(self.secret, 'xxx')\n self.logger... | <|body_start_0|>
self.repo_path = repo_path
self.logger = logger
self.secret = secret
<|end_body_0|>
<|body_start_1|>
assert command and len(command)
command = ['git'] + list(command)
if self.logger:
command_str = ' '.join(map(pipes.quote, command))
... | Helper class for running git commands | GitCommand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitCommand:
"""Helper class for running git commands"""
def __init__(self, repo_path, secret=None):
""":param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' wh... | stack_v2_sparse_classes_36k_train_003735 | 3,785 | no_license | [
{
"docstring": ":param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' when logging.",
"name": "__init__",
"signature": "def __init__(self, repo_path, secret=None)"
},
{
"d... | 3 | null | Implement the Python class `GitCommand` described below.
Class description:
Helper class for running git commands
Method signatures and docstrings:
- def __init__(self, repo_path, secret=None): :param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. ... | Implement the Python class `GitCommand` described below.
Class description:
Helper class for running git commands
Method signatures and docstrings:
- def __init__(self, repo_path, secret=None): :param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. ... | 8ef71a98892473434dbd903647a11b6903b3c92a | <|skeleton|>
class GitCommand:
"""Helper class for running git commands"""
def __init__(self, repo_path, secret=None):
""":param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GitCommand:
"""Helper class for running git commands"""
def __init__(self, repo_path, secret=None):
""":param repo_path: the full path to the git repo. :param logger: if set the command executed will be logged with level info. :param secret: this string will be replaced with 'xxx' when logging.""... | the_stack_v2_python_sparse | vcssync/mozvcssync/gitutil.py | mjzffr/version-control-tools | train | 1 |
3522289e97b2f7d8ff97dd19f855ae501c79922d | [
"if validator is not None and (not isinstance(validator, Evaluator)):\n raise TypeError(f'validator must be a monai.engines.evaluator.Evaluator but is {type(validator).__name__}.')\nself.validator = validator\nself.interval = interval\nself.epoch_level = epoch_level",
"if not isinstance(validator, Evaluator):\... | <|body_start_0|>
if validator is not None and (not isinstance(validator, Evaluator)):
raise TypeError(f'validator must be a monai.engines.evaluator.Evaluator but is {type(validator).__name__}.')
self.validator = validator
self.interval = interval
self.epoch_level = epoch_leve... | Attach validator to the trainer engine in Ignite. It can support to execute validation every N epochs or every N iterations. | ValidationHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidationHandler:
"""Attach validator to the trainer engine in Ignite. It can support to execute validation every N epochs or every N iterations."""
def __init__(self, interval: int, validator: Evaluator | None=None, epoch_level: bool=True) -> None:
"""Args: interval: do validation ... | stack_v2_sparse_classes_36k_train_003736 | 3,269 | permissive | [
{
"docstring": "Args: interval: do validation every N epochs or every N iterations during training. validator: run the validator when trigger validation, suppose to be Evaluator. if None, should call `set_validator()` before training. epoch_level: execute validation every N epochs or N iterations. `True` is epo... | 4 | stack_v2_sparse_classes_30k_train_017663 | Implement the Python class `ValidationHandler` described below.
Class description:
Attach validator to the trainer engine in Ignite. It can support to execute validation every N epochs or every N iterations.
Method signatures and docstrings:
- def __init__(self, interval: int, validator: Evaluator | None=None, epoch_... | Implement the Python class `ValidationHandler` described below.
Class description:
Attach validator to the trainer engine in Ignite. It can support to execute validation every N epochs or every N iterations.
Method signatures and docstrings:
- def __init__(self, interval: int, validator: Evaluator | None=None, epoch_... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class ValidationHandler:
"""Attach validator to the trainer engine in Ignite. It can support to execute validation every N epochs or every N iterations."""
def __init__(self, interval: int, validator: Evaluator | None=None, epoch_level: bool=True) -> None:
"""Args: interval: do validation ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidationHandler:
"""Attach validator to the trainer engine in Ignite. It can support to execute validation every N epochs or every N iterations."""
def __init__(self, interval: int, validator: Evaluator | None=None, epoch_level: bool=True) -> None:
"""Args: interval: do validation every N epoch... | the_stack_v2_python_sparse | monai/handlers/validation_handler.py | Project-MONAI/MONAI | train | 4,805 |
4b2213cfa726901a00f300e46d4d805883f21bdc | [
"self.base_descriptors = sum([list(d) for d in descriptor_list], []) if isinstance(descriptor_list, (list, tuple)) else list(descriptor_list)\nif con_names is not None:\n self.connections = sum(sum([[list(d) for d in self.base_descriptors if d.name == k] for k in con_names], []), [])\nelse:\n self.connections... | <|body_start_0|>
self.base_descriptors = sum([list(d) for d in descriptor_list], []) if isinstance(descriptor_list, (list, tuple)) else list(descriptor_list)
if con_names is not None:
self.connections = sum(sum([[list(d) for d in self.base_descriptors if d.name == k] for k in con_names], [])... | DescriptorConcatenator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DescriptorConcatenator:
def __init__(self, descriptor_list, con_names=None):
"""Parameters ---------- descriptor_list : List<decereb.descriptor.[ClassDerivingFromMetaDescriptor]> con_names : List<str> [TODO: is this still used?]"""
<|body_0|>
def __iter__(self):
"""I... | stack_v2_sparse_classes_36k_train_003737 | 23,780 | no_license | [
{
"docstring": "Parameters ---------- descriptor_list : List<decereb.descriptor.[ClassDerivingFromMetaDescriptor]> con_names : List<str> [TODO: is this still used?]",
"name": "__init__",
"signature": "def __init__(self, descriptor_list, con_names=None)"
},
{
"docstring": "Iteration over the Desc... | 2 | stack_v2_sparse_classes_30k_test_001174 | Implement the Python class `DescriptorConcatenator` described below.
Class description:
Implement the DescriptorConcatenator class.
Method signatures and docstrings:
- def __init__(self, descriptor_list, con_names=None): Parameters ---------- descriptor_list : List<decereb.descriptor.[ClassDerivingFromMetaDescriptor]... | Implement the Python class `DescriptorConcatenator` described below.
Class description:
Implement the DescriptorConcatenator class.
Method signatures and docstrings:
- def __init__(self, descriptor_list, con_names=None): Parameters ---------- descriptor_list : List<decereb.descriptor.[ClassDerivingFromMetaDescriptor]... | 3c8aed76ac4dd5aa38539897a0d93b51801031b1 | <|skeleton|>
class DescriptorConcatenator:
def __init__(self, descriptor_list, con_names=None):
"""Parameters ---------- descriptor_list : List<decereb.descriptor.[ClassDerivingFromMetaDescriptor]> con_names : List<str> [TODO: is this still used?]"""
<|body_0|>
def __iter__(self):
"""I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DescriptorConcatenator:
def __init__(self, descriptor_list, con_names=None):
"""Parameters ---------- descriptor_list : List<decereb.descriptor.[ClassDerivingFromMetaDescriptor]> con_names : List<str> [TODO: is this still used?]"""
self.base_descriptors = sum([list(d) for d in descriptor_list]... | the_stack_v2_python_sparse | descriptor.py | m-guggenmos/decog | train | 1 | |
d76887b7945bfb659eaf5799ec2af6e2d61c0d77 | [
"classes = [super(GeverLayoutPolicy, self).bodyClass(template, view)]\nif is_bumblebee_feature_enabled():\n classes.append('feature-bumblebee')\nif is_meeting_feature_enabled():\n classes.append('feature-word-meeting')\nif ISQLObjectWrapper.providedBy(self.context):\n normalize = getUtility(IIDNormalizer).... | <|body_start_0|>
classes = [super(GeverLayoutPolicy, self).bodyClass(template, view)]
if is_bumblebee_feature_enabled():
classes.append('feature-bumblebee')
if is_meeting_feature_enabled():
classes.append('feature-word-meeting')
if ISQLObjectWrapper.providedBy(sel... | Adds gever specific layout configurations | GeverLayoutPolicy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeverLayoutPolicy:
"""Adds gever specific layout configurations"""
def bodyClass(self, template, view):
"""Extends the default body class with the `feature-bumblebee` class, if the bumblebeefeature is enabled."""
<|body_0|>
def renderBase(self):
"""Fixes the base... | stack_v2_sparse_classes_36k_train_003738 | 1,970 | no_license | [
{
"docstring": "Extends the default body class with the `feature-bumblebee` class, if the bumblebeefeature is enabled.",
"name": "bodyClass",
"signature": "def bodyClass(self, template, view)"
},
{
"docstring": "Fixes the base url in the case of contentish objects. LayoutPolicy incorrectly retur... | 2 | null | Implement the Python class `GeverLayoutPolicy` described below.
Class description:
Adds gever specific layout configurations
Method signatures and docstrings:
- def bodyClass(self, template, view): Extends the default body class with the `feature-bumblebee` class, if the bumblebeefeature is enabled.
- def renderBase(... | Implement the Python class `GeverLayoutPolicy` described below.
Class description:
Adds gever specific layout configurations
Method signatures and docstrings:
- def bodyClass(self, template, view): Extends the default body class with the `feature-bumblebee` class, if the bumblebeefeature is enabled.
- def renderBase(... | a01bec6c00d203c21a1b0449f8d489d0033c02b7 | <|skeleton|>
class GeverLayoutPolicy:
"""Adds gever specific layout configurations"""
def bodyClass(self, template, view):
"""Extends the default body class with the `feature-bumblebee` class, if the bumblebeefeature is enabled."""
<|body_0|>
def renderBase(self):
"""Fixes the base... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeverLayoutPolicy:
"""Adds gever specific layout configurations"""
def bodyClass(self, template, view):
"""Extends the default body class with the `feature-bumblebee` class, if the bumblebeefeature is enabled."""
classes = [super(GeverLayoutPolicy, self).bodyClass(template, view)]
... | the_stack_v2_python_sparse | opengever/base/browser/layout.py | 4teamwork/opengever.core | train | 19 |
684d92dfddc21c01a55c788089e173b79e71fe19 | [
"super(AssignSample, self).setUp()\nschema = [('color1', str), ('predicted', str)]\nself.frame = self.context.frame.import_csv(self.get_file('model_color.csv'), schema=schema)",
"self.frame.assign_sample([0.6, 0.3, 0.1], ['one', 'two', 'three'], 'label_column', 2)\nbaseline = {'one': 0.6, 'two': 0.3, 'three': 0.1... | <|body_start_0|>
super(AssignSample, self).setUp()
schema = [('color1', str), ('predicted', str)]
self.frame = self.context.frame.import_csv(self.get_file('model_color.csv'), schema=schema)
<|end_body_0|>
<|body_start_1|>
self.frame.assign_sample([0.6, 0.3, 0.1], ['one', 'two', 'three']... | AssignSample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AssignSample:
def setUp(self):
"""Build test frame"""
<|body_0|>
def test_label_column(self):
"""Test splitting on the label column"""
<|body_1|>
def test_sample_bin(self):
"""Test splitting on the sample_bin column"""
<|body_2|>
def... | stack_v2_sparse_classes_36k_train_003739 | 3,247 | permissive | [
{
"docstring": "Build test frame",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test splitting on the label column",
"name": "test_label_column",
"signature": "def test_label_column(self)"
},
{
"docstring": "Test splitting on the sample_bin column",
"nam... | 5 | null | Implement the Python class `AssignSample` described below.
Class description:
Implement the AssignSample class.
Method signatures and docstrings:
- def setUp(self): Build test frame
- def test_label_column(self): Test splitting on the label column
- def test_sample_bin(self): Test splitting on the sample_bin column
-... | Implement the Python class `AssignSample` described below.
Class description:
Implement the AssignSample class.
Method signatures and docstrings:
- def setUp(self): Build test frame
- def test_label_column(self): Test splitting on the label column
- def test_sample_bin(self): Test splitting on the sample_bin column
-... | 5548fc925b5c278263cbdebbd9e8c7593320c2f4 | <|skeleton|>
class AssignSample:
def setUp(self):
"""Build test frame"""
<|body_0|>
def test_label_column(self):
"""Test splitting on the label column"""
<|body_1|>
def test_sample_bin(self):
"""Test splitting on the sample_bin column"""
<|body_2|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AssignSample:
def setUp(self):
"""Build test frame"""
super(AssignSample, self).setUp()
schema = [('color1', str), ('predicted', str)]
self.frame = self.context.frame.import_csv(self.get_file('model_color.csv'), schema=schema)
def test_label_column(self):
"""Test s... | the_stack_v2_python_sparse | regression-tests/sparktkregtests/testcases/frames/assign_sample_test.py | trustedanalytics/spark-tk | train | 35 | |
de8eae67e75addc5df5a513a283c116ed9e78e41 | [
"if not isinstance(prior, dict):\n raise TypeError(\"Prior must be dict not '{0}'\".format(type(prior)))\nmean_mean = prior.get('mean_mean', np.zeros(self.num_dim))\nmean_sd = prior.get('mean_sd', np.ones(self.num_dim))\ncov_psi = prior.get('cov_psi', np.eye(self.num_dim))\ncov_nu = prior.get('cov_nu', self.num_... | <|body_start_0|>
if not isinstance(prior, dict):
raise TypeError("Prior must be dict not '{0}'".format(type(prior)))
mean_mean = prior.get('mean_mean', np.zeros(self.num_dim))
mean_sd = prior.get('mean_sd', np.ones(self.num_dim))
cov_psi = prior.get('cov_psi', np.eye(self.num... | Student T Distribution | StudentTComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentTComponent:
"""Student T Distribution"""
def sample_parameters(self, prior={}):
"""Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart c... | stack_v2_sparse_classes_36k_train_003740 | 16,562 | permissive | [
{
"docstring": "Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart cov_nu (double): df parameter for inverse Wishart df_alpha (double): shape for Gamma df_beta (double): ... | 2 | stack_v2_sparse_classes_30k_test_000159 | Implement the Python class `StudentTComponent` described below.
Class description:
Student T Distribution
Method signatures and docstrings:
- def sample_parameters(self, prior={}): Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_ps... | Implement the Python class `StudentTComponent` described below.
Class description:
Student T Distribution
Method signatures and docstrings:
- def sample_parameters(self, prior={}): Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_ps... | 3b2e8c3addeab2343837b9e86e9cb57b00798b9a | <|skeleton|>
class StudentTComponent:
"""Student T Distribution"""
def sample_parameters(self, prior={}):
"""Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StudentTComponent:
"""Student T Distribution"""
def sample_parameters(self, prior={}):
"""Sample parameters Args: prior (dict): (optional) mean_mean (ndarray): mean for mean mean_sd (ndarray): standard deviation for mean cov_psi (ndarray): scale matrix parameter for inverse Wishart cov_nu (double... | the_stack_v2_python_sparse | ep_clustering/data/_mixture_data.py | PeiKaLunCi/EP_Collapsed_Gibbs | train | 0 |
89fbfd9ba53fb920ac320e65d19e19f09400f151 | [
"if not root:\n return None\nres1 = self.lowestCommonAncestor(root.left, p, q)\nres2 = self.lowestCommonAncestor(root.right, p, q)\nif res1 and res2 or (root == p or root == q):\n return root\nelse:\n return res1 or res2",
"stack = [root]\nparent = {root: None}\nwhile p not in parent or q not in parent:\... | <|body_start_0|>
if not root:
return None
res1 = self.lowestCommonAncestor(root.left, p, q)
res2 = self.lowestCommonAncestor(root.right, p, q)
if res1 and res2 or (root == p or root == q):
return root
else:
return res1 or res2
<|end_body_0|>
<... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""DFS Recursive approach: T(n) = O(n) S(n) = O(log(n))"""
<|body_0|>
def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
... | stack_v2_sparse_classes_36k_train_003741 | 2,672 | no_license | [
{
"docstring": "DFS Recursive approach: T(n) = O(n) S(n) = O(log(n))",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode'"
},
{
"docstring": "Using parent pointers: Save parent pointers for each node Save all... | 2 | stack_v2_sparse_classes_30k_train_016909 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': DFS Recursive approach: T(n) = O(n) S(n) = O(log(n))
- def lowestCommonAncestor2(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': DFS Recursive approach: T(n) = O(n) S(n) = O(log(n))
- def lowestCommonAncestor2(sel... | 48f56fcaf9f2a62515079181aee6722a549e4d5f | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""DFS Recursive approach: T(n) = O(n) S(n) = O(log(n))"""
<|body_0|>
def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
"""DFS Recursive approach: T(n) = O(n) S(n) = O(log(n))"""
if not root:
return None
res1 = self.lowestCommonAncestor(root.left, p, q)
res2 = self.lowestCommonAnce... | the_stack_v2_python_sparse | Lowest Common Ancestor of a Binary Tree.py | YashK1299/LeetCode | train | 0 | |
4057a5d8f4fb473914ff1f6f8c7c14c9efb501eb | [
"if data is not None:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) <= 2:\n raise ValueError('data must contain multiple values')\n mean = sum(data) / len(data)\n self.lambtha = 1 / mean\nelse:\n if lambtha <= 0:\n raise ValueError('lamb... | <|body_start_0|>
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('data must contain multiple values')
mean = sum(data) / len(data)
self.lambtha = 1 / mea... | Exponential class | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Exponential class"""
def __init__(self, data=None, lambtha=1.0):
"""Class contructor"""
<|body_0|>
def pdf(self, x):
"""Calculates the value of the PDF for a given time period"""
<|body_1|>
def cdf(self, x):
"""Calculates the ... | stack_v2_sparse_classes_36k_train_003742 | 1,196 | no_license | [
{
"docstring": "Class contructor",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Calculates the value of the PDF for a given time period",
"name": "pdf",
"signature": "def pdf(self, x)"
},
{
"docstring": "Calculates the value of ... | 3 | null | Implement the Python class `Exponential` described below.
Class description:
Exponential class
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Class contructor
- def pdf(self, x): Calculates the value of the PDF for a given time period
- def cdf(self, x): Calculates the value of the CD... | Implement the Python class `Exponential` described below.
Class description:
Exponential class
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Class contructor
- def pdf(self, x): Calculates the value of the PDF for a given time period
- def cdf(self, x): Calculates the value of the CD... | 23162e01761cfa56158a1ebc88ac7709ff1c2af2 | <|skeleton|>
class Exponential:
"""Exponential class"""
def __init__(self, data=None, lambtha=1.0):
"""Class contructor"""
<|body_0|>
def pdf(self, x):
"""Calculates the value of the PDF for a given time period"""
<|body_1|>
def cdf(self, x):
"""Calculates the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exponential:
"""Exponential class"""
def __init__(self, data=None, lambtha=1.0):
"""Class contructor"""
if data is not None:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <= 2:
raise ValueError('d... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | emmanavarro/holbertonschool-machine_learning | train | 0 |
58483fd26ded2eef48506baf01f41c8d30f8086e | [
"if not 0 <= dim_mask <= rbf_hparam['num_feat_per_dim'] // 2:\n raise pyrado.ValueErr(given=dim_mask, ge_constraint='0', le_constraint=f\"{rbf_hparam['num_feat_per_dim'] // 2}\")\nself._feats = RBFFeat(**rbf_hparam)\nsuper().__init__(spec, FeatureStack([self._feats]), init_param_kwargs, use_cuda)\nif not self._n... | <|body_start_0|>
if not 0 <= dim_mask <= rbf_hparam['num_feat_per_dim'] // 2:
raise pyrado.ValueErr(given=dim_mask, ge_constraint='0', le_constraint=f"{rbf_hparam['num_feat_per_dim'] // 2}")
self._feats = RBFFeat(**rbf_hparam)
super().__init__(spec, FeatureStack([self._feats]), init_... | A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we reduce the number of parameters, while... | DualRBFLinearPolicy | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_36k_train_003743 | 25,612 | permissive | [
{
"docstring": "Constructor :param spec: specification of environment :param rbf_hparam: hyper-parameters for the RBF-features, see `RBFFeat` :param dim_mask: number of RBF features to mask out at the beginning and the end of every dimension, pass 1 to remove the first and the last features for the policy, pass... | 2 | stack_v2_sparse_classes_30k_train_012831 | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we redu... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/environment_specific.py | jacarvalho/SimuRLacra | train | 0 |
44c41be0793e1e44975f1ce6da060a775979e655 | [
"self.group = game.all_sprites\npygame.sprite.Sprite.__init__(self)\nself.layer = 0\nself.group.add(self, layer=self.layer)\nself.game = game\nself.timer = 0\nself.frame = 0\nself.images = images\nself.image = self.images[0]\nself.rect = self.image.get_rect()\nself.rect.center = pos\nself.game = game\nself.pos = po... | <|body_start_0|>
self.group = game.all_sprites
pygame.sprite.Sprite.__init__(self)
self.layer = 0
self.group.add(self, layer=self.layer)
self.game = game
self.timer = 0
self.frame = 0
self.images = images
self.image = self.images[0]
self.re... | This class is base class for effects. Animation is played from images list and destroyed itself. | Effect | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Effect:
"""This class is base class for effects. Animation is played from images list and destroyed itself."""
def __init__(self, game, pos, images, delay):
"""__init__ method for Explosion class Args: game (<class 'Integrate.Game'>): Integrate.Game class object. pos (tuple length 2)... | stack_v2_sparse_classes_36k_train_003744 | 1,620 | no_license | [
{
"docstring": "__init__ method for Explosion class Args: game (<class 'Integrate.Game'>): Integrate.Game class object. pos (tuple length 2): position of the player (x,y). images (<list>): image list from sprites. delay (int): delay between animation images",
"name": "__init__",
"signature": "def __init... | 2 | stack_v2_sparse_classes_30k_train_014246 | Implement the Python class `Effect` described below.
Class description:
This class is base class for effects. Animation is played from images list and destroyed itself.
Method signatures and docstrings:
- def __init__(self, game, pos, images, delay): __init__ method for Explosion class Args: game (<class 'Integrate.G... | Implement the Python class `Effect` described below.
Class description:
This class is base class for effects. Animation is played from images list and destroyed itself.
Method signatures and docstrings:
- def __init__(self, game, pos, images, delay): __init__ method for Explosion class Args: game (<class 'Integrate.G... | 74524cd52988c4c3f720150a418ff283a8d05683 | <|skeleton|>
class Effect:
"""This class is base class for effects. Animation is played from images list and destroyed itself."""
def __init__(self, game, pos, images, delay):
"""__init__ method for Explosion class Args: game (<class 'Integrate.Game'>): Integrate.Game class object. pos (tuple length 2)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Effect:
"""This class is base class for effects. Animation is played from images list and destroyed itself."""
def __init__(self, game, pos, images, delay):
"""__init__ method for Explosion class Args: game (<class 'Integrate.Game'>): Integrate.Game class object. pos (tuple length 2): position of... | the_stack_v2_python_sparse | effects/Effect.py | ImpulseLimited/momentus-proto | train | 0 |
accb6513c1a16a4cac4e95db8fa6cfd2b4c37b33 | [
"self._pr_related_columns = PULL_REQUEST_RELATED_COLUMNS\nself._file_related_columns = FILE_RELATED_COLUMNS\nself._file_level_data = pd.DataFrame()\nif not file_level_data.empty:\n self._file_level_data = file_level_data[file_level_data['file name'].notna()]",
"start_date = datetime.fromisoformat(date) - timed... | <|body_start_0|>
self._pr_related_columns = PULL_REQUEST_RELATED_COLUMNS
self._file_related_columns = FILE_RELATED_COLUMNS
self._file_level_data = pd.DataFrame()
if not file_level_data.empty:
self._file_level_data = file_level_data[file_level_data['file name'].notna()]
<|end_... | Class that takes a pandas DataFrame and aggregate the file level signals. This class will aggregate the file level signals transformed from pull request level signals based on date. For a given date and a time range, it will aggregate all the file data within this time range and aggregate them together. Attributes: _pr... | DataAggregator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataAggregator:
"""Class that takes a pandas DataFrame and aggregate the file level signals. This class will aggregate the file level signals transformed from pull request level signals based on date. For a given date and a time range, it will aggregate all the file data within this time range an... | stack_v2_sparse_classes_36k_train_003745 | 7,487 | permissive | [
{
"docstring": "Inits DataAggregator with the CSV file name. Args: file_level_data: The pandas data frame of file level data.",
"name": "__init__",
"signature": "def __init__(self, file_level_data: pd.DataFrame) -> None"
},
{
"docstring": "Aggregates the historical file level signals on input da... | 4 | stack_v2_sparse_classes_30k_train_000801 | Implement the Python class `DataAggregator` described below.
Class description:
Class that takes a pandas DataFrame and aggregate the file level signals. This class will aggregate the file level signals transformed from pull request level signals based on date. For a given date and a time range, it will aggregate all ... | Implement the Python class `DataAggregator` described below.
Class description:
Class that takes a pandas DataFrame and aggregate the file level signals. This class will aggregate the file level signals transformed from pull request level signals based on date. For a given date and a time range, it will aggregate all ... | 686cf49cd57ce61cba3cc11f0574b2a2cec596be | <|skeleton|>
class DataAggregator:
"""Class that takes a pandas DataFrame and aggregate the file level signals. This class will aggregate the file level signals transformed from pull request level signals based on date. For a given date and a time range, it will aggregate all the file data within this time range an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataAggregator:
"""Class that takes a pandas DataFrame and aggregate the file level signals. This class will aggregate the file level signals transformed from pull request level signals based on date. For a given date and a time range, it will aggregate all the file data within this time range and aggregate t... | the_stack_v2_python_sparse | data/file_level_aggregation.py | googleinterns/cl_analysis | train | 5 |
20053f4ccf78d2dc3b2610f623bd107c24a7d816 | [
"from . import primitives\ntransform = np.eye(4)\ntransform[:3, 3] = self.bounds.mean(axis=0)\naabb = primitives.Box(transform=transform, extents=self.extents, mutable=False)\nreturn aabb",
"from . import primitives, bounds\nto_origin, extents = bounds.oriented_bounds(self)\nobb = primitives.Box(transform=np.lina... | <|body_start_0|>
from . import primitives
transform = np.eye(4)
transform[:3, 3] = self.bounds.mean(axis=0)
aabb = primitives.Box(transform=transform, extents=self.extents, mutable=False)
return aabb
<|end_body_0|>
<|body_start_1|>
from . import primitives, bounds
... | The `Geometry3D` object is the parent object of geometry objects which are three dimensional, including Trimesh, PointCloud, and Scene objects. | Geometry3D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Geometry3D:
"""The `Geometry3D` object is the parent object of geometry objects which are three dimensional, including Trimesh, PointCloud, and Scene objects."""
def bounding_box(self):
"""An axis aligned bounding box for the current mesh. Returns ---------- aabb : trimesh.primitives... | stack_v2_sparse_classes_36k_train_003746 | 9,565 | permissive | [
{
"docstring": "An axis aligned bounding box for the current mesh. Returns ---------- aabb : trimesh.primitives.Box Box object with transform and extents defined representing the axis aligned bounding box of the mesh",
"name": "bounding_box",
"signature": "def bounding_box(self)"
},
{
"docstring... | 6 | null | Implement the Python class `Geometry3D` described below.
Class description:
The `Geometry3D` object is the parent object of geometry objects which are three dimensional, including Trimesh, PointCloud, and Scene objects.
Method signatures and docstrings:
- def bounding_box(self): An axis aligned bounding box for the c... | Implement the Python class `Geometry3D` described below.
Class description:
The `Geometry3D` object is the parent object of geometry objects which are three dimensional, including Trimesh, PointCloud, and Scene objects.
Method signatures and docstrings:
- def bounding_box(self): An axis aligned bounding box for the c... | a2f89a6917d69e76914b09c7864acea3a5193f47 | <|skeleton|>
class Geometry3D:
"""The `Geometry3D` object is the parent object of geometry objects which are three dimensional, including Trimesh, PointCloud, and Scene objects."""
def bounding_box(self):
"""An axis aligned bounding box for the current mesh. Returns ---------- aabb : trimesh.primitives... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Geometry3D:
"""The `Geometry3D` object is the parent object of geometry objects which are three dimensional, including Trimesh, PointCloud, and Scene objects."""
def bounding_box(self):
"""An axis aligned bounding box for the current mesh. Returns ---------- aabb : trimesh.primitives.Box Box obje... | the_stack_v2_python_sparse | trimesh/parent.py | mikedh/trimesh | train | 2,512 |
f6a6982890fb6b47bf30de64e1f40f101254656c | [
"if not heights:\n return 0\narea, size = (0, len(heights))\nleft_max = [0 for _ in range(size)]\nright_max = [0 for _ in range(size)]\nleft_max[0], right_max[-1] = (heights[0], heights[-1])\nfor i in range(1, size):\n left_max[i] = max(heights[i], left_max[i - 1])\nfor i in range(size - 2, -1, -1):\n righ... | <|body_start_0|>
if not heights:
return 0
area, size = (0, len(heights))
left_max = [0 for _ in range(size)]
right_max = [0 for _ in range(size)]
left_max[0], right_max[-1] = (heights[0], heights[-1])
for i in range(1, size):
left_max[i] = max(heig... | RainWater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainWater:
def trap_(self, heights: List[int]) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(N) :param heights: :return:"""
<|body_0|>
def trap(self, heights: List[int]) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Compl... | stack_v2_sparse_classes_36k_train_003747 | 2,690 | no_license | [
{
"docstring": "Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(N) :param heights: :return:",
"name": "trap_",
"signature": "def trap_(self, heights: List[int]) -> int"
},
{
"docstring": "Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param heights: :return... | 3 | null | Implement the Python class `RainWater` described below.
Class description:
Implement the RainWater class.
Method signatures and docstrings:
- def trap_(self, heights: List[int]) -> int: Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(N) :param heights: :return:
- def trap(self, heights: List[int]) ->... | Implement the Python class `RainWater` described below.
Class description:
Implement the RainWater class.
Method signatures and docstrings:
- def trap_(self, heights: List[int]) -> int: Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(N) :param heights: :return:
- def trap(self, heights: List[int]) ->... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class RainWater:
def trap_(self, heights: List[int]) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(N) :param heights: :return:"""
<|body_0|>
def trap(self, heights: List[int]) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Compl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RainWater:
def trap_(self, heights: List[int]) -> int:
"""Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(N) :param heights: :return:"""
if not heights:
return 0
area, size = (0, len(heights))
left_max = [0 for _ in range(size)]
right_max = ... | the_stack_v2_python_sparse | goldman_sachs/trapping_rain_water.py | Shiv2157k/leet_code | train | 1 | |
8a65f9de7cee785624030d6760a6faa341ca55ce | [
"super(Message, self).__init__(target_name, converter)\nself.fields = kwargs\nif not self.fields:\n raise ValueError('Message must contain fields')",
"ValidateType(value, dict)\nresult = {}\nfor source_key, field_schema in self.fields.iteritems():\n if source_key not in value:\n continue\n source_... | <|body_start_0|>
super(Message, self).__init__(target_name, converter)
self.fields = kwargs
if not self.fields:
raise ValueError('Message must contain fields')
<|end_body_0|>
<|body_start_1|>
ValidateType(value, dict)
result = {}
for source_key, field_schema ... | A message has a collection of fields which should be converted. Expected input type: Dictionary Output type: Dictionary | Message | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""A message has a collection of fields which should be converted. Expected input type: Dictionary Output type: Dictionary"""
def __init__(self, target_name=None, converter=None, **kwargs):
"""Constructor. Args: target_name: New field name to use when creating an output dict... | stack_v2_sparse_classes_36k_train_003748 | 10,860 | permissive | [
{
"docstring": "Constructor. Args: target_name: New field name to use when creating an output dictionary. If None is specified, then the original name is used. converter: A function which performs a transformation on the value of the field. **kwargs: Kwargs where the keys are names of the fields and values are ... | 2 | null | Implement the Python class `Message` described below.
Class description:
A message has a collection of fields which should be converted. Expected input type: Dictionary Output type: Dictionary
Method signatures and docstrings:
- def __init__(self, target_name=None, converter=None, **kwargs): Constructor. Args: target... | Implement the Python class `Message` described below.
Class description:
A message has a collection of fields which should be converted. Expected input type: Dictionary Output type: Dictionary
Method signatures and docstrings:
- def __init__(self, target_name=None, converter=None, **kwargs): Constructor. Args: target... | c98b58aeb0994e011df960163541e9379ae7ea06 | <|skeleton|>
class Message:
"""A message has a collection of fields which should be converted. Expected input type: Dictionary Output type: Dictionary"""
def __init__(self, target_name=None, converter=None, **kwargs):
"""Constructor. Args: target_name: New field name to use when creating an output dict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Message:
"""A message has a collection of fields which should be converted. Expected input type: Dictionary Output type: Dictionary"""
def __init__(self, target_name=None, converter=None, **kwargs):
"""Constructor. Args: target_name: New field name to use when creating an output dictionary. If No... | the_stack_v2_python_sparse | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/third_party/appengine/admin/tools/conversion/schema.py | KaranToor/MA450 | train | 1 |
e5afab72c410928c2e58b74a29abda331d944473 | [
"self.filepath = filepath\nself.folder, self.filename = os.path.split(filepath)\nself.parsed = None",
"r = csv.reader(open(self.filepath, 'r'))\nlines = [line for line in r]\npath_list = lines[0][1].split('\\\\')\nimage_filename = os.path.splitext(path_list[-1])[0]\nhscale, vscale = (np.ceil(float(l)) for l in li... | <|body_start_0|>
self.filepath = filepath
self.folder, self.filename = os.path.split(filepath)
self.parsed = None
<|end_body_0|>
<|body_start_1|>
r = csv.reader(open(self.filepath, 'r'))
lines = [line for line in r]
path_list = lines[0][1].split('\\')
image_filen... | CPCFileParser | [
"Zlib"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPCFileParser:
def __init__(self, filepath):
"""This class parses a CPCe file (*.cpc) into a more useful and manageable format than the original. All data should be retained, and the output can be saved to file. NB: IT ASSUMES THE CPC FILE REFERS ONLY TO A SINGLE IMAGE. filepath: (str) p... | stack_v2_sparse_classes_36k_train_003749 | 5,789 | permissive | [
{
"docstring": "This class parses a CPCe file (*.cpc) into a more useful and manageable format than the original. All data should be retained, and the output can be saved to file. NB: IT ASSUMES THE CPC FILE REFERS ONLY TO A SINGLE IMAGE. filepath: (str) path to the .cpc file.",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_002025 | Implement the Python class `CPCFileParser` described below.
Class description:
Implement the CPCFileParser class.
Method signatures and docstrings:
- def __init__(self, filepath): This class parses a CPCe file (*.cpc) into a more useful and manageable format than the original. All data should be retained, and the out... | Implement the Python class `CPCFileParser` described below.
Class description:
Implement the CPCFileParser class.
Method signatures and docstrings:
- def __init__(self, filepath): This class parses a CPCe file (*.cpc) into a more useful and manageable format than the original. All data should be retained, and the out... | 2a2ef0046702fab756c384411b9dd5ac970c3904 | <|skeleton|>
class CPCFileParser:
def __init__(self, filepath):
"""This class parses a CPCe file (*.cpc) into a more useful and manageable format than the original. All data should be retained, and the output can be saved to file. NB: IT ASSUMES THE CPC FILE REFERS ONLY TO A SINGLE IMAGE. filepath: (str) p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CPCFileParser:
def __init__(self, filepath):
"""This class parses a CPCe file (*.cpc) into a more useful and manageable format than the original. All data should be retained, and the output can be saved to file. NB: IT ASSUMES THE CPC FILE REFERS ONLY TO A SINGLE IMAGE. filepath: (str) path to the .cp... | the_stack_v2_python_sparse | collection/cpc.py | acfrmarine/squidle | train | 6 | |
01abd400d05e338f57cffa098f004631f5bfd013 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BrowserSiteList()",
"from .browser_shared_cookie import BrowserSharedCookie\nfrom .browser_site import BrowserSite\nfrom .browser_site_list_status import BrowserSiteListStatus\nfrom .entity import Entity\nfrom .identity_set import Iden... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BrowserSiteList()
<|end_body_0|>
<|body_start_1|>
from .browser_shared_cookie import BrowserSharedCookie
from .browser_site import BrowserSite
from .browser_site_list_status impo... | A singleton entity which is used to specify IE mode site list metadata | BrowserSiteList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserSiteList:
"""A singleton entity which is used to specify IE mode site list metadata"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSiteList:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node... | stack_v2_sparse_classes_36k_train_003750 | 5,207 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BrowserSiteList",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | null | Implement the Python class `BrowserSiteList` described below.
Class description:
A singleton entity which is used to specify IE mode site list metadata
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSiteList: Creates a new instance of the approp... | Implement the Python class `BrowserSiteList` described below.
Class description:
A singleton entity which is used to specify IE mode site list metadata
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSiteList: Creates a new instance of the approp... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BrowserSiteList:
"""A singleton entity which is used to specify IE mode site list metadata"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSiteList:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrowserSiteList:
"""A singleton entity which is used to specify IE mode site list metadata"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BrowserSiteList:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse n... | the_stack_v2_python_sparse | msgraph/generated/models/browser_site_list.py | microsoftgraph/msgraph-sdk-python | train | 135 |
bdc091f140eaeb47fb0b6a08dccecc8cf0a27717 | [
"course = Course.objects.create(pk=9001, semester_id=1)\nuser = UserProfile.objects.create(pk=9001)\nuser = UserProfile.objects.create(pk=9002, username='1')\nuser = UserProfile.objects.create(pk=9003, username='2')\nquestionnaire = Questionnaire.objects.create(pk=9001, index=0, is_for_contributors=True)\nContribut... | <|body_start_0|>
course = Course.objects.create(pk=9001, semester_id=1)
user = UserProfile.objects.create(pk=9001)
user = UserProfile.objects.create(pk=9002, username='1')
user = UserProfile.objects.create(pk=9003, username='2')
questionnaire = Questionnaire.objects.create(pk=900... | ContributorFormTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContributorFormTests:
def test_dont_validate_deleted_contributions(self):
"""Tests whether contributions marked for deletion are validated. Regression test for #415 and #244"""
<|body_0|>
def test_take_deleted_contributions_into_account(self):
"""Tests whether contri... | stack_v2_sparse_classes_36k_train_003751 | 38,195 | no_license | [
{
"docstring": "Tests whether contributions marked for deletion are validated. Regression test for #415 and #244",
"name": "test_dont_validate_deleted_contributions",
"signature": "def test_dont_validate_deleted_contributions(self)"
},
{
"docstring": "Tests whether contributions marked for delet... | 2 | stack_v2_sparse_classes_30k_train_011274 | Implement the Python class `ContributorFormTests` described below.
Class description:
Implement the ContributorFormTests class.
Method signatures and docstrings:
- def test_dont_validate_deleted_contributions(self): Tests whether contributions marked for deletion are validated. Regression test for #415 and #244
- def... | Implement the Python class `ContributorFormTests` described below.
Class description:
Implement the ContributorFormTests class.
Method signatures and docstrings:
- def test_dont_validate_deleted_contributions(self): Tests whether contributions marked for deletion are validated. Regression test for #415 and #244
- def... | 323672d06780258b6b3135f7c4f6c61a3ced1bcb | <|skeleton|>
class ContributorFormTests:
def test_dont_validate_deleted_contributions(self):
"""Tests whether contributions marked for deletion are validated. Regression test for #415 and #244"""
<|body_0|>
def test_take_deleted_contributions_into_account(self):
"""Tests whether contri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContributorFormTests:
def test_dont_validate_deleted_contributions(self):
"""Tests whether contributions marked for deletion are validated. Regression test for #415 and #244"""
course = Course.objects.create(pk=9001, semester_id=1)
user = UserProfile.objects.create(pk=9001)
use... | the_stack_v2_python_sparse | evap/staff/tests.py | numberpi/EvaP | train | 1 | |
29a99e89f46b3107c77d6c87ba335e147339d2af | [
"n, end, start, step = (len(nums), 0, 0, 0)\nwhile end < n - 1:\n step += 1\n maxend = end + 1\n for i in range(start, end + 1):\n if i + nums[i] >= n - 1:\n return step\n maxend = max(maxend, i + nums[i])\n start, end = (end + 1, maxend)\nreturn step",
"dp = [i for i in range... | <|body_start_0|>
n, end, start, step = (len(nums), 0, 0, 0)
while end < n - 1:
step += 1
maxend = end + 1
for i in range(start, end + 1):
if i + nums[i] >= n - 1:
return step
maxend = max(maxend, i + nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dp_jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n, end, start, step = (len(nums), 0, 0, 0)
while... | stack_v2_sparse_classes_36k_train_003752 | 964 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "dp_jump",
"signature": "def dp_jump(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int
- def dp_jump(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int
- def dp_jump(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def jump(self, nums):
... | 30bfafb6a7727c9305b22933b63d9d645182c633 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def dp_jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
n, end, start, step = (len(nums), 0, 0, 0)
while end < n - 1:
step += 1
maxend = end + 1
for i in range(start, end + 1):
if i + nums[i] >= n - 1:
... | the_stack_v2_python_sparse | leetcode/Array/jump-game-ii.py | iCodeIN/competitive-programming-5 | train | 0 | |
d4bf45420edd8bda00e72acc9168c4f09b3bd65d | [
"if method == 'POST':\n path = '/api/rest/subscription/%s/@self/@app' % os_user_id\nelif method == 'GET':\n path = '/api/rest/subscription/%s/@self/@app/%s' % (os_user_id, transaction_id)\nreturn path",
"path = self._api_path(method, os_user_id, transaction_id)\nLog.debug('MonthlypaymentGree:_api_request')\... | <|body_start_0|>
if method == 'POST':
path = '/api/rest/subscription/%s/@self/@app' % os_user_id
elif method == 'GET':
path = '/api/rest/subscription/%s/@self/@app/%s' % (os_user_id, transaction_id)
return path
<|end_body_0|>
<|body_start_1|>
path = self._api_pat... | Monthly Payment API Greeクラス Monthly Payment API Gree Class | MonthlypaymentGree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonthlypaymentGree:
"""Monthly Payment API Greeクラス Monthly Payment API Gree Class"""
def _api_path(self, method, os_user_id, transaction_id=None):
"""apiリスエスト用のpath生成 Create paths for api request"""
<|body_0|>
def _api_request(self, method, os_user_id, transaction_id=Non... | stack_v2_sparse_classes_36k_train_003753 | 2,766 | no_license | [
{
"docstring": "apiリスエスト用のpath生成 Create paths for api request",
"name": "_api_path",
"signature": "def _api_path(self, method, os_user_id, transaction_id=None)"
},
{
"docstring": "apiにリスエスト送信 返り値 正常時: リスエストのレスポンス 異常時: None Request to the api. return value Usually: Request response If problems:No... | 3 | stack_v2_sparse_classes_30k_train_011346 | Implement the Python class `MonthlypaymentGree` described below.
Class description:
Monthly Payment API Greeクラス Monthly Payment API Gree Class
Method signatures and docstrings:
- def _api_path(self, method, os_user_id, transaction_id=None): apiリスエスト用のpath生成 Create paths for api request
- def _api_request(self, method... | Implement the Python class `MonthlypaymentGree` described below.
Class description:
Monthly Payment API Greeクラス Monthly Payment API Gree Class
Method signatures and docstrings:
- def _api_path(self, method, os_user_id, transaction_id=None): apiリスエスト用のpath生成 Create paths for api request
- def _api_request(self, method... | eefd311c6f1edad483b89f9a513bcc2f9dfabe14 | <|skeleton|>
class MonthlypaymentGree:
"""Monthly Payment API Greeクラス Monthly Payment API Gree Class"""
def _api_path(self, method, os_user_id, transaction_id=None):
"""apiリスエスト用のpath生成 Create paths for api request"""
<|body_0|>
def _api_request(self, method, os_user_id, transaction_id=Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MonthlypaymentGree:
"""Monthly Payment API Greeクラス Monthly Payment API Gree Class"""
def _api_path(self, method, os_user_id, transaction_id=None):
"""apiリスエスト用のpath生成 Create paths for api request"""
if method == 'POST':
path = '/api/rest/subscription/%s/@self/@app' % os_user_i... | the_stack_v2_python_sparse | anchovy/submodule/gsocial/utils/monthlypayment/gree.py | arpsabbir/anchovy | train | 0 |
fcf48dc02688cb559e4924fd123426eff43e8e45 | [
"logger.info('%s initialization' % obj.name)\nsuper(self.__class__, self).__init__(obj, parent)\nself.local_data['near_robots'] = {}\ntry:\n self._range = self.blender_obj['Range']\nexcept KeyError:\n self._range = 100\nlogger.info('Component initialized')",
"self.local_data['near_robots'] = {}\nparent = se... | <|body_start_0|>
logger.info('%s initialization' % obj.name)
super(self.__class__, self).__init__(obj, parent)
self.local_data['near_robots'] = {}
try:
self._range = self.blender_obj['Range']
except KeyError:
self._range = 100
logger.info('Componen... | Distance sensor to detect nearby robots | ProximitySensorClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProximitySensorClass:
"""Distance sensor to detect nearby robots"""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
def default_action... | stack_v2_sparse_classes_36k_train_003754 | 1,799 | permissive | [
{
"docstring": "Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.",
"name": "__init__",
"signature": "def __init__(self, obj, parent=None)"
},
{
"docstring": "Create a list of robots within a certain radius of the se... | 3 | stack_v2_sparse_classes_30k_train_010784 | Implement the Python class `ProximitySensorClass` described below.
Class description:
Distance sensor to detect nearby robots
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the objec... | Implement the Python class `ProximitySensorClass` described below.
Class description:
Distance sensor to detect nearby robots
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the objec... | 25b8e1532e8fa21793c3b2973fc1fc3ac7a04ebd | <|skeleton|>
class ProximitySensorClass:
"""Distance sensor to detect nearby robots"""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
def default_action... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProximitySensorClass:
"""Distance sensor to detect nearby robots"""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
logger.info('%s initialization' % obj.name)
... | the_stack_v2_python_sparse | src/morse/sensors/proximity.py | peterroelants/morse | train | 1 |
fc19996499b88471d1ac2da206fe9d54c8e44d1a | [
"self.object = None\nif (account := db.Account.get(username=self.cleaned.username)):\n self.object = account\n self.blueprint.objects[account] = self\n return (account,)\nreturn ()",
"username = self.cleaned.username\npassword = self.cleaned.password\nemail = self.cleaned.email\nif isinstance(password, s... | <|body_start_0|>
self.object = None
if (account := db.Account.get(username=self.cleaned.username)):
self.object = account
self.blueprint.objects[account] = self
return (account,)
return ()
<|end_body_0|>
<|body_start_1|>
username = self.cleaned.userna... | Account document to add accounts in blueprints. | AccountDocument | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountDocument:
"""Account document to add accounts in blueprints."""
def register(self):
"""Register the object for the blueprint."""
<|body_0|>
def apply(self):
"""Apply the document, create or update an account."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_003755 | 4,152 | permissive | [
{
"docstring": "Register the object for the blueprint.",
"name": "register",
"signature": "def register(self)"
},
{
"docstring": "Apply the document, create or update an account.",
"name": "apply",
"signature": "def apply(self)"
}
] | 2 | null | Implement the Python class `AccountDocument` described below.
Class description:
Account document to add accounts in blueprints.
Method signatures and docstrings:
- def register(self): Register the object for the blueprint.
- def apply(self): Apply the document, create or update an account. | Implement the Python class `AccountDocument` described below.
Class description:
Account document to add accounts in blueprints.
Method signatures and docstrings:
- def register(self): Register the object for the blueprint.
- def apply(self): Apply the document, create or update an account.
<|skeleton|>
class Accoun... | fb7f98d331e47e2032ee1e51bf3e4b2592807fdf | <|skeleton|>
class AccountDocument:
"""Account document to add accounts in blueprints."""
def register(self):
"""Register the object for the blueprint."""
<|body_0|>
def apply(self):
"""Apply the document, create or update an account."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountDocument:
"""Account document to add accounts in blueprints."""
def register(self):
"""Register the object for the blueprint."""
self.object = None
if (account := db.Account.get(username=self.cleaned.username)):
self.object = account
self.blueprint.o... | the_stack_v2_python_sparse | src/data/blueprints/account.py | vincent-lg/avenew.one | train | 0 |
8368fe730a8fafae6bb5c7cbd05ce808fb43f6e9 | [
"if parent_dir and (not isinstance(parent_dir, S3Path)):\n raise ETLInputError('parent_dir must be S3Path')\nif parent_dir and (not parent_dir.is_directory):\n raise ETLInputError('parent_dir must be a directory')\nself.is_directory = is_directory\nself.key = None\nif uri is not None:\n if key or parent_di... | <|body_start_0|>
if parent_dir and (not isinstance(parent_dir, S3Path)):
raise ETLInputError('parent_dir must be S3Path')
if parent_dir and (not parent_dir.is_directory):
raise ETLInputError('parent_dir must be a directory')
self.is_directory = is_directory
self.k... | S3 Path object that provides basic functions to interact with an S3 path The s3 path ensures that there is a regular way of representing paths in s3, and distinguishing between directories and files. Note: We don't connect with S3 using boto for any checks here. | S3Path | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3Path:
"""S3 Path object that provides basic functions to interact with an S3 path The s3 path ensures that there is a regular way of representing paths in s3, and distinguishing between directories and files. Note: We don't connect with S3 using boto for any checks here."""
def __init__(se... | stack_v2_sparse_classes_36k_train_003756 | 3,980 | permissive | [
{
"docstring": "Constructor for the S3 Path object If key is specified then bucket needs to be specified as well. You can only specify either uri or key & bucket pair Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Args... | 4 | null | Implement the Python class `S3Path` described below.
Class description:
S3 Path object that provides basic functions to interact with an S3 path The s3 path ensures that there is a regular way of representing paths in s3, and distinguishing between directories and files. Note: We don't connect with S3 using boto for a... | Implement the Python class `S3Path` described below.
Class description:
S3 Path object that provides basic functions to interact with an S3 path The s3 path ensures that there is a regular way of representing paths in s3, and distinguishing between directories and files. Note: We don't connect with S3 using boto for a... | 797cb719e6c2abeda0751ada3339c72bfb19c8f2 | <|skeleton|>
class S3Path:
"""S3 Path object that provides basic functions to interact with an S3 path The s3 path ensures that there is a regular way of representing paths in s3, and distinguishing between directories and files. Note: We don't connect with S3 using boto for any checks here."""
def __init__(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3Path:
"""S3 Path object that provides basic functions to interact with an S3 path The s3 path ensures that there is a regular way of representing paths in s3, and distinguishing between directories and files. Note: We don't connect with S3 using boto for any checks here."""
def __init__(self, key=None,... | the_stack_v2_python_sparse | dataduct/s3/s3_path.py | EverFi/dataduct | train | 3 |
7942d5556e07b63ce4e8bf5fc006d31ecfd4ea81 | [
"staff_orser_event_qs = StaffOrderEvent.query(**search_info)\nstaff_orser_event_qs = staff_orser_event_qs.order_by('-create_time')\nreturn Splitor(current_page, staff_orser_event_qs)",
"try:\n return StaffOrderEvent.query(order=order)[0]\nexcept:\n return None",
"try:\n return StaffOrderEvent.search(st... | <|body_start_0|>
staff_orser_event_qs = StaffOrderEvent.query(**search_info)
staff_orser_event_qs = staff_orser_event_qs.order_by('-create_time')
return Splitor(current_page, staff_orser_event_qs)
<|end_body_0|>
<|body_start_1|>
try:
return StaffOrderEvent.query(order=order)... | StaffOrderEventServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaffOrderEventServer:
def search(cls, current_page, **search_info):
"""查询事件列表"""
<|body_0|>
def get_event_byorder(cls, order):
"""通过订单查询事件"""
<|body_1|>
def get_event_bystaff(cls, staff_list):
"""通过员工查询事件"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_003757 | 5,325 | no_license | [
{
"docstring": "查询事件列表",
"name": "search",
"signature": "def search(cls, current_page, **search_info)"
},
{
"docstring": "通过订单查询事件",
"name": "get_event_byorder",
"signature": "def get_event_byorder(cls, order)"
},
{
"docstring": "通过员工查询事件",
"name": "get_event_bystaff",
"s... | 3 | null | Implement the Python class `StaffOrderEventServer` described below.
Class description:
Implement the StaffOrderEventServer class.
Method signatures and docstrings:
- def search(cls, current_page, **search_info): 查询事件列表
- def get_event_byorder(cls, order): 通过订单查询事件
- def get_event_bystaff(cls, staff_list): 通过员工查询事件 | Implement the Python class `StaffOrderEventServer` described below.
Class description:
Implement the StaffOrderEventServer class.
Method signatures and docstrings:
- def search(cls, current_page, **search_info): 查询事件列表
- def get_event_byorder(cls, order): 通过订单查询事件
- def get_event_bystaff(cls, staff_list): 通过员工查询事件
<... | c22e772bc24381f7f57e1d6e41ae0289e7f11e57 | <|skeleton|>
class StaffOrderEventServer:
def search(cls, current_page, **search_info):
"""查询事件列表"""
<|body_0|>
def get_event_byorder(cls, order):
"""通过订单查询事件"""
<|body_1|>
def get_event_bystaff(cls, staff_list):
"""通过员工查询事件"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StaffOrderEventServer:
def search(cls, current_page, **search_info):
"""查询事件列表"""
staff_orser_event_qs = StaffOrderEvent.query(**search_info)
staff_orser_event_qs = staff_orser_event_qs.order_by('-create_time')
return Splitor(current_page, staff_orser_event_qs)
def get_eve... | the_stack_v2_python_sparse | codes/crm-be/tuoen/abs/service/order/manager.py | MaseraTiGo/Maserati_Go | train | 0 | |
f8ee82da5e5e5c8e58fe06ba91e15fddab3a5999 | [
"self.variables = {}\ntry:\n JoinVariablesPass(tree)\n InitialTypeInfoPass(tree, self)\n PropagateTypes(tree, self)\n AssignmentsPass(tree)\n FunctionCallsPass(tree)\n TransformIndexExpressionPass(tree)\n LastCleanupPass(tree)\nexcept MCError as err:\n print('/Error when doing semantic analy... | <|body_start_0|>
self.variables = {}
try:
JoinVariablesPass(tree)
InitialTypeInfoPass(tree, self)
PropagateTypes(tree, self)
AssignmentsPass(tree)
FunctionCallsPass(tree)
TransformIndexExpressionPass(tree)
LastCleanupPas... | A user defined payoff expression, including vars and params | UDMCSemanticAnalyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UDMCSemanticAnalyzer:
"""A user defined payoff expression, including vars and params"""
def __init__(self, tree):
"""Create an instance given text definition"""
<|body_0|>
def add_variable(self, varname, vartype, isparam, isprocess, initinfo, impid):
"""Add a var... | stack_v2_sparse_classes_36k_train_003758 | 15,420 | no_license | [
{
"docstring": "Create an instance given text definition",
"name": "__init__",
"signature": "def __init__(self, tree)"
},
{
"docstring": "Add a variable",
"name": "add_variable",
"signature": "def add_variable(self, varname, vartype, isparam, isprocess, initinfo, impid)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_019684 | Implement the Python class `UDMCSemanticAnalyzer` described below.
Class description:
A user defined payoff expression, including vars and params
Method signatures and docstrings:
- def __init__(self, tree): Create an instance given text definition
- def add_variable(self, varname, vartype, isparam, isprocess, initin... | Implement the Python class `UDMCSemanticAnalyzer` described below.
Class description:
A user defined payoff expression, including vars and params
Method signatures and docstrings:
- def __init__(self, tree): Create an instance given text definition
- def add_variable(self, varname, vartype, isparam, isprocess, initin... | 5e7cc7de3495145501ca53deb9efee2233ab7e1c | <|skeleton|>
class UDMCSemanticAnalyzer:
"""A user defined payoff expression, including vars and params"""
def __init__(self, tree):
"""Create an instance given text definition"""
<|body_0|>
def add_variable(self, varname, vartype, isparam, isprocess, initinfo, impid):
"""Add a var... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UDMCSemanticAnalyzer:
"""A user defined payoff expression, including vars and params"""
def __init__(self, tree):
"""Create an instance given text definition"""
self.variables = {}
try:
JoinVariablesPass(tree)
InitialTypeInfoPass(tree, self)
Pro... | the_stack_v2_python_sparse | Extensions/UDMCMod/FPythonCode/FUDMCSemanticAnalyzer_CPP.py | webclinic017/fa-absa-py3 | train | 0 |
4e8e4f8ac59bf3999019f640c8a0d72c2bc2ca5e | [
"self._obj_holidays = obj_holidays\nself._workdays = workdays\nself._excludes = excludes\nself._days_offset = days_offset\nself._attr_extra_state_attributes = {CONF_WORKDAYS: workdays, CONF_EXCLUDES: excludes, CONF_OFFSET: days_offset}\nself._attr_unique_id = entry_id\nself._attr_device_info = DeviceInfo(entry_type... | <|body_start_0|>
self._obj_holidays = obj_holidays
self._workdays = workdays
self._excludes = excludes
self._days_offset = days_offset
self._attr_extra_state_attributes = {CONF_WORKDAYS: workdays, CONF_EXCLUDES: excludes, CONF_OFFSET: days_offset}
self._attr_unique_id = e... | Implementation of a Workday sensor. | IsWorkdaySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsWorkdaySensor:
"""Implementation of a Workday sensor."""
def __init__(self, obj_holidays: HolidayBase, workdays: list[str], excludes: list[str], days_offset: int, name: str, entry_id: str) -> None:
"""Initialize the Workday sensor."""
<|body_0|>
def is_include(self, da... | stack_v2_sparse_classes_36k_train_003759 | 8,017 | permissive | [
{
"docstring": "Initialize the Workday sensor.",
"name": "__init__",
"signature": "def __init__(self, obj_holidays: HolidayBase, workdays: list[str], excludes: list[str], days_offset: int, name: str, entry_id: str) -> None"
},
{
"docstring": "Check if given day is in the includes list.",
"na... | 4 | null | Implement the Python class `IsWorkdaySensor` described below.
Class description:
Implementation of a Workday sensor.
Method signatures and docstrings:
- def __init__(self, obj_holidays: HolidayBase, workdays: list[str], excludes: list[str], days_offset: int, name: str, entry_id: str) -> None: Initialize the Workday s... | Implement the Python class `IsWorkdaySensor` described below.
Class description:
Implementation of a Workday sensor.
Method signatures and docstrings:
- def __init__(self, obj_holidays: HolidayBase, workdays: list[str], excludes: list[str], days_offset: int, name: str, entry_id: str) -> None: Initialize the Workday s... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class IsWorkdaySensor:
"""Implementation of a Workday sensor."""
def __init__(self, obj_holidays: HolidayBase, workdays: list[str], excludes: list[str], days_offset: int, name: str, entry_id: str) -> None:
"""Initialize the Workday sensor."""
<|body_0|>
def is_include(self, da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsWorkdaySensor:
"""Implementation of a Workday sensor."""
def __init__(self, obj_holidays: HolidayBase, workdays: list[str], excludes: list[str], days_offset: int, name: str, entry_id: str) -> None:
"""Initialize the Workday sensor."""
self._obj_holidays = obj_holidays
self._work... | the_stack_v2_python_sparse | homeassistant/components/workday/binary_sensor.py | home-assistant/core | train | 35,501 |
e569d7770f6d5efbb5c419fc5b8a3dc056908dac | [
"super(Pix2PixModel, self).__init__(opt)\nself.netG = define_G(input_nc=opt.A_nc, output_nc=self.opt.B_nc, ngf=self.opt.ngf, device=self.opt.device, num_downs=opt.n_downG, norm_type=self.opt.norm_type, use_dropout=not self.opt.no_dropout, init_gain=self.opt.init_gain, affine=not self.opt.no_affine)\nif not self.opt... | <|body_start_0|>
super(Pix2PixModel, self).__init__(opt)
self.netG = define_G(input_nc=opt.A_nc, output_nc=self.opt.B_nc, ngf=self.opt.ngf, device=self.opt.device, num_downs=opt.n_downG, norm_type=self.opt.norm_type, use_dropout=not self.opt.no_dropout, init_gain=self.opt.init_gain, affine=not self.opt.... | Pix2PixModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pix2PixModel:
def __init__(self, opt):
"""モデル,ロス,オプティマイザーに関する初期化 Args: opt (Namespace): オプション"""
<|body_0|>
def __call__(self, data_dict):
"""forward してloss を計算. Parameters ---------- data_dict : dict of nn.Tensor 学習データ.キーは "A"(入力), "B"(出力). Returns ------- losses : ... | stack_v2_sparse_classes_36k_train_003760 | 4,641 | no_license | [
{
"docstring": "モデル,ロス,オプティマイザーに関する初期化 Args: opt (Namespace): オプション",
"name": "__init__",
"signature": "def __init__(self, opt)"
},
{
"docstring": "forward してloss を計算. Parameters ---------- data_dict : dict of nn.Tensor 学習データ.キーは \"A\"(入力), \"B\"(出力). Returns ------- losses : 各loss の Loss. Each ... | 2 | stack_v2_sparse_classes_30k_train_011730 | Implement the Python class `Pix2PixModel` described below.
Class description:
Implement the Pix2PixModel class.
Method signatures and docstrings:
- def __init__(self, opt): モデル,ロス,オプティマイザーに関する初期化 Args: opt (Namespace): オプション
- def __call__(self, data_dict): forward してloss を計算. Parameters ---------- data_dict : dict o... | Implement the Python class `Pix2PixModel` described below.
Class description:
Implement the Pix2PixModel class.
Method signatures and docstrings:
- def __init__(self, opt): モデル,ロス,オプティマイザーに関する初期化 Args: opt (Namespace): オプション
- def __call__(self, data_dict): forward してloss を計算. Parameters ---------- data_dict : dict o... | 3e4cfd28bb9ef0fd3bb9ed64c435d183236a0b72 | <|skeleton|>
class Pix2PixModel:
def __init__(self, opt):
"""モデル,ロス,オプティマイザーに関する初期化 Args: opt (Namespace): オプション"""
<|body_0|>
def __call__(self, data_dict):
"""forward してloss を計算. Parameters ---------- data_dict : dict of nn.Tensor 学習データ.キーは "A"(入力), "B"(出力). Returns ------- losses : ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pix2PixModel:
def __init__(self, opt):
"""モデル,ロス,オプティマイザーに関する初期化 Args: opt (Namespace): オプション"""
super(Pix2PixModel, self).__init__(opt)
self.netG = define_G(input_nc=opt.A_nc, output_nc=self.opt.B_nc, ngf=self.opt.ngf, device=self.opt.device, num_downs=opt.n_downG, norm_type=self.opt.... | the_stack_v2_python_sparse | models/pix2pix_model.py | haru-256/pix2pix.pytorch | train | 1 | |
ffd5ee77cb95c1e1abe8e063d13c88bfa785d9db | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthDeviceModelPerformance()",
"from .entity import Entity\nfrom .user_experience_analytics_health_state import UserExperienceAnalyticsHealthState\nfrom .entity import Entity\nfrom .user_experience_analytics... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsAppHealthDeviceModelPerformance()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .user_experience_analytics_health_state import UserExperienceAnal... | The user experience analytics device model performance entity contains device model performance details. | UserExperienceAnalyticsAppHealthDeviceModelPerformance | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsAppHealthDeviceModelPerformance:
"""The user experience analytics device model performance entity contains device model performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDeviceModelPerfo... | stack_v2_sparse_classes_36k_train_003761 | 4,467 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsAppHealthDeviceModelPerformance",
"name": "create_from_discriminator_value",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_018442 | Implement the Python class `UserExperienceAnalyticsAppHealthDeviceModelPerformance` described below.
Class description:
The user experience analytics device model performance entity contains device model performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[... | Implement the Python class `UserExperienceAnalyticsAppHealthDeviceModelPerformance` described below.
Class description:
The user experience analytics device model performance entity contains device model performance details.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsAppHealthDeviceModelPerformance:
"""The user experience analytics device model performance entity contains device model performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDeviceModelPerfo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsAppHealthDeviceModelPerformance:
"""The user experience analytics device model performance entity contains device model performance details."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthDeviceModelPerformance:
... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_app_health_device_model_performance.py | microsoftgraph/msgraph-sdk-python | train | 135 |
139bc12ad36a417dafb096b4d213836cbb068138 | [
"res = ApiFactory.get_order_api().order_list_api(1)\nlogging.info('请求地址:{}'.format(res.url))\nlogging.info('响应数据:{}'.format(res.json()))\nutils.common_assert_code(res)\nassert False not in [i in res.text for i in ['current_page', 'data', 'snap_name']]",
"product_id = 12\ncount = 7\nres = ApiFactory.get_order_api(... | <|body_start_0|>
res = ApiFactory.get_order_api().order_list_api(1)
logging.info('请求地址:{}'.format(res.url))
logging.info('响应数据:{}'.format(res.json()))
utils.common_assert_code(res)
assert False not in [i in res.text for i in ['current_page', 'data', 'snap_name']]
<|end_body_0|>
... | TestOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOrder:
def test_order_list(self):
"""订单列表"""
<|body_0|>
def test_create_order(self):
"""创建订单"""
<|body_1|>
def test_query_order(self):
"""查看订单"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
res = ApiFactory.get_order_api().... | stack_v2_sparse_classes_36k_train_003762 | 1,694 | no_license | [
{
"docstring": "订单列表",
"name": "test_order_list",
"signature": "def test_order_list(self)"
},
{
"docstring": "创建订单",
"name": "test_create_order",
"signature": "def test_create_order(self)"
},
{
"docstring": "查看订单",
"name": "test_query_order",
"signature": "def test_query_... | 3 | stack_v2_sparse_classes_30k_train_000550 | Implement the Python class `TestOrder` described below.
Class description:
Implement the TestOrder class.
Method signatures and docstrings:
- def test_order_list(self): 订单列表
- def test_create_order(self): 创建订单
- def test_query_order(self): 查看订单 | Implement the Python class `TestOrder` described below.
Class description:
Implement the TestOrder class.
Method signatures and docstrings:
- def test_order_list(self): 订单列表
- def test_create_order(self): 创建订单
- def test_query_order(self): 查看订单
<|skeleton|>
class TestOrder:
def test_order_list(self):
""... | 8c0f3b3b499311f2dc0e2e5a1738476e0af77cac | <|skeleton|>
class TestOrder:
def test_order_list(self):
"""订单列表"""
<|body_0|>
def test_create_order(self):
"""创建订单"""
<|body_1|>
def test_query_order(self):
"""查看订单"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestOrder:
def test_order_list(self):
"""订单列表"""
res = ApiFactory.get_order_api().order_list_api(1)
logging.info('请求地址:{}'.format(res.url))
logging.info('响应数据:{}'.format(res.json()))
utils.common_assert_code(res)
assert False not in [i in res.text for i in ['cur... | the_stack_v2_python_sparse | Scripts/testOrder.py | yang9801/ego | train | 1 | |
d67be17c6f8112b45a4c855d2a72f0bc7de8ca1d | [
"super(mod_dump, self).__init__(address=address, **kwds)\nself._basename = cspad_tbx.getOptString(out_basename)\nself._dirname = cspad_tbx.getOptString(out_dirname)\nself._format = cspad_tbx.getOptString(out_format)",
"super(mod_dump, self).event(evt, env)\nif evt.get('skip_event'):\n return\nif self.cspad_img... | <|body_start_0|>
super(mod_dump, self).__init__(address=address, **kwds)
self._basename = cspad_tbx.getOptString(out_basename)
self._dirname = cspad_tbx.getOptString(out_dirname)
self._format = cspad_tbx.getOptString(out_format)
<|end_body_0|>
<|body_start_1|>
super(mod_dump, se... | Class for outputting images to the file system within the pyana analysis framework. XXX This should eventually deprecate the 'write_dict' dispatch from mod_hitfind. | mod_dump | [
"BSD-3-Clause-LBNL",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mod_dump:
"""Class for outputting images to the file system within the pyana analysis framework. XXX This should eventually deprecate the 'write_dict' dispatch from mod_hitfind."""
def __init__(self, address, out_dirname, out_basename, out_format='pickle', **kwds):
"""The mod_dump cl... | stack_v2_sparse_classes_36k_train_003763 | 3,281 | permissive | [
{
"docstring": "The mod_dump class constructor stores the parameters passed from the pyana configuration file in instance variables. @param address Full data source address of the DAQ device @param out_dirname Directory portion of output image pathname @param out_basename Filename prefix of output image pathnam... | 2 | stack_v2_sparse_classes_30k_train_009443 | Implement the Python class `mod_dump` described below.
Class description:
Class for outputting images to the file system within the pyana analysis framework. XXX This should eventually deprecate the 'write_dict' dispatch from mod_hitfind.
Method signatures and docstrings:
- def __init__(self, address, out_dirname, ou... | Implement the Python class `mod_dump` described below.
Class description:
Class for outputting images to the file system within the pyana analysis framework. XXX This should eventually deprecate the 'write_dict' dispatch from mod_hitfind.
Method signatures and docstrings:
- def __init__(self, address, out_dirname, ou... | 77d66c719b5746f37af51ad593e2941ed6fbba17 | <|skeleton|>
class mod_dump:
"""Class for outputting images to the file system within the pyana analysis framework. XXX This should eventually deprecate the 'write_dict' dispatch from mod_hitfind."""
def __init__(self, address, out_dirname, out_basename, out_format='pickle', **kwds):
"""The mod_dump cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mod_dump:
"""Class for outputting images to the file system within the pyana analysis framework. XXX This should eventually deprecate the 'write_dict' dispatch from mod_hitfind."""
def __init__(self, address, out_dirname, out_basename, out_format='pickle', **kwds):
"""The mod_dump class construct... | the_stack_v2_python_sparse | modules/cctbx_project/xfel/cxi/cspad_ana/mod_dump.py | jorgediazjr/dials-dev20191018 | train | 0 |
41fde5b59a7754a12ad5ac91625ca0573e650832 | [
"rotations = {0: 0, 1: 1, 2: 5, 3: None, 4: None, 5: 2, 6: 9, 7: None, 8: 8, 9: 6}\nstr_n = []\nfor s in str(n):\n if rotations[int(s)] is None:\n return None\n else:\n str_n.append(str(rotations[int(s)]))\nreturn int(''.join(str_n))",
"result = 0\nfor n in range(1, N + 1):\n rotate = self.... | <|body_start_0|>
rotations = {0: 0, 1: 1, 2: 5, 3: None, 4: None, 5: 2, 6: 9, 7: None, 8: 8, 9: 6}
str_n = []
for s in str(n):
if rotations[int(s)] is None:
return None
else:
str_n.append(str(rotations[int(s)]))
return int(''.join(s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate_number(self, n):
""":param n: is an integer :return: the number after rotation"""
<|body_0|>
def rotatedDigits(self, N):
""":type N: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rotations = {0: 0, 1: 1, 2: 5, ... | stack_v2_sparse_classes_36k_train_003764 | 1,881 | no_license | [
{
"docstring": ":param n: is an integer :return: the number after rotation",
"name": "rotate_number",
"signature": "def rotate_number(self, n)"
},
{
"docstring": ":type N: int :rtype: int",
"name": "rotatedDigits",
"signature": "def rotatedDigits(self, N)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_number(self, n): :param n: is an integer :return: the number after rotation
- def rotatedDigits(self, N): :type N: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_number(self, n): :param n: is an integer :return: the number after rotation
- def rotatedDigits(self, N): :type N: int :rtype: int
<|skeleton|>
class Solution:
d... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def rotate_number(self, n):
""":param n: is an integer :return: the number after rotation"""
<|body_0|>
def rotatedDigits(self, N):
""":type N: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate_number(self, n):
""":param n: is an integer :return: the number after rotation"""
rotations = {0: 0, 1: 1, 2: 5, 3: None, 4: None, 5: 2, 6: 9, 7: None, 8: 8, 9: 6}
str_n = []
for s in str(n):
if rotations[int(s)] is None:
return ... | the_stack_v2_python_sparse | algo/string/rotated_digits.py | xys234/coding-problems | train | 0 | |
7b0d0bb1372091161ced08173134246cef937a87 | [
"pairs = sorted(pairs, key=lambda x: x[0])\nif not pairs:\n return 0\ndp = [1] * len(pairs)\nfor i in range(len(pairs)):\n for j in range(i):\n if pairs[j][1] < pairs[i][0]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"cur, ans = (float('-inf'), 0)\nfor x, y in sorted(pairs, key=lamb... | <|body_start_0|>
pairs = sorted(pairs, key=lambda x: x[0])
if not pairs:
return 0
dp = [1] * len(pairs)
for i in range(len(pairs)):
for j in range(i):
if pairs[j][1] < pairs[i][0]:
dp[i] = max(dp[i], dp[j] + 1)
return ma... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLongestChain(self, pairs):
"""time O(n^2) space O(n) :type pairs: List[List[int]] :rtype: int"""
<|body_0|>
def findLongestChain_greedy(self, pairs):
"""time O(nlogn), sorting logn, rest linear space O(n), cur & ans O(1), sorting O(n) :param pairs: ... | stack_v2_sparse_classes_36k_train_003765 | 1,087 | no_license | [
{
"docstring": "time O(n^2) space O(n) :type pairs: List[List[int]] :rtype: int",
"name": "findLongestChain",
"signature": "def findLongestChain(self, pairs)"
},
{
"docstring": "time O(nlogn), sorting logn, rest linear space O(n), cur & ans O(1), sorting O(n) :param pairs: :return:",
"name":... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLongestChain(self, pairs): time O(n^2) space O(n) :type pairs: List[List[int]] :rtype: int
- def findLongestChain_greedy(self, pairs): time O(nlogn), sorting logn, rest l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLongestChain(self, pairs): time O(n^2) space O(n) :type pairs: List[List[int]] :rtype: int
- def findLongestChain_greedy(self, pairs): time O(nlogn), sorting logn, rest l... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def findLongestChain(self, pairs):
"""time O(n^2) space O(n) :type pairs: List[List[int]] :rtype: int"""
<|body_0|>
def findLongestChain_greedy(self, pairs):
"""time O(nlogn), sorting logn, rest linear space O(n), cur & ans O(1), sorting O(n) :param pairs: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLongestChain(self, pairs):
"""time O(n^2) space O(n) :type pairs: List[List[int]] :rtype: int"""
pairs = sorted(pairs, key=lambda x: x[0])
if not pairs:
return 0
dp = [1] * len(pairs)
for i in range(len(pairs)):
for j in range(i... | the_stack_v2_python_sparse | LeetCode/DynamicProgramming/646_maximum_length_of_pair_chain.py | XyK0907/for_work | train | 0 | |
4b3bc3a838611b6489e7f8e82271732a3ab55519 | [
"contexts = {}\nfor name in arguments:\n clazz = annotations.get(name)\n if clazz is None:\n raise TypeError('Expected an annotation of class for argument %s' % name)\n if not isclass(clazz):\n raise TypeError('Not a class %s for argument %s' % (clazz, name))\n if not issubclass(clazz, Con... | <|body_start_0|>
contexts = {}
for name in arguments:
clazz = annotations.get(name)
if clazz is None:
raise TypeError('Expected an annotation of class for argument %s' % name)
if not isclass(clazz):
raise TypeError('Not a class %s for a... | A processor that takes as the call a function and uses the annotations on the function arguments to extract the contexts. | Contextual | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Contextual:
"""A processor that takes as the call a function and uses the annotations on the function arguments to extract the contexts."""
def contextsFrom(arguments, annotations):
"""Provides the contexts based on the provided list of arguments and annotations."""
<|body_0|... | stack_v2_sparse_classes_36k_train_003766 | 43,744 | no_license | [
{
"docstring": "Provides the contexts based on the provided list of arguments and annotations.",
"name": "contextsFrom",
"signature": "def contextsFrom(arguments, annotations)"
},
{
"docstring": "Constructs a processor based on a function. @see: Function.__init__ @param function: function|method... | 2 | stack_v2_sparse_classes_30k_train_004093 | Implement the Python class `Contextual` described below.
Class description:
A processor that takes as the call a function and uses the annotations on the function arguments to extract the contexts.
Method signatures and docstrings:
- def contextsFrom(arguments, annotations): Provides the contexts based on the provide... | Implement the Python class `Contextual` described below.
Class description:
A processor that takes as the call a function and uses the annotations on the function arguments to extract the contexts.
Method signatures and docstrings:
- def contextsFrom(arguments, annotations): Provides the contexts based on the provide... | 550aa1d0a58fc30aa9faccbfd24c79a0ceb83352 | <|skeleton|>
class Contextual:
"""A processor that takes as the call a function and uses the annotations on the function arguments to extract the contexts."""
def contextsFrom(arguments, annotations):
"""Provides the contexts based on the provided list of arguments and annotations."""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Contextual:
"""A processor that takes as the call a function and uses the annotations on the function arguments to extract the contexts."""
def contextsFrom(arguments, annotations):
"""Provides the contexts based on the provided list of arguments and annotations."""
contexts = {}
... | the_stack_v2_python_sparse | components/ally-utilities/ally/design/processor.py | galiminus/my_liveblog | train | 0 |
0ead2501442b165a2866880bb24f9ebbe1a15ecf | [
"nn.Module.__init__(self)\nif shared_backbone is not None:\n self.backbone = shared_backbone\n head_cfg.configs.input_size = self.calculate_fc_input_size(head_cfg.configs.state_size)\nelif not backbone_cfg:\n self.backbone = identity\n head_cfg.configs.input_size = head_cfg.configs.state_size[0]\nelse:\... | <|body_start_0|>
nn.Module.__init__(self)
if shared_backbone is not None:
self.backbone = shared_backbone
head_cfg.configs.input_size = self.calculate_fc_input_size(head_cfg.configs.state_size)
elif not backbone_cfg:
self.backbone = identity
head_c... | Class for holding backbone and head networks. | Brain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Brain:
"""Class for holding backbone and head networks."""
def __init__(self, backbone_cfg: ConfigDict, head_cfg: ConfigDict, shared_backbone: nn.Module=None):
"""Initialize."""
<|body_0|>
def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, ...]... | stack_v2_sparse_classes_36k_train_003767 | 7,737 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, backbone_cfg: ConfigDict, head_cfg: ConfigDict, shared_backbone: nn.Module=None)"
},
{
"docstring": "Forward method implementation. Use in get_action method in agent.",
"name": "forward",
"signature": "def... | 4 | null | Implement the Python class `Brain` described below.
Class description:
Class for holding backbone and head networks.
Method signatures and docstrings:
- def __init__(self, backbone_cfg: ConfigDict, head_cfg: ConfigDict, shared_backbone: nn.Module=None): Initialize.
- def forward(self, x: torch.Tensor) -> Union[torch.... | Implement the Python class `Brain` described below.
Class description:
Class for holding backbone and head networks.
Method signatures and docstrings:
- def __init__(self, backbone_cfg: ConfigDict, head_cfg: ConfigDict, shared_backbone: nn.Module=None): Initialize.
- def forward(self, x: torch.Tensor) -> Union[torch.... | fdfac4e7056ee5a9d5b48b7b9653ce844a03ca22 | <|skeleton|>
class Brain:
"""Class for holding backbone and head networks."""
def __init__(self, backbone_cfg: ConfigDict, head_cfg: ConfigDict, shared_backbone: nn.Module=None):
"""Initialize."""
<|body_0|>
def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, ...]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Brain:
"""Class for holding backbone and head networks."""
def __init__(self, backbone_cfg: ConfigDict, head_cfg: ConfigDict, shared_backbone: nn.Module=None):
"""Initialize."""
nn.Module.__init__(self)
if shared_backbone is not None:
self.backbone = shared_backbone
... | the_stack_v2_python_sparse | rl_algorithms/common/networks/brain.py | medipixel/rl_algorithms | train | 525 |
9ba47b375c792fa78e178b8594479003ffefe53b | [
"res = []\ni = 0\nj = 0\nwhile 1:\n if i < m and j < n:\n if nums1[i] < nums2[j]:\n res.append(nums1[i])\n i += 1\n else:\n res.append(nums2[j])\n j += 1\n elif i < m and j >= n:\n res.append(nums1[i])\n i += 1\n elif i >= m and j < n:... | <|body_start_0|>
res = []
i = 0
j = 0
while 1:
if i < m and j < n:
if nums1[i] < nums2[j]:
res.append(nums1[i])
i += 1
else:
res.append(nums2[j])
j += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
"""时间复杂度O(m+n),空间复杂度O(m+n) :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1, m, nums2, n):
"... | stack_v2_sparse_classes_36k_train_003768 | 4,751 | no_license | [
{
"docstring": "时间复杂度O(m+n),空间复杂度O(m+n) :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature": "def merge(self, nums1, m, nums2, n)"
},
{
"docstring": "时间复杂度O(m+nlogm+n),空间复杂度O(m+... | 4 | stack_v2_sparse_classes_30k_test_000679 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): 时间复杂度O(m+n),空间复杂度O(m+n) :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): 时间复杂度O(m+n),空间复杂度O(m+n) :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify n... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
"""时间复杂度O(m+n),空间复杂度O(m+n) :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1, m, nums2, n):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge(self, nums1, m, nums2, n):
"""时间复杂度O(m+n),空间复杂度O(m+n) :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
res = []
i = 0
j = 0
while 1:
if i < m an... | the_stack_v2_python_sparse | leetcode/88.py | yanggelinux/algorithm-data-structure | train | 0 | |
ca84783c9f3d9e280bf45a63ccfd1a4e5bf4a6db | [
"pidb = ParsedItemsDb()\nwith ZipFile(path) as fzip:\n for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()):\n pidb = cls._parse_data(file_from_zip(path, fname).decode('utf-8'), pidb)\nreturn pidb",
"via_target = None\naddress = None\nport = None\njarm = None\nfor line in data.... | <|body_start_0|>
pidb = ParsedItemsDb()
with ZipFile(path) as fzip:
for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()):
pidb = cls._parse_data(file_from_zip(path, fname).decode('utf-8'), pidb)
return pidb
<|end_body_0|>
<|body_start_1|>
... | jarm output parser | ParserModule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParserModule:
"""jarm output parser"""
def parse_path(cls, path):
"""parse data from path"""
<|body_0|>
def _parse_data(data, pidb):
"""parse raw string data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pidb = ParsedItemsDb()
with Zip... | stack_v2_sparse_classes_36k_train_003769 | 1,754 | permissive | [
{
"docstring": "parse data from path",
"name": "parse_path",
"signature": "def parse_path(cls, path)"
},
{
"docstring": "parse raw string data",
"name": "_parse_data",
"signature": "def _parse_data(data, pidb)"
}
] | 2 | null | Implement the Python class `ParserModule` described below.
Class description:
jarm output parser
Method signatures and docstrings:
- def parse_path(cls, path): parse data from path
- def _parse_data(data, pidb): parse raw string data | Implement the Python class `ParserModule` described below.
Class description:
jarm output parser
Method signatures and docstrings:
- def parse_path(cls, path): parse data from path
- def _parse_data(data, pidb): parse raw string data
<|skeleton|>
class ParserModule:
"""jarm output parser"""
def parse_path(c... | d5d8e9cdd6dd058dd91eb119965a3f9f737e5c34 | <|skeleton|>
class ParserModule:
"""jarm output parser"""
def parse_path(cls, path):
"""parse data from path"""
<|body_0|>
def _parse_data(data, pidb):
"""parse raw string data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParserModule:
"""jarm output parser"""
def parse_path(cls, path):
"""parse data from path"""
pidb = ParsedItemsDb()
with ZipFile(path) as fzip:
for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()):
pidb = cls._parse_data(file_f... | the_stack_v2_python_sparse | sner/plugin/jarm/parser.py | bodik/sner4 | train | 13 |
b574c35b5bdd3724bdd91054f3c83f3b485a194b | [
"assert len(scheduler_list) > 0\nfor i in six.moves.range(len(scheduler_list) - 1):\n assert scheduler_list[i][0] < scheduler_list[i + 1][0], 'step of scheduler_list should be incremental.'\nself.scheduler_list = scheduler_list\nself.cur_index = 0\nself.cur_step = 0\nself.cur_value = self.scheduler_list[0][1]\ns... | <|body_start_0|>
assert len(scheduler_list) > 0
for i in six.moves.range(len(scheduler_list) - 1):
assert scheduler_list[i][0] < scheduler_list[i + 1][0], 'step of scheduler_list should be incremental.'
self.scheduler_list = scheduler_list
self.cur_index = 0
self.cur_... | Set hyper parameters by a predefined step-based scheduler. | PiecewiseScheduler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiecewiseScheduler:
"""Set hyper parameters by a predefined step-based scheduler."""
def __init__(self, scheduler_list):
"""Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]"""
<|body_0|>
def step... | stack_v2_sparse_classes_36k_train_003770 | 3,280 | permissive | [
{
"docstring": "Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]",
"name": "__init__",
"signature": "def __init__(self, scheduler_list)"
},
{
"docstring": "Step step_num and fetch value according to following rule: Given... | 2 | null | Implement the Python class `PiecewiseScheduler` described below.
Class description:
Set hyper parameters by a predefined step-based scheduler.
Method signatures and docstrings:
- def __init__(self, scheduler_list): Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.0... | Implement the Python class `PiecewiseScheduler` described below.
Class description:
Set hyper parameters by a predefined step-based scheduler.
Method signatures and docstrings:
- def __init__(self, scheduler_list): Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.0... | 3bb5fe36d245f4d69bae0710dc1dc9d1a172f64d | <|skeleton|>
class PiecewiseScheduler:
"""Set hyper parameters by a predefined step-based scheduler."""
def __init__(self, scheduler_list):
"""Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]"""
<|body_0|>
def step... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PiecewiseScheduler:
"""Set hyper parameters by a predefined step-based scheduler."""
def __init__(self, scheduler_list):
"""Piecewise scheduler of hyper parameter. Args: scheduler_list: list of (step, value) pair. E.g. [(0, 0.001), (10000, 0.0005)]"""
assert len(scheduler_list) > 0
... | the_stack_v2_python_sparse | parl/utils/scheduler.py | PaddlePaddle/PARL | train | 3,818 |
ed2bd943e10a0f65db0af0b164989cc9456ad5ba | [
"exist_serial = PpsnackSerialNums.query.filter_by(serial_num=request.json['serial_num']).first()\nif exist_serial is None:\n return ({'msg': 'Serial number is invalid. Please check again.'}, 404)\nif exist_serial.registered == 1:\n return ({'msg': 'Serial number is already registered. please check again.'}, 4... | <|body_start_0|>
exist_serial = PpsnackSerialNums.query.filter_by(serial_num=request.json['serial_num']).first()
if exist_serial is None:
return ({'msg': 'Serial number is invalid. Please check again.'}, 404)
if exist_serial.registered == 1:
return ({'msg': 'Serial number... | PpsnackApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PpsnackApi:
def post(self, ppcam_id):
"""/ppcam/<int:ppcam_id>/ppsnack Register ppsnack by ppcam :path: ppcam_id: int :body: serial_num: str, feedback: float *** Persist state of ppsnack ***"""
<|body_0|>
def get(self, ppcam_id):
"""Return ppsnack data by ppcam id :p... | stack_v2_sparse_classes_36k_train_003771 | 5,180 | permissive | [
{
"docstring": "/ppcam/<int:ppcam_id>/ppsnack Register ppsnack by ppcam :path: ppcam_id: int :body: serial_num: str, feedback: float *** Persist state of ppsnack ***",
"name": "post",
"signature": "def post(self, ppcam_id)"
},
{
"docstring": "Return ppsnack data by ppcam id :path: ppcam_id: int ... | 3 | stack_v2_sparse_classes_30k_train_011137 | Implement the Python class `PpsnackApi` described below.
Class description:
Implement the PpsnackApi class.
Method signatures and docstrings:
- def post(self, ppcam_id): /ppcam/<int:ppcam_id>/ppsnack Register ppsnack by ppcam :path: ppcam_id: int :body: serial_num: str, feedback: float *** Persist state of ppsnack **... | Implement the Python class `PpsnackApi` described below.
Class description:
Implement the PpsnackApi class.
Method signatures and docstrings:
- def post(self, ppcam_id): /ppcam/<int:ppcam_id>/ppsnack Register ppsnack by ppcam :path: ppcam_id: int :body: serial_num: str, feedback: float *** Persist state of ppsnack **... | 02cea28c6a79f02b1aac05fe733e04a51f84e13a | <|skeleton|>
class PpsnackApi:
def post(self, ppcam_id):
"""/ppcam/<int:ppcam_id>/ppsnack Register ppsnack by ppcam :path: ppcam_id: int :body: serial_num: str, feedback: float *** Persist state of ppsnack ***"""
<|body_0|>
def get(self, ppcam_id):
"""Return ppsnack data by ppcam id :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PpsnackApi:
def post(self, ppcam_id):
"""/ppcam/<int:ppcam_id>/ppsnack Register ppsnack by ppcam :path: ppcam_id: int :body: serial_num: str, feedback: float *** Persist state of ppsnack ***"""
exist_serial = PpsnackSerialNums.query.filter_by(serial_num=request.json['serial_num']).first()
... | the_stack_v2_python_sparse | app/resources/ppsnack.py | badger777/goodpp-ml-backend | train | 0 | |
c11dcf1fd67c8b7a5d1af7a4b1801a7d46b112ad | [
"super().__init__(dist, sources, target, rv_mode=rv_mode)\nq_size = prod(self._shape) + 1\nbound = min([bound, q_size]) if bound is not None else q_size\nself._construct_auxvars([(self._rvs | self._crvs, bound)])\nentropies = [entropy(dist, source + target) for source in sources]\nmutual_informations = [mutual_info... | <|body_start_0|>
super().__init__(dist, sources, target, rv_mode=rv_mode)
q_size = prod(self._shape) + 1
bound = min([bound, q_size]) if bound is not None else q_size
self._construct_auxvars([(self._rvs | self._crvs, bound)])
entropies = [entropy(dist, source + target) for source... | Optimizer for the Griffith & Ho redundancy. | GHOptimizer | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GHOptimizer:
"""Optimizer for the Griffith & Ho redundancy."""
def __init__(self, dist, sources, target, bound=None, rv_mode=None):
"""Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute i_gh of. sources : list, None A list of lists. Each i... | stack_v2_sparse_classes_36k_train_003772 | 5,217 | permissive | [
{
"docstring": "Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute i_gh of. sources : list, None A list of lists. Each inner list specifies the indexes of the random variables used to calculate the intrinsic mutual information. If None, then it is calculated over all... | 3 | null | Implement the Python class `GHOptimizer` described below.
Class description:
Optimizer for the Griffith & Ho redundancy.
Method signatures and docstrings:
- def __init__(self, dist, sources, target, bound=None, rv_mode=None): Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to comp... | Implement the Python class `GHOptimizer` described below.
Class description:
Optimizer for the Griffith & Ho redundancy.
Method signatures and docstrings:
- def __init__(self, dist, sources, target, bound=None, rv_mode=None): Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to comp... | b13c5020a2b8524527a4a0db5a81d8549142228c | <|skeleton|>
class GHOptimizer:
"""Optimizer for the Griffith & Ho redundancy."""
def __init__(self, dist, sources, target, bound=None, rv_mode=None):
"""Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute i_gh of. sources : list, None A list of lists. Each i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GHOptimizer:
"""Optimizer for the Griffith & Ho redundancy."""
def __init__(self, dist, sources, target, bound=None, rv_mode=None):
"""Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to compute i_gh of. sources : list, None A list of lists. Each inner list spe... | the_stack_v2_python_sparse | dit/pid/measures/igh.py | dit/dit | train | 468 |
b9065262c686927b9a018da11360dceffaa92c6c | [
"super(CLIHelper, self).__init__()\nself.mock_responses = mock_responses\nself.preferred_encoding = locale.getpreferredencoding()",
"if self.mock_responses:\n return_values = self.mock_responses.get(command, None)\n if not return_values:\n raise AttributeError('Unrecognized command.')\n return ret... | <|body_start_0|>
super(CLIHelper, self).__init__()
self.mock_responses = mock_responses
self.preferred_encoding = locale.getpreferredencoding()
<|end_body_0|>
<|body_start_1|>
if self.mock_responses:
return_values = self.mock_responses.get(command, None)
if not r... | Command line interface (CLI) helper. Attributes: mock_responses (dict[str, str]): mappings of commands to responses. preferred_encoding (str): preferred encoding of output. | CLIHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLIHelper:
"""Command line interface (CLI) helper. Attributes: mock_responses (dict[str, str]): mappings of commands to responses. preferred_encoding (str): preferred encoding of output."""
def __init__(self, mock_responses=None):
"""Initializes a CLI helper. Args: mock_responses (Op... | stack_v2_sparse_classes_36k_train_003773 | 1,925 | permissive | [
{
"docstring": "Initializes a CLI helper. Args: mock_responses (Optional[dict[str, str]]): mappings of commands to responses, for testing.",
"name": "__init__",
"signature": "def __init__(self, mock_responses=None)"
},
{
"docstring": "Runs a command. Args: command (str): command to run. Returns:... | 2 | stack_v2_sparse_classes_30k_train_009687 | Implement the Python class `CLIHelper` described below.
Class description:
Command line interface (CLI) helper. Attributes: mock_responses (dict[str, str]): mappings of commands to responses. preferred_encoding (str): preferred encoding of output.
Method signatures and docstrings:
- def __init__(self, mock_responses=... | Implement the Python class `CLIHelper` described below.
Class description:
Command line interface (CLI) helper. Attributes: mock_responses (dict[str, str]): mappings of commands to responses. preferred_encoding (str): preferred encoding of output.
Method signatures and docstrings:
- def __init__(self, mock_responses=... | 34709706cc3bee84db45883043b9dfc1811ba65b | <|skeleton|>
class CLIHelper:
"""Command line interface (CLI) helper. Attributes: mock_responses (dict[str, str]): mappings of commands to responses. preferred_encoding (str): preferred encoding of output."""
def __init__(self, mock_responses=None):
"""Initializes a CLI helper. Args: mock_responses (Op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CLIHelper:
"""Command line interface (CLI) helper. Attributes: mock_responses (dict[str, str]): mappings of commands to responses. preferred_encoding (str): preferred encoding of output."""
def __init__(self, mock_responses=None):
"""Initializes a CLI helper. Args: mock_responses (Optional[dict[s... | the_stack_v2_python_sparse | l2tdevtools/review_helpers/cli.py | log2timeline/l2tdevtools | train | 7 |
d3e40139f22daa32029e281bff8d2017593308b9 | [
"if isinstance(xml, (str, bytes)):\n try:\n xml = parse_xml_data(xml)\n except XMLSyntaxError as e:\n raise XmlError(str(e)) from e\nassert isinstance(xml, LxmlElement)\nreturn self._build_from_etree(xml)",
"if isinstance(xml, (str, bytes)):\n try:\n xml = parse_xml_data(xml)\n ex... | <|body_start_0|>
if isinstance(xml, (str, bytes)):
try:
xml = parse_xml_data(xml)
except XMLSyntaxError as e:
raise XmlError(str(e)) from e
assert isinstance(xml, LxmlElement)
return self._build_from_etree(xml)
<|end_body_0|>
<|body_start_... | XmlDictParser | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlDictParser:
def parse(self, xml: str | bytes | LxmlElement) -> XmlDict:
"""Build a generic XML tree from an XML string, bytes or lxml.etree.Element. Note that any text or tail on the root element is discarded."""
<|body_0|>
def parse_interleaved(self, xml: str | bytes | L... | stack_v2_sparse_classes_36k_train_003774 | 4,570 | permissive | [
{
"docstring": "Build a generic XML tree from an XML string, bytes or lxml.etree.Element. Note that any text or tail on the root element is discarded.",
"name": "parse",
"signature": "def parse(self, xml: str | bytes | LxmlElement) -> XmlDict"
},
{
"docstring": "Build a generic XML tree from an ... | 4 | null | Implement the Python class `XmlDictParser` described below.
Class description:
Implement the XmlDictParser class.
Method signatures and docstrings:
- def parse(self, xml: str | bytes | LxmlElement) -> XmlDict: Build a generic XML tree from an XML string, bytes or lxml.etree.Element. Note that any text or tail on the ... | Implement the Python class `XmlDictParser` described below.
Class description:
Implement the XmlDictParser class.
Method signatures and docstrings:
- def parse(self, xml: str | bytes | LxmlElement) -> XmlDict: Build a generic XML tree from an XML string, bytes or lxml.etree.Element. Note that any text or tail on the ... | d66cfd4cc9b7de3b18c3cdf8e31eadec8ebb875b | <|skeleton|>
class XmlDictParser:
def parse(self, xml: str | bytes | LxmlElement) -> XmlDict:
"""Build a generic XML tree from an XML string, bytes or lxml.etree.Element. Note that any text or tail on the root element is discarded."""
<|body_0|>
def parse_interleaved(self, xml: str | bytes | L... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XmlDictParser:
def parse(self, xml: str | bytes | LxmlElement) -> XmlDict:
"""Build a generic XML tree from an XML string, bytes or lxml.etree.Element. Note that any text or tail on the root element is discarded."""
if isinstance(xml, (str, bytes)):
try:
xml = parse... | the_stack_v2_python_sparse | pithy/xml/xmldict.py | gwk/pithy | train | 8 | |
dfb7731c9054940e42053b58d8e62477283bf941 | [
"response = HttpResponse(200, None, json.dumps({'value': [{'name': 'test1', 'folder': {}}, {'name': 'test2'}]}))\ninstance = MockHttpProvider.return_value\ninstance.send.return_value = response\ninstance = MockAuthProvider.return_value\ninstance.authenticate.return_value = 'blah'\ninstance.authenticate_request.retu... | <|body_start_0|>
response = HttpResponse(200, None, json.dumps({'value': [{'name': 'test1', 'folder': {}}, {'name': 'test2'}]}))
instance = MockHttpProvider.return_value
instance.send.return_value = response
instance = MockAuthProvider.return_value
instance.authenticate.return_va... | TestCollections | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCollections:
def test_page_creation(self, MockHttpProvider, MockAuthProvider):
"""Test page creation when there is no nextLink attached to the collection"""
<|body_0|>
def test_paging(self, MockHttpProvider, MockAuthProvider):
"""Test paging of a file in situatio... | stack_v2_sparse_classes_36k_train_003775 | 2,797 | permissive | [
{
"docstring": "Test page creation when there is no nextLink attached to the collection",
"name": "test_page_creation",
"signature": "def test_page_creation(self, MockHttpProvider, MockAuthProvider)"
},
{
"docstring": "Test paging of a file in situations where more than one page is available",
... | 2 | stack_v2_sparse_classes_30k_train_013421 | Implement the Python class `TestCollections` described below.
Class description:
Implement the TestCollections class.
Method signatures and docstrings:
- def test_page_creation(self, MockHttpProvider, MockAuthProvider): Test page creation when there is no nextLink attached to the collection
- def test_paging(self, Mo... | Implement the Python class `TestCollections` described below.
Class description:
Implement the TestCollections class.
Method signatures and docstrings:
- def test_page_creation(self, MockHttpProvider, MockAuthProvider): Test page creation when there is no nextLink attached to the collection
- def test_paging(self, Mo... | a5151a43c44acf61c513efdf286d40234c0795f0 | <|skeleton|>
class TestCollections:
def test_page_creation(self, MockHttpProvider, MockAuthProvider):
"""Test page creation when there is no nextLink attached to the collection"""
<|body_0|>
def test_paging(self, MockHttpProvider, MockAuthProvider):
"""Test paging of a file in situatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCollections:
def test_page_creation(self, MockHttpProvider, MockAuthProvider):
"""Test page creation when there is no nextLink attached to the collection"""
response = HttpResponse(200, None, json.dumps({'value': [{'name': 'test1', 'folder': {}}, {'name': 'test2'}]}))
instance = Mo... | the_stack_v2_python_sparse | testonedrivesdk/test_collections.py | AtakamaLLC/onedrive-sdk-python | train | 20 | |
6bfe2abecf0cef8f536a6b41891993bfbf63d71b | [
"user = self.ss.get_user()\ncards = self.cs.list(user)\nreturn cards",
"v = Validator(card_schema)\nargs = v.validated(request.get_json())\nif args is None:\n return ApiResponse(status=4001, errors=v.errors)\nforeign = args.get(u'foreign')\nnative = args.get(u'native')\ngroup_id = args.get(u'group_id')\ntransc... | <|body_start_0|>
user = self.ss.get_user()
cards = self.cs.list(user)
return cards
<|end_body_0|>
<|body_start_1|>
v = Validator(card_schema)
args = v.validated(request.get_json())
if args is None:
return ApiResponse(status=4001, errors=v.errors)
fore... | CardsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CardsAPI:
def get(self):
"""Get all user's cards :return:"""
<|body_0|>
def post(self):
"""Creates new card and adds it to group. :return: Card"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = self.ss.get_user()
cards = self.cs.list(us... | stack_v2_sparse_classes_36k_train_003776 | 4,506 | permissive | [
{
"docstring": "Get all user's cards :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates new card and adds it to group. :return: Card",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `CardsAPI` described below.
Class description:
Implement the CardsAPI class.
Method signatures and docstrings:
- def get(self): Get all user's cards :return:
- def post(self): Creates new card and adds it to group. :return: Card | Implement the Python class `CardsAPI` described below.
Class description:
Implement the CardsAPI class.
Method signatures and docstrings:
- def get(self): Get all user's cards :return:
- def post(self): Creates new card and adds it to group. :return: Card
<|skeleton|>
class CardsAPI:
def get(self):
"""G... | 9a336d1e467d08c6b3875bd8b83dea0dc3b9236d | <|skeleton|>
class CardsAPI:
def get(self):
"""Get all user's cards :return:"""
<|body_0|>
def post(self):
"""Creates new card and adds it to group. :return: Card"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CardsAPI:
def get(self):
"""Get all user's cards :return:"""
user = self.ss.get_user()
cards = self.cs.list(user)
return cards
def post(self):
"""Creates new card and adds it to group. :return: Card"""
v = Validator(card_schema)
args = v.validated(r... | the_stack_v2_python_sparse | we-web/api/resources/cards/cards.py | avatar29A/wordeater-web | train | 0 | |
3bae9edb576e50b6e1bcc0c8d37e47b715e60fb4 | [
"self.extractor = None\nself.stain_matrix_target = None\nself.target_concentrations = None\nself.maxC_target = None\nself.stain_matrix_target_RGB = None",
"od = rgb2od(img).reshape((-1, 3))\nx, _, _, _ = np.linalg.lstsq(stain_matrix.T, od.T, rcond=-1)\nreturn x.T",
"self.stain_matrix_target = self.extractor.get... | <|body_start_0|>
self.extractor = None
self.stain_matrix_target = None
self.target_concentrations = None
self.maxC_target = None
self.stain_matrix_target_RGB = None
<|end_body_0|>
<|body_start_1|>
od = rgb2od(img).reshape((-1, 3))
x, _, _, _ = np.linalg.lstsq(sta... | Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.ndarray`): Stain matrix of target. target_conc... | StainNormalizer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StainNormalizer:
"""Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.nda... | stack_v2_sparse_classes_36k_train_003777 | 13,553 | permissive | [
{
"docstring": "Initialize :class:`StainNormalizer`.",
"name": "__init__",
"signature": "def __init__(self: StainNormalizer) -> None"
},
{
"docstring": "Estimate concentration matrix given an image and stain matrix. Args: img (:class:`numpy.ndarray`): Input image. stain_matrix (:class:`numpy.nda... | 4 | stack_v2_sparse_classes_30k_train_004214 | Implement the Python class `StainNormalizer` described below.
Class description:
Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor.... | Implement the Python class `StainNormalizer` described below.
Class description:
Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor.... | f26387f46f675a7b9a8a48c95dad26e819229f2f | <|skeleton|>
class StainNormalizer:
"""Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.nda... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StainNormalizer:
"""Stain normalization base class. This class contains code inspired by StainTools [https://github.com/Peter554/StainTools] written by Peter Byfield. Attributes: extractor (CustomExtractor, RuifrokExtractor): Method specific stain extractor. stain_matrix_target (:class:`numpy.ndarray`): Stain... | the_stack_v2_python_sparse | tiatoolbox/tools/stainnorm.py | TissueImageAnalytics/tiatoolbox | train | 222 |
8833d88228d4cd13b8f1c1357938aaa7dc715d21 | [
"serializer_class = WellListSerializer\nif self.request.user and self.request.user.is_authenticated and self.request.user.groups.filter(name=WELLS_VIEWER_ROLE).exists():\n serializer_class = WellListAdminSerializer\nreturn serializer_class",
"if self.request.user.groups.filter(name=WELLS_EDIT_ROLE).exists():\n... | <|body_start_0|>
serializer_class = WellListSerializer
if self.request.user and self.request.user.is_authenticated and self.request.user.groups.filter(name=WELLS_VIEWER_ROLE).exists():
serializer_class = WellListAdminSerializer
return serializer_class
<|end_body_0|>
<|body_start_1|>... | List and create wells get: returns a list of wells | WellListAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WellListAPIView:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
<|body_0|>
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissio... | stack_v2_sparse_classes_36k_train_003778 | 24,123 | permissive | [
{
"docstring": "Returns a different serializer class for admin users.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Excludes Unpublished wells for users without edit permissions",
"name": "get_queryset",
"signature": "def get_queryset(... | 2 | null | Implement the Python class `WellListAPIView` described below.
Class description:
List and create wells get: returns a list of wells
Method signatures and docstrings:
- def get_serializer_class(self): Returns a different serializer class for admin users.
- def get_queryset(self): Excludes Unpublished wells for users w... | Implement the Python class `WellListAPIView` described below.
Class description:
List and create wells get: returns a list of wells
Method signatures and docstrings:
- def get_serializer_class(self): Returns a different serializer class for admin users.
- def get_queryset(self): Excludes Unpublished wells for users w... | 88e801bf58d281aa6b7bf7092a83c1f6e12d5b83 | <|skeleton|>
class WellListAPIView:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
<|body_0|>
def get_queryset(self):
"""Excludes Unpublished wells for users without edit permissio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WellListAPIView:
"""List and create wells get: returns a list of wells"""
def get_serializer_class(self):
"""Returns a different serializer class for admin users."""
serializer_class = WellListSerializer
if self.request.user and self.request.user.is_authenticated and self.request.... | the_stack_v2_python_sparse | app/backend/wells/views.py | anissa-agahchen/gwells | train | 1 |
1da156c7473e8185e08199fe843c908cdcc3459a | [
"queue = deque()\nqueue.append(root)\nseq = ''\nwhile queue:\n for _ in range(len(queue)):\n node = queue.popleft()\n if not node:\n seq += ',#'\n elif not seq:\n seq += f'{node.val}'\n else:\n seq += f',{node.val}'\n if node:\n queue... | <|body_start_0|>
queue = deque()
queue.append(root)
seq = ''
while queue:
for _ in range(len(queue)):
node = queue.popleft()
if not node:
seq += ',#'
elif not seq:
seq += f'{node.val}'
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_003779 | 3,302 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_013831 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 04c2b38fb387c0b25cba01773d3b126cc916eb03 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
queue = deque()
queue.append(root)
seq = ''
while queue:
for _ in range(len(queue)):
node = queue.popleft()
if not nod... | the_stack_v2_python_sparse | BinaryTree/297.二叉树的序列化与反序列化.py | snow-tyan/LeetCode | train | 0 | |
e5b35620670ff5b339947fd859034c8133b85b47 | [
"self.attrs = {}\nself.kwargs = kwargs\nself.inputs = []\nself.form = form\nself.main_field = main_field\nself.appended_fields = appended_fields\nself.legend_text = legend_text\nself.help_text = help_text\nself.build_inline_layout()",
"if self.main_field:\n self.layout = cfl.Layout(*list(self.form.fields.keys(... | <|body_start_0|>
self.attrs = {}
self.kwargs = kwargs
self.inputs = []
self.form = form
self.main_field = main_field
self.appended_fields = appended_fields
self.legend_text = legend_text
self.help_text = help_text
self.build_inline_layout()
<|end_b... | Helper class for creating an inline filtering form with a primary field. | InlineFilterFormHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InlineFilterFormHelper:
"""Helper class for creating an inline filtering form with a primary field."""
def __init__(self, form, main_field: str, appended_fields: list[str], legend_text: str | None=None, help_text: str | None=None, **kwargs):
"""Inline form field helper, with primary ... | stack_v2_sparse_classes_36k_train_003780 | 15,821 | permissive | [
{
"docstring": "Inline form field helper, with primary search and appended fields. This form will have a single search bar with a primary search, inline appended fields, and inline cancel/search buttons. Args: form: form main_field: A text input field appended_fields: 1 or more checkbox or select fields (to rig... | 3 | null | Implement the Python class `InlineFilterFormHelper` described below.
Class description:
Helper class for creating an inline filtering form with a primary field.
Method signatures and docstrings:
- def __init__(self, form, main_field: str, appended_fields: list[str], legend_text: str | None=None, help_text: str | None... | Implement the Python class `InlineFilterFormHelper` described below.
Class description:
Helper class for creating an inline filtering form with a primary field.
Method signatures and docstrings:
- def __init__(self, form, main_field: str, appended_fields: list[str], legend_text: str | None=None, help_text: str | None... | 51177c6fb9354cd028f7099fc10d83b1051fd50d | <|skeleton|>
class InlineFilterFormHelper:
"""Helper class for creating an inline filtering form with a primary field."""
def __init__(self, form, main_field: str, appended_fields: list[str], legend_text: str | None=None, help_text: str | None=None, **kwargs):
"""Inline form field helper, with primary ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InlineFilterFormHelper:
"""Helper class for creating an inline filtering form with a primary field."""
def __init__(self, form, main_field: str, appended_fields: list[str], legend_text: str | None=None, help_text: str | None=None, **kwargs):
"""Inline form field helper, with primary search and ap... | the_stack_v2_python_sparse | hawc/apps/common/forms.py | shapiromatron/hawc | train | 25 |
9a98d12604a05e250f9d36eee9d7c262b6f3d96d | [
"self.path = path\nself.name = name\nself.category = category\nself.query = query\nself.outputGeomTypes = output_geometry_types\nself.whiteListValues = white_list_values\nself.iniFile = self.category + '-' + self.name + '.ini'\nself.queryFile = self.category + '-' + self.name + '.xml'\nself.config = ConfigParser.Co... | <|body_start_0|>
self.path = path
self.name = name
self.category = category
self.query = query
self.outputGeomTypes = output_geometry_types
self.whiteListValues = white_list_values
self.iniFile = self.category + '-' + self.name + '.ini'
self.queryFile = se... | Write a query and metadata into files | FileQueryWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileQueryWriter:
"""Write a query and metadata into files"""
def __init__(self, path, name, category, query, white_list_values, output_geometry_types):
"""Constructor @param path:Folder where to save the query @type path:str @param name:Query's name @type name:str @param category:Que... | stack_v2_sparse_classes_36k_train_003781 | 4,125 | no_license | [
{
"docstring": "Constructor @param path:Folder where to save the query @type path:str @param name:Query's name @type name:str @param category:Query's category @type category:str @param query:query @type query:str @param white_list_values:doc of layers with columns @type white_list_values:dic @param output_geome... | 2 | stack_v2_sparse_classes_30k_train_009263 | Implement the Python class `FileQueryWriter` described below.
Class description:
Write a query and metadata into files
Method signatures and docstrings:
- def __init__(self, path, name, category, query, white_list_values, output_geometry_types): Constructor @param path:Folder where to save the query @type path:str @p... | Implement the Python class `FileQueryWriter` described below.
Class description:
Write a query and metadata into files
Method signatures and docstrings:
- def __init__(self, path, name, category, query, white_list_values, output_geometry_types): Constructor @param path:Folder where to save the query @type path:str @p... | 9d7da29107070e9bd20680d1d193046ea7bdb790 | <|skeleton|>
class FileQueryWriter:
"""Write a query and metadata into files"""
def __init__(self, path, name, category, query, white_list_values, output_geometry_types):
"""Constructor @param path:Folder where to save the query @type path:str @param name:Query's name @type name:str @param category:Que... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileQueryWriter:
"""Write a query and metadata into files"""
def __init__(self, path, name, category, query, white_list_values, output_geometry_types):
"""Constructor @param path:Folder where to save the query @type path:str @param name:Query's name @type name:str @param category:Query's category... | the_stack_v2_python_sparse | core/file_query_writer.py | YassineGIS/OSMData | train | 0 |
4fd5b3dd8426deaa626db5224b69d9e336256732 | [
"pub = self.publication\nmodel_mod = importlib.import_module(pub.model_module)\nmodel_cls = getattr(model_mod, pub.model_class)\ntmpl_mod = importlib.import_module(pub.template_module)\ntmpl_cls = getattr(tmpl_mod, pub.template_class)\nqs = self.exec_query(model_cls).aggregate(ids=ArrayAgg('id'))\nself.queryset = q... | <|body_start_0|>
pub = self.publication
model_mod = importlib.import_module(pub.model_module)
model_cls = getattr(model_mod, pub.model_class)
tmpl_mod = importlib.import_module(pub.template_module)
tmpl_cls = getattr(tmpl_mod, pub.template_class)
qs = self.exec_query(mode... | A subscription is an object representing the relation between a client and a publication. It also stores the _id of the component that subscribes to a given publication, and the queryset computed from that publication query. This queryset is computed per-subscription to permit user specific sets After being instanciate... | Subscriptions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subscriptions:
"""A subscription is an object representing the relation between a client and a publication. It also stores the _id of the component that subscribes to a given publication, and the queryset computed from that publication query. This queryset is computed per-subscription to permit u... | stack_v2_sparse_classes_36k_train_003782 | 5,014 | no_license | [
{
"docstring": "This method is used to populate the component which made the current subsription with its content, and to compute the queryset for the first time. This part is subject to near changes when SSR will be implemented",
"name": "init",
"signature": "def init(self)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_001827 | Implement the Python class `Subscriptions` described below.
Class description:
A subscription is an object representing the relation between a client and a publication. It also stores the _id of the component that subscribes to a given publication, and the queryset computed from that publication query. This queryset i... | Implement the Python class `Subscriptions` described below.
Class description:
A subscription is an object representing the relation between a client and a publication. It also stores the _id of the component that subscribes to a given publication, and the queryset computed from that publication query. This queryset i... | 942c1198d4538990b7905e7f7a054425f61a06e9 | <|skeleton|>
class Subscriptions:
"""A subscription is an object representing the relation between a client and a publication. It also stores the _id of the component that subscribes to a given publication, and the queryset computed from that publication query. This queryset is computed per-subscription to permit u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subscriptions:
"""A subscription is an object representing the relation between a client and a publication. It also stores the _id of the component that subscribes to a given publication, and the queryset computed from that publication query. This queryset is computed per-subscription to permit user specific ... | the_stack_v2_python_sparse | ryzom/models.py | thommignot/Ryzom | train | 0 |
5177544b0d090e1ac89168a9bb95dbdd270f2136 | [
"freq = Counter(nums)\nfor num, count in freq.items():\n if count == 1:\n return num",
"visited = set()\nresult = set()\nfor i in nums:\n if i in visited:\n if i in result:\n result.remove(i)\n else:\n visited.add(i)\n result.add(i)\nreturn result.pop()"
] | <|body_start_0|>
freq = Counter(nums)
for num, count in freq.items():
if count == 1:
return num
<|end_body_0|>
<|body_start_1|>
visited = set()
result = set()
for i in nums:
if i in visited:
if i in result:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""使用Counter计数"""
<|body_0|>
def singleNumber2(self, nums: List[int]) -> int:
"""使用两个set分别记录:已经访问过的,和可能是单个数字的。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
freq = Counter(nums)
for... | stack_v2_sparse_classes_36k_train_003783 | 1,205 | no_license | [
{
"docstring": "使用Counter计数",
"name": "singleNumber",
"signature": "def singleNumber(self, nums: List[int]) -> int"
},
{
"docstring": "使用两个set分别记录:已经访问过的,和可能是单个数字的。",
"name": "singleNumber2",
"signature": "def singleNumber2(self, nums: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums: List[int]) -> int: 使用Counter计数
- def singleNumber2(self, nums: List[int]) -> int: 使用两个set分别记录:已经访问过的,和可能是单个数字的。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums: List[int]) -> int: 使用Counter计数
- def singleNumber2(self, nums: List[int]) -> int: 使用两个set分别记录:已经访问过的,和可能是单个数字的。
<|skeleton|>
class Solution:
de... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""使用Counter计数"""
<|body_0|>
def singleNumber2(self, nums: List[int]) -> int:
"""使用两个set分别记录:已经访问过的,和可能是单个数字的。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""使用Counter计数"""
freq = Counter(nums)
for num, count in freq.items():
if count == 1:
return num
def singleNumber2(self, nums: List[int]) -> int:
"""使用两个set分别记录:已经访问过的,和可能是单个数字的。"""
... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer II 004. 只出现一次的数字 .py | tenqaz/crazy_arithmetic | train | 0 | |
e0ac23f49cf7dc24aff358c9c91fe01245862cc2 | [
"self.resolvers = resolvers\nself.resolver = dns.resolver.Resolver(configure=False)\nself.resolver.nameservers = self.resolvers\nLOGGER.debug('resolver initialized for %s' % self.resolvers)",
"ipv4addresses = []\ntry:\n LOGGER.debug('trying resolve A record for %s' % domain)\n answer = self.resolver.query(d... | <|body_start_0|>
self.resolvers = resolvers
self.resolver = dns.resolver.Resolver(configure=False)
self.resolver.nameservers = self.resolvers
LOGGER.debug('resolver initialized for %s' % self.resolvers)
<|end_body_0|>
<|body_start_1|>
ipv4addresses = []
try:
... | 指定されたフルリゾルバのいずれかを用いて名前解決を行う 解決したいRTYPE毎にメソッドを実装する | FullResolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullResolver:
"""指定されたフルリゾルバのいずれかを用いて名前解決を行う 解決したいRTYPE毎にメソッドを実装する"""
def __init__(self, resolvers):
"""コンストラクタ Parameters ---------- resolvers : list フルリゾルバのIPアドレスを表らす文字列のリスト"""
<|body_0|>
def resolve_a(self, domain):
"""ドメイン名のIPv4アドレスを解決して返す Returns ------- ipv... | stack_v2_sparse_classes_36k_train_003784 | 2,146 | no_license | [
{
"docstring": "コンストラクタ Parameters ---------- resolvers : list フルリゾルバのIPアドレスを表らす文字列のリスト",
"name": "__init__",
"signature": "def __init__(self, resolvers)"
},
{
"docstring": "ドメイン名のIPv4アドレスを解決して返す Returns ------- ipv4addresses : list IPv4アドレスの文字列リスト",
"name": "resolve_a",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_val_000188 | Implement the Python class `FullResolver` described below.
Class description:
指定されたフルリゾルバのいずれかを用いて名前解決を行う 解決したいRTYPE毎にメソッドを実装する
Method signatures and docstrings:
- def __init__(self, resolvers): コンストラクタ Parameters ---------- resolvers : list フルリゾルバのIPアドレスを表らす文字列のリスト
- def resolve_a(self, domain): ドメイン名のIPv4アドレスを解決して返... | Implement the Python class `FullResolver` described below.
Class description:
指定されたフルリゾルバのいずれかを用いて名前解決を行う 解決したいRTYPE毎にメソッドを実装する
Method signatures and docstrings:
- def __init__(self, resolvers): コンストラクタ Parameters ---------- resolvers : list フルリゾルバのIPアドレスを表らす文字列のリスト
- def resolve_a(self, domain): ドメイン名のIPv4アドレスを解決して返... | 6f9072739ba623b065a18a97ed2b3946efc3d366 | <|skeleton|>
class FullResolver:
"""指定されたフルリゾルバのいずれかを用いて名前解決を行う 解決したいRTYPE毎にメソッドを実装する"""
def __init__(self, resolvers):
"""コンストラクタ Parameters ---------- resolvers : list フルリゾルバのIPアドレスを表らす文字列のリスト"""
<|body_0|>
def resolve_a(self, domain):
"""ドメイン名のIPv4アドレスを解決して返す Returns ------- ipv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullResolver:
"""指定されたフルリゾルバのいずれかを用いて名前解決を行う 解決したいRTYPE毎にメソッドを実装する"""
def __init__(self, resolvers):
"""コンストラクタ Parameters ---------- resolvers : list フルリゾルバのIPアドレスを表らす文字列のリスト"""
self.resolvers = resolvers
self.resolver = dns.resolver.Resolver(configure=False)
self.resolve... | the_stack_v2_python_sparse | src/common/net/resolver/rec_resolver.py | moratori/dnsprobe | train | 6 |
c83b9658c19f0b6b96b61d2b938aa37939ffda63 | [
"self._container_fn = container_fn\nself._memo = {}\nself._filter_fn = filter_fn\nself._name_fn = name_fn",
"container = self._container_fn()\n\ndef container_contains(idx, itm):\n return idx < len(container) and self._filter_fn(container[idx]) and (self._name_fn(container[idx]) == itm)\nif isinstance(item, st... | <|body_start_0|>
self._container_fn = container_fn
self._memo = {}
self._filter_fn = filter_fn
self._name_fn = name_fn
<|end_body_0|>
<|body_start_1|>
container = self._container_fn()
def container_contains(idx, itm):
return idx < len(container) and self._fi... | Implemets a memo for lookup in a list of items where each has a unique name | EnumeratedMemo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumeratedMemo:
"""Implemets a memo for lookup in a list of items where each has a unique name"""
def __init__(self, container_fn: tp.Callable, name_fn: tp.Callable, filter_fn: tp.Optional[tp.Callable]):
"""Parameters ---------- container_fn A callable that returns the container (lis... | stack_v2_sparse_classes_36k_train_003785 | 2,436 | permissive | [
{
"docstring": "Parameters ---------- container_fn A callable that returns the container (list) where to search name_fn A callable that returns the associated name for each object in the container filter_fn An optional filter to ignore certain objects in the container",
"name": "__init__",
"signature": ... | 3 | stack_v2_sparse_classes_30k_val_000245 | Implement the Python class `EnumeratedMemo` described below.
Class description:
Implemets a memo for lookup in a list of items where each has a unique name
Method signatures and docstrings:
- def __init__(self, container_fn: tp.Callable, name_fn: tp.Callable, filter_fn: tp.Optional[tp.Callable]): Parameters ---------... | Implement the Python class `EnumeratedMemo` described below.
Class description:
Implemets a memo for lookup in a list of items where each has a unique name
Method signatures and docstrings:
- def __init__(self, container_fn: tp.Callable, name_fn: tp.Callable, filter_fn: tp.Optional[tp.Callable]): Parameters ---------... | 2822b84220e512c8012b1b4ec51d6e534bd4d652 | <|skeleton|>
class EnumeratedMemo:
"""Implemets a memo for lookup in a list of items where each has a unique name"""
def __init__(self, container_fn: tp.Callable, name_fn: tp.Callable, filter_fn: tp.Optional[tp.Callable]):
"""Parameters ---------- container_fn A callable that returns the container (lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnumeratedMemo:
"""Implemets a memo for lookup in a list of items where each has a unique name"""
def __init__(self, container_fn: tp.Callable, name_fn: tp.Callable, filter_fn: tp.Optional[tp.Callable]):
"""Parameters ---------- container_fn A callable that returns the container (list) where to s... | the_stack_v2_python_sparse | blox2/utils/memo.py | vladstreltsin/blox | train | 0 |
223d3f6d1816edcc589d692698f7e0bd81e661cc | [
"super().__init__(name=name)\nself.num_output = num_output\nself.initializer = initializer\nself.use_bias = use_bias\nself.bias_init = bias_init",
"n_channels = int(inputs.shape[-1])\nweight_shape = [n_channels, self.num_output]\nif self.initializer == 'linear':\n weight_init = hk.initializers.VarianceScaling(... | <|body_start_0|>
super().__init__(name=name)
self.num_output = num_output
self.initializer = initializer
self.use_bias = use_bias
self.bias_init = bias_init
<|end_body_0|>
<|body_start_1|>
n_channels = int(inputs.shape[-1])
weight_shape = [n_channels, self.num_ou... | Protein folding specific Linear Module. This differs from the standard Haiku Linear in a few ways: * It supports inputs of arbitrary rank * Initializers are specified by strings This code is adapted from DeepMind's AlphaFold code release (https://github.com/deepmind/alphafold). Examples -------- >>> import deepchem as ... | Linear | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linear:
"""Protein folding specific Linear Module. This differs from the standard Haiku Linear in a few ways: * It supports inputs of arbitrary rank * Initializers are specified by strings This code is adapted from DeepMind's AlphaFold code release (https://github.com/deepmind/alphafold). Example... | stack_v2_sparse_classes_36k_train_003786 | 3,408 | permissive | [
{
"docstring": "Constructs Linear Module. Parameters ---------- num_output: int number of output channels. initializer: str (default 'linear') What initializer to use, should be one of {'linear', 'relu', 'zeros'} use_bias: bool (default True) Whether to include trainable bias bias_init: float (default 0) Value ... | 2 | null | Implement the Python class `Linear` described below.
Class description:
Protein folding specific Linear Module. This differs from the standard Haiku Linear in a few ways: * It supports inputs of arbitrary rank * Initializers are specified by strings This code is adapted from DeepMind's AlphaFold code release (https://... | Implement the Python class `Linear` described below.
Class description:
Protein folding specific Linear Module. This differs from the standard Haiku Linear in a few ways: * It supports inputs of arbitrary rank * Initializers are specified by strings This code is adapted from DeepMind's AlphaFold code release (https://... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class Linear:
"""Protein folding specific Linear Module. This differs from the standard Haiku Linear in a few ways: * It supports inputs of arbitrary rank * Initializers are specified by strings This code is adapted from DeepMind's AlphaFold code release (https://github.com/deepmind/alphafold). Example... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linear:
"""Protein folding specific Linear Module. This differs from the standard Haiku Linear in a few ways: * It supports inputs of arbitrary rank * Initializers are specified by strings This code is adapted from DeepMind's AlphaFold code release (https://github.com/deepmind/alphafold). Examples -------- >>... | the_stack_v2_python_sparse | deepchem/models/jax_models/layers.py | deepchem/deepchem | train | 4,876 |
d188643cfb30660ce3d0c6b8de28ca366868efba | [
"assert not np.isinf(domain[0]) and (not np.isinf(domain[1]))\nif not domain[0] < 0 < domain[1]:\n print('Domain must contain 0!')\n raise AssertionError\nself.J = J\ntry:\n self.ignore_zeros = kwargs['ignore_zeros']\nexcept KeyError:\n self.ignore_zeros = False\ntry:\n self.epsabs = kwargs['epsabs']... | <|body_start_0|>
assert not np.isinf(domain[0]) and (not np.isinf(domain[1]))
if not domain[0] < 0 < domain[1]:
print('Domain must contain 0!')
raise AssertionError
self.J = J
try:
self.ignore_zeros = kwargs['ignore_zeros']
except KeyError:
... | GKQuadDiscretizedSymmetricBath | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GKQuadDiscretizedSymmetricBath:
def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs):
"""Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ g... | stack_v2_sparse_classes_36k_train_003787 | 5,510 | permissive | [
{
"docstring": "Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral density. A function defined on 'domain', must be >0 in the inner part of domain :param domain: List/tup... | 2 | stack_v2_sparse_classes_30k_train_010046 | Implement the Python class `GKQuadDiscretizedSymmetricBath` described below.
Class description:
Implement the GKQuadDiscretizedSymmetricBath class.
Method signatures and docstrings:
- def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): Generates direct discretization coefficients f... | Implement the Python class `GKQuadDiscretizedSymmetricBath` described below.
Class description:
Implement the GKQuadDiscretizedSymmetricBath class.
Method signatures and docstrings:
- def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): Generates direct discretization coefficients f... | daf37f522f8acb6af2285d44f39cab31f34b01a4 | <|skeleton|>
class GKQuadDiscretizedSymmetricBath:
def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs):
"""Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GKQuadDiscretizedSymmetricBath:
def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs):
"""Generates direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :para... | the_stack_v2_python_sparse | mapping/star/discretized_bath/symmetric_gk_quad.py | fhoeb/py-mapping | train | 2 | |
0f8df2cb216af96101232d2d9192d337726afab7 | [
"super().__init__()\nself.redis_conn_id = redis_conn_id\nself.redis = None\nself.host = None\nself.port = None\nself.password = None\nself.db = None",
"conn = self.get_connection(self.redis_conn_id)\nself.host = conn.host\nself.port = conn.port\nself.password = None if str(conn.password).lower() in ['none', 'fals... | <|body_start_0|>
super().__init__()
self.redis_conn_id = redis_conn_id
self.redis = None
self.host = None
self.port = None
self.password = None
self.db = None
<|end_body_0|>
<|body_start_1|>
conn = self.get_connection(self.redis_conn_id)
self.host... | Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``. | RedisHook | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisHook:
"""Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``."""
... | stack_v2_sparse_classes_36k_train_003788 | 2,945 | permissive | [
{
"docstring": "Prepares hook to connect to a Redis database. :param conn_id: the name of the connection that has the parameters we need to connect to Redis.",
"name": "__init__",
"signature": "def __init__(self, redis_conn_id: str=default_conn_name) -> None"
},
{
"docstring": "Returns a Redis c... | 2 | null | Implement the Python class `RedisHook` described below.
Class description:
Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_... | Implement the Python class `RedisHook` described below.
Class description:
Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_... | 1b122c15030e99cef9d4ff26d3781a7a9d6949bc | <|skeleton|>
class RedisHook:
"""Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisHook:
"""Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_cert_file": "/path/to/cert.pem", etc}``."""
def __in... | the_stack_v2_python_sparse | airflow/providers/redis/hooks/redis.py | apache/airflow | train | 22,756 |
84faeb1def341eff7cba0f872c6088ebee2449b4 | [
"k = m + n - 1\ni = m - 1\nj = n - 1\nwhile k > -1:\n if i == -1:\n nums1[k] = nums2[j]\n j -= 1\n elif j == -1:\n nums1[k] = nums1[i]\n i -= 1\n elif nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n i -= 1\n else:\n nums1[k] = nums2[j]\n j -= 1\n k... | <|body_start_0|>
k = m + n - 1
i = m - 1
j = n - 1
while k > -1:
if i == -1:
nums1[k] = nums2[j]
j -= 1
elif j == -1:
nums1[k] = nums1[i]
i -= 1
elif nums1[i] > nums2[j]:
n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) ->... | stack_v2_sparse_classes_36k_train_003789 | 1,008 | no_license | [
{
"docstring": ":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.",
"name": "merge",
"signature": "def merge(self, nums1, m, nums2, n)"
},
{
"docstring": "Do not return anything, modify nums1 in-place inste... | 2 | stack_v2_sparse_classes_30k_train_017323 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge(self, nums1, m, nums2, n): :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead.
-... | 46ab9dabcca845a13f55efcb3f9be3bf3f2908a9 | <|skeleton|>
class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
<|body_0|>
def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) ->... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge(self, nums1, m, nums2, n):
""":type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead."""
k = m + n - 1
i = m - 1
j = n - 1
while k > -1:
if i == -1:
... | the_stack_v2_python_sparse | easy/88_merge_sorted_arrays.py | zehrahayirci/LeetCode | train | 0 | |
cc4a92e6c57e061dde4c4601695171de66c6e4dc | [
"ratio_product = 1\nfor i in ratio:\n ratio_product *= i\naddress_space_size = int(math.log(ratio_product, 2))\nword_size = Vector(*word_size)\nsuper(MemoryAccessUnit, self).__init__(address_space_size)\nself.input_address = self.add_input(input_address)\nself.ratio = Vector(*ratio)\nself.word_size = word_size\n... | <|body_start_0|>
ratio_product = 1
for i in ratio:
ratio_product *= i
address_space_size = int(math.log(ratio_product, 2))
word_size = Vector(*word_size)
super(MemoryAccessUnit, self).__init__(address_space_size)
self.input_address = self.add_input(input_addre... | This unit provides basic functionality for accessing memory and preforming some user-defined action. See example of use in the ReadUnit. | MemoryAccessUnit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemoryAccessUnit:
"""This unit provides basic functionality for accessing memory and preforming some user-defined action. See example of use in the ReadUnit."""
def __init__(self, ratio=(1, 16, 16), word_size=(8, 1, 1), raw_memory=None, input_address=std_logic.InputRegister):
""":par... | stack_v2_sparse_classes_36k_train_003790 | 6,650 | no_license | [
{
"docstring": ":param ratio: The ration of words distributed in 3D space. :param word_size: the size of a word. by default it is a 8 bits facing east. :param raw_memory: This is the actual \"raw\" memory on which this access unit is operating. If no is specified, Memory block will be generated from the ratios ... | 2 | null | Implement the Python class `MemoryAccessUnit` described below.
Class description:
This unit provides basic functionality for accessing memory and preforming some user-defined action. See example of use in the ReadUnit.
Method signatures and docstrings:
- def __init__(self, ratio=(1, 16, 16), word_size=(8, 1, 1), raw_... | Implement the Python class `MemoryAccessUnit` described below.
Class description:
This unit provides basic functionality for accessing memory and preforming some user-defined action. See example of use in the ReadUnit.
Method signatures and docstrings:
- def __init__(self, ratio=(1, 16, 16), word_size=(8, 1, 1), raw_... | 8bbb26b2c3bbaa0712b5321d85b9f3834a0016fb | <|skeleton|>
class MemoryAccessUnit:
"""This unit provides basic functionality for accessing memory and preforming some user-defined action. See example of use in the ReadUnit."""
def __init__(self, ratio=(1, 16, 16), word_size=(8, 1, 1), raw_memory=None, input_address=std_logic.InputRegister):
""":par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemoryAccessUnit:
"""This unit provides basic functionality for accessing memory and preforming some user-defined action. See example of use in the ReadUnit."""
def __init__(self, ratio=(1, 16, 16), word_size=(8, 1, 1), raw_memory=None, input_address=std_logic.InputRegister):
""":param ratio: The... | the_stack_v2_python_sparse | cbac/std_unit/ram_unit.py | bowiz2/cbac | train | 1 |
230f5f17b1dc1a7d637581d25d54f89adaa38d6f | [
"super(SelfAtt, self).__init__()\nself.query, self.key, self.value = nn.CellList([nn.SequentialCell([nn.Dense(n_in, n_out), nn.Tanh()]) for _ in range(3)])\nself.bmm = ops.BatchMatMul()\nself.softmax = ops.Softmax()\nself.scale = Tensor(n_out, ms.float32)",
"query = self.query(x)\nkey = self.key(x)\nvalue = self.... | <|body_start_0|>
super(SelfAtt, self).__init__()
self.query, self.key, self.value = nn.CellList([nn.SequentialCell([nn.Dense(n_in, n_out), nn.Tanh()]) for _ in range(3)])
self.bmm = ops.BatchMatMul()
self.softmax = ops.Softmax()
self.scale = Tensor(n_out, ms.float32)
<|end_body_0... | Self-attention. | SelfAtt | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAtt:
"""Self-attention."""
def __init__(self, n_in: int, n_out: int):
"""Parameters ---------- n_in : int input dimension. n_out : int output dimension."""
<|body_0|>
def construct(self, x: Tensor) -> Tensor:
"""Parameters ---------- x : Tensor [..., size, di... | stack_v2_sparse_classes_36k_train_003791 | 9,199 | permissive | [
{
"docstring": "Parameters ---------- n_in : int input dimension. n_out : int output dimension.",
"name": "__init__",
"signature": "def __init__(self, n_in: int, n_out: int)"
},
{
"docstring": "Parameters ---------- x : Tensor [..., size, dim]. Returns ------- out : Tensor [..., size, dim].",
... | 2 | stack_v2_sparse_classes_30k_train_019104 | Implement the Python class `SelfAtt` described below.
Class description:
Self-attention.
Method signatures and docstrings:
- def __init__(self, n_in: int, n_out: int): Parameters ---------- n_in : int input dimension. n_out : int output dimension.
- def construct(self, x: Tensor) -> Tensor: Parameters ---------- x : ... | Implement the Python class `SelfAtt` described below.
Class description:
Self-attention.
Method signatures and docstrings:
- def __init__(self, n_in: int, n_out: int): Parameters ---------- n_in : int input dimension. n_out : int output dimension.
- def construct(self, x: Tensor) -> Tensor: Parameters ---------- x : ... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class SelfAtt:
"""Self-attention."""
def __init__(self, n_in: int, n_out: int):
"""Parameters ---------- n_in : int input dimension. n_out : int output dimension."""
<|body_0|>
def construct(self, x: Tensor) -> Tensor:
"""Parameters ---------- x : Tensor [..., size, di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAtt:
"""Self-attention."""
def __init__(self, n_in: int, n_out: int):
"""Parameters ---------- n_in : int input dimension. n_out : int output dimension."""
super(SelfAtt, self).__init__()
self.query, self.key, self.value = nn.CellList([nn.SequentialCell([nn.Dense(n_in, n_out),... | the_stack_v2_python_sparse | research/gnn/nri-mpm/models/base.py | mindspore-ai/models | train | 301 |
14316b1bc48a2d0d7dc23719bc176e72d20ad812 | [
"self.not_rated = not_rated\nself.pred = pred\nself.movie_data = movie_data",
"dic_prediction = {i: j for i, j in zip(self.not_rated, self.pred)}\nsort_prediction = OrderedDict(sorted(dic_prediction.items(), key=itemgetter(1), reverse=True))\nrecomm = [(self.movie_data[0][i, 1], self.movie_data[0][i, 2]) for i in... | <|body_start_0|>
self.not_rated = not_rated
self.pred = pred
self.movie_data = movie_data
<|end_body_0|>
<|body_start_1|>
dic_prediction = {i: j for i, j in zip(self.not_rated, self.pred)}
sort_prediction = OrderedDict(sorted(dic_prediction.items(), key=itemgetter(1), reverse=Tr... | This class returns a list of ten recommendation for a new user. | make_recommendation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class make_recommendation:
"""This class returns a list of ten recommendation for a new user."""
def __init__(self, not_rated, pred, movie_data):
"""An instance created by that class is characterized by the following attributes: - not_rated : is the list of indices of not yet rated items, ... | stack_v2_sparse_classes_36k_train_003792 | 1,421 | no_license | [
{
"docstring": "An instance created by that class is characterized by the following attributes: - not_rated : is the list of indices of not yet rated items, - pred : is the array of predictions, return of the *new_user_prediction* function, - movie_data : is the return of *load_data.adjust_data()* method, it co... | 2 | stack_v2_sparse_classes_30k_train_012731 | Implement the Python class `make_recommendation` described below.
Class description:
This class returns a list of ten recommendation for a new user.
Method signatures and docstrings:
- def __init__(self, not_rated, pred, movie_data): An instance created by that class is characterized by the following attributes: - no... | Implement the Python class `make_recommendation` described below.
Class description:
This class returns a list of ten recommendation for a new user.
Method signatures and docstrings:
- def __init__(self, not_rated, pred, movie_data): An instance created by that class is characterized by the following attributes: - no... | bd9c841811f487a077ef58d9310cdeaeafcca7bb | <|skeleton|>
class make_recommendation:
"""This class returns a list of ten recommendation for a new user."""
def __init__(self, not_rated, pred, movie_data):
"""An instance created by that class is characterized by the following attributes: - not_rated : is the list of indices of not yet rated items, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class make_recommendation:
"""This class returns a list of ten recommendation for a new user."""
def __init__(self, not_rated, pred, movie_data):
"""An instance created by that class is characterized by the following attributes: - not_rated : is the list of indices of not yet rated items, - pred : is t... | the_stack_v2_python_sparse | recommended_movies.py | NaveganteX/Recommender-System-1 | train | 0 |
987d42df036be470f2e3fad417894d620094dcb2 | [
"try:\n payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])\nexcept jwt.ExpiredSignatureError:\n raise serializers.ValidationError('Verification link has expired.')\nexcept jwt.PyJWTError:\n raise serializers.ValidationError('Invalid token')\nif payload['type'] != 'email_confirmation':\n ... | <|body_start_0|>
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.ValidationError('Verification link has expired.')
except jwt.PyJWTError:
raise serializers.ValidationError('Invalid ... | Account verification serializer. | AccountVerificationSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_003793 | 8,178 | no_license | [
{
"docstring": "Verify token is valid.",
"name": "validate_token",
"signature": "def validate_token(self, data)"
},
{
"docstring": "Update user's verified status.",
"name": "save",
"signature": "def save(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004501 | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def save(self): Update user's verified status. | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def save(self): Update user's verified status.
<|skeleton|>
class AccountVerificationSerializer:... | fae5c0b2e388239e2e32a3fbf52aa7cfd48a7cbb | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers... | the_stack_v2_python_sparse | facebook/app/users/serializers/users.py | ricagome/Api-Facebook-Clone | train | 0 |
4245fbe8e84e590f9869f8bb546c1a979c22217b | [
"self.height = height\nself.width = width\nself.food = deque()\nself.score = 0\nself.snake = deque()\nself.snake.appendleft([0, 0])\nfor r, c in food:\n self.food.appendleft((r, c))",
"dir = {'U': [-1, 0], 'D': [1, 0], 'L': [0, -1], 'R': [0, 1]}\ncurRow, curCol = self.snake[0]\nnextRow, nextCol = (curRow + dir... | <|body_start_0|>
self.height = height
self.width = width
self.food = deque()
self.score = 0
self.snake = deque()
self.snake.appendleft([0, 0])
for r, c in food:
self.food.appendleft((r, c))
<|end_body_0|>
<|body_start_1|>
dir = {'U': [-1, 0], ... | SnakeGame | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [... | stack_v2_sparse_classes_36k_train_003794 | 3,642 | permissive | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_008622 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food p... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food p... | 6a83cb798cc317d1e4357ac6b2b1fbf76fa034fb | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]."""
... | the_stack_v2_python_sparse | Month 01/Week 03/Day 07/a.py | KevinKnott/Coding-Review | train | 0 | |
60a2f6fe75dfb6667769403e14c469232d8ac81f | [
"super(ConvQNetworkDuel, self).__init__()\nself.action_size = action_size\nself.seed = torch.manual_seed(seed)\nself.conv1 = nn.Conv2d(1, 32, kernel_size=8, stride=4)\nself.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\nself.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\nself.fc1 = nn.Linear(7 * 7 * 64, 5... | <|body_start_0|>
super(ConvQNetworkDuel, self).__init__()
self.action_size = action_size
self.seed = torch.manual_seed(seed)
self.conv1 = nn.Conv2d(1, 32, kernel_size=8, stride=4)
self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)
self.conv3 = nn.Conv2d(64, 64, kerne... | ConvQNetworkDuel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvQNetworkDuel:
def __init__(self, state_size, action_size, seed):
"""Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers"""
... | stack_v2_sparse_classes_36k_train_003795 | 2,797 | no_license | [
{
"docstring": "Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers",
"name": "__init__",
"signature": "def __init__(self, state_size, action_s... | 2 | stack_v2_sparse_classes_30k_train_016885 | Implement the Python class `ConvQNetworkDuel` described below.
Class description:
Implement the ConvQNetworkDuel class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed): Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_s... | Implement the Python class `ConvQNetworkDuel` described below.
Class description:
Implement the ConvQNetworkDuel class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed): Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_s... | bcb0b7beb8a41a8cd008a3c790dd007356190abc | <|skeleton|>
class ConvQNetworkDuel:
def __init__(self, state_size, action_size, seed):
"""Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvQNetworkDuel:
def __init__(self, state_size, action_size, seed):
"""Model initialization Parameters ---------- state_size (discrete or numpy) - shape of environment state action_size (discrete or numpy) - shape of action applied to environment seed (int) - seed for random numbers"""
super(... | the_stack_v2_python_sparse | conv_model.py | jeffreyfeng99/reinforcement_learning | train | 0 | |
c3be555197e89c6c3b94d4ae4eb7ec346824340c | [
"self.index = deque()\nself.dic = {}\nself.capacity = capacity",
"if key in self.index:\n self.index.remove(key)\n self.index.append(key)\nreturn self.dic.get(key, -1)",
"if key in self.index:\n self.index.remove(key)\n self.index.append(key)\nelse:\n if len(self.index) == self.capacity:\n ... | <|body_start_0|>
self.index = deque()
self.dic = {}
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key in self.index:
self.index.remove(key)
self.index.append(key)
return self.dic.get(key, -1)
<|end_body_1|>
<|body_start_2|>
if key i... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_003796 | 1,093 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 013f6f222c6c2a617787b258f8a37003a9f51526 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.index = deque()
self.dic = {}
self.capacity = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key in self.index:
self.index.remove(key)
self.inde... | the_stack_v2_python_sparse | all/146_LRUCache.py | terrifyzhao/leetcode | train | 0 | |
0c8e418d0dcbcd8a68827bfc0b7ed2dedd385c47 | [
"super(OFCLearner, self).__init__(batch_size, *args, **kwargs)\nself.B = B\nself.F_dict = F_dict\nself.A = A",
"try:\n current_state = np.mat(current_state).reshape(-1, 1)\n target_state = np.mat(target_state).reshape(-1, 1)\n F = self.F_dict[task_state]\n A = self.A\n B = self.B\n return A * cu... | <|body_start_0|>
super(OFCLearner, self).__init__(batch_size, *args, **kwargs)
self.B = B
self.F_dict = F_dict
self.A = A
<|end_body_0|>
<|body_start_1|>
try:
current_state = np.mat(current_state).reshape(-1, 1)
target_state = np.mat(target_state).reshape... | An intention estimator where the subject is assumed to operate like a muiti-modal LQR controller | OFCLearner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OFCLearner:
"""An intention estimator where the subject is assumed to operate like a muiti-modal LQR controller"""
def __init__(self, batch_size, A, B, F_dict, *args, **kwargs):
"""Constructor for OFCLearner Parameters ---------- batch_size : int size of batch of samples to pass to t... | stack_v2_sparse_classes_36k_train_003797 | 43,699 | permissive | [
{
"docstring": "Constructor for OFCLearner Parameters ---------- batch_size : int size of batch of samples to pass to the Updater to estimate new decoder parameters A : np.mat State transition matrix of the modeled discrete-time system B : np.mat Control input matrix of the modeled discrete-time system F_dict :... | 2 | null | Implement the Python class `OFCLearner` described below.
Class description:
An intention estimator where the subject is assumed to operate like a muiti-modal LQR controller
Method signatures and docstrings:
- def __init__(self, batch_size, A, B, F_dict, *args, **kwargs): Constructor for OFCLearner Parameters --------... | Implement the Python class `OFCLearner` described below.
Class description:
An intention estimator where the subject is assumed to operate like a muiti-modal LQR controller
Method signatures and docstrings:
- def __init__(self, batch_size, A, B, F_dict, *args, **kwargs): Constructor for OFCLearner Parameters --------... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class OFCLearner:
"""An intention estimator where the subject is assumed to operate like a muiti-modal LQR controller"""
def __init__(self, batch_size, A, B, F_dict, *args, **kwargs):
"""Constructor for OFCLearner Parameters ---------- batch_size : int size of batch of samples to pass to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OFCLearner:
"""An intention estimator where the subject is assumed to operate like a muiti-modal LQR controller"""
def __init__(self, batch_size, A, B, F_dict, *args, **kwargs):
"""Constructor for OFCLearner Parameters ---------- batch_size : int size of batch of samples to pass to the Updater to... | the_stack_v2_python_sparse | riglib/bmi/clda.py | carmenalab/brain-python-interface | train | 9 |
5f2fbc92981c64b0c15780adb33f866e14c185cd | [
"if self.action in ['list']:\n permission_classes = [UserIsReferralUnitMember]\nelif self.action in ['create']:\n permission_classes = [UserIsReferralUnitMember]\nelse:\n try:\n permission_classes = getattr(self, self.action).kwargs.get('permission_classes')\n except AttributeError:\n perm... | <|body_start_0|>
if self.action in ['list']:
permission_classes = [UserIsReferralUnitMember]
elif self.action in ['create']:
permission_classes = [UserIsReferralUnitMember]
else:
try:
permission_classes = getattr(self, self.action).kwargs.get('... | API endpoints for report messages. | ReportEventViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportEventViewSet:
"""API endpoints for report messages."""
def get_permissions(self):
"""Manage permissions for default methods separately, delegating to @action defined permissions for other actions."""
<|body_0|>
def create(self, request, *args, **kwargs):
""... | stack_v2_sparse_classes_36k_train_003798 | 4,524 | permissive | [
{
"docstring": "Manage permissions for default methods separately, delegating to @action defined permissions for other actions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Create a new report message as the client issues a POST on the reportevents end... | 3 | null | Implement the Python class `ReportEventViewSet` described below.
Class description:
API endpoints for report messages.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for default methods separately, delegating to @action defined permissions for other actions.
- def create(self, reque... | Implement the Python class `ReportEventViewSet` described below.
Class description:
API endpoints for report messages.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for default methods separately, delegating to @action defined permissions for other actions.
- def create(self, reque... | 22e4afa728a851bb4c2479fbb6f5944a75984b9b | <|skeleton|>
class ReportEventViewSet:
"""API endpoints for report messages."""
def get_permissions(self):
"""Manage permissions for default methods separately, delegating to @action defined permissions for other actions."""
<|body_0|>
def create(self, request, *args, **kwargs):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportEventViewSet:
"""API endpoints for report messages."""
def get_permissions(self):
"""Manage permissions for default methods separately, delegating to @action defined permissions for other actions."""
if self.action in ['list']:
permission_classes = [UserIsReferralUnitMem... | the_stack_v2_python_sparse | src/backend/partaj/core/api/report_event.py | MTES-MCT/partaj | train | 4 |
03ef2d1b7ccd3387384920667193fdba7791550b | [
"b = os.popen('adb shell dumpsys window policy|grep mScreenOnFully')\na = b.read().strip()\ndeng = a[-5:]\nlogging.info(f'判断是否锁屏{deng}')\nif deng == str('false'):\n logging.info('屏幕是灭的,等待解锁')\n os.popen('adb shell input keyevent 26')\n time.sleep(1)\n os.popen('adb shell input swipe 50 1000 50 0 100')\n... | <|body_start_0|>
b = os.popen('adb shell dumpsys window policy|grep mScreenOnFully')
a = b.read().strip()
deng = a[-5:]
logging.info(f'判断是否锁屏{deng}')
if deng == str('false'):
logging.info('屏幕是灭的,等待解锁')
os.popen('adb shell input keyevent 26')
ti... | Pingmu_unlock_the_screen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pingmu_unlock_the_screen:
def pingmu_jiesuo(self):
""":return: 手机本身的解锁"""
<|body_0|>
def App_jiesuo(self):
""":return: 解锁app内部的滑动解锁"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
b = os.popen('adb shell dumpsys window policy|grep mScreenOnFully')
... | stack_v2_sparse_classes_36k_train_003799 | 14,739 | no_license | [
{
"docstring": ":return: 手机本身的解锁",
"name": "pingmu_jiesuo",
"signature": "def pingmu_jiesuo(self)"
},
{
"docstring": ":return: 解锁app内部的滑动解锁",
"name": "App_jiesuo",
"signature": "def App_jiesuo(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001935 | Implement the Python class `Pingmu_unlock_the_screen` described below.
Class description:
Implement the Pingmu_unlock_the_screen class.
Method signatures and docstrings:
- def pingmu_jiesuo(self): :return: 手机本身的解锁
- def App_jiesuo(self): :return: 解锁app内部的滑动解锁 | Implement the Python class `Pingmu_unlock_the_screen` described below.
Class description:
Implement the Pingmu_unlock_the_screen class.
Method signatures and docstrings:
- def pingmu_jiesuo(self): :return: 手机本身的解锁
- def App_jiesuo(self): :return: 解锁app内部的滑动解锁
<|skeleton|>
class Pingmu_unlock_the_screen:
def pin... | 93fe784a3127e76995e9ae018605efbe78238385 | <|skeleton|>
class Pingmu_unlock_the_screen:
def pingmu_jiesuo(self):
""":return: 手机本身的解锁"""
<|body_0|>
def App_jiesuo(self):
""":return: 解锁app内部的滑动解锁"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pingmu_unlock_the_screen:
def pingmu_jiesuo(self):
""":return: 手机本身的解锁"""
b = os.popen('adb shell dumpsys window policy|grep mScreenOnFully')
a = b.read().strip()
deng = a[-5:]
logging.info(f'判断是否锁屏{deng}')
if deng == str('false'):
logging.info('屏幕是灭... | the_stack_v2_python_sparse | 早期/熊猫.py | huangno27/learn | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.