blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22990d0b1f5882fcfc624a0e400985c330efa804 | [
"default: Union[Callable[[], list], Callable[[], Tensor]]\nif multidim_average == 'samplewise':\n default = list\n dist_reduce_fx = 'cat'\nelse:\n default = lambda: torch.zeros(size, dtype=torch.long)\n dist_reduce_fx = 'sum'\nself.add_state('tp', default(), dist_reduce_fx=dist_reduce_fx)\nself.add_stat... | <|body_start_0|>
default: Union[Callable[[], list], Callable[[], Tensor]]
if multidim_average == 'samplewise':
default = list
dist_reduce_fx = 'cat'
else:
default = lambda: torch.zeros(size, dtype=torch.long)
dist_reduce_fx = 'sum'
self.add... | _AbstractStatScores | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _AbstractStatScores:
def _create_state(self, size: int, multidim_average: Literal['global', 'samplewise']='global') -> None:
"""Initialize the states for the different statistics."""
<|body_0|>
def _update_state(self, tp: Tensor, fp: Tensor, tn: Tensor, fn: Tensor) -> None:
... | stack_v2_sparse_classes_75kplus_train_072500 | 24,621 | permissive | [
{
"docstring": "Initialize the states for the different statistics.",
"name": "_create_state",
"signature": "def _create_state(self, size: int, multidim_average: Literal['global', 'samplewise']='global') -> None"
},
{
"docstring": "Update states depending on multidim_average argument.",
"nam... | 3 | null | Implement the Python class `_AbstractStatScores` described below.
Class description:
Implement the _AbstractStatScores class.
Method signatures and docstrings:
- def _create_state(self, size: int, multidim_average: Literal['global', 'samplewise']='global') -> None: Initialize the states for the different statistics.
... | Implement the Python class `_AbstractStatScores` described below.
Class description:
Implement the _AbstractStatScores class.
Method signatures and docstrings:
- def _create_state(self, size: int, multidim_average: Literal['global', 'samplewise']='global') -> None: Initialize the states for the different statistics.
... | 66f1859c5fefffcb37de4f430a6fbf71fb6c8c6b | <|skeleton|>
class _AbstractStatScores:
def _create_state(self, size: int, multidim_average: Literal['global', 'samplewise']='global') -> None:
"""Initialize the states for the different statistics."""
<|body_0|>
def _update_state(self, tp: Tensor, fp: Tensor, tn: Tensor, fn: Tensor) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _AbstractStatScores:
def _create_state(self, size: int, multidim_average: Literal['global', 'samplewise']='global') -> None:
"""Initialize the states for the different statistics."""
default: Union[Callable[[], list], Callable[[], Tensor]]
if multidim_average == 'samplewise':
... | the_stack_v2_python_sparse | src/torchmetrics/classification/stat_scores.py | Lightning-AI/torchmetrics | train | 295 | |
aa6953f701a6695492254eaf213c58ed26689ed6 | [
"sexy.IconEntry.__init__(self)\nself.__gobject_init__()\nself._handler_changed = self.connect_after('changed', self._on_changed)\nself.connect('icon-pressed', self._on_icon_pressed)\nimage = gtk.Image()\npixbuf = icon_theme.load_icon(gtk.STOCK_CLEAR, gtk.ICON_SIZE_MENU, 0)\nimage.set_from_pixbuf(pixbuf)\nself.set_i... | <|body_start_0|>
sexy.IconEntry.__init__(self)
self.__gobject_init__()
self._handler_changed = self.connect_after('changed', self._on_changed)
self.connect('icon-pressed', self._on_icon_pressed)
image = gtk.Image()
pixbuf = icon_theme.load_icon(gtk.STOCK_CLEAR, gtk.ICON_S... | SearchEntry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchEntry:
def __init__(self, icon_theme):
"""Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active"""
<|body_0|>
def _on_icon_pressed(self, widget, icon, mouse_button):
"""Emit the terms... | stack_v2_sparse_classes_75kplus_train_072501 | 4,000 | no_license | [
{
"docstring": "Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active",
"name": "__init__",
"signature": "def __init__(self, icon_theme)"
},
{
"docstring": "Emit the terms-changed signal without any time out when the c... | 4 | stack_v2_sparse_classes_30k_val_002497 | Implement the Python class `SearchEntry` described below.
Class description:
Implement the SearchEntry class.
Method signatures and docstrings:
- def __init__(self, icon_theme): Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active
- def _o... | Implement the Python class `SearchEntry` described below.
Class description:
Implement the SearchEntry class.
Method signatures and docstrings:
- def __init__(self, icon_theme): Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active
- def _o... | d08f7bf370a82b6970387bb9f165d374a9d9092b | <|skeleton|>
class SearchEntry:
def __init__(self, icon_theme):
"""Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active"""
<|body_0|>
def _on_icon_pressed(self, widget, icon, mouse_button):
"""Emit the terms... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchEntry:
def __init__(self, icon_theme):
"""Creates an enhanced IconEntry that supports a time out when typing and uses a different background colour when the search is active"""
sexy.IconEntry.__init__(self)
self.__gobject_init__()
self._handler_changed = self.connect_afte... | the_stack_v2_python_sparse | usr/share/pyshared/AppInstall/widgets/SearchEntry.py | haniokasai/netwalker-rootfs | train | 2 | |
3661ef7e587b99f6b13fe983769e6280679a686e | [
"if timing_info.camera_mid_exposure_timestamp is not None:\n timestamp = clock.server_to_local_time(timing_info.camera_mid_exposure_timestamp)\n system_latency_ticks = timing_info.transmit_timestamp - timing_info.camera_mid_exposure_timestamp\n system_latency = clock.server_ticks_to_seconds(system_latency_... | <|body_start_0|>
if timing_info.camera_mid_exposure_timestamp is not None:
timestamp = clock.server_to_local_time(timing_info.camera_mid_exposure_timestamp)
system_latency_ticks = timing_info.transmit_timestamp - timing_info.camera_mid_exposure_timestamp
system_latency = cloc... | Timing information for a received mocap frame. Attributes: timestamp (float): Camera mid-exposure timestamp (according to local clock) system_latency (float): Time from camera mid-exposure to Motive transmitting frame transit_latency (float): Time from transmitting frame to receiving frame processing_latency (float): T... | TimestampAndLatency | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimestampAndLatency:
"""Timing information for a received mocap frame. Attributes: timestamp (float): Camera mid-exposure timestamp (according to local clock) system_latency (float): Time from camera mid-exposure to Motive transmitting frame transit_latency (float): Time from transmitting frame t... | stack_v2_sparse_classes_75kplus_train_072502 | 26,663 | permissive | [
{
"docstring": "Calculate latencies and local timestamp. Args: received_timestamp (float): timing_info (:class:`~protocol.MocapFrameMessage.TimingInfo`): clock (:class:`ClockSynchronizer`):",
"name": "_calculate",
"signature": "def _calculate(cls, received_timestamp, timing_info, clock)"
},
{
"d... | 2 | null | Implement the Python class `TimestampAndLatency` described below.
Class description:
Timing information for a received mocap frame. Attributes: timestamp (float): Camera mid-exposure timestamp (according to local clock) system_latency (float): Time from camera mid-exposure to Motive transmitting frame transit_latency ... | Implement the Python class `TimestampAndLatency` described below.
Class description:
Timing information for a received mocap frame. Attributes: timestamp (float): Camera mid-exposure timestamp (according to local clock) system_latency (float): Time from camera mid-exposure to Motive transmitting frame transit_latency ... | aa0d7030584dc7f6a4be3f37f81f6c1e9b016ef8 | <|skeleton|>
class TimestampAndLatency:
"""Timing information for a received mocap frame. Attributes: timestamp (float): Camera mid-exposure timestamp (according to local clock) system_latency (float): Time from camera mid-exposure to Motive transmitting frame transit_latency (float): Time from transmitting frame t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimestampAndLatency:
"""Timing information for a received mocap frame. Attributes: timestamp (float): Camera mid-exposure timestamp (according to local clock) system_latency (float): Time from camera mid-exposure to Motive transmitting frame transit_latency (float): Time from transmitting frame to receiving f... | the_stack_v2_python_sparse | src/natnet/comms.py | smorad/python_natnet | train | 0 |
fffed213ed11b43a5328b06caca1320208cf87be | [
"queryset = self.get_queryset()\nslug = self.kwargs.get(self.slug_url_kwarg)\nif slug is not None:\n slug_field = self.get_slug_field()\n queryset = queryset.filter(**{slug_field: slug})\n try:\n part = queryset.get()\n return part\n except queryset.model.MultipleObjectsReturned:\n ... | <|body_start_0|>
queryset = self.get_queryset()
slug = self.kwargs.get(self.slug_url_kwarg)
if slug is not None:
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})
try:
part = queryset.get()
retu... | Part detail view using the IPN (internal part number) of the Part as the lookup field | PartDetailFromIPN | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartDetailFromIPN:
"""Part detail view using the IPN (internal part number) of the Part as the lookup field"""
def get_object(self):
"""Return Part object which IPN field matches the slug value."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Attempt to... | stack_v2_sparse_classes_75kplus_train_072503 | 28,283 | permissive | [
{
"docstring": "Return Part object which IPN field matches the slug value.",
"name": "get_object",
"signature": "def get_object(self)"
},
{
"docstring": "Attempt to match slug to a Part, else redirect to PartIndex view.",
"name": "get",
"signature": "def get(self, request, *args, **kwarg... | 2 | stack_v2_sparse_classes_30k_train_017884 | Implement the Python class `PartDetailFromIPN` described below.
Class description:
Part detail view using the IPN (internal part number) of the Part as the lookup field
Method signatures and docstrings:
- def get_object(self): Return Part object which IPN field matches the slug value.
- def get(self, request, *args, ... | Implement the Python class `PartDetailFromIPN` described below.
Class description:
Part detail view using the IPN (internal part number) of the Part as the lookup field
Method signatures and docstrings:
- def get_object(self): Return Part object which IPN field matches the slug value.
- def get(self, request, *args, ... | 5a08ef908dd5344b4433436a4679d122f7f99e41 | <|skeleton|>
class PartDetailFromIPN:
"""Part detail view using the IPN (internal part number) of the Part as the lookup field"""
def get_object(self):
"""Return Part object which IPN field matches the slug value."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Attempt to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PartDetailFromIPN:
"""Part detail view using the IPN (internal part number) of the Part as the lookup field"""
def get_object(self):
"""Return Part object which IPN field matches the slug value."""
queryset = self.get_queryset()
slug = self.kwargs.get(self.slug_url_kwarg)
... | the_stack_v2_python_sparse | InvenTree/part/views.py | onurtatli/InvenTree | train | 0 |
4cdcd2254e219ca22f778cf162069424188aa01a | [
"super().__init__()\nself.in_dim = in_dim\nself.r_dim = r_dim\nself.attention_dims = attention_dims\nif probabilistic_dims is None:\n self.probabilistic_dims = [self.r_dim, self.r_dim]\nelse:\n self.probabilistic_dims = probabilistic_dims\nself.self_att = self_att\nself.self_attentive_network = SelfAttentiveV... | <|body_start_0|>
super().__init__()
self.in_dim = in_dim
self.r_dim = r_dim
self.attention_dims = attention_dims
if probabilistic_dims is None:
self.probabilistic_dims = [self.r_dim, self.r_dim]
else:
self.probabilistic_dims = probabilistic_dims
... | Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only. | AttentiveProbabilisticEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentiveProbabilisticEncoder:
"""Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only."""
def __init__(self, in_dim, r_dim, attention_dims, probabilistic_dims=None, self_att=True, min_var=0.001):... | stack_v2_sparse_classes_75kplus_train_072504 | 16,175 | no_license | [
{
"docstring": ":param in_dim: An integer describing the dimensionality of the input to the encoder; in this case the sum of x_dim and y_dim :param r_dim: An integer describing the dimensionality of the embedding, r_i :param encoder_n_hidden: An integer describing the number of hidden layers in the neural netwo... | 2 | stack_v2_sparse_classes_30k_train_042284 | Implement the Python class `AttentiveProbabilisticEncoder` described below.
Class description:
Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only.
Method signatures and docstrings:
- def __init__(self, in_dim, r_dim, att... | Implement the Python class `AttentiveProbabilisticEncoder` described below.
Class description:
Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only.
Method signatures and docstrings:
- def __init__(self, in_dim, r_dim, att... | de60f831ee082ab2ae232c498cf2755da7c14c27 | <|skeleton|>
class AttentiveProbabilisticEncoder:
"""Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only."""
def __init__(self, in_dim, r_dim, attention_dims, probabilistic_dims=None, self_att=True, min_var=0.001):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttentiveProbabilisticEncoder:
"""Attentive probabilistic encoder as implemented in the ANP paper, where it is described as the Latent Encoder. Includes option of self attention only."""
def __init__(self, in_dim, r_dim, attention_dims, probabilistic_dims=None, self_att=True, min_var=0.001):
""":... | the_stack_v2_python_sparse | models/networks/np_networks.py | PenelopeJones/neural_processes | train | 4 |
16dab4443bd2449796e5a4f4bb84c7febc15d049 | [
"self.ai_settings = ai_settings\nself.reset_stats()\nself.game_active = False\nself.scores_visible = False\nself.high_score = 0\nself.level = 1\nself.lives_left = self.ai_settings.number_lives\nself.high_scores_list = open('high_scores.txt', 'r')\nself.scores_list = []\nwhile True:\n self.current_score = self.hi... | <|body_start_0|>
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.scores_visible = False
self.high_score = 0
self.level = 1
self.lives_left = self.ai_settings.number_lives
self.high_scores_list = open('high_scores.txt', 'r')
... | Track statistics for Alien Invasion | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""Track statistics for Alien Invasion"""
def __init__(self, ai_settings):
"""Initialize statistics"""
<|body_0|>
def reset_stats(self):
"""Initialize statistics that can change during the game"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072505 | 1,659 | no_license | [
{
"docstring": "Initialize statistics",
"name": "__init__",
"signature": "def __init__(self, ai_settings)"
},
{
"docstring": "Initialize statistics that can change during the game",
"name": "reset_stats",
"signature": "def reset_stats(self)"
}
] | 2 | null | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Alien Invasion
Method signatures and docstrings:
- def __init__(self, ai_settings): Initialize statistics
- def reset_stats(self): Initialize statistics that can change during the game | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Alien Invasion
Method signatures and docstrings:
- def __init__(self, ai_settings): Initialize statistics
- def reset_stats(self): Initialize statistics that can change during the game
<|skeleton|>
class GameStats:
""... | 3de7b3a23cd24ba380bf3e00df0c558ab40c2128 | <|skeleton|>
class GameStats:
"""Track statistics for Alien Invasion"""
def __init__(self, ai_settings):
"""Initialize statistics"""
<|body_0|>
def reset_stats(self):
"""Initialize statistics that can change during the game"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameStats:
"""Track statistics for Alien Invasion"""
def __init__(self, ai_settings):
"""Initialize statistics"""
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = False
self.scores_visible = False
self.high_score = 0
self.level =... | the_stack_v2_python_sparse | venv/game_stats.py | john-shelton789/PacManPortal | train | 0 |
994759d9e670c492143de7d01e73649296e47679 | [
"self.models = models\nself.coord = coord\nself.orig_coord = deepcopy(coord)",
"T, R, pivot = fit_to_mean(models=self.models, coord=self.coord, centroid=params, verbosity=0)\nval = atomic_rmsd(self.coord)\nself.coord = deepcopy(self.orig_coord)\nreturn val"
] | <|body_start_0|>
self.models = models
self.coord = coord
self.orig_coord = deepcopy(coord)
<|end_body_0|>
<|body_start_1|>
T, R, pivot = fit_to_mean(models=self.models, coord=self.coord, centroid=params, verbosity=0)
val = atomic_rmsd(self.coord)
self.coord = deepcopy(se... | Class for finding the optimal pivot point for motions between the given models. | Pivot_finder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pivot_finder:
"""Class for finding the optimal pivot point for motions between the given models."""
def __init__(self, models, coord):
"""Set up the class for pivot point optimisation for an ensemble of structures. @keyword models: The list of models to use. If set to None, then all ... | stack_v2_sparse_classes_75kplus_train_072506 | 3,384 | no_license | [
{
"docstring": "Set up the class for pivot point optimisation for an ensemble of structures. @keyword models: The list of models to use. If set to None, then all models will be used. @type models: list of int or None @keyword coord: The array of molecular coordinates. The first dimension corresponds to the mode... | 2 | stack_v2_sparse_classes_30k_train_044113 | Implement the Python class `Pivot_finder` described below.
Class description:
Class for finding the optimal pivot point for motions between the given models.
Method signatures and docstrings:
- def __init__(self, models, coord): Set up the class for pivot point optimisation for an ensemble of structures. @keyword mod... | Implement the Python class `Pivot_finder` described below.
Class description:
Class for finding the optimal pivot point for motions between the given models.
Method signatures and docstrings:
- def __init__(self, models, coord): Set up the class for pivot point optimisation for an ensemble of structures. @keyword mod... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Pivot_finder:
"""Class for finding the optimal pivot point for motions between the given models."""
def __init__(self, models, coord):
"""Set up the class for pivot point optimisation for an ensemble of structures. @keyword models: The list of models to use. If set to None, then all ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pivot_finder:
"""Class for finding the optimal pivot point for motions between the given models."""
def __init__(self, models, coord):
"""Set up the class for pivot point optimisation for an ensemble of structures. @keyword models: The list of models to use. If set to None, then all models will b... | the_stack_v2_python_sparse | target_functions/ens_pivot_finder.py | jlec/relax | train | 4 |
a8ea3dae157cc11c9a635002a126dbbc8a299d79 | [
"errors = validate_party_key_pair_values(request)\nif errors:\n return error(400, '{} key missing'.format(', '.join(errors)))\ndata = request.get_json()\nif check_for_blanks(data):\n return error(400, '{} cannot be blank'.format(', '.join(check_for_blanks(data))))\nname = data.get('name')\nhqAddress = data.ge... | <|body_start_0|>
errors = validate_party_key_pair_values(request)
if errors:
return error(400, '{} key missing'.format(', '.join(errors)))
data = request.get_json()
if check_for_blanks(data):
return error(400, '{} cannot be blank'.format(', '.join(check_for_blanks... | Party API Endpoints | PartyEndPoint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartyEndPoint:
"""Party API Endpoints"""
def party():
"""Create party endpoint"""
<|body_0|>
def get_parties():
"""Get all parties endpoint"""
<|body_1|>
def get_specific_party(id):
"""Get a specific political party"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_072507 | 3,880 | permissive | [
{
"docstring": "Create party endpoint",
"name": "party",
"signature": "def party()"
},
{
"docstring": "Get all parties endpoint",
"name": "get_parties",
"signature": "def get_parties()"
},
{
"docstring": "Get a specific political party",
"name": "get_specific_party",
"sig... | 5 | stack_v2_sparse_classes_30k_train_013242 | Implement the Python class `PartyEndPoint` described below.
Class description:
Party API Endpoints
Method signatures and docstrings:
- def party(): Create party endpoint
- def get_parties(): Get all parties endpoint
- def get_specific_party(id): Get a specific political party
- def patch_party(id, name): Edit specifi... | Implement the Python class `PartyEndPoint` described below.
Class description:
Party API Endpoints
Method signatures and docstrings:
- def party(): Create party endpoint
- def get_parties(): Get all parties endpoint
- def get_specific_party(id): Get a specific political party
- def patch_party(id, name): Edit specifi... | f813c38a61aa281e4729c3ede0225fb603aaa088 | <|skeleton|>
class PartyEndPoint:
"""Party API Endpoints"""
def party():
"""Create party endpoint"""
<|body_0|>
def get_parties():
"""Get all parties endpoint"""
<|body_1|>
def get_specific_party(id):
"""Get a specific political party"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PartyEndPoint:
"""Party API Endpoints"""
def party():
"""Create party endpoint"""
errors = validate_party_key_pair_values(request)
if errors:
return error(400, '{} key missing'.format(', '.join(errors)))
data = request.get_json()
if check_for_blanks(dat... | the_stack_v2_python_sparse | app/api/v2/views/parties_views.py | kelvinbe/politico_platform_API | train | 0 |
50830ff154af20e2f581efa6f8121df3a594122b | [
"out = self.nanoutput()\ndffs = {}\nfor cs in config.stimuli():\n stim = self.analysis('stim_dff_%s' % cs)\n dffs[cs] = np.copy(stim) if stim is not None else None\n if np.sum(np.invert(np.isfinite(dffs[cs]))) > 4:\n stim = self.analysis('stim_dff_all_%s' % cs)\n dffs[cs] = np.copy(stim) if s... | <|body_start_0|>
out = self.nanoutput()
dffs = {}
for cs in config.stimuli():
stim = self.analysis('stim_dff_%s' % cs)
dffs[cs] = np.copy(stim) if stim is not None else None
if np.sum(np.invert(np.isfinite(dffs[cs]))) > 4:
stim = self.analysis(... | Sort | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sort:
def run(self, date):
"""Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values"""
<|body_0|>
def simple(dffs, preferred_order):
"""Return a simple sort based on preferred resp... | stack_v2_sparse_classes_75kplus_train_072508 | 2,623 | no_license | [
{
"docstring": "Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values",
"name": "run",
"signature": "def run(self, date)"
},
{
"docstring": "Return a simple sort based on preferred response category with an in... | 2 | stack_v2_sparse_classes_30k_train_051851 | Implement the Python class `Sort` described below.
Class description:
Implement the Sort class.
Method signatures and docstrings:
- def run(self, date): Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values
- def simple(dffs, prefe... | Implement the Python class `Sort` described below.
Class description:
Implement the Sort class.
Method signatures and docstrings:
- def run(self, date): Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values
- def simple(dffs, prefe... | c4e9699fb78db7bd7cc14bc1bd6bd7d2b4e3a16b | <|skeleton|>
class Sort:
def run(self, date):
"""Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values"""
<|body_0|>
def simple(dffs, preferred_order):
"""Return a simple sort based on preferred resp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sort:
def run(self, date):
"""Run all analyses and returns results in a dictionary. Parameters ---------- date : Date object Returns ------- dict All of the output values"""
out = self.nanoutput()
dffs = {}
for cs in config.stimuli():
stim = self.analysis('stim_dff_... | the_stack_v2_python_sparse | pool/analyses/sort.py | jzaremba/pool | train | 0 | |
6b1c63dcbf62cb9c56e782e98dc299aac98953b8 | [
"self.set_header('content-type', 'application/json')\ntry:\n incident_list = IncidentDao().get_incident_list()\n self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': incident_list}))\nexcept Exception as e:\n logger.error(e)\n self.process_error(400, 'fail to get incidents from database')",
"se... | <|body_start_0|>
self.set_header('content-type', 'application/json')
try:
incident_list = IncidentDao().get_incident_list()
self.finish(json_dumps({'status': 0, 'msg': 'ok', 'values': incident_list}))
except Exception as e:
logger.error(e)
self.pro... | IncidentListHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncidentListHandler:
def get(self):
"""list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions... | stack_v2_sparse_classes_75kplus_train_072509 | 20,674 | permissive | [
{
"docstring": "list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions/Error'",
"name": "get",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_048967 | Implement the Python class `IncidentListHandler` described below.
Class description:
Implement the IncidentListHandler class.
Method signatures and docstrings:
- def get(self): list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incident... | Implement the Python class `IncidentListHandler` described below.
Class description:
Implement the IncidentListHandler class.
Method signatures and docstrings:
- def get(self): list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incident... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class IncidentListHandler:
def get(self):
"""list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IncidentListHandler:
def get(self):
"""list all incidents @API summary: list all incidents notes: get details for incidents tags: - platform responses: '200': description: incidents schema: $ref: '#/definitions/Incident' default: description: Unexcepted error schema: $ref: '#/definitions/Error'"""
... | the_stack_v2_python_sparse | nebula/views/risk_incident.py | threathunterX/nebula_web | train | 2 | |
8d3c118a12c611f0920fa78ba72e8a550b9d02db | [
"cls.logger.debug('In GET: reqid = %s, parametricjob_id = %s', request_id, parametricjob_id)\nwith cherrypy.HTTPError.handle(ValueError, 400, 'Bad request_id: %r' % request_id):\n request_id = int(request_id)\nif parametricjob_id is not None:\n with cherrypy.HTTPError.handle(ValueError, 400, 'Bad parametricjo... | <|body_start_0|>
cls.logger.debug('In GET: reqid = %s, parametricjob_id = %s', request_id, parametricjob_id)
with cherrypy.HTTPError.handle(ValueError, 400, 'Bad request_id: %r' % request_id):
request_id = int(request_id)
if parametricjob_id is not None:
with cherrypy.HTT... | Parametric Jobs RESTful API. | ParametricJobsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParametricJobsAPI:
"""Parametric Jobs RESTful API."""
def GET(cls, request_id, parametricjob_id=None):
"""REST Get method. Returns all ParametricJobs for a given request id."""
<|body_0|>
def PUT(cls, request_id, parametricjob_id, reschedule):
"""REST Put method.... | stack_v2_sparse_classes_75kplus_train_072510 | 14,924 | permissive | [
{
"docstring": "REST Get method. Returns all ParametricJobs for a given request id.",
"name": "GET",
"signature": "def GET(cls, request_id, parametricjob_id=None)"
},
{
"docstring": "REST Put method.",
"name": "PUT",
"signature": "def PUT(cls, request_id, parametricjob_id, reschedule)"
... | 2 | stack_v2_sparse_classes_30k_train_009506 | Implement the Python class `ParametricJobsAPI` described below.
Class description:
Parametric Jobs RESTful API.
Method signatures and docstrings:
- def GET(cls, request_id, parametricjob_id=None): REST Get method. Returns all ParametricJobs for a given request id.
- def PUT(cls, request_id, parametricjob_id, reschedu... | Implement the Python class `ParametricJobsAPI` described below.
Class description:
Parametric Jobs RESTful API.
Method signatures and docstrings:
- def GET(cls, request_id, parametricjob_id=None): REST Get method. Returns all ParametricJobs for a given request id.
- def PUT(cls, request_id, parametricjob_id, reschedu... | 43225a155a985a7a56402df23dd550e48e22b436 | <|skeleton|>
class ParametricJobsAPI:
"""Parametric Jobs RESTful API."""
def GET(cls, request_id, parametricjob_id=None):
"""REST Get method. Returns all ParametricJobs for a given request id."""
<|body_0|>
def PUT(cls, request_id, parametricjob_id, reschedule):
"""REST Put method.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParametricJobsAPI:
"""Parametric Jobs RESTful API."""
def GET(cls, request_id, parametricjob_id=None):
"""REST Get method. Returns all ParametricJobs for a given request id."""
cls.logger.debug('In GET: reqid = %s, parametricjob_id = %s', request_id, parametricjob_id)
with cherryp... | the_stack_v2_python_sparse | productionsystem/webapp/services/RESTfulAPI.py | alexanderrichards/ProductionSystem | train | 0 |
2f451f5a058b17f29c47f3487fe409f45cde8135 | [
"result = set()\nresult.add(tuple())\n\ndef find_subsets(array):\n \"\"\" Adds all subsets of array to result.\n \"\"\"\n if not array:\n return\n result.add(tuple(array))\n for i in range(len(array)):\n find_subsets(array[:i] + array[i + 1:])\nfind_subsets(nums)\nreturn result"... | <|body_start_0|>
result = set()
result.add(tuple())
def find_subsets(array):
""" Adds all subsets of array to result.
"""
if not array:
return
result.add(tuple(array))
for i in range(len(array)):
... | SolutionLeetcode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionLeetcode:
def subsets_brute(self, nums):
"""Returns an array of tuples, where each tuple is a subset of original array nums."""
<|body_0|>
def subsets_brute(self, nums):
"""Returns an array of tuples, where each tuple is a subset of original array nums."""
... | stack_v2_sparse_classes_75kplus_train_072511 | 2,902 | no_license | [
{
"docstring": "Returns an array of tuples, where each tuple is a subset of original array nums.",
"name": "subsets_brute",
"signature": "def subsets_brute(self, nums)"
},
{
"docstring": "Returns an array of tuples, where each tuple is a subset of original array nums.",
"name": "subsets_brut... | 4 | stack_v2_sparse_classes_30k_train_047826 | Implement the Python class `SolutionLeetcode` described below.
Class description:
Implement the SolutionLeetcode class.
Method signatures and docstrings:
- def subsets_brute(self, nums): Returns an array of tuples, where each tuple is a subset of original array nums.
- def subsets_brute(self, nums): Returns an array ... | Implement the Python class `SolutionLeetcode` described below.
Class description:
Implement the SolutionLeetcode class.
Method signatures and docstrings:
- def subsets_brute(self, nums): Returns an array of tuples, where each tuple is a subset of original array nums.
- def subsets_brute(self, nums): Returns an array ... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class SolutionLeetcode:
def subsets_brute(self, nums):
"""Returns an array of tuples, where each tuple is a subset of original array nums."""
<|body_0|>
def subsets_brute(self, nums):
"""Returns an array of tuples, where each tuple is a subset of original array nums."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolutionLeetcode:
def subsets_brute(self, nums):
"""Returns an array of tuples, where each tuple is a subset of original array nums."""
result = set()
result.add(tuple())
def find_subsets(array):
""" Adds all subsets of array to result.
"""
... | the_stack_v2_python_sparse | Backtracking/subsets.py | vladn90/Algorithms | train | 0 | |
b744073ea85926a5d7a1e7064b47a907e428bff3 | [
"self.a = a\nself.m = m\nself.j = j",
"modificateur = -1\nd = PAS_CALCULE = 1000\n\ndef quotient_mois(m):\n qm, __osef__ = divmod(23 * m / 9, 1)\n return qm\n\ndef test_annee_bissextile_div_par_4(z):\n qa, __osef__ = divmod(z / 4, 1)\n return qa\n\ndef test_annee_bissextile_div_par_100(z):\n quotie... | <|body_start_0|>
self.a = a
self.m = m
self.j = j
<|end_body_0|>
<|body_start_1|>
modificateur = -1
d = PAS_CALCULE = 1000
def quotient_mois(m):
qm, __osef__ = divmod(23 * m / 9, 1)
return qm
def test_annee_bissextile_div_par_4(z):
... | CalculJourLundiADimanche | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalculJourLundiADimanche:
def __init__(self, a, m, j):
"""Constructor"""
<|body_0|>
def calcul(self):
"""Algorithme de Mike Keith wikipedia. https://fr.wikibooks.org/wiki/Curiosit%C3%A9s_math%C3%A9matiques/Trouver_le_jour_de_la_semaine_avec_une_date_donn%C3%A9e 0 = d... | stack_v2_sparse_classes_75kplus_train_072512 | 2,074 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, a, m, j)"
},
{
"docstring": "Algorithme de Mike Keith wikipedia. https://fr.wikibooks.org/wiki/Curiosit%C3%A9s_math%C3%A9matiques/Trouver_le_jour_de_la_semaine_avec_une_date_donn%C3%A9e 0 = dimanche 1 = lundi.... ... | 2 | null | Implement the Python class `CalculJourLundiADimanche` described below.
Class description:
Implement the CalculJourLundiADimanche class.
Method signatures and docstrings:
- def __init__(self, a, m, j): Constructor
- def calcul(self): Algorithme de Mike Keith wikipedia. https://fr.wikibooks.org/wiki/Curiosit%C3%A9s_mat... | Implement the Python class `CalculJourLundiADimanche` described below.
Class description:
Implement the CalculJourLundiADimanche class.
Method signatures and docstrings:
- def __init__(self, a, m, j): Constructor
- def calcul(self): Algorithme de Mike Keith wikipedia. https://fr.wikibooks.org/wiki/Curiosit%C3%A9s_mat... | 528433989ebfc54d0f65f3c321b95762cad62644 | <|skeleton|>
class CalculJourLundiADimanche:
def __init__(self, a, m, j):
"""Constructor"""
<|body_0|>
def calcul(self):
"""Algorithme de Mike Keith wikipedia. https://fr.wikibooks.org/wiki/Curiosit%C3%A9s_math%C3%A9matiques/Trouver_le_jour_de_la_semaine_avec_une_date_donn%C3%A9e 0 = d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalculJourLundiADimanche:
def __init__(self, a, m, j):
"""Constructor"""
self.a = a
self.m = m
self.j = j
def calcul(self):
"""Algorithme de Mike Keith wikipedia. https://fr.wikibooks.org/wiki/Curiosit%C3%A9s_math%C3%A9matiques/Trouver_le_jour_de_la_semaine_avec_un... | the_stack_v2_python_sparse | pkg_date_heure/pkg_Calculer_jour/calcul_jour_lundi_a_dimanche.py | ben5962/python_planning | train | 0 | |
b6f1641052400f5074e0e9ab484124dc6015fd23 | [
"b = cs.Board()\np = cs.LazyPlayer(b, dropped_steps=3)\nassert isinstance(p, cs.LazyPlayer)\nassert isinstance(p, cs.Player)",
"b = cs.Board()\np = cs.LazyPlayer(b)\np.move()"
] | <|body_start_0|>
b = cs.Board()
p = cs.LazyPlayer(b, dropped_steps=3)
assert isinstance(p, cs.LazyPlayer)
assert isinstance(p, cs.Player)
<|end_body_0|>
<|body_start_1|>
b = cs.Board()
p = cs.LazyPlayer(b)
p.move()
<|end_body_1|>
| TestLazyPlayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLazyPlayer:
def test_constructor(self):
"""LazyPlayer can be constructed."""
<|body_0|>
def test_move(self):
"""LazyPlayer can move."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
b = cs.Board()
p = cs.LazyPlayer(b, dropped_steps=3)
... | stack_v2_sparse_classes_75kplus_train_072513 | 5,004 | no_license | [
{
"docstring": "LazyPlayer can be constructed.",
"name": "test_constructor",
"signature": "def test_constructor(self)"
},
{
"docstring": "LazyPlayer can move.",
"name": "test_move",
"signature": "def test_move(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014538 | Implement the Python class `TestLazyPlayer` described below.
Class description:
Implement the TestLazyPlayer class.
Method signatures and docstrings:
- def test_constructor(self): LazyPlayer can be constructed.
- def test_move(self): LazyPlayer can move. | Implement the Python class `TestLazyPlayer` described below.
Class description:
Implement the TestLazyPlayer class.
Method signatures and docstrings:
- def test_constructor(self): LazyPlayer can be constructed.
- def test_move(self): LazyPlayer can move.
<|skeleton|>
class TestLazyPlayer:
def test_constructor(s... | 9bfa22c85866eeb019c2c24bc5bbfcd600fadcb5 | <|skeleton|>
class TestLazyPlayer:
def test_constructor(self):
"""LazyPlayer can be constructed."""
<|body_0|>
def test_move(self):
"""LazyPlayer can move."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestLazyPlayer:
def test_constructor(self):
"""LazyPlayer can be constructed."""
b = cs.Board()
p = cs.LazyPlayer(b, dropped_steps=3)
assert isinstance(p, cs.LazyPlayer)
assert isinstance(p, cs.Player)
def test_move(self):
"""LazyPlayer can move."""
... | the_stack_v2_python_sparse | src/YOUR_NAME_ex/pa02/test_base_pa02.py | pkhetland/INF200-2019-Exercises | train | 1 | |
e9a451f16b5dfa531807aedab5c83dc5c9a5f8a4 | [
"super(CouldNotPassStrategy, self).__init__(decision, member, bill)\nself._name = 'Could Not Pass'\nself._NOT_PASS_RATIO = 1.0",
"result = self._majority()\nif result == outcomes.AGN and self._could_not_pass():\n return self._set_decision(result)",
"if self._bill.vote_tally:\n return self._bill.vote_tally... | <|body_start_0|>
super(CouldNotPassStrategy, self).__init__(decision, member, bill)
self._name = 'Could Not Pass'
self._NOT_PASS_RATIO = 1.0
<|end_body_0|>
<|body_start_1|>
result = self._majority()
if result == outcomes.AGN and self._could_not_pass():
return self._s... | From Professor Slade's Lisp code: ================================================================== 9 It couldn't pass [C] (IT-COULD-NOT-PASS) Remarks: Do not waste a vote on a symbolic measure. Better to build credibility and a consensus for the future. Quote: Why waste a vote on a measure that has so little chance o... | CouldNotPassStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouldNotPassStrategy:
"""From Professor Slade's Lisp code: ================================================================== 9 It couldn't pass [C] (IT-COULD-NOT-PASS) Remarks: Do not waste a vote on a symbolic measure. Better to build credibility and a consensus for the future. Quote: Why waste... | stack_v2_sparse_classes_75kplus_train_072514 | 3,853 | no_license | [
{
"docstring": "Constructs a new ChangeOfHeartStrategy. Arguments: decision: The Decision object the Strategy will attempt to compute a result for. member: A Member object of the member who is deciding on the bill bill: A Bill object of the bill being decided upon.",
"name": "__init__",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_018566 | Implement the Python class `CouldNotPassStrategy` described below.
Class description:
From Professor Slade's Lisp code: ================================================================== 9 It couldn't pass [C] (IT-COULD-NOT-PASS) Remarks: Do not waste a vote on a symbolic measure. Better to build credibility and a con... | Implement the Python class `CouldNotPassStrategy` described below.
Class description:
From Professor Slade's Lisp code: ================================================================== 9 It couldn't pass [C] (IT-COULD-NOT-PASS) Remarks: Do not waste a vote on a symbolic measure. Better to build credibility and a con... | 6df6e0ba491a839908ddcebe7feed9bff0f4db4d | <|skeleton|>
class CouldNotPassStrategy:
"""From Professor Slade's Lisp code: ================================================================== 9 It couldn't pass [C] (IT-COULD-NOT-PASS) Remarks: Do not waste a vote on a symbolic measure. Better to build credibility and a consensus for the future. Quote: Why waste... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CouldNotPassStrategy:
"""From Professor Slade's Lisp code: ================================================================== 9 It couldn't pass [C] (IT-COULD-NOT-PASS) Remarks: Do not waste a vote on a symbolic measure. Better to build credibility and a consensus for the future. Quote: Why waste a vote on a ... | the_stack_v2_python_sparse | src/classes/strategies/could_not_pass_strategy.py | WEB3-GForce/VOTE | train | 4 |
3f568d9ec724a72d090dc6b6b64677a7114ebe44 | [
"with open(fname, 'r') as f:\n self.alpha = array([float64(L.split(',')) for L in f.readlines()])\nself.sigmaIdx = 5\nself.logSigmaIdx = 5",
"self.pressure = pressure\nself.temperature = temperature\nn = self.alpha.shape[1]\nself.p = sum(self.alpha * (log(self.pressure) ** arange(n))[newaxis, ...], axis=1)\nse... | <|body_start_0|>
with open(fname, 'r') as f:
self.alpha = array([float64(L.split(',')) for L in f.readlines()])
self.sigmaIdx = 5
self.logSigmaIdx = 5
<|end_body_0|>
<|body_start_1|>
self.pressure = pressure
self.temperature = temperature
n = self.alpha.shape... | dangolaViscosity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dangolaViscosity:
def __init__(self, fname):
"""read in the polynomial coeffs from the csv"""
<|body_0|>
def __call__(self, pressure, temperature=linspace(0, 20000, 201)):
"""compute the parameters at the given temperature and pressure pressure in atmospheres"""
... | stack_v2_sparse_classes_75kplus_train_072515 | 14,107 | no_license | [
{
"docstring": "read in the polynomial coeffs from the csv",
"name": "__init__",
"signature": "def __init__(self, fname)"
},
{
"docstring": "compute the parameters at the given temperature and pressure pressure in atmospheres",
"name": "__call__",
"signature": "def __call__(self, pressur... | 2 | stack_v2_sparse_classes_30k_train_019360 | Implement the Python class `dangolaViscosity` described below.
Class description:
Implement the dangolaViscosity class.
Method signatures and docstrings:
- def __init__(self, fname): read in the polynomial coeffs from the csv
- def __call__(self, pressure, temperature=linspace(0, 20000, 201)): compute the parameters ... | Implement the Python class `dangolaViscosity` described below.
Class description:
Implement the dangolaViscosity class.
Method signatures and docstrings:
- def __init__(self, fname): read in the polynomial coeffs from the csv
- def __call__(self, pressure, temperature=linspace(0, 20000, 201)): compute the parameters ... | 1886f25add30570eb3c3b3d40342de5e2d83d344 | <|skeleton|>
class dangolaViscosity:
def __init__(self, fname):
"""read in the polynomial coeffs from the csv"""
<|body_0|>
def __call__(self, pressure, temperature=linspace(0, 20000, 201)):
"""compute the parameters at the given temperature and pressure pressure in atmospheres"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class dangolaViscosity:
def __init__(self, fname):
"""read in the polynomial coeffs from the csv"""
with open(fname, 'r') as f:
self.alpha = array([float64(L.split(',')) for L in f.readlines()])
self.sigmaIdx = 5
self.logSigmaIdx = 5
def __call__(self, pressure, temp... | the_stack_v2_python_sparse | gasModel/scr_dangola_air_parameters_pickling.py | mcannamela/mike-cs-code | train | 0 | |
7131cc49b4cd2839bd16d7ead5d97b84962ec609 | [
"self.name = str(name)\nself.default_units = get_default_units(config)\ncode_exceptions_def = config.find('LateralityCodeExceptions')\nlaterality_exceptions = get_laterality_exceptions(code_exceptions_def)\nself.data_elements = {'Plan Property': dict(), 'Structure': dict(), 'Reference Point': dict()}\ndvh_data = ge... | <|body_start_0|>
self.name = str(name)
self.default_units = get_default_units(config)
code_exceptions_def = config.find('LateralityCodeExceptions')
laterality_exceptions = get_laterality_exceptions(code_exceptions_def)
self.data_elements = {'Plan Property': dict(), 'Structure': d... | Contains all plan elements for a single plan. Class Attributes: default_units: type dict The default units for plan elements. Key-Value pairs are: 'DoseUnit': One of ('Gy', 'cGy', '%') 'VolumeUnit': One of ('cc', '%') 'DistanceUnit': 'cm') Instance Attributes: dvh_data_source: type Path The path to a file containing th... | Plan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plan:
"""Contains all plan elements for a single plan. Class Attributes: default_units: type dict The default units for plan elements. Key-Value pairs are: 'DoseUnit': One of ('Gy', 'cGy', '%') 'VolumeUnit': One of ('cc', '%') 'DistanceUnit': 'cm') Instance Attributes: dvh_data_source: type Path ... | stack_v2_sparse_classes_75kplus_train_072516 | 41,645 | no_license | [
{
"docstring": "Load the plan data. Arguments: config {ET.Element} -- An XML element containing default paths, settings and tables. Keyword Arguments: name {str} -- The name of the plan. Default is 'Plan' dvh_file {DvhSource} -- A DvhFile object, the path, to a .dvh file, or the name of a .dvh file in the defau... | 6 | stack_v2_sparse_classes_30k_train_002872 | Implement the Python class `Plan` described below.
Class description:
Contains all plan elements for a single plan. Class Attributes: default_units: type dict The default units for plan elements. Key-Value pairs are: 'DoseUnit': One of ('Gy', 'cGy', '%') 'VolumeUnit': One of ('cc', '%') 'DistanceUnit': 'cm') Instance ... | Implement the Python class `Plan` described below.
Class description:
Contains all plan elements for a single plan. Class Attributes: default_units: type dict The default units for plan elements. Key-Value pairs are: 'DoseUnit': One of ('Gy', 'cGy', '%') 'VolumeUnit': One of ('cc', '%') 'DistanceUnit': 'cm') Instance ... | b14ab5f7fa54592086f692dc8a0cdbf0beb54a22 | <|skeleton|>
class Plan:
"""Contains all plan elements for a single plan. Class Attributes: default_units: type dict The default units for plan elements. Key-Value pairs are: 'DoseUnit': One of ('Gy', 'cGy', '%') 'VolumeUnit': One of ('cc', '%') 'DistanceUnit': 'cm') Instance Attributes: dvh_data_source: type Path ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Plan:
"""Contains all plan elements for a single plan. Class Attributes: default_units: type dict The default units for plan elements. Key-Value pairs are: 'DoseUnit': One of ('Gy', 'cGy', '%') 'VolumeUnit': One of ('cc', '%') 'DistanceUnit': 'cm') Instance Attributes: dvh_data_source: type Path The path to a... | the_stack_v2_python_sparse | sabr_plan_report/plan_data.py | GregSal/PlanEvaluation | train | 0 |
1a327a9baf0e8679700c937f96f46ea003a09a11 | [
"self.drop_pdbs_if_exists = drop_pdbs_if_exists\nself.existing_cdb = existing_cdb\nself.include_in_restore = include_in_restore\nself.pdb_entity_info_vec = pdb_entity_info_vec\nself.rename_pdb_map = rename_pdb_map",
"if dictionary is None:\n return None\ndrop_pdbs_if_exists = dictionary.get('dropPdbsIfExists')... | <|body_start_0|>
self.drop_pdbs_if_exists = drop_pdbs_if_exists
self.existing_cdb = existing_cdb
self.include_in_restore = include_in_restore
self.pdb_entity_info_vec = pdb_entity_info_vec
self.rename_pdb_map = rename_pdb_map
<|end_body_0|>
<|body_start_1|>
if dictionary... | Implementation of the 'PDBRestoreParam' model. TODO: type description here. Attributes: drop_pdbs_if_exists (bool): During the restore workflow, drop the pdb if the same name pdb exists. existing_cdb (bool): Restore given list of pdbs to an existing CDB. include_in_restore (bool): Whether or not to restore the PDB when... | PDBRestoreParam | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDBRestoreParam:
"""Implementation of the 'PDBRestoreParam' model. TODO: type description here. Attributes: drop_pdbs_if_exists (bool): During the restore workflow, drop the pdb if the same name pdb exists. existing_cdb (bool): Restore given list of pdbs to an existing CDB. include_in_restore (bo... | stack_v2_sparse_classes_75kplus_train_072517 | 3,630 | permissive | [
{
"docstring": "Constructor for the PDBRestoreParam class",
"name": "__init__",
"signature": "def __init__(self, drop_pdbs_if_exists=None, existing_cdb=None, include_in_restore=None, pdb_entity_info_vec=None, rename_pdb_map=None)"
},
{
"docstring": "Creates an instance of this model from a dicti... | 2 | stack_v2_sparse_classes_30k_train_007806 | Implement the Python class `PDBRestoreParam` described below.
Class description:
Implementation of the 'PDBRestoreParam' model. TODO: type description here. Attributes: drop_pdbs_if_exists (bool): During the restore workflow, drop the pdb if the same name pdb exists. existing_cdb (bool): Restore given list of pdbs to ... | Implement the Python class `PDBRestoreParam` described below.
Class description:
Implementation of the 'PDBRestoreParam' model. TODO: type description here. Attributes: drop_pdbs_if_exists (bool): During the restore workflow, drop the pdb if the same name pdb exists. existing_cdb (bool): Restore given list of pdbs to ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PDBRestoreParam:
"""Implementation of the 'PDBRestoreParam' model. TODO: type description here. Attributes: drop_pdbs_if_exists (bool): During the restore workflow, drop the pdb if the same name pdb exists. existing_cdb (bool): Restore given list of pdbs to an existing CDB. include_in_restore (bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PDBRestoreParam:
"""Implementation of the 'PDBRestoreParam' model. TODO: type description here. Attributes: drop_pdbs_if_exists (bool): During the restore workflow, drop the pdb if the same name pdb exists. existing_cdb (bool): Restore given list of pdbs to an existing CDB. include_in_restore (bool): Whether ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pdb_restore_param.py | cohesity/management-sdk-python | train | 24 |
a727fe440553de8b4097b679686bcf767ac28e5c | [
"stacks = Stack.objects.all()\nprofile = Profile.objects.get(user=request.auth.user)\ncustomer = Customer.objects.get(profile=profile)\nif customer is not None:\n stacks = stacks.filter(customer_id=customer)\nserializer = StackSerializer(stacks, many=True, context={'request': request})\nreturn Response(serialize... | <|body_start_0|>
stacks = Stack.objects.all()
profile = Profile.objects.get(user=request.auth.user)
customer = Customer.objects.get(profile=profile)
if customer is not None:
stacks = stacks.filter(customer_id=customer)
serializer = StackSerializer(stacks, many=True, c... | Fullstack shops | Stacks | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stacks:
"""Fullstack shops"""
def list(self, request):
"""Handle GET requests to get all stacks for current customer Returns: Response -- JSON serialized list of stacks"""
<|body_0|>
def create(self, request):
"""Handle POST operations"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_072518 | 2,729 | no_license | [
{
"docstring": "Handle GET requests to get all stacks for current customer Returns: Response -- JSON serialized list of stacks",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Handle POST operations",
"name": "create",
"signature": "def create(self, request)"
... | 3 | stack_v2_sparse_classes_30k_train_042413 | Implement the Python class `Stacks` described below.
Class description:
Fullstack shops
Method signatures and docstrings:
- def list(self, request): Handle GET requests to get all stacks for current customer Returns: Response -- JSON serialized list of stacks
- def create(self, request): Handle POST operations
- def ... | Implement the Python class `Stacks` described below.
Class description:
Fullstack shops
Method signatures and docstrings:
- def list(self, request): Handle GET requests to get all stacks for current customer Returns: Response -- JSON serialized list of stacks
- def create(self, request): Handle POST operations
- def ... | ea345ab516efcfd893dd2fc2fae0fe2d7c33a905 | <|skeleton|>
class Stacks:
"""Fullstack shops"""
def list(self, request):
"""Handle GET requests to get all stacks for current customer Returns: Response -- JSON serialized list of stacks"""
<|body_0|>
def create(self, request):
"""Handle POST operations"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Stacks:
"""Fullstack shops"""
def list(self, request):
"""Handle GET requests to get all stacks for current customer Returns: Response -- JSON serialized list of stacks"""
stacks = Stack.objects.all()
profile = Profile.objects.get(user=request.auth.user)
customer = Custome... | the_stack_v2_python_sparse | server/fullstackapi/views/stack.py | atphy/fullstack | train | 0 |
97a7a71507640e4392b8ba029febfab9a047e027 | [
"Module.__init__(self, **kws)\nself.images = []\nself.x, self.y, self.z = (0, 0, 0)\nself.extent = None\nself.running = 0\nself.depth = 8\nself.reset()",
"Module.reset(self)\nself.preview = None\nself.intensityTransferFunctions = []\nself.extent = None",
"Module.addInput(self, dataunit, data)\nsettings = dataun... | <|body_start_0|>
Module.__init__(self, **kws)
self.images = []
self.x, self.y, self.z = (0, 0, 0)
self.extent = None
self.running = 0
self.depth = 8
self.reset()
<|end_body_0|>
<|body_start_1|>
Module.reset(self)
self.preview = None
self.i... | Process a dataunit using an intensity transfer funtion | Adjust | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adjust:
"""Process a dataunit using an intensity transfer funtion"""
def __init__(self, **kws):
"""Initialization"""
<|body_0|>
def reset(self):
"""Resets the module to initial state. This method is used mainly when doing previews, when the parameters that contro... | stack_v2_sparse_classes_75kplus_train_072519 | 3,725 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, **kws)"
},
{
"docstring": "Resets the module to initial state. This method is used mainly when doing previews, when the parameters that control the colocalization are changed and the preview data becomes invali... | 5 | stack_v2_sparse_classes_30k_train_023260 | Implement the Python class `Adjust` described below.
Class description:
Process a dataunit using an intensity transfer funtion
Method signatures and docstrings:
- def __init__(self, **kws): Initialization
- def reset(self): Resets the module to initial state. This method is used mainly when doing previews, when the p... | Implement the Python class `Adjust` described below.
Class description:
Process a dataunit using an intensity transfer funtion
Method signatures and docstrings:
- def __init__(self, **kws): Initialization
- def reset(self): Resets the module to initial state. This method is used mainly when doing previews, when the p... | ea8bafa073de5090bd8f83fb4f5ca16669d0211f | <|skeleton|>
class Adjust:
"""Process a dataunit using an intensity transfer funtion"""
def __init__(self, **kws):
"""Initialization"""
<|body_0|>
def reset(self):
"""Resets the module to initial state. This method is used mainly when doing previews, when the parameters that contro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Adjust:
"""Process a dataunit using an intensity transfer funtion"""
def __init__(self, **kws):
"""Initialization"""
Module.__init__(self, **kws)
self.images = []
self.x, self.y, self.z = (0, 0, 0)
self.extent = None
self.running = 0
self.depth = 8
... | the_stack_v2_python_sparse | Graphs/LX-2/molecule_otsu = False/BioImageXD-1.0/Modules/Task/Adjust/Adjust.py | giacomo21/Image-analysis | train | 1 |
20ea00ae97c2606337ef98005649db73c71547c2 | [
"resource_args.AddStreamObjectResourceArg(parser)\nobject_identifier_parser = parser.add_group(required=True, mutex=True)\nso_flags.AddOracleObjectIdentifier(object_identifier_parser)\nso_flags.AddMysqlObjectIdentifier(object_identifier_parser)\nso_flags.AddPostgresqlObjectIdentifier(object_identifier_parser)",
"... | <|body_start_0|>
resource_args.AddStreamObjectResourceArg(parser)
object_identifier_parser = parser.add_group(required=True, mutex=True)
so_flags.AddOracleObjectIdentifier(object_identifier_parser)
so_flags.AddMysqlObjectIdentifier(object_identifier_parser)
so_flags.AddPostgresql... | Lookup a Datastream stream object. | Lookup | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lookup:
"""Lookup a Datastream stream object."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed."... | stack_v2_sparse_classes_75kplus_train_072520 | 3,006 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_044663 | Implement the Python class `Lookup` described below.
Class description:
Lookup a Datastream stream object.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command li... | Implement the Python class `Lookup` described below.
Class description:
Lookup a Datastream stream object.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command li... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Lookup:
"""Lookup a Datastream stream object."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lookup:
"""Lookup a Datastream stream object."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed."""
re... | the_stack_v2_python_sparse | lib/surface/datastream/objects/lookup.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
3824000ae199af7ff144cdacf11ccae3dbfd895e | [
"args = []\nfor item in self.get_query_set().all().values('target', 'value', 'kind'):\n key = '{target}__{kindfunc}'.format(target=item['target'], kindfunc=item['kind'])\n args.append({key: item['value']})\nreturn tuple(args)",
"args = []\nfor item in self.get_query_set().all().values('target', 'value', 'ki... | <|body_start_0|>
args = []
for item in self.get_query_set().all().values('target', 'value', 'kind'):
key = '{target}__{kindfunc}'.format(target=item['target'], kindfunc=item['kind'])
args.append({key: item['value']})
return tuple(args)
<|end_body_0|>
<|body_start_1|>
... | FilterEntry manager | FilterEntryManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterEntryManager:
"""FilterEntry manager"""
def get_filters_kwargs(self):
"""Return filters as a tuple of dicts kwargs"""
<|body_0|>
def get_filters(self):
"""Return filters as a tuple of tuples (target, pattern, kind)"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_072521 | 9,169 | permissive | [
{
"docstring": "Return filters as a tuple of dicts kwargs",
"name": "get_filters_kwargs",
"signature": "def get_filters_kwargs(self)"
},
{
"docstring": "Return filters as a tuple of tuples (target, pattern, kind)",
"name": "get_filters",
"signature": "def get_filters(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017103 | Implement the Python class `FilterEntryManager` described below.
Class description:
FilterEntry manager
Method signatures and docstrings:
- def get_filters_kwargs(self): Return filters as a tuple of dicts kwargs
- def get_filters(self): Return filters as a tuple of tuples (target, pattern, kind) | Implement the Python class `FilterEntryManager` described below.
Class description:
FilterEntry manager
Method signatures and docstrings:
- def get_filters_kwargs(self): Return filters as a tuple of dicts kwargs
- def get_filters(self): Return filters as a tuple of tuples (target, pattern, kind)
<|skeleton|>
class F... | 4a24104ad754f0e08ace4fe7371a713b3812d8bd | <|skeleton|>
class FilterEntryManager:
"""FilterEntry manager"""
def get_filters_kwargs(self):
"""Return filters as a tuple of dicts kwargs"""
<|body_0|>
def get_filters(self):
"""Return filters as a tuple of tuples (target, pattern, kind)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilterEntryManager:
"""FilterEntry manager"""
def get_filters_kwargs(self):
"""Return filters as a tuple of dicts kwargs"""
args = []
for item in self.get_query_set().all().values('target', 'value', 'kind'):
key = '{target}__{kindfunc}'.format(target=item['target'], ki... | the_stack_v2_python_sparse | djangotribune/models.py | sveetch/djangotribune | train | 8 |
49acd97c978a8494e0c1aa453a56a026bf480c2a | [
"super(UniformList, self).__init__(default=default, column_name=column_name)\nself.datatype = datatype\nself.translator = UniformListTranslator(self.datatype.translator)",
"dt = deepcopy(self.datatype)\ndt._index = idx\nreturn dt"
] | <|body_start_0|>
super(UniformList, self).__init__(default=default, column_name=column_name)
self.datatype = datatype
self.translator = UniformListTranslator(self.datatype.translator)
<|end_body_0|>
<|body_start_1|>
dt = deepcopy(self.datatype)
dt._index = idx
return dt
... | A class to represent Lists of entirely the same datatype The Base List class uses a Guesser to try and determine the datatype to use for the each item in the array. A UniformList does not need to guess, since the datatype is consistent and stored as an attribute | UniformList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniformList:
"""A class to represent Lists of entirely the same datatype The Base List class uses a Guesser to try and determine the datatype to use for the each item in the array. A UniformList does not need to guess, since the datatype is consistent and stored as an attribute"""
def __init... | stack_v2_sparse_classes_75kplus_train_072522 | 1,571 | permissive | [
{
"docstring": "constructor for UniformList Parameters: datatype: Any DynamoDataType that each item in the List will be default: a default value for the column. It can be a value or function column_name: a string defining the name of the column on the table",
"name": "__init__",
"signature": "def __init... | 2 | stack_v2_sparse_classes_30k_train_026406 | Implement the Python class `UniformList` described below.
Class description:
A class to represent Lists of entirely the same datatype The Base List class uses a Guesser to try and determine the datatype to use for the each item in the array. A UniformList does not need to guess, since the datatype is consistent and st... | Implement the Python class `UniformList` described below.
Class description:
A class to represent Lists of entirely the same datatype The Base List class uses a Guesser to try and determine the datatype to use for the each item in the array. A UniformList does not need to guess, since the datatype is consistent and st... | e97c0baa42c4bdfb10bbe3b4b859873e3d50aa3a | <|skeleton|>
class UniformList:
"""A class to represent Lists of entirely the same datatype The Base List class uses a Guesser to try and determine the datatype to use for the each item in the array. A UniformList does not need to guess, since the datatype is consistent and stored as an attribute"""
def __init... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniformList:
"""A class to represent Lists of entirely the same datatype The Base List class uses a Guesser to try and determine the datatype to use for the each item in the array. A UniformList does not need to guess, since the datatype is consistent and stored as an attribute"""
def __init__(self, data... | the_stack_v2_python_sparse | cerami/datatype/uniform_list.py | gummybuns/cerami | train | 0 |
0818e254432373c532faf9115e7249289bd46415 | [
"self.cbc_api = cbc_api\nself.shas = shas\nself.expiration_seconds = expiration_seconds\nself.found = []\nself.not_found = []\nself.attempt_num = 0",
"body = {'sha256': self.shas, 'expiration_seconds': self.expiration_seconds}\nurl = self.urlobject.format(self.cbc_api.credentials.org_key)\ndownload = self.cbc_api... | <|body_start_0|>
self.cbc_api = cbc_api
self.shas = shas
self.expiration_seconds = expiration_seconds
self.found = []
self.not_found = []
self.attempt_num = 0
<|end_body_0|>
<|body_start_1|>
body = {'sha256': self.shas, 'expiration_seconds': self.expiration_secon... | Values and function to redownload any hashes that experienced an error during the initial download attempt. Args: cbc_api (cbc_sdk.CBCloudAPI): Carbon Black Cloud API object. shas (List[str]): hashes to be redownloaded. expiration_seconds (int): Desired timeout for AWS links to binaries. Attributes: urlobject (str): Ca... | RedownloadHashes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedownloadHashes:
"""Values and function to redownload any hashes that experienced an error during the initial download attempt. Args: cbc_api (cbc_sdk.CBCloudAPI): Carbon Black Cloud API object. shas (List[str]): hashes to be redownloaded. expiration_seconds (int): Desired timeout for AWS links ... | stack_v2_sparse_classes_75kplus_train_072523 | 8,495 | permissive | [
{
"docstring": "Redownload Hashes constructor",
"name": "__init__",
"signature": "def __init__(self, cbc_api, shas, expiration_seconds)"
},
{
"docstring": "Attempts to redownload hashes up to `RETRY_LIMIT` times before exiting.",
"name": "redownload",
"signature": "def redownload(self)"
... | 2 | stack_v2_sparse_classes_30k_train_043481 | Implement the Python class `RedownloadHashes` described below.
Class description:
Values and function to redownload any hashes that experienced an error during the initial download attempt. Args: cbc_api (cbc_sdk.CBCloudAPI): Carbon Black Cloud API object. shas (List[str]): hashes to be redownloaded. expiration_second... | Implement the Python class `RedownloadHashes` described below.
Class description:
Values and function to redownload any hashes that experienced an error during the initial download attempt. Args: cbc_api (cbc_sdk.CBCloudAPI): Carbon Black Cloud API object. shas (List[str]): hashes to be redownloaded. expiration_second... | 92c90b80e3c3e0b5c2473ef2086d2ce2fb651db4 | <|skeleton|>
class RedownloadHashes:
"""Values and function to redownload any hashes that experienced an error during the initial download attempt. Args: cbc_api (cbc_sdk.CBCloudAPI): Carbon Black Cloud API object. shas (List[str]): hashes to be redownloaded. expiration_seconds (int): Desired timeout for AWS links ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedownloadHashes:
"""Values and function to redownload any hashes that experienced an error during the initial download attempt. Args: cbc_api (cbc_sdk.CBCloudAPI): Carbon Black Cloud API object. shas (List[str]): hashes to be redownloaded. expiration_seconds (int): Desired timeout for AWS links to binaries. ... | the_stack_v2_python_sparse | src/cbc_binary_toolkit/ubs.py | carbonblack/cbc-binary-toolkit | train | 10 |
6c0abc2e2f0cbefc9e52a42b3ee4fcdd8625ddf0 | [
"if request.user.is_superuser:\n departments = Department.objects.filter()\nelse:\n departments = Department.objects.filter(adminuserinformation__user=request.user)\nactivitys = []\nfor activity in Activity.objects.filter(department__in=departments).order_by('zipcode'):\n activitys.append((str(activity.pk)... | <|body_start_0|>
if request.user.is_superuser:
departments = Department.objects.filter()
else:
departments = Department.objects.filter(adminuserinformation__user=request.user)
activitys = []
for activity in Activity.objects.filter(department__in=departments).order... | ActivivtyInviteActivityListFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivivtyInviteActivityListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in t... | stack_v2_sparse_classes_75kplus_train_072524 | 45,186 | no_license | [
{
"docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.",
"name": "lookups",
"signature": "def lookups(self, request,... | 2 | stack_v2_sparse_classes_30k_train_000089 | Implement the Python class `ActivivtyInviteActivityListFilter` described below.
Class description:
Implement the ActivivtyInviteActivityListFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the op... | Implement the Python class `ActivivtyInviteActivityListFilter` described below.
Class description:
Implement the ActivivtyInviteActivityListFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the op... | 69dfbb0f2d947418112a1af631275ee598743fff | <|skeleton|>
class ActivivtyInviteActivityListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivivtyInviteActivityListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sideb... | the_stack_v2_python_sparse | members/admin.py | sunenilausen/forenings_medlemmer | train | 0 | |
aa44665a5ea0f8888c9e8c3f99ed0c0392de6291 | [
"self.id = host_id\nself.cluster_name = None\nhost_file_path = fs.join(introspection.pts_user_dir, 'hosts', host_id + '.cfg')\nif not os.path.isfile(host_file_path):\n raise ValueError('The configuration settings for remote host ' + host_id + ' could not be found in the PTS/user/hosts directory')\nconfig = confi... | <|body_start_0|>
self.id = host_id
self.cluster_name = None
host_file_path = fs.join(introspection.pts_user_dir, 'hosts', host_id + '.cfg')
if not os.path.isfile(host_file_path):
raise ValueError('The configuration settings for remote host ' + host_id + ' could not be found i... | This class ... | Host | [
"MIT",
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Host:
"""This class ..."""
def __init__(self, host_id, cluster=None):
"""The constructor ... :param host_id: :param cluster: :return:"""
<|body_0|>
def system_name(self):
"""This function ... :return:"""
<|body_1|>
def requires_vpn(self):
"""... | stack_v2_sparse_classes_75kplus_train_072525 | 7,356 | permissive | [
{
"docstring": "The constructor ... :param host_id: :param cluster: :return:",
"name": "__init__",
"signature": "def __init__(self, host_id, cluster=None)"
},
{
"docstring": "This function ... :return:",
"name": "system_name",
"signature": "def system_name(self)"
},
{
"docstring"... | 3 | null | Implement the Python class `Host` described below.
Class description:
This class ...
Method signatures and docstrings:
- def __init__(self, host_id, cluster=None): The constructor ... :param host_id: :param cluster: :return:
- def system_name(self): This function ... :return:
- def requires_vpn(self): This function .... | Implement the Python class `Host` described below.
Class description:
This class ...
Method signatures and docstrings:
- def __init__(self, host_id, cluster=None): The constructor ... :param host_id: :param cluster: :return:
- def system_name(self): This function ... :return:
- def requires_vpn(self): This function .... | 62b2339beb2eb956565e1605d44d92f934361ad7 | <|skeleton|>
class Host:
"""This class ..."""
def __init__(self, host_id, cluster=None):
"""The constructor ... :param host_id: :param cluster: :return:"""
<|body_0|>
def system_name(self):
"""This function ... :return:"""
<|body_1|>
def requires_vpn(self):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Host:
"""This class ..."""
def __init__(self, host_id, cluster=None):
"""The constructor ... :param host_id: :param cluster: :return:"""
self.id = host_id
self.cluster_name = None
host_file_path = fs.join(introspection.pts_user_dir, 'hosts', host_id + '.cfg')
if no... | the_stack_v2_python_sparse | CAAPR/CAAPR_AstroMagic/PTS/pts/core/basics/host.py | Stargrazer82301/CAAPR | train | 8 |
d913dc706a20de4948d0623c829250a6e5df2477 | [
"self.linksUrl = 'http://blogsearch.google.com/changes.xml?last=120'\nself.rxUrls = re.compile('url=\"([^\"]*?)\"')\nself.selfPath = os.path.dirname(__file__)\nself.linksFileName = os.path.join(self.selfPath, 'links.txt')\nself.filtersFileName = os.path.join(self.selfPath, 'filters.txt')\nself.linksList = []\nif os... | <|body_start_0|>
self.linksUrl = 'http://blogsearch.google.com/changes.xml?last=120'
self.rxUrls = re.compile('url="([^"]*?)"')
self.selfPath = os.path.dirname(__file__)
self.linksFileName = os.path.join(self.selfPath, 'links.txt')
self.filtersFileName = os.path.join(self.selfPat... | Hrefer v.6.0 | Hrefer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hrefer:
"""Hrefer v.6.0"""
def __init__(self):
"""Инициализация"""
<|body_0|>
def _GetHost(self, url):
"""Получаем хост по урлу"""
<|body_1|>
def Start(self):
"""Запускаем парсинг"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072526 | 2,310 | no_license | [
{
"docstring": "Инициализация",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Получаем хост по урлу",
"name": "_GetHost",
"signature": "def _GetHost(self, url)"
},
{
"docstring": "Запускаем парсинг",
"name": "Start",
"signature": "def Start(self... | 3 | null | Implement the Python class `Hrefer` described below.
Class description:
Hrefer v.6.0
Method signatures and docstrings:
- def __init__(self): Инициализация
- def _GetHost(self, url): Получаем хост по урлу
- def Start(self): Запускаем парсинг | Implement the Python class `Hrefer` described below.
Class description:
Hrefer v.6.0
Method signatures and docstrings:
- def __init__(self): Инициализация
- def _GetHost(self, url): Получаем хост по урлу
- def Start(self): Запускаем парсинг
<|skeleton|>
class Hrefer:
"""Hrefer v.6.0"""
def __init__(self):
... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class Hrefer:
"""Hrefer v.6.0"""
def __init__(self):
"""Инициализация"""
<|body_0|>
def _GetHost(self, url):
"""Получаем хост по урлу"""
<|body_1|>
def Start(self):
"""Запускаем парсинг"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hrefer:
"""Hrefer v.6.0"""
def __init__(self):
"""Инициализация"""
self.linksUrl = 'http://blogsearch.google.com/changes.xml?last=120'
self.rxUrls = re.compile('url="([^"]*?)"')
self.selfPath = os.path.dirname(__file__)
self.linksFileName = os.path.join(self.selfPa... | the_stack_v2_python_sparse | doorsagents/hrefer/hrefer6.py | cash2one/doorscenter | train | 0 |
d4587ee8eb5e8cd6030a70dbf8d9367a3e698bc6 | [
"super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')\nself.F = tf.keras.layers.Dense(vocab)\nself.attention = SelfAttention(units)",
"context_v, _ =... | <|body_start_0|>
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform')
self.F = tf.keras.layers.Dense(vocab)
self.atte... | class RNNDecoder | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""call function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(RNNDecoder... | stack_v2_sparse_classes_75kplus_train_072527 | 1,101 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "call function",
"name": "call",
"signature": "def call(self, x, s_prev, hidden_states)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002612 | Implement the Python class `RNNDecoder` described below.
Class description:
class RNNDecoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): class constructor
- def call(self, x, s_prev, hidden_states): call function | Implement the Python class `RNNDecoder` described below.
Class description:
class RNNDecoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): class constructor
- def call(self, x, s_prev, hidden_states): call function
<|skeleton|>
class RNNDecoder:
"""class RNNDecoder"""
... | a49eb348ff994f35b0efbbd5ac3ac8ae8ccb57d2 | <|skeleton|>
class RNNDecoder:
"""class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""class constructor"""
<|body_0|>
def call(self, x, s_prev, hidden_states):
"""call function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNDecoder:
"""class RNNDecoder"""
def __init__(self, vocab, embedding, units, batch):
"""class constructor"""
super(RNNDecoder, self).__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, return_sequences=True, retur... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | salmenz/holbertonschool-machine_learning | train | 4 |
e0b58014da78b7d8cc1c5dfc20c4146e4fe7be0f | [
"self.n = int(n)\nself.p = float(p)\nif data is None:\n if self.n < 1:\n raise ValueError('n must be a positive value')\n elif self.p <= 0 or self.p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\nelse:\n if type(data) is not list:\n raise TypeError('data must be ... | <|body_start_0|>
self.n = int(n)
self.p = float(p)
if data is None:
if self.n < 1:
raise ValueError('n must be a positive value')
elif self.p <= 0 or self.p >= 1:
raise ValueError('p must be greater than 0 and less than 1')
else:
... | Tye class to call methods of Binomial distribution CDF and PMF | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""Tye class to call methods of Binomial distribution CDF and PMF"""
def __init__(self, data=None, n=1, p=0.5):
"""Initialize method data: type list data elements n: int element to be evaluated p: Boolean value"""
<|body_0|>
def pmf(self, k):
"""Method ... | stack_v2_sparse_classes_75kplus_train_072528 | 2,202 | no_license | [
{
"docstring": "Initialize method data: type list data elements n: int element to be evaluated p: Boolean value",
"name": "__init__",
"signature": "def __init__(self, data=None, n=1, p=0.5)"
},
{
"docstring": "Method Probability Mass Function for binomial k: integer value of the data return: PMF... | 3 | stack_v2_sparse_classes_30k_train_028679 | Implement the Python class `Binomial` described below.
Class description:
Tye class to call methods of Binomial distribution CDF and PMF
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Initialize method data: type list data elements n: int element to be evaluated p: Boolean value
- def ... | Implement the Python class `Binomial` described below.
Class description:
Tye class to call methods of Binomial distribution CDF and PMF
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Initialize method data: type list data elements n: int element to be evaluated p: Boolean value
- def ... | c277c8bfcc2e65c8d0a483c08dd72cd093274c02 | <|skeleton|>
class Binomial:
"""Tye class to call methods of Binomial distribution CDF and PMF"""
def __init__(self, data=None, n=1, p=0.5):
"""Initialize method data: type list data elements n: int element to be evaluated p: Boolean value"""
<|body_0|>
def pmf(self, k):
"""Method ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Binomial:
"""Tye class to call methods of Binomial distribution CDF and PMF"""
def __init__(self, data=None, n=1, p=0.5):
"""Initialize method data: type list data elements n: int element to be evaluated p: Boolean value"""
self.n = int(n)
self.p = float(p)
if data is None... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | JDorangetree/holbertonschool-machine_learning | train | 0 |
f4a18906597ab9c90d04ebc0a0a290b303af67a4 | [
"if not s and (not t):\n return True\nsize_s, size_t = (len(s), len(t))\ni, j = (0, 0)\nwhile i < size_s and j < size_t:\n if s[i] == t[j]:\n i, j = (i + 1, j + 1)\n else:\n j += 1\nreturn i == size_s",
"if not s and (not t):\n return True\nsize_s, size_t = (len(s), len(t))\ndp = [[False... | <|body_start_0|>
if not s and (not t):
return True
size_s, size_t = (len(s), len(t))
i, j = (0, 0)
while i < size_s and j < size_t:
if s[i] == t[j]:
i, j = (i + 1, j + 1)
else:
j += 1
return i == size_s
<|end_bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""双指针法"""
<|body_0|>
def isSubsequence_1(self, s: str, t: str) -> bool:
"""动态规划"""
<|body_1|>
def isSubsequence_2(self, s: str, t: str) -> bool:
"""自底向上的动态规划"""
<|body_2|>
d... | stack_v2_sparse_classes_75kplus_train_072529 | 2,388 | no_license | [
{
"docstring": "双指针法",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s: str, t: str) -> bool"
},
{
"docstring": "动态规划",
"name": "isSubsequence_1",
"signature": "def isSubsequence_1(self, s: str, t: str) -> bool"
},
{
"docstring": "自底向上的动态规划",
"name": "isSubse... | 4 | stack_v2_sparse_classes_30k_train_030490 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 双指针法
- def isSubsequence_1(self, s: str, t: str) -> bool: 动态规划
- def isSubsequence_2(self, s: str, t: str) -> bool: 自底向上的动态规划
- d... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 双指针法
- def isSubsequence_1(self, s: str, t: str) -> bool: 动态规划
- def isSubsequence_2(self, s: str, t: str) -> bool: 自底向上的动态规划
- d... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""双指针法"""
<|body_0|>
def isSubsequence_1(self, s: str, t: str) -> bool:
"""动态规划"""
<|body_1|>
def isSubsequence_2(self, s: str, t: str) -> bool:
"""自底向上的动态规划"""
<|body_2|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""双指针法"""
if not s and (not t):
return True
size_s, size_t = (len(s), len(t))
i, j = (0, 0)
while i < size_s and j < size_t:
if s[i] == t[j]:
i, j = (i + 1, j + 1)
... | the_stack_v2_python_sparse | algorithm/leetcode/dp/17-判断子序列.py | lxconfig/UbuntuCode_bak | train | 0 | |
e2793bfa7e79fa1e6f00e4584a5e11656097c08c | [
"if id is not None:\n self.id = id\nelse:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects",
"if list_dictionaries is None or len(list_dictionaries) is 0:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)",
"filename = '{}.json'.format(cls.__name__)\nif list_objs is None:\n lis... | <|body_start_0|>
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None or len(list_dictionaries) is 0:
return '[]'
else:
return jso... | Base class | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Base class"""
def __init__(self, id=None):
"""Constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""To json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""Save to json file"""
<|body_2|>
def from... | stack_v2_sparse_classes_75kplus_train_072530 | 1,896 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "To json string",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "Save to json file",
"name": "save_to_file",
"... | 6 | null | Implement the Python class `Base` described below.
Class description:
Base class
Method signatures and docstrings:
- def __init__(self, id=None): Constructor
- def to_json_string(list_dictionaries): To json string
- def save_to_file(cls, list_objs): Save to json file
- def from_json_string(json_string): From json to ... | Implement the Python class `Base` described below.
Class description:
Base class
Method signatures and docstrings:
- def __init__(self, id=None): Constructor
- def to_json_string(list_dictionaries): To json string
- def save_to_file(cls, list_objs): Save to json file
- def from_json_string(json_string): From json to ... | 9d0ebf054b26707a1ba8f21a3a8f307e906ca8df | <|skeleton|>
class Base:
"""Base class"""
def __init__(self, id=None):
"""Constructor"""
<|body_0|>
def to_json_string(list_dictionaries):
"""To json string"""
<|body_1|>
def save_to_file(cls, list_objs):
"""Save to json file"""
<|body_2|>
def from... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""Base class"""
def __init__(self, id=None):
"""Constructor"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
def to_json_string(list_dictionaries):
"""To json string"""
if li... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | BrianFs04/holbertonschool-higher_level_programming | train | 0 |
e6f926167837f772ace7305112339a0a384fe1b9 | [
"args = recon_parser.parse_args()\nif args['recon_id'] is not None:\n result = ReconResource.query.filter_by(recon_id=args['recon_id'])\nelse:\n result = ReconResource.query.all()\nreturn {'resources': result}",
"try:\n res = ReconResource.from_dict(request.json)\n db.session.add(res)\n AppInformat... | <|body_start_0|>
args = recon_parser.parse_args()
if args['recon_id'] is not None:
result = ReconResource.query.filter_by(recon_id=args['recon_id'])
else:
result = ReconResource.query.all()
return {'resources': result}
<|end_body_0|>
<|body_start_1|>
try:... | ResourceCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceCollection:
def get(self):
"""Get Resources list 200 Success"""
<|body_0|>
def post(self):
"""Add a Resource 201 Success 400 Validation error :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = recon_parser.parse_args()
i... | stack_v2_sparse_classes_75kplus_train_072531 | 5,113 | no_license | [
{
"docstring": "Get Resources list 200 Success",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a Resource 201 Success 400 Validation error :return:",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011830 | Implement the Python class `ResourceCollection` described below.
Class description:
Implement the ResourceCollection class.
Method signatures and docstrings:
- def get(self): Get Resources list 200 Success
- def post(self): Add a Resource 201 Success 400 Validation error :return: | Implement the Python class `ResourceCollection` described below.
Class description:
Implement the ResourceCollection class.
Method signatures and docstrings:
- def get(self): Get Resources list 200 Success
- def post(self): Add a Resource 201 Success 400 Validation error :return:
<|skeleton|>
class ResourceCollectio... | e748e9ce9bd40018389a6154aeba2d0c3c77430f | <|skeleton|>
class ResourceCollection:
def get(self):
"""Get Resources list 200 Success"""
<|body_0|>
def post(self):
"""Add a Resource 201 Success 400 Validation error :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceCollection:
def get(self):
"""Get Resources list 200 Success"""
args = recon_parser.parse_args()
if args['recon_id'] is not None:
result = ReconResource.query.filter_by(recon_id=args['recon_id'])
else:
result = ReconResource.query.all()
r... | the_stack_v2_python_sparse | app/api/endpoints/Resources.py | averdier/elittoral_api | train | 0 | |
095ad7bef982ef908aae6b22867f33205388c756 | [
"self.episode_length = episode_length\nself.env_num = env_num\nself.gamma = gamma\nself.gae_lambda = gae_lambda\nself._use_popart = use_popart\nself.share_obs = np.zeros((self.episode_length + 1, self.env_num, share_obs_shape), dtype=np.float32)\nself.obs = np.zeros((self.episode_length + 1, self.env_num, obs_shape... | <|body_start_0|>
self.episode_length = episode_length
self.env_num = env_num
self.gamma = gamma
self.gae_lambda = gae_lambda
self._use_popart = use_popart
self.share_obs = np.zeros((self.episode_length + 1, self.env_num, share_obs_shape), dtype=np.float32)
self.ob... | SeparatedReplayBuffer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeparatedReplayBuffer:
def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart):
"""ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length fo... | stack_v2_sparse_classes_75kplus_train_072532 | 6,900 | permissive | [
{
"docstring": "ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length for any episode env_num (int): Number of parallel envs to train gamma (float): discount factor for rewards gae_lambda (float): gae lambda parameter obs... | 5 | stack_v2_sparse_classes_30k_train_004975 | Implement the Python class `SeparatedReplayBuffer` described below.
Class description:
Implement the SeparatedReplayBuffer class.
Method signatures and docstrings:
- def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart): ReplayBuffer for each agent Args: mod... | Implement the Python class `SeparatedReplayBuffer` described below.
Class description:
Implement the SeparatedReplayBuffer class.
Method signatures and docstrings:
- def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart): ReplayBuffer for each agent Args: mod... | 3bb5fe36d245f4d69bae0710dc1dc9d1a172f64d | <|skeleton|>
class SeparatedReplayBuffer:
def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart):
"""ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SeparatedReplayBuffer:
def __init__(self, episode_length, env_num, gamma, gae_lambda, obs_shape, share_obs_shape, act_space, use_popart):
"""ReplayBuffer for each agent Args: model (parl.Model): model that contains both value network and policy network episode_length (int): max length for any episode ... | the_stack_v2_python_sparse | benchmark/torch/mappo/mappo_buffer.py | PaddlePaddle/PARL | train | 3,818 | |
1b7f01bf65725529bad8f820d7fc8db15a52bae0 | [
"if isinstance(value, FileDescriptor):\n return value\nelif isinstance(value, str):\n return FileDescriptor(value, file_field=self)\nelif isinstance(value, dict):\n try:\n path = value['file']\n except KeyError:\n raise ValidationError(\"dictionary must contain a 'file' element\")\n if ... | <|body_start_0|>
if isinstance(value, FileDescriptor):
return value
elif isinstance(value, str):
return FileDescriptor(value, file_field=self)
elif isinstance(value, dict):
try:
path = value['file']
except KeyError:
... | File field. | FileField | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileField:
"""File field."""
def to_python(self, value):
"""Convert value if needed."""
<|body_0|>
def to_output(self, value):
"""Convert value to process output format. Also copy the referenced file to the data volume."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_072533 | 42,700 | permissive | [
{
"docstring": "Convert value if needed.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Convert value to process output format. Also copy the referenced file to the data volume.",
"name": "to_output",
"signature": "def to_output(self, value)"
}
] | 2 | null | Implement the Python class `FileField` described below.
Class description:
File field.
Method signatures and docstrings:
- def to_python(self, value): Convert value if needed.
- def to_output(self, value): Convert value to process output format. Also copy the referenced file to the data volume. | Implement the Python class `FileField` described below.
Class description:
File field.
Method signatures and docstrings:
- def to_python(self, value): Convert value if needed.
- def to_output(self, value): Convert value to process output format. Also copy the referenced file to the data volume.
<|skeleton|>
class Fi... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class FileField:
"""File field."""
def to_python(self, value):
"""Convert value if needed."""
<|body_0|>
def to_output(self, value):
"""Convert value to process output format. Also copy the referenced file to the data volume."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileField:
"""File field."""
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, FileDescriptor):
return value
elif isinstance(value, str):
return FileDescriptor(value, file_field=self)
elif isinstance(value, dict):
... | the_stack_v2_python_sparse | resolwe/process/fields.py | genialis/resolwe | train | 35 |
e2efdd245d74950ea82c2e4557e0c9f8b3ab98ef | [
"util = _MScriptUtil()\nutil.createFromDouble(0.0, 0.0, 0.0)\nptr = util.asDoublePtr()\nself.getScale(ptr)\nreturn [_MScriptUtil.getDoubleArrayItem(ptr, 0), _MScriptUtil.getDoubleArrayItem(ptr, 1), _MScriptUtil.getDoubleArrayItem(ptr, 2)]",
"util = _MScriptUtil()\nutil.createFromList(scale, 3)\nptr = util.asDoubl... | <|body_start_0|>
util = _MScriptUtil()
util.createFromDouble(0.0, 0.0, 0.0)
ptr = util.asDoublePtr()
self.getScale(ptr)
return [_MScriptUtil.getDoubleArrayItem(ptr, 0), _MScriptUtil.getDoubleArrayItem(ptr, 1), _MScriptUtil.getDoubleArrayItem(ptr, 2)]
<|end_body_0|>
<|body_start_... | Container for the extensions. | MFnTransform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFnTransform:
"""Container for the extensions."""
def bnGetScale(self):
"""Retrieve the scale component. Categories: :term:`MScriptUtil`. Returns ------- list [x, y, z] The scale component."""
<|body_0|>
def bnSetScale(self, scale):
"""Set the scale component. Ca... | stack_v2_sparse_classes_75kplus_train_072534 | 2,822 | permissive | [
{
"docstring": "Retrieve the scale component. Categories: :term:`MScriptUtil`. Returns ------- list [x, y, z] The scale component.",
"name": "bnGetScale",
"signature": "def bnGetScale(self)"
},
{
"docstring": "Set the scale component. Categories: :term:`MScriptUtil`. Parameters ---------- scale ... | 6 | stack_v2_sparse_classes_30k_train_023010 | Implement the Python class `MFnTransform` described below.
Class description:
Container for the extensions.
Method signatures and docstrings:
- def bnGetScale(self): Retrieve the scale component. Categories: :term:`MScriptUtil`. Returns ------- list [x, y, z] The scale component.
- def bnSetScale(self, scale): Set th... | Implement the Python class `MFnTransform` described below.
Class description:
Container for the extensions.
Method signatures and docstrings:
- def bnGetScale(self): Retrieve the scale component. Categories: :term:`MScriptUtil`. Returns ------- list [x, y, z] The scale component.
- def bnSetScale(self, scale): Set th... | 8087df05ba9844b4d78d3c4699948ca61cf7621d | <|skeleton|>
class MFnTransform:
"""Container for the extensions."""
def bnGetScale(self):
"""Retrieve the scale component. Categories: :term:`MScriptUtil`. Returns ------- list [x, y, z] The scale component."""
<|body_0|>
def bnSetScale(self, scale):
"""Set the scale component. Ca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MFnTransform:
"""Container for the extensions."""
def bnGetScale(self):
"""Retrieve the scale component. Categories: :term:`MScriptUtil`. Returns ------- list [x, y, z] The scale component."""
util = _MScriptUtil()
util.createFromDouble(0.0, 0.0, 0.0)
ptr = util.asDoublePt... | the_stack_v2_python_sparse | bana/OpenMaya/MFnTransform.py | christophercrouzet/bana | train | 27 |
62da91a16ff40032e992fece978fb0533fee0e2b | [
"trie = lambda: defaultdict(trie)\n\ndef trie():\n return defaultdict(trie)\nself.trie = trie()",
"child = self.trie\nfor c in word:\n child = child[c]\nchild['is_word'] = True",
"child = self.trie\nfor c in word:\n if c in child:\n child = child[c]\n else:\n return False\nreturn child... | <|body_start_0|>
trie = lambda: defaultdict(trie)
def trie():
return defaultdict(trie)
self.trie = trie()
<|end_body_0|>
<|body_start_1|>
child = self.trie
for c in word:
child = child[c]
child['is_word'] = True
<|end_body_1|>
<|body_start_2|>
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_75kplus_train_072535 | 3,882 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
},
{
"docstring": "Returns if the word is in the tr... | 4 | stack_v2_sparse_classes_30k_train_040508 | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 5d29bcf7ea1a9e489a92bc36d2158456de25829e | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trie:
def __init__(self):
"""Initialize your data structure here."""
trie = lambda: defaultdict(trie)
def trie():
return defaultdict(trie)
self.trie = trie()
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
child = self.... | the_stack_v2_python_sparse | 208.实现-trie-前缀树.py | oceanbei333/leetcode | train | 0 | |
2e81bb7e27adeeba46def270b8a270596ea4ee6c | [
"self.lang_dict = {}\nself.lang_total = 0\nself.country_dict = {}\nself.read_data(file)",
"try:\n f = open(file_name)\nexcept FileNotFoundError:\n print(file_name, 'is not found')\n return\nself.count_data(f)",
"line = f.readline().strip().split(',')\nlang_idx = line.index('language')\ncountry_idx = li... | <|body_start_0|>
self.lang_dict = {}
self.lang_total = 0
self.country_dict = {}
self.read_data(file)
<|end_body_0|>
<|body_start_1|>
try:
f = open(file_name)
except FileNotFoundError:
print(file_name, 'is not found')
return
sel... | A class representing DataAnalysis | DataAnalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataAnalysis:
"""A class representing DataAnalysis"""
def __init__(self, file):
"""constructs DataAnalysis object"""
<|body_0|>
def read_data(self, file_name):
"""read the data and get the counts"""
<|body_1|>
def count_data(self, f):
"""coun... | stack_v2_sparse_classes_75kplus_train_072536 | 1,906 | no_license | [
{
"docstring": "constructs DataAnalysis object",
"name": "__init__",
"signature": "def __init__(self, file)"
},
{
"docstring": "read the data and get the counts",
"name": "read_data",
"signature": "def read_data(self, file_name)"
},
{
"docstring": "counts language and 2-letter co... | 5 | null | Implement the Python class `DataAnalysis` described below.
Class description:
A class representing DataAnalysis
Method signatures and docstrings:
- def __init__(self, file): constructs DataAnalysis object
- def read_data(self, file_name): read the data and get the counts
- def count_data(self, f): counts language and... | Implement the Python class `DataAnalysis` described below.
Class description:
A class representing DataAnalysis
Method signatures and docstrings:
- def __init__(self, file): constructs DataAnalysis object
- def read_data(self, file_name): read the data and get the counts
- def count_data(self, f): counts language and... | 778d79fe826588d888df654b0b6548340abb31ff | <|skeleton|>
class DataAnalysis:
"""A class representing DataAnalysis"""
def __init__(self, file):
"""constructs DataAnalysis object"""
<|body_0|>
def read_data(self, file_name):
"""read the data and get the counts"""
<|body_1|>
def count_data(self, f):
"""coun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataAnalysis:
"""A class representing DataAnalysis"""
def __init__(self, file):
"""constructs DataAnalysis object"""
self.lang_dict = {}
self.lang_total = 0
self.country_dict = {}
self.read_data(file)
def read_data(self, file_name):
"""read the data an... | the_stack_v2_python_sparse | lab08/user_data_starter/data_analysis.py | sry19/python5001 | train | 0 |
29b22433f0f6b68655313b858c2de4a5943aea92 | [
"acl.enforce('action_executions:get', context.ctx())\nLOG.debug('Fetch action_execution [id=%s]', id)\nreturn _get_action_execution(id, fields=fields)",
"acl.enforce('action_executions:create', context.ctx())\nLOG.debug('Create action_execution [action_execution=%s]', action_ex)\nname = action_ex.name\ndescriptio... | <|body_start_0|>
acl.enforce('action_executions:get', context.ctx())
LOG.debug('Fetch action_execution [id=%s]', id)
return _get_action_execution(id, fields=fields)
<|end_body_0|>
<|body_start_1|>
acl.enforce('action_executions:create', context.ctx())
LOG.debug('Create action_ex... | ActionExecutionsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionExecutionsController:
def get(self, id, fields=None):
"""Return the specified action_execution. :param id: UUID of action execution to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if it's ... | stack_v2_sparse_classes_75kplus_train_072537 | 19,625 | permissive | [
{
"docstring": "Return the specified action_execution. :param id: UUID of action execution to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if it's not provided.",
"name": "get",
"signature": "def get(self, id, ... | 5 | null | Implement the Python class `ActionExecutionsController` described below.
Class description:
Implement the ActionExecutionsController class.
Method signatures and docstrings:
- def get(self, id, fields=None): Return the specified action_execution. :param id: UUID of action execution to retrieve :param fields: Optional... | Implement the Python class `ActionExecutionsController` described below.
Class description:
Implement the ActionExecutionsController class.
Method signatures and docstrings:
- def get(self, id, fields=None): Return the specified action_execution. :param id: UUID of action execution to retrieve :param fields: Optional... | 7baff017d0cf01d19c44055ad201ca59131b9f94 | <|skeleton|>
class ActionExecutionsController:
def get(self, id, fields=None):
"""Return the specified action_execution. :param id: UUID of action execution to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if it's ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActionExecutionsController:
def get(self, id, fields=None):
"""Return the specified action_execution. :param id: UUID of action execution to retrieve :param fields: Optional. A specified list of fields of the resource to be returned. 'id' will be included automatically in fields if it's not provided."... | the_stack_v2_python_sparse | mistral/api/controllers/v2/action_execution.py | openstack/mistral | train | 214 | |
ccbef90130de1fbf4727a978813ce0d2f3d4a926 | [
"self.x = 0\nself.y = 0\nself.theta = 0\nself.velocity = 0\nself.steering = 0\nself.th_dot = 0\nself.prev_loc = 0\nself.wheelbase = sim_conf.l_f + sim_conf.l_r\nself.mass = sim_conf.m\nself.mu = sim_conf.mu\nself.max_d_dot = sim_conf.max_d_dot\nself.max_steer = sim_conf.max_steer\nself.max_a = sim_conf.max_a\nself.... | <|body_start_0|>
self.x = 0
self.y = 0
self.theta = 0
self.velocity = 0
self.steering = 0
self.th_dot = 0
self.prev_loc = 0
self.wheelbase = sim_conf.l_f + sim_conf.l_r
self.mass = sim_conf.m
self.mu = sim_conf.mu
self.max_d_dot = s... | A simple class which holds the state of a car and can update the dynamics based on the bicycle model Data Members: x: x location of vehicle on map y: y location of vehicle on map theta: orientation of vehicle velocity: steering: delta steering angle th_dot: the change in orientation due to steering | CarModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CarModel:
"""A simple class which holds the state of a car and can update the dynamics based on the bicycle model Data Members: x: x location of vehicle on map y: y location of vehicle on map theta: orientation of vehicle velocity: steering: delta steering angle th_dot: the change in orientation ... | stack_v2_sparse_classes_75kplus_train_072538 | 18,344 | permissive | [
{
"docstring": "Init function Args: sim_conf: a config namespace with relevant car parameters",
"name": "__init__",
"signature": "def __init__(self, sim_conf)"
},
{
"docstring": "Updates the internal state of the vehicle according to the kinematic equations for a bicycle model Args: a: accelerat... | 4 | null | Implement the Python class `CarModel` described below.
Class description:
A simple class which holds the state of a car and can update the dynamics based on the bicycle model Data Members: x: x location of vehicle on map y: y location of vehicle on map theta: orientation of vehicle velocity: steering: delta steering a... | Implement the Python class `CarModel` described below.
Class description:
A simple class which holds the state of a car and can update the dynamics based on the bicycle model Data Members: x: x location of vehicle on map y: y location of vehicle on map theta: orientation of vehicle velocity: steering: delta steering a... | 8d9d13c8f563cc331809836d148b3dc83dd5d9ac | <|skeleton|>
class CarModel:
"""A simple class which holds the state of a car and can update the dynamics based on the bicycle model Data Members: x: x location of vehicle on map y: y location of vehicle on map theta: orientation of vehicle velocity: steering: delta steering angle th_dot: the change in orientation ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CarModel:
"""A simple class which holds the state of a car and can update the dynamics based on the bicycle model Data Members: x: x location of vehicle on map y: y location of vehicle on map theta: orientation of vehicle velocity: steering: delta steering angle th_dot: the change in orientation due to steeri... | the_stack_v2_python_sparse | ReferenceModification/Simulator/BaseSimClasses.py | BDEvan5/ReferenceModification | train | 1 |
32941d7b0ae746384319ea8390d0b8ea7c56848f | [
"loss, roc = (0.0, 0.0)\nacc, F1, recall = (0.0, 0.0, 0.0)\nprecision, jac, AJI = (0.0, 0.0, 0.0)\ninit_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\nself.sess.run(init_op)\nself.Saver()\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(coord=coord)\nfor s... | <|body_start_0|>
loss, roc = (0.0, 0.0)
acc, F1, recall = (0.0, 0.0, 0.0)
precision, jac, AJI = (0.0, 0.0, 0.0)
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
self.sess.run(init_op)
self.Saver()
coord = tf.train.Coordinator... | Model | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def test(self, p1, p2, steps):
"""How the model tests"""
<|body_0|>
def validation(self, DG_TEST, p1, p2, save_path):
"""How the model validates"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
loss, roc = (0.0, 0.0)
acc, F1, recall = ... | stack_v2_sparse_classes_75kplus_train_072539 | 6,889 | permissive | [
{
"docstring": "How the model tests",
"name": "test",
"signature": "def test(self, p1, p2, steps)"
},
{
"docstring": "How the model validates",
"name": "validation",
"signature": "def validation(self, DG_TEST, p1, p2, save_path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018625 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def test(self, p1, p2, steps): How the model tests
- def validation(self, DG_TEST, p1, p2, save_path): How the model validates | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def test(self, p1, p2, steps): How the model tests
- def validation(self, DG_TEST, p1, p2, save_path): How the model validates
<|skeleton|>
class Model:
def test(self, p1, p2, st... | a35e01d516e9b491c09eaca6701e7e0fe9e56880 | <|skeleton|>
class Model:
def test(self, p1, p2, steps):
"""How the model tests"""
<|body_0|>
def validation(self, DG_TEST, p1, p2, save_path):
"""How the model validates"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
def test(self, p1, p2, steps):
"""How the model tests"""
loss, roc = (0.0, 0.0)
acc, F1, recall = (0.0, 0.0, 0.0)
precision, jac, AJI = (0.0, 0.0, 0.0)
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
self.sess.run(i... | the_stack_v2_python_sparse | src_RealData/Dist.py | lucas-sancere/DRFNS | train | 1 | |
95e3177b9171172f8e40d2f6ed2f224b9e553734 | [
"if not vals.get('name', False):\n emp_job = self.pool.get('hr.job').read(cr, uid, vals['job_id'], ['name'], context=context)\n emp_level = self.pool.get('hr.employee.level').read(cr, uid, vals['level_id'], ['name'], context=context)\n vals['name'] = emp_job['name'] + ' ' + emp_level['name']\nreturn super(... | <|body_start_0|>
if not vals.get('name', False):
emp_job = self.pool.get('hr.job').read(cr, uid, vals['job_id'], ['name'], context=context)
emp_level = self.pool.get('hr.employee.level').read(cr, uid, vals['level_id'], ['name'], context=context)
vals['name'] = emp_job['name']... | hr_employee_grade | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hr_employee_grade:
def create(self, cr, uid, vals, context=None):
"""Override fnct: Get grade name"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override fnct: Get grade name"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n... | stack_v2_sparse_classes_75kplus_train_072540 | 1,858 | no_license | [
{
"docstring": "Override fnct: Get grade name",
"name": "create",
"signature": "def create(self, cr, uid, vals, context=None)"
},
{
"docstring": "Override fnct: Get grade name",
"name": "write",
"signature": "def write(self, cr, uid, ids, vals, context=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046095 | Implement the Python class `hr_employee_grade` described below.
Class description:
Implement the hr_employee_grade class.
Method signatures and docstrings:
- def create(self, cr, uid, vals, context=None): Override fnct: Get grade name
- def write(self, cr, uid, ids, vals, context=None): Override fnct: Get grade name | Implement the Python class `hr_employee_grade` described below.
Class description:
Implement the hr_employee_grade class.
Method signatures and docstrings:
- def create(self, cr, uid, vals, context=None): Override fnct: Get grade name
- def write(self, cr, uid, ids, vals, context=None): Override fnct: Get grade name
... | 673dd0f2a7c0b69a984342b20f55164a97a00529 | <|skeleton|>
class hr_employee_grade:
def create(self, cr, uid, vals, context=None):
"""Override fnct: Get grade name"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override fnct: Get grade name"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class hr_employee_grade:
def create(self, cr, uid, vals, context=None):
"""Override fnct: Get grade name"""
if not vals.get('name', False):
emp_job = self.pool.get('hr.job').read(cr, uid, vals['job_id'], ['name'], context=context)
emp_level = self.pool.get('hr.employee.level'... | the_stack_v2_python_sparse | addons/app-trobz-hr/__unported__/trobz_hr_payslip_parameter/model/hr_employee_grade.py | TinPlusIT05/tms | train | 0 | |
9d0b40f1de553fc7e30ad1059dc13feb2c2384c2 | [
"self.manifest_dataset = manifest_dataset\nself.field_name = field_name\nself.engine_type = engine_type",
"if isinstance(self.manifest_dataset, ayeaye.Connect):\n manifest_dataset = self.manifest_dataset.clone()\nelse:\n manifest_dataset = self.manifest_dataset\ne_url = ayeaye.connector_resolver.resolve(man... | <|body_start_0|>
self.manifest_dataset = manifest_dataset
self.field_name = field_name
self.engine_type = engine_type
<|end_body_0|>
<|body_start_1|>
if isinstance(self.manifest_dataset, ayeaye.Connect):
manifest_dataset = self.manifest_dataset.clone()
else:
... | Make engine_urls stored in a manifest file available to :class:`ayeaye.Connector`s in an :class:`ayeaye.Model`. Each engine_url represents a specific version of a source dataset so this pattern can be used to create versioned ETL builds by storing versioning information in a manifest file. A manifest file is a dataset ... | EngineFromManifest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EngineFromManifest:
"""Make engine_urls stored in a manifest file available to :class:`ayeaye.Connector`s in an :class:`ayeaye.Model`. Each engine_url represents a specific version of a source dataset so this pattern can be used to create versioned ETL builds by storing versioning information in ... | stack_v2_sparse_classes_75kplus_train_072541 | 12,776 | permissive | [
{
"docstring": ":param manifest_dataset (subclass :class:`DataConnector` object): with .data and dictionary access to .data. :param field_name (str): field within manifest_dataset.data[field_name] :param engine_type (str): prefix to engine_url. e.g. 'json' would give 'json://'",
"name": "__init__",
"sig... | 2 | stack_v2_sparse_classes_30k_train_003697 | Implement the Python class `EngineFromManifest` described below.
Class description:
Make engine_urls stored in a manifest file available to :class:`ayeaye.Connector`s in an :class:`ayeaye.Model`. Each engine_url represents a specific version of a source dataset so this pattern can be used to create versioned ETL build... | Implement the Python class `EngineFromManifest` described below.
Class description:
Make engine_urls stored in a manifest file available to :class:`ayeaye.Connector`s in an :class:`ayeaye.Model`. Each engine_url represents a specific version of a source dataset so this pattern can be used to create versioned ETL build... | 048888b4dc393a882e56802c836d61316c477387 | <|skeleton|>
class EngineFromManifest:
"""Make engine_urls stored in a manifest file available to :class:`ayeaye.Connector`s in an :class:`ayeaye.Model`. Each engine_url represents a specific version of a source dataset so this pattern can be used to create versioned ETL builds by storing versioning information in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EngineFromManifest:
"""Make engine_urls stored in a manifest file available to :class:`ayeaye.Connector`s in an :class:`ayeaye.Model`. Each engine_url represents a specific version of a source dataset so this pattern can be used to create versioned ETL builds by storing versioning information in a manifest fi... | the_stack_v2_python_sparse | lib/ayeaye/common_pattern/manifest.py | Aye-Aye-Dev/AyeAye | train | 9 |
32ce5660a515575c1e42f153bda5c95c948c92a9 | [
"self.window_size = window_size\nself.stride_size = stride_size\nself.scope = scope\nself.device_spec = get_device_spec(default_gpu_id, num_gpus)\nwith tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec):\n self.pooling_layer = tf.layers.AveragePooling3D(self.window_size, self.stride_... | <|body_start_0|>
self.window_size = window_size
self.stride_size = stride_size
self.scope = scope
self.device_spec = get_device_spec(default_gpu_id, num_gpus)
with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE), tf.device(self.device_spec):
self.pooling_layer = tf... | average pooling layer | AveragePooling3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AveragePooling3D:
"""average pooling layer"""
def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='avg_pool_3d'):
"""initialize 3d average pooling layer"""
<|body_0|>
def __call__(self, input_data, input_mask):
"""call 3d average pool... | stack_v2_sparse_classes_75kplus_train_072542 | 6,321 | permissive | [
{
"docstring": "initialize 3d average pooling layer",
"name": "__init__",
"signature": "def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='avg_pool_3d')"
},
{
"docstring": "call 3d average pooling layer",
"name": "__call__",
"signature": "def __call__(self,... | 2 | stack_v2_sparse_classes_30k_train_047026 | Implement the Python class `AveragePooling3D` described below.
Class description:
average pooling layer
Method signatures and docstrings:
- def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='avg_pool_3d'): initialize 3d average pooling layer
- def __call__(self, input_data, input_mask):... | Implement the Python class `AveragePooling3D` described below.
Class description:
average pooling layer
Method signatures and docstrings:
- def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='avg_pool_3d'): initialize 3d average pooling layer
- def __call__(self, input_data, input_mask):... | 05fcbec15e359e3db86af6c3798c13be8a6c58ee | <|skeleton|>
class AveragePooling3D:
"""average pooling layer"""
def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='avg_pool_3d'):
"""initialize 3d average pooling layer"""
<|body_0|>
def __call__(self, input_data, input_mask):
"""call 3d average pool... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AveragePooling3D:
"""average pooling layer"""
def __init__(self, window_size, stride_size, num_gpus=1, default_gpu_id=0, scope='avg_pool_3d'):
"""initialize 3d average pooling layer"""
self.window_size = window_size
self.stride_size = stride_size
self.scope = scope
... | the_stack_v2_python_sparse | sequence_labeling/layer/pooling.py | stevezheng23/sequence_labeling_tf | train | 18 |
e83204661e02ac86ddd888d31829646ef755e478 | [
"self.rec_alg = recommend_algorithm\nself.precision = None\nself.recall = None\nself.coverage = None\nself.popularity = None",
"self.precision, self.recall = self.__precision_recall()\nprint('准确率 = ' + str(self.precision * 100) + '% 召回率 = ' + str(self.recall * 100) + '%')\nself.coverage = self.__coverage()\nprin... | <|body_start_0|>
self.rec_alg = recommend_algorithm
self.precision = None
self.recall = None
self.coverage = None
self.popularity = None
<|end_body_0|>
<|body_start_1|>
self.precision, self.recall = self.__precision_recall()
print('准确率 = ' + str(self.precision * ... | Evaluation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaluation:
def __init__(self, recommend_algorithm):
"""对推荐算法recommend_algorithm计算各种评测指标。 :param recommend_algorithm: 推荐算法,包括推荐结果列表,数据集等"""
<|body_0|>
def evaluate(self):
"""评测指标的计算。"""
<|body_1|>
def __precision_recall(self):
"""计算准确率和召回率。 :retu... | stack_v2_sparse_classes_75kplus_train_072543 | 11,243 | no_license | [
{
"docstring": "对推荐算法recommend_algorithm计算各种评测指标。 :param recommend_algorithm: 推荐算法,包括推荐结果列表,数据集等",
"name": "__init__",
"signature": "def __init__(self, recommend_algorithm)"
},
{
"docstring": "评测指标的计算。",
"name": "evaluate",
"signature": "def evaluate(self)"
},
{
"docstring": "计算准... | 5 | stack_v2_sparse_classes_30k_train_041681 | Implement the Python class `Evaluation` described below.
Class description:
Implement the Evaluation class.
Method signatures and docstrings:
- def __init__(self, recommend_algorithm): 对推荐算法recommend_algorithm计算各种评测指标。 :param recommend_algorithm: 推荐算法,包括推荐结果列表,数据集等
- def evaluate(self): 评测指标的计算。
- def __precision_rec... | Implement the Python class `Evaluation` described below.
Class description:
Implement the Evaluation class.
Method signatures and docstrings:
- def __init__(self, recommend_algorithm): 对推荐算法recommend_algorithm计算各种评测指标。 :param recommend_algorithm: 推荐算法,包括推荐结果列表,数据集等
- def evaluate(self): 评测指标的计算。
- def __precision_rec... | 3fec32e36f698f1f1f7d0940ec75da8e2c8eeaba | <|skeleton|>
class Evaluation:
def __init__(self, recommend_algorithm):
"""对推荐算法recommend_algorithm计算各种评测指标。 :param recommend_algorithm: 推荐算法,包括推荐结果列表,数据集等"""
<|body_0|>
def evaluate(self):
"""评测指标的计算。"""
<|body_1|>
def __precision_recall(self):
"""计算准确率和召回率。 :retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Evaluation:
def __init__(self, recommend_algorithm):
"""对推荐算法recommend_algorithm计算各种评测指标。 :param recommend_algorithm: 推荐算法,包括推荐结果列表,数据集等"""
self.rec_alg = recommend_algorithm
self.precision = None
self.recall = None
self.coverage = None
self.popularity = None
... | the_stack_v2_python_sparse | src/lsim/lsim_model.py | littlemesie/recommend-learning | train | 40 | |
4d39cf7aa089e6ba0b4eddacfd3aa8241280e189 | [
"config = Utils().get_config_file('config.ini')\nowner = config.get('Repository', 'owner')\nrepository_name = config.get('Repository', 'repository_name')\nmock_res = {'open_pr_time': 119576.0}\ntype(mock_created_time).return_value = mock.PropertyMock(return_value=mock_res)\nmock_res = {'closed_pr_time': 44010646.0}... | <|body_start_0|>
config = Utils().get_config_file('config.ini')
owner = config.get('Repository', 'owner')
repository_name = config.get('Repository', 'repository_name')
mock_res = {'open_pr_time': 119576.0}
type(mock_created_time).return_value = mock.PropertyMock(return_value=mock... | Testcase for Repository | FetchingDataTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchingDataTest:
"""Testcase for Repository"""
def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_count, mock_closed_pull_reque... | stack_v2_sparse_classes_75kplus_train_072544 | 5,632 | no_license | [
{
"docstring": "test fetching_data method",
"name": "test_fetching_data",
"signature": "def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_c... | 2 | stack_v2_sparse_classes_30k_train_031005 | Implement the Python class `FetchingDataTest` described below.
Class description:
Testcase for Repository
Method signatures and docstrings:
- def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed... | Implement the Python class `FetchingDataTest` described below.
Class description:
Testcase for Repository
Method signatures and docstrings:
- def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed... | 4b31f2c7d87c3ad15c7ab8b71a94abdada1faf63 | <|skeleton|>
class FetchingDataTest:
"""Testcase for Repository"""
def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_count, mock_closed_pull_reque... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FetchingDataTest:
"""Testcase for Repository"""
def test_fetching_data(self, mock_get_label, mock_get_repo_probability, mock_get_open_issue_count, mock_watchers_count, mock_pushed_time, mock_get_forks_count, mock_get_changed_files, mock_get_commits, mock_open_pr_count, mock_closed_pull_request_time, mock... | the_stack_v2_python_sparse | unit_test/fetching_data_test.py | iamthebj/GitPred | train | 0 |
66bdb5fcdfce90314e43760d276bcf93ba639532 | [
"if not username:\n raise ValueError('Users must have an username address')\nuser = self.model(email=email, username=username, first_name=first_name, last_name=last_name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, username, password=password)\nuser.is... | <|body_start_0|>
if not username:
raise ValueError('Users must have an username address')
user = self.model(email=email, username=username, first_name=first_name, last_name=last_name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|... | AccountManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountManager:
def create_user(self, email, username, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password):
"""Creates and s... | stack_v2_sparse_classes_75kplus_train_072545 | 7,081 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, username, first_name=None, last_name=None, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of... | 2 | stack_v2_sparse_classes_30k_train_023081 | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, username, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, date of birth and password.
- d... | Implement the Python class `AccountManager` described below.
Class description:
Implement the AccountManager class.
Method signatures and docstrings:
- def create_user(self, email, username, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, date of birth and password.
- d... | 21f16fde395a1c5ab64ba9bfc02373454389d073 | <|skeleton|>
class AccountManager:
def create_user(self, email, username, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, username, password):
"""Creates and s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountManager:
def create_user(self, email, username, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not username:
raise ValueError('Users must have an username address')
user = self.mode... | the_stack_v2_python_sparse | service-python/authserver/accounts/models.py | firmanJS/picasso-backend | train | 1 | |
6f572dd12b3e3e5b34b8f30b2406ff388094305b | [
"new_user = get_user_model().objects.create_user(email, password)\nnew_user.is_active = False\nnew_user.save()\nregistration_profile = self.create_profile(new_user)\nif send_email:\n registration_profile.send_activation_email(site, request)\nreturn new_user",
"new_user = get_user_model().objects.create_user(em... | <|body_start_0|>
new_user = get_user_model().objects.create_user(email, password)
new_user.is_active = False
new_user.save()
registration_profile = self.create_profile(new_user)
if send_email:
registration_profile.send_activation_email(site, request)
return ne... | RegistrationManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationManager:
def create_inactive_user(self, email, password, site, send_email=True, request=None):
"""Overwiding the method from the base class to not use the username. Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User`... | stack_v2_sparse_classes_75kplus_train_072546 | 33,522 | no_license | [
{
"docstring": "Overwiding the method from the base class to not use the username. Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``s... | 3 | stack_v2_sparse_classes_30k_train_022768 | Implement the Python class `RegistrationManager` described below.
Class description:
Implement the RegistrationManager class.
Method signatures and docstrings:
- def create_inactive_user(self, email, password, site, send_email=True, request=None): Overwiding the method from the base class to not use the username. Cre... | Implement the Python class `RegistrationManager` described below.
Class description:
Implement the RegistrationManager class.
Method signatures and docstrings:
- def create_inactive_user(self, email, password, site, send_email=True, request=None): Overwiding the method from the base class to not use the username. Cre... | 5440928238428c9e60be61e75910ad8d78866426 | <|skeleton|>
class RegistrationManager:
def create_inactive_user(self, email, password, site, send_email=True, request=None):
"""Overwiding the method from the base class to not use the username. Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationManager:
def create_inactive_user(self, email, password, site, send_email=True, request=None):
"""Overwiding the method from the base class to not use the username. Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning t... | the_stack_v2_python_sparse | members/models.py | trouvaay/trouvaay | train | 0 | |
6ff872a7b1c69eacdbf6068b0ebd846c543febe0 | [
"copied = copy.deepcopy(data)\nin_secs = data.scan_duration.total_seconds()\ncopied.scan_duration = in_secs\nreturn copied",
"scan_duration = timedelta(seconds=data.get('scan_duration'))\ntmc_config = TMCConfiguration(scan_duration=scan_duration)\nreturn tmc_config"
] | <|body_start_0|>
copied = copy.deepcopy(data)
in_secs = data.scan_duration.total_seconds()
copied.scan_duration = in_secs
return copied
<|end_body_0|>
<|body_start_1|>
scan_duration = timedelta(seconds=data.get('scan_duration'))
tmc_config = TMCConfiguration(scan_duratio... | Create the Schema for ScanDuration using timedelta | TMCConfigurationSchema | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TMCConfigurationSchema:
"""Create the Schema for ScanDuration using timedelta"""
def convert_scan_duration_timedelta_to_float(self, data: TMCConfiguration, **_):
"""Process scan_duration and convert it to a float :param data: the scan_duration timedelta :param _: kwargs passed by Mar... | stack_v2_sparse_classes_75kplus_train_072547 | 1,676 | permissive | [
{
"docstring": "Process scan_duration and convert it to a float :param data: the scan_duration timedelta :param _: kwargs passed by Marshallow :return: float converted",
"name": "convert_scan_duration_timedelta_to_float",
"signature": "def convert_scan_duration_timedelta_to_float(self, data: TMCConfigur... | 2 | stack_v2_sparse_classes_30k_train_046504 | Implement the Python class `TMCConfigurationSchema` described below.
Class description:
Create the Schema for ScanDuration using timedelta
Method signatures and docstrings:
- def convert_scan_duration_timedelta_to_float(self, data: TMCConfiguration, **_): Process scan_duration and convert it to a float :param data: t... | Implement the Python class `TMCConfigurationSchema` described below.
Class description:
Create the Schema for ScanDuration using timedelta
Method signatures and docstrings:
- def convert_scan_duration_timedelta_to_float(self, data: TMCConfiguration, **_): Process scan_duration and convert it to a float :param data: t... | 87083655aca8f8f53a26dba253a0189d8519714b | <|skeleton|>
class TMCConfigurationSchema:
"""Create the Schema for ScanDuration using timedelta"""
def convert_scan_duration_timedelta_to_float(self, data: TMCConfiguration, **_):
"""Process scan_duration and convert it to a float :param data: the scan_duration timedelta :param _: kwargs passed by Mar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TMCConfigurationSchema:
"""Create the Schema for ScanDuration using timedelta"""
def convert_scan_duration_timedelta_to_float(self, data: TMCConfiguration, **_):
"""Process scan_duration and convert it to a float :param data: the scan_duration timedelta :param _: kwargs passed by Marshallow :retu... | the_stack_v2_python_sparse | src/ska_tmc_cdm/schemas/subarray_node/configure/tmc.py | ska-telescope/cdm-shared-library | train | 0 |
ec3866cec08471e03bec4059ad89725643ebe1f4 | [
"assert relpos.is_contiguous()\nassert query_batch_cnt.is_contiguous()\nassert query_features.is_contiguous()\nassert lookup_table.is_contiguous()\nb = query_batch_cnt.shape[0]\ntotal_query_num, local_size = relpos.size()\nl, nhead, hdim = lookup_table.size()\nassert query_features.shape[0] == total_query_num\noutp... | <|body_start_0|>
assert relpos.is_contiguous()
assert query_batch_cnt.is_contiguous()
assert query_features.is_contiguous()
assert lookup_table.is_contiguous()
b = query_batch_cnt.shape[0]
total_query_num, local_size = relpos.size()
l, nhead, hdim = lookup_table.s... | Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead) | RelativePositionalEmbeddingQIndex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelativePositionalEmbeddingQIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
def ... | stack_v2_sparse_classes_75kplus_train_072548 | 11,582 | no_license | [
{
"docstring": ":param ctx: :param relpos: A float tensor with shape [total_query_num, local_size] :param query_batch_cnt: A integer tensor with shape [bs], indicating the query amount for each batch. :param query_features: A float tensor with shape [total_query_num, nhead, hdim] :param lookup_table: A float te... | 2 | stack_v2_sparse_classes_30k_train_050911 | Implement the Python class `RelativePositionalEmbeddingQIndex` described below.
Class description:
Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_que... | Implement the Python class `RelativePositionalEmbeddingQIndex` described below.
Class description:
Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_que... | bbc78ca91e851f0f04459b1a8bbe96ab44bf41bc | <|skeleton|>
class RelativePositionalEmbeddingQIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelativePositionalEmbeddingQIndex:
"""Based on: * the generated attention pair index (total_query_num, local_size); * query features (total_query_num, nhead, hdim) * key features (total_key_num, nhead, hdim) Generate the attention weight matrix. * (total_query_num, local_size, nhead)"""
def forward(ctx, ... | the_stack_v2_python_sparse | EQNet/eqnet/ops/crpe/crpe_utils_v2.py | dvlab-research/DeepVision3D | train | 94 |
bc4a2db3a55671a2b192212ad1b0db2993ccb623 | [
"super(LightweightConvolution2D, self).__init__()\nassert n_feat % wshare == 0\nself.wshare = wshare\nself.use_kernel_mask = use_kernel_mask\nself.dropout_rate = dropout_rate\nself.kernel_size = kernel_size\nself.padding_size = int(kernel_size / 2)\nself.linear1 = nn.Linear(n_feat, n_feat * 2)\nself.linear2 = nn.Li... | <|body_start_0|>
super(LightweightConvolution2D, self).__init__()
assert n_feat % wshare == 0
self.wshare = wshare
self.use_kernel_mask = use_kernel_mask
self.dropout_rate = dropout_rate
self.kernel_size = kernel_size
self.padding_size = int(kernel_size / 2)
... | Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_size (int): kernel size (length) use_kernel_mask (boo... | LightweightConvolution2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightweightConvolution2D:
"""Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_s... | stack_v2_sparse_classes_75kplus_train_072549 | 4,229 | permissive | [
{
"docstring": "Construct Lightweight 2-Dimensional Convolution layer.",
"name": "__init__",
"signature": "def __init__(self, wshare, n_feat, dropout_rate, kernel_size, use_kernel_mask=False, use_bias=False)"
},
{
"docstring": "Forward of 'Lightweight 2-Dimensional Convolution'. This function ta... | 2 | stack_v2_sparse_classes_30k_train_028758 | Implement the Python class `LightweightConvolution2D` described below.
Class description:
Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features drop... | Implement the Python class `LightweightConvolution2D` described below.
Class description:
Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features drop... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class LightweightConvolution2D:
"""Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LightweightConvolution2D:
"""Lightweight 2-Dimensional Convolution layer. This implementation is based on https://github.com/pytorch/fairseq/tree/master/fairseq Args: wshare (int): the number of kernel of convolution n_feat (int): the number of features dropout_rate (float): dropout_rate kernel_size (int): ke... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/lightconv2d.py | espnet/espnet | train | 7,242 |
982bbb03464e2612e49448ac27da3d91264aaa51 | [
"if not self.decoded:\n orig = self.getOriginal()\n if isinstance(orig, tuple(self.native_types)):\n self.decoded = orig\n elif code == codeType.STRING:\n self.decoded = orig\n self.encoded = orig\n else:\n raise DecodeUnknownType(code, self.__class__)\nreturn copy.deepcopy(s... | <|body_start_0|>
if not self.decoded:
orig = self.getOriginal()
if isinstance(orig, tuple(self.native_types)):
self.decoded = orig
elif code == codeType.STRING:
self.decoded = orig
self.encoded = orig
else:
... | Messages in TTL format Single message = single TTL statement | TTLMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TTLMessage:
"""Messages in TTL format Single message = single TTL statement"""
def decode(self, code=codeType.STRING):
"""Decode original data as TTL. Currently takes text as it is. TODO: check some formal matter to confirm the string is TTL."""
<|body_0|>
def encode(sel... | stack_v2_sparse_classes_75kplus_train_072550 | 6,388 | no_license | [
{
"docstring": "Decode original data as TTL. Currently takes text as it is. TODO: check some formal matter to confirm the string is TTL.",
"name": "decode",
"signature": "def decode(self, code=codeType.STRING)"
},
{
"docstring": "Encode TTL as CODE.",
"name": "encode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_007328 | Implement the Python class `TTLMessage` described below.
Class description:
Messages in TTL format Single message = single TTL statement
Method signatures and docstrings:
- def decode(self, code=codeType.STRING): Decode original data as TTL. Currently takes text as it is. TODO: check some formal matter to confirm the... | Implement the Python class `TTLMessage` described below.
Class description:
Messages in TTL format Single message = single TTL statement
Method signatures and docstrings:
- def decode(self, code=codeType.STRING): Decode original data as TTL. Currently takes text as it is. TODO: check some formal matter to confirm the... | d747cbec7170db58533f3cdefcbb8fe10ec9bfd2 | <|skeleton|>
class TTLMessage:
"""Messages in TTL format Single message = single TTL statement"""
def decode(self, code=codeType.STRING):
"""Decode original data as TTL. Currently takes text as it is. TODO: check some formal matter to confirm the string is TTL."""
<|body_0|>
def encode(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TTLMessage:
"""Messages in TTL format Single message = single TTL statement"""
def decode(self, code=codeType.STRING):
"""Decode original data as TTL. Currently takes text as it is. TODO: check some formal matter to confirm the string is TTL."""
if not self.decoded:
orig = sel... | the_stack_v2_python_sparse | Utils/Dataflow/pyDKB/dataflow/communication/messages.py | PanDAWMS/dkb | train | 1 |
7987a187406127b52440f18b46854964281e83f5 | [
"Frame.__init__(self, master)\nself.pack()\nself.createWidgets()",
"top_frame = Frame(self)\nself.text_in1 = Entry(top_frame)\nself.text_in2 = Entry(top_frame)\nself.label = Label(top_frame, text='Output')\nself.text_in1.pack(side=LEFT)\nself.text_in2.pack(side=RIGHT)\nself.label.pack()\nself.r = IntVar()\ntop_fr... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createWidgets()
<|end_body_0|>
<|body_start_1|>
top_frame = Frame(self)
self.text_in1 = Entry(top_frame)
self.text_in2 = Entry(top_frame)
self.label = Label(top_frame, text='Output')
self.text... | Application main window class. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_75kplus_train_072551 | 1,514 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createWidgets",
"signature": "def createWidgets(self)"
},
{
"docstring": "Handle ... | 3 | null | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handle a c... | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createWidgets(self): Add all the widgets to the main frame.
- def handle(self): Handle a c... | 36ebcda7653068237f010e705310922ad8d8a61e | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
"""Add all the widgets to the main fram... | the_stack_v2_python_sparse | Orielly/gui1.py | pfischer8989/python_work | train | 0 |
040721f192918114ed0ae438c061f107e3931fab | [
"self.mouse = tcod.Mouse()\nself.tile_width = tile_width\nself.tile_height = tile_height\nself.mouse_x = None\nself.mouse_y = None\nself.mouse_moved = False\nself.lclick = False\nself.rclick = False\nself.key = tcod.Key()\nself.quit = False\nself.bus = bus",
"tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS | tcod.E... | <|body_start_0|>
self.mouse = tcod.Mouse()
self.tile_width = tile_width
self.tile_height = tile_height
self.mouse_x = None
self.mouse_y = None
self.mouse_moved = False
self.lclick = False
self.rclick = False
self.key = tcod.Key()
self.quit ... | Inputs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inputs:
def __init__(self, bus, tile_width, tile_height):
"""Building the input reader simply requires to give the event bus so we can write inside."""
<|body_0|>
def poll(self):
"""Check key and mouse input."""
<|body_1|>
def poll_keys(self):
""... | stack_v2_sparse_classes_75kplus_train_072552 | 4,073 | no_license | [
{
"docstring": "Building the input reader simply requires to give the event bus so we can write inside.",
"name": "__init__",
"signature": "def __init__(self, bus, tile_width, tile_height)"
},
{
"docstring": "Check key and mouse input.",
"name": "poll",
"signature": "def poll(self)"
},... | 4 | stack_v2_sparse_classes_30k_train_034934 | Implement the Python class `Inputs` described below.
Class description:
Implement the Inputs class.
Method signatures and docstrings:
- def __init__(self, bus, tile_width, tile_height): Building the input reader simply requires to give the event bus so we can write inside.
- def poll(self): Check key and mouse input.... | Implement the Python class `Inputs` described below.
Class description:
Implement the Inputs class.
Method signatures and docstrings:
- def __init__(self, bus, tile_width, tile_height): Building the input reader simply requires to give the event bus so we can write inside.
- def poll(self): Check key and mouse input.... | 049141c31fc165bb5cf4b2d224b90cbe9655997c | <|skeleton|>
class Inputs:
def __init__(self, bus, tile_width, tile_height):
"""Building the input reader simply requires to give the event bus so we can write inside."""
<|body_0|>
def poll(self):
"""Check key and mouse input."""
<|body_1|>
def poll_keys(self):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Inputs:
def __init__(self, bus, tile_width, tile_height):
"""Building the input reader simply requires to give the event bus so we can write inside."""
self.mouse = tcod.Mouse()
self.tile_width = tile_width
self.tile_height = tile_height
self.mouse_x = None
self... | the_stack_v2_python_sparse | groggy/inputs/input.py | Raveline/groggy | train | 0 | |
049e533d9559a7f5cc5d7f888dd4b09ca8833758 | [
"read_block_size = 1024\ntry:\n e = AES.new(self.symmetric_key, AES.MODE_CBC, self.IV)\n if not os.path.exists(in_filename):\n return False\n with open(in_filename, 'rb') as infile:\n with open(out_filename, 'wb') as outfile:\n while True:\n buf = infile.read(read_bl... | <|body_start_0|>
read_block_size = 1024
try:
e = AES.new(self.symmetric_key, AES.MODE_CBC, self.IV)
if not os.path.exists(in_filename):
return False
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
... | IronBoxKeyData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IronBoxKeyData:
def encrypt_file(self, in_filename, out_filename) -> bool:
"""Encrypts a file using the symmetric key data :param in_filename: :param out_filename: :return: True if success, else False"""
<|body_0|>
def decrypt_file(self, in_filename: str, out_filename: str) ... | stack_v2_sparse_classes_75kplus_train_072553 | 33,328 | no_license | [
{
"docstring": "Encrypts a file using the symmetric key data :param in_filename: :param out_filename: :return: True if success, else False",
"name": "encrypt_file",
"signature": "def encrypt_file(self, in_filename, out_filename) -> bool"
},
{
"docstring": "Decrypts a file using the symmetric key... | 2 | stack_v2_sparse_classes_30k_train_031608 | Implement the Python class `IronBoxKeyData` described below.
Class description:
Implement the IronBoxKeyData class.
Method signatures and docstrings:
- def encrypt_file(self, in_filename, out_filename) -> bool: Encrypts a file using the symmetric key data :param in_filename: :param out_filename: :return: True if succ... | Implement the Python class `IronBoxKeyData` described below.
Class description:
Implement the IronBoxKeyData class.
Method signatures and docstrings:
- def encrypt_file(self, in_filename, out_filename) -> bool: Encrypts a file using the symmetric key data :param in_filename: :param out_filename: :return: True if succ... | 4cd34eea9d42bb0354082c3a042bd3cb07aabccc | <|skeleton|>
class IronBoxKeyData:
def encrypt_file(self, in_filename, out_filename) -> bool:
"""Encrypts a file using the symmetric key data :param in_filename: :param out_filename: :return: True if success, else False"""
<|body_0|>
def decrypt_file(self, in_filename: str, out_filename: str) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IronBoxKeyData:
def encrypt_file(self, in_filename, out_filename) -> bool:
"""Encrypts a file using the symmetric key data :param in_filename: :param out_filename: :return: True if success, else False"""
read_block_size = 1024
try:
e = AES.new(self.symmetric_key, AES.MODE_C... | the_stack_v2_python_sparse | IronBoxREST.py | seve-martinez/ironbox-client-python | train | 0 | |
cd27fe89552bbf3af4e4044db3a33afbc07f7ca1 | [
"super().__init__(scope, id, **kwargs)\nvpc = ec2.Vpc.from_lookup(self, f'{id}-vpc', vpc_id='vpc-dfff4bb4')\nbucket = s3.Bucket.from_bucket_name(self, f'{id}-export-bucket', 'rezoning-exports')\ns3_access_policy = iam.PolicyStatement(actions=['s3:*'], resources=[bucket.bucket_arn, f'{bucket.bucket_arn}/*', f'arn:aw... | <|body_start_0|>
super().__init__(scope, id, **kwargs)
vpc = ec2.Vpc.from_lookup(self, f'{id}-vpc', vpc_id='vpc-dfff4bb4')
bucket = s3.Bucket.from_bucket_name(self, f'{id}-export-bucket', 'rezoning-exports')
s3_access_policy = iam.PolicyStatement(actions=['s3:*'], resources=[bucket.bucke... | rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/app.py author: @ciaranevans | rezoningApiLambdaStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class rezoningApiLambdaStack:
"""rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/a... | stack_v2_sparse_classes_75kplus_train_072554 | 7,248 | no_license | [
{
"docstring": "Define stack.",
"name": "__init__",
"signature": "def __init__(self, scope: core.Construct, id: str, memory: int=1024, timeout: int=30, concurrent: int=100, code_dir: str='./', **kwargs: Any) -> None"
},
{
"docstring": "Build docker image and create package.",
"name": "create... | 2 | stack_v2_sparse_classes_30k_train_032487 | Implement the Python class `rezoningApiLambdaStack` described below.
Class description:
rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec... | Implement the Python class `rezoningApiLambdaStack` described below.
Class description:
rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec... | 27a2a48d861d4be636ec36a7b11ac856032b5053 | <|skeleton|>
class rezoningApiLambdaStack:
"""rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class rezoningApiLambdaStack:
"""rezoning API Lambda Stack This code is freely adapted from - https://github.com/leothomas/titiler/blob/10df64fbbdd342a0762444eceebaac18d8867365/stack/app.py author: @leothomas - https://github.com/ciaranevans/titiler/blob/3a4e04cec2bd9b90e6f80decc49dc3229b6ef569/stack/app.py author:... | the_stack_v2_python_sparse | stack/app.py | zacharlie/rezoning-explorer-api | train | 0 |
f5c17ead6b571794dfabdb397c2dfa2f8f2699e7 | [
"try:\n payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])\nexcept jwt.ExpiredSignatureError:\n raise serializers.ValidationError('1012: El token expiro')\nexcept jwt.PyJWTError:\n raise serializers.ValidationError('1010: El token es incorrecto')\nif payload['type'] != 'reset_password':\... | <|body_start_0|>
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.ValidationError('1012: El token expiro')
except jwt.PyJWTError:
raise serializers.ValidationError('1010: El token es... | Serializer del reseteo de contraseña. | ResetPasswordSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPasswordSerializer:
"""Serializer del reseteo de contraseña."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def validate(self, data):
"""Validamos las nuevas contraseñas"""
<|body_1|>
def save(self):
"""Resete... | stack_v2_sparse_classes_75kplus_train_072555 | 4,981 | no_license | [
{
"docstring": "Verify token is valid.",
"name": "validate_token",
"signature": "def validate_token(self, data)"
},
{
"docstring": "Validamos las nuevas contraseñas",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Reseteo de contraseña",
"name"... | 3 | stack_v2_sparse_classes_30k_train_013124 | Implement the Python class `ResetPasswordSerializer` described below.
Class description:
Serializer del reseteo de contraseña.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def validate(self, data): Validamos las nuevas contraseñas
- def save(self): Reseteo de contraseña | Implement the Python class `ResetPasswordSerializer` described below.
Class description:
Serializer del reseteo de contraseña.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def validate(self, data): Validamos las nuevas contraseñas
- def save(self): Reseteo de contraseña... | 4d008e315d49f942e314ac79f9bcdb5c0f84c568 | <|skeleton|>
class ResetPasswordSerializer:
"""Serializer del reseteo de contraseña."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def validate(self, data):
"""Validamos las nuevas contraseñas"""
<|body_1|>
def save(self):
"""Resete... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResetPasswordSerializer:
"""Serializer del reseteo de contraseña."""
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 | foodyplus/foodyplus/users/serializers/users.py | Sanguet/Platzi-Olimpiada | train | 0 |
3a7415cc395d9c016636c8edf0115be038eedba5 | [
"_expected = {'csv_path': 'numom2b_preprocessing/unittests/config_tests/sample_config_files/', 'files': [{'name': 'csv1.csv'}, {'name': 'csv2.csv'}], 'target': ('numom2b_preprocessing/unittests/config_tests/sample_config_files/target1.csv', []), 'paths': [('numom2b_preprocessing/unittests/config_tests/sample_config... | <|body_start_0|>
_expected = {'csv_path': 'numom2b_preprocessing/unittests/config_tests/sample_config_files/', 'files': [{'name': 'csv1.csv'}, {'name': 'csv2.csv'}], 'target': ('numom2b_preprocessing/unittests/config_tests/sample_config_files/target1.csv', []), 'paths': [('numom2b_preprocessing/unittests/config... | Initialize loading from config files with (possibly) ideal settings: good formatting, correct path variables, etc. | InitializeConfigurationTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitializeConfigurationTest:
"""Initialize loading from config files with (possibly) ideal settings: good formatting, correct path variables, etc."""
def test_initialize_configuration_1(self):
"""Test contents of ``config_tests/sample_config_files/config1.json``."""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_072556 | 4,762 | permissive | [
{
"docstring": "Test contents of ``config_tests/sample_config_files/config1.json``.",
"name": "test_initialize_configuration_1",
"signature": "def test_initialize_configuration_1(self)"
},
{
"docstring": "Test contents of ``config_tests/sample_config_files/config2.json`` This contains \"drop\" d... | 3 | stack_v2_sparse_classes_30k_train_020922 | Implement the Python class `InitializeConfigurationTest` described below.
Class description:
Initialize loading from config files with (possibly) ideal settings: good formatting, correct path variables, etc.
Method signatures and docstrings:
- def test_initialize_configuration_1(self): Test contents of ``config_tests... | Implement the Python class `InitializeConfigurationTest` described below.
Class description:
Initialize loading from config files with (possibly) ideal settings: good formatting, correct path variables, etc.
Method signatures and docstrings:
- def test_initialize_configuration_1(self): Test contents of ``config_tests... | 2e89bc55a61ce2a4ce77646bb427f5b3040f672c | <|skeleton|>
class InitializeConfigurationTest:
"""Initialize loading from config files with (possibly) ideal settings: good formatting, correct path variables, etc."""
def test_initialize_configuration_1(self):
"""Test contents of ``config_tests/sample_config_files/config1.json``."""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InitializeConfigurationTest:
"""Initialize loading from config files with (possibly) ideal settings: good formatting, correct path variables, etc."""
def test_initialize_configuration_1(self):
"""Test contents of ``config_tests/sample_config_files/config1.json``."""
_expected = {'csv_path... | the_stack_v2_python_sparse | numom2b_preprocessing/unittests/config_tests/test_initialize_settings.py | hayesall/nuMoM2b_preprocessing | train | 2 |
c6a8bf052bd1d377565c9aeb15e3dcde937a35ec | [
"self.to = to\nself.mfrom = mfrom\nself.application_id = application_id\nself.scope = scope\nself.message = message\nself.digits = digits",
"if dictionary is None:\n return None\nto = dictionary.get('to')\nmfrom = dictionary.get('from')\napplication_id = dictionary.get('applicationId')\nmessage = dictionary.ge... | <|body_start_0|>
self.to = to
self.mfrom = mfrom
self.application_id = application_id
self.scope = scope
self.message = message
self.digits = digits
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
to = dictionary.get('to')
... | Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The application unique ID, obtained from Bandwidth. scope (st... | TwoFactorCodeRequestSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoFactorCodeRequestSchema:
"""Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The app... | stack_v2_sparse_classes_75kplus_train_072557 | 3,300 | permissive | [
{
"docstring": "Constructor for the TwoFactorCodeRequestSchema class",
"name": "__init__",
"signature": "def __init__(self, to=None, mfrom=None, application_id=None, message=None, digits=None, scope=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (d... | 2 | stack_v2_sparse_classes_30k_train_030508 | Implement the Python class `TwoFactorCodeRequestSchema` described below.
Class description:
Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa... | Implement the Python class `TwoFactorCodeRequestSchema` described below.
Class description:
Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class TwoFactorCodeRequestSchema:
"""Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The app... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoFactorCodeRequestSchema:
"""Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The application uniq... | the_stack_v2_python_sparse | bandwidth/multifactorauth/models/two_factor_code_request_schema.py | Bandwidth/python-sdk | train | 10 |
8c16098949430a781a03906f3a133e045bc48283 | [
"threading.Thread.__init__(self)\nself.threadName = name\nself.people = people",
"print('开始线程:' + self.threadName)\nchi(self.people)\nprint('结束线程:' + self.name)"
] | <|body_start_0|>
threading.Thread.__init__(self)
self.threadName = name
self.people = people
<|end_body_0|>
<|body_start_1|>
print('开始线程:' + self.threadName)
chi(self.people)
print('结束线程:' + self.name)
<|end_body_1|>
| myThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
<|body_0|>
def run(self):
"""重写run方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
threading.Thread.__init__(self)
self.threadName = name
self.people = peopl... | stack_v2_sparse_classes_75kplus_train_072558 | 1,105 | no_license | [
{
"docstring": "重写threading.Thread初始化内容",
"name": "__init__",
"signature": "def __init__(self, people, name)"
},
{
"docstring": "重写run方法",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046849 | Implement the Python class `myThread` described below.
Class description:
Implement the myThread class.
Method signatures and docstrings:
- def __init__(self, people, name): 重写threading.Thread初始化内容
- def run(self): 重写run方法 | Implement the Python class `myThread` described below.
Class description:
Implement the myThread class.
Method signatures and docstrings:
- def __init__(self, people, name): 重写threading.Thread初始化内容
- def run(self): 重写run方法
<|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thr... | 56197668482f3f776e97258b845ec80adbe8e6cc | <|skeleton|>
class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
<|body_0|>
def run(self):
"""重写run方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class myThread:
def __init__(self, people, name):
"""重写threading.Thread初始化内容"""
threading.Thread.__init__(self)
self.threadName = name
self.people = people
def run(self):
"""重写run方法"""
print('开始线程:' + self.threadName)
chi(self.people)
print('结束线程:... | the_stack_v2_python_sparse | Script/threading/case_threading_02.py | gentle-yu/PythonProject | train | 0 | |
5d051dfd7b6141086072e8a5ce1f9819f14be4e6 | [
"if self is None:\n pass\nloc = obj.location\nreturn loc.desc",
"field = super(LawAdmin, self).formfield_for_dbfield(db_field, request, **kwargs)\nif db_field.name == 'title':\n field.widget.attrs['rows'] = 2\nif db_field.name == 'summary':\n field.widget.attrs['rows'] = 10\nif db_field.name == 'relevanc... | <|body_start_0|>
if self is None:
pass
loc = obj.location
return loc.desc
<|end_body_0|>
<|body_start_1|>
field = super(LawAdmin, self).formfield_for_dbfield(db_field, request, **kwargs)
if db_field.name == 'title':
field.widget.attrs['rows'] = 2
... | Admin for cfc_app_law | LawAdmin | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LawAdmin:
"""Admin for cfc_app_law"""
def loc_desc(self, obj):
"""Get location description"""
<|body_0|>
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Override formfield for text areas"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072559 | 2,236 | permissive | [
{
"docstring": "Get location description",
"name": "loc_desc",
"signature": "def loc_desc(self, obj)"
},
{
"docstring": "Override formfield for text areas",
"name": "formfield_for_dbfield",
"signature": "def formfield_for_dbfield(self, db_field, request, **kwargs)"
}
] | 2 | null | Implement the Python class `LawAdmin` described below.
Class description:
Admin for cfc_app_law
Method signatures and docstrings:
- def loc_desc(self, obj): Get location description
- def formfield_for_dbfield(self, db_field, request, **kwargs): Override formfield for text areas | Implement the Python class `LawAdmin` described below.
Class description:
Admin for cfc_app_law
Method signatures and docstrings:
- def loc_desc(self, obj): Get location description
- def formfield_for_dbfield(self, db_field, request, **kwargs): Override formfield for text areas
<|skeleton|>
class LawAdmin:
"""A... | 0c49ee0f10da97ed52121d0d2eb9ee200803af5d | <|skeleton|>
class LawAdmin:
"""Admin for cfc_app_law"""
def loc_desc(self, obj):
"""Get location description"""
<|body_0|>
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Override formfield for text areas"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LawAdmin:
"""Admin for cfc_app_law"""
def loc_desc(self, obj):
"""Get location description"""
if self is None:
pass
loc = obj.location
return loc.desc
def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Override formfield for text area... | the_stack_v2_python_sparse | cfc_app/admin.py | AmericanAirlines/Legit-Info | train | 1 |
bb095e081f5d6a2733bde415bf5eba254e089542 | [
"if len(nums) == 1:\n return 0\ntmp = [0]\nlen_nums = len(nums)\nfor k in range(len_nums):\n if k + nums[k] < len_nums - 1:\n for i in range(len(tmp) - 1, k + nums[k]):\n tmp.append(tmp[k] + 1)\n else:\n return tmp[k] + 1",
"if len(nums) == 1:\n return 0\nlen_nums = len(nums)\... | <|body_start_0|>
if len(nums) == 1:
return 0
tmp = [0]
len_nums = len(nums)
for k in range(len_nums):
if k + nums[k] < len_nums - 1:
for i in range(len(tmp) - 1, k + nums[k]):
tmp.append(tmp[k] + 1)
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump01(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 1:
return 0
tmp = [0]... | stack_v2_sparse_classes_75kplus_train_072560 | 1,494 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump01",
"signature": "def jump01(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 jump01(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 jump01(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def jump(self, nums):
... | 01f2edd79a1e922bfefecad69e5f2e1ff3a479e5 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump01(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 1:
return 0
tmp = [0]
len_nums = len(nums)
for k in range(len_nums):
if k + nums[k] < len_nums - 1:
for i in range(len(tmp) - 1, k + nums[k]):... | the_stack_v2_python_sparse | archives/leetcode/0045. Jump Game II.py | yangzongwu/leetcode | train | 10 | |
e2167a7a9ed7fca76e924eafff1113f689c2db97 | [
"self.num_classes = num_classes\nself.shape = shape\nself.is_infer = is_infer\nself.image_vector_size = shape[0] * shape[1]\nself.__declare_input_layers__()\nself.__build_nn__()",
"self.image = layer.data(name='image', type=paddle.data_type.dense_vector(self.image_vector_size), height=self.shape[0], width=self.sh... | <|body_start_0|>
self.num_classes = num_classes
self.shape = shape
self.is_infer = is_infer
self.image_vector_size = shape[0] * shape[1]
self.__declare_input_layers__()
self.__build_nn__()
<|end_body_0|>
<|body_start_1|>
self.image = layer.data(name='image', type... | Model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :t... | stack_v2_sparse_classes_75kplus_train_072561 | 4,286 | permissive | [
{
"docstring": ":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :type shape: bool",
"name": "__init__",
"signature": "def __init__(s... | 4 | stack_v2_sparse_classes_30k_train_007679 | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, num_classes, shape, is_infer=False): :param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type sha... | Implement the Python class `Model` described below.
Class description:
Implement the Model class.
Method signatures and docstrings:
- def __init__(self, num_classes, shape, is_infer=False): :param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type sha... | 420527996b6da60ca401717a734329f126ed0680 | <|skeleton|>
class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Model:
def __init__(self, num_classes, shape, is_infer=False):
""":param num_classes: The size of the character dict. :type num_classes: int :param shape: The size of the input images. :type shape: tuple of 2 int :param is_infer: The boolean parameter indicating inferring or training. :type shape: boo... | the_stack_v2_python_sparse | legacy/scene_text_recognition/network_conf.py | chenbjin/models | train | 3 | |
2fd2b022924359c529bbb013722c8240e56a971f | [
"try:\n cases_query = InterfacesTestCase.extend()\n if case_id is not None:\n cases_query = cases_query.filter(InterfacesTestCase.cases == int(case_id))\n case_interfaces = await self.application.objects.execute(cases_query)\n for case_interface in case_interfaces:\n case_interface_index =... | <|body_start_0|>
try:
cases_query = InterfacesTestCase.extend()
if case_id is not None:
cases_query = cases_query.filter(InterfacesTestCase.cases == int(case_id))
case_interfaces = await self.application.objects.execute(cases_query)
for case_interf... | TestCaseChangeHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCaseChangeHandler:
async def delete(self, case_id, *args, **kwargs):
"""用例删除 :param case_id: 用例编号"""
<|body_0|>
async def patch(self, case_id, *args, **kwargs):
"""用例修改 :param case_id: 用例id"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_072562 | 30,636 | permissive | [
{
"docstring": "用例删除 :param case_id: 用例编号",
"name": "delete",
"signature": "async def delete(self, case_id, *args, **kwargs)"
},
{
"docstring": "用例修改 :param case_id: 用例id",
"name": "patch",
"signature": "async def patch(self, case_id, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036822 | Implement the Python class `TestCaseChangeHandler` described below.
Class description:
Implement the TestCaseChangeHandler class.
Method signatures and docstrings:
- async def delete(self, case_id, *args, **kwargs): 用例删除 :param case_id: 用例编号
- async def patch(self, case_id, *args, **kwargs): 用例修改 :param case_id: 用例id | Implement the Python class `TestCaseChangeHandler` described below.
Class description:
Implement the TestCaseChangeHandler class.
Method signatures and docstrings:
- async def delete(self, case_id, *args, **kwargs): 用例删除 :param case_id: 用例编号
- async def patch(self, case_id, *args, **kwargs): 用例修改 :param case_id: 用例id... | dc9b4c55f0b3ace180c30b7f080eb5d88bb38fdb | <|skeleton|>
class TestCaseChangeHandler:
async def delete(self, case_id, *args, **kwargs):
"""用例删除 :param case_id: 用例编号"""
<|body_0|>
async def patch(self, case_id, *args, **kwargs):
"""用例修改 :param case_id: 用例id"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCaseChangeHandler:
async def delete(self, case_id, *args, **kwargs):
"""用例删除 :param case_id: 用例编号"""
try:
cases_query = InterfacesTestCase.extend()
if case_id is not None:
cases_query = cases_query.filter(InterfacesTestCase.cases == int(case_id))
... | the_stack_v2_python_sparse | apps/interface_test/handlers.py | xiaoxiaolulu/MagicTestPlatform | train | 5 | |
5051ac5be5a764f665200709ab56a62295318e55 | [
"if 'password' in values and confirm_password != values['password']:\n raise ValueError(\"doesn't match to password\")\nreturn confirm_password",
"if not MIN_FIELD_LENGTH < len(username) < MAX_FIELD_LENGTH:\n raise ValueError('must contain between 3 to 20 charactars')\nreturn username",
"if not MIN_FIELD_... | <|body_start_0|>
if 'password' in values and confirm_password != values['password']:
raise ValueError("doesn't match to password")
return confirm_password
<|end_body_0|>
<|body_start_1|>
if not MIN_FIELD_LENGTH < len(username) < MAX_FIELD_LENGTH:
raise ValueError('must c... | Validating fields types | UserCreate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreate:
"""Validating fields types"""
def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]:
"""Validating passwords fields identical."""
<|body_0|>
def username_length(cls, username: str) -> Union[ValueError, str]:
"""Va... | stack_v2_sparse_classes_75kplus_train_072563 | 2,838 | permissive | [
{
"docstring": "Validating passwords fields identical.",
"name": "passwords_match",
"signature": "def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]"
},
{
"docstring": "Validating username length is legal",
"name": "username_length",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_003840 | Implement the Python class `UserCreate` described below.
Class description:
Validating fields types
Method signatures and docstrings:
- def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]: Validating passwords fields identical.
- def username_length(cls, username: str) -> Union... | Implement the Python class `UserCreate` described below.
Class description:
Validating fields types
Method signatures and docstrings:
- def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]: Validating passwords fields identical.
- def username_length(cls, username: str) -> Union... | 23a33703a0038d0eae8ce7299a93ad172c8f68e9 | <|skeleton|>
class UserCreate:
"""Validating fields types"""
def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]:
"""Validating passwords fields identical."""
<|body_0|>
def username_length(cls, username: str) -> Union[ValueError, str]:
"""Va... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserCreate:
"""Validating fields types"""
def passwords_match(cls, confirm_password: str, values: UserBase) -> Union[ValueError, str]:
"""Validating passwords fields identical."""
if 'password' in values and confirm_password != values['password']:
raise ValueError("doesn't mat... | the_stack_v2_python_sparse | app/database/schemas.py | ofir96/calendar | train | 1 |
56f23719986161accc7c9bd14e4eab6ea632c9d6 | [
"sentence = 'Hello, good day!'\nexpected = 'day! good Hello,'\nself.assertEqual(reverse_words(sentence), expected)",
"sentence = 'Hello'\nexpected = sentence\nself.assertEqual(reverse_words(sentence), expected)",
"sentence = 'Hello my name is Dolly and I would like to be your friend'\nexpected = 'friend your be... | <|body_start_0|>
sentence = 'Hello, good day!'
expected = 'day! good Hello,'
self.assertEqual(reverse_words(sentence), expected)
<|end_body_0|>
<|body_start_1|>
sentence = 'Hello'
expected = sentence
self.assertEqual(reverse_words(sentence), expected)
<|end_body_1|>
<|b... | test_reverse_words_implementation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_reverse_words_implementation:
def test_simple_case(self):
"""test a simple three word sentence"""
<|body_0|>
def test_case_where_nothing_changes(self):
"""test a one-word sentence where a reversal of words should do nothing"""
<|body_1|>
def test_a_... | stack_v2_sparse_classes_75kplus_train_072564 | 855 | no_license | [
{
"docstring": "test a simple three word sentence",
"name": "test_simple_case",
"signature": "def test_simple_case(self)"
},
{
"docstring": "test a one-word sentence where a reversal of words should do nothing",
"name": "test_case_where_nothing_changes",
"signature": "def test_case_where... | 3 | stack_v2_sparse_classes_30k_train_028707 | Implement the Python class `test_reverse_words_implementation` described below.
Class description:
Implement the test_reverse_words_implementation class.
Method signatures and docstrings:
- def test_simple_case(self): test a simple three word sentence
- def test_case_where_nothing_changes(self): test a one-word sente... | Implement the Python class `test_reverse_words_implementation` described below.
Class description:
Implement the test_reverse_words_implementation class.
Method signatures and docstrings:
- def test_simple_case(self): test a simple three word sentence
- def test_case_where_nothing_changes(self): test a one-word sente... | 7e884adb19b84a2e5960d1b6e81cd926f0b46705 | <|skeleton|>
class test_reverse_words_implementation:
def test_simple_case(self):
"""test a simple three word sentence"""
<|body_0|>
def test_case_where_nothing_changes(self):
"""test a one-word sentence where a reversal of words should do nothing"""
<|body_1|>
def test_a_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_reverse_words_implementation:
def test_simple_case(self):
"""test a simple three word sentence"""
sentence = 'Hello, good day!'
expected = 'day! good Hello,'
self.assertEqual(reverse_words(sentence), expected)
def test_case_where_nothing_changes(self):
"""test... | the_stack_v2_python_sparse | questions/arrays_and_strings/strings/reverse_words_test.py | qdonnellan/random_questions | train | 0 | |
ae26f22227c885419efa8fca34fa78d760a17f1e | [
"self.clf = clf\nself.costs = costs\nself.m = m\nself.data_row = data_row\nself.for_individual = for_individual\nself.min_max = min_max",
"if self.for_individual:\n self._build_model_from_scratch()\nelse:\n self._build_model()\nif self.m.Status == 2:\n self._get_values(True)\nelif self.m.Status == 3:\n ... | <|body_start_0|>
self.clf = clf
self.costs = costs
self.m = m
self.data_row = data_row
self.for_individual = for_individual
self.min_max = min_max
<|end_body_0|>
<|body_start_1|>
if self.for_individual:
self._build_model_from_scratch()
else:
... | Find minimal flipset per row of input data with a predicted negative outcome. | FlipsetAlgorithm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlipsetAlgorithm:
"""Find minimal flipset per row of input data with a predicted negative outcome."""
def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None):
"""Initialise variables needed."""
<|body_0|>
def run(self):
"""Build the m... | stack_v2_sparse_classes_75kplus_train_072565 | 4,227 | no_license | [
{
"docstring": "Initialise variables needed.",
"name": "__init__",
"signature": "def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None)"
},
{
"docstring": "Build the model, get the new values, and write them to an output file.",
"name": "run",
"signature": "... | 5 | stack_v2_sparse_classes_30k_train_041795 | Implement the Python class `FlipsetAlgorithm` described below.
Class description:
Find minimal flipset per row of input data with a predicted negative outcome.
Method signatures and docstrings:
- def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None): Initialise variables needed.
- def r... | Implement the Python class `FlipsetAlgorithm` described below.
Class description:
Find minimal flipset per row of input data with a predicted negative outcome.
Method signatures and docstrings:
- def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None): Initialise variables needed.
- def r... | 05804150a03ab903a3192ce5846e8aa26c652cdb | <|skeleton|>
class FlipsetAlgorithm:
"""Find minimal flipset per row of input data with a predicted negative outcome."""
def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None):
"""Initialise variables needed."""
<|body_0|>
def run(self):
"""Build the m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlipsetAlgorithm:
"""Find minimal flipset per row of input data with a predicted negative outcome."""
def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None):
"""Initialise variables needed."""
self.clf = clf
self.costs = costs
self.m = m
... | the_stack_v2_python_sparse | ActionableClassification_and_Fairness/flipset_algorithm.py | AminaTkh/Benchmarking-for-actionable-recourse-solutions | train | 0 |
b3b933311205d8e249ba7dc6720b1549dd09b901 | [
"eoo = BaseEdxOAuth2(strategy=load_strategy())\nresult = eoo.get_user_details({'id': 5, 'username': 'darth', 'email': 'darth@deathst.ar', 'name': 'Darth Vader'})\nassert {'edx_id': 'darth', 'username': 'darth', 'fullname': 'Darth Vader', 'email': 'darth@deathst.ar', 'first_name': '', 'last_name': ''} == result",
... | <|body_start_0|>
eoo = BaseEdxOAuth2(strategy=load_strategy())
result = eoo.get_user_details({'id': 5, 'username': 'darth', 'email': 'darth@deathst.ar', 'name': 'Darth Vader'})
assert {'edx_id': 'darth', 'username': 'darth', 'fullname': 'Darth Vader', 'email': 'darth@deathst.ar', 'first_name': '... | Tests for BaseEdxOAuth2 | BaseEdxOAuth2Tests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseEdxOAuth2Tests:
"""Tests for BaseEdxOAuth2"""
def test_response_parsing(self):
"""Should have properly formed payload if working."""
<|body_0|>
def test_single_name(self):
"""If the user only has one name, last_name should be blank."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_072566 | 1,396 | permissive | [
{
"docstring": "Should have properly formed payload if working.",
"name": "test_response_parsing",
"signature": "def test_response_parsing(self)"
},
{
"docstring": "If the user only has one name, last_name should be blank.",
"name": "test_single_name",
"signature": "def test_single_name(... | 2 | stack_v2_sparse_classes_30k_train_003416 | Implement the Python class `BaseEdxOAuth2Tests` described below.
Class description:
Tests for BaseEdxOAuth2
Method signatures and docstrings:
- def test_response_parsing(self): Should have properly formed payload if working.
- def test_single_name(self): If the user only has one name, last_name should be blank. | Implement the Python class `BaseEdxOAuth2Tests` described below.
Class description:
Tests for BaseEdxOAuth2
Method signatures and docstrings:
- def test_response_parsing(self): Should have properly formed payload if working.
- def test_single_name(self): If the user only has one name, last_name should be blank.
<|sk... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class BaseEdxOAuth2Tests:
"""Tests for BaseEdxOAuth2"""
def test_response_parsing(self):
"""Should have properly formed payload if working."""
<|body_0|>
def test_single_name(self):
"""If the user only has one name, last_name should be blank."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseEdxOAuth2Tests:
"""Tests for BaseEdxOAuth2"""
def test_response_parsing(self):
"""Should have properly formed payload if working."""
eoo = BaseEdxOAuth2(strategy=load_strategy())
result = eoo.get_user_details({'id': 5, 'username': 'darth', 'email': 'darth@deathst.ar', 'name': ... | the_stack_v2_python_sparse | backends/base_test.py | mitodl/micromasters | train | 35 |
ce8cd1433ff91a6b83173b53dcdc62ddb8d66c01 | [
"super(VMRuntimeInstanceFactory, self).__init__(request_data, 8 if runtime_config_getter().threadsafe else 1, 10)\nself._runtime_config_getter = runtime_config_getter\nself._module_configuration = module_configuration\nself._docker_client = containers.NewDockerClient(version='1.9', timeout=self.DOCKER_D_REQUEST_TIM... | <|body_start_0|>
super(VMRuntimeInstanceFactory, self).__init__(request_data, 8 if runtime_config_getter().threadsafe else 1, 10)
self._runtime_config_getter = runtime_config_getter
self._module_configuration = module_configuration
self._docker_client = containers.NewDockerClient(version... | A factory that creates new VM runtime Instances. | VMRuntimeInstanceFactory | [
"Apache-2.0",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"MIT",
"GPL-2.0-or-later",
"MPL-1.1",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VMRuntimeInstanceFactory:
"""A factory that creates new VM runtime Instances."""
def __init__(self, request_data, runtime_config_getter, module_configuration):
"""Initializer for VMRuntimeInstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided w... | stack_v2_sparse_classes_75kplus_train_072567 | 4,064 | permissive | [
{
"docstring": "Initializer for VMRuntimeInstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided with request information for use by API stubs. runtime_config_getter: A function that can be called without arguments and returns the runtime_config_pb2.Config containing the c... | 2 | stack_v2_sparse_classes_30k_train_023568 | Implement the Python class `VMRuntimeInstanceFactory` described below.
Class description:
A factory that creates new VM runtime Instances.
Method signatures and docstrings:
- def __init__(self, request_data, runtime_config_getter, module_configuration): Initializer for VMRuntimeInstanceFactory. Args: request_data: A ... | Implement the Python class `VMRuntimeInstanceFactory` described below.
Class description:
A factory that creates new VM runtime Instances.
Method signatures and docstrings:
- def __init__(self, request_data, runtime_config_getter, module_configuration): Initializer for VMRuntimeInstanceFactory. Args: request_data: A ... | d379afa2db3582d5c3be652165f0e9e2e0c154c6 | <|skeleton|>
class VMRuntimeInstanceFactory:
"""A factory that creates new VM runtime Instances."""
def __init__(self, request_data, runtime_config_getter, module_configuration):
"""Initializer for VMRuntimeInstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VMRuntimeInstanceFactory:
"""A factory that creates new VM runtime Instances."""
def __init__(self, request_data, runtime_config_getter, module_configuration):
"""Initializer for VMRuntimeInstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided with request i... | the_stack_v2_python_sparse | y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/vm_runtime_factory.py | ychen820/microblog | train | 0 |
f2c1ef9a1b7c75b50cf673b0c029b57c7f71376d | [
"itrs_m = defaultdict(list)\nfor w in words:\n itrs_m[w[0]].append(iter(w[1:]))\nfor a in S:\n itrs = itrs_m.pop(a, [])\n for itr in itrs:\n v = next(itr, None)\n itrs_m[v].append(itr)\nreturn len(itrs_m[None])",
"I = [0 for _ in words]\nfor a in S:\n for wi, i in enumerate(I):\n ... | <|body_start_0|>
itrs_m = defaultdict(list)
for w in words:
itrs_m[w[0]].append(iter(w[1:]))
for a in S:
itrs = itrs_m.pop(a, [])
for itr in itrs:
v = next(itr, None)
itrs_m[v].append(itr)
return len(itrs_m[None])
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
"""Linear O(|S| + sum(|word|)) no need to if-check HashMap + Iterator"""
<|body_0|>
def numMatchingSubseq_TLE(self, S: str, words: List[str]) -> int:
"""Brute force O(|S| |Words| M) Is a better w... | stack_v2_sparse_classes_75kplus_train_072568 | 1,814 | no_license | [
{
"docstring": "Linear O(|S| + sum(|word|)) no need to if-check HashMap + Iterator",
"name": "numMatchingSubseq",
"signature": "def numMatchingSubseq(self, S: str, words: List[str]) -> int"
},
{
"docstring": "Brute force O(|S| |Words| M) Is a better way to check subsequence? No Can we parallel t... | 2 | stack_v2_sparse_classes_30k_train_035446 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S: str, words: List[str]) -> int: Linear O(|S| + sum(|word|)) no need to if-check HashMap + Iterator
- def numMatchingSubseq_TLE(self, S: str, words: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S: str, words: List[str]) -> int: Linear O(|S| + sum(|word|)) no need to if-check HashMap + Iterator
- def numMatchingSubseq_TLE(self, S: str, words: ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
"""Linear O(|S| + sum(|word|)) no need to if-check HashMap + Iterator"""
<|body_0|>
def numMatchingSubseq_TLE(self, S: str, words: List[str]) -> int:
"""Brute force O(|S| |Words| M) Is a better w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
"""Linear O(|S| + sum(|word|)) no need to if-check HashMap + Iterator"""
itrs_m = defaultdict(list)
for w in words:
itrs_m[w[0]].append(iter(w[1:]))
for a in S:
itrs = itrs_m.pop(a, ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/792 Number of Matching Subsequences.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
76cd6aabee6122feb7811b641799bc8b292e3529 | [
"nums.sort()\nresults = []\nfor i in range(len(nums) - 3):\n if i == 0 or nums[i] != nums[i - 1]:\n threeResult = self.threeSum(nums[i + 1:], target - nums[i])\n for item in threeResult:\n results.append([nums[i]] + item)\nreturn results",
"res = []\nnums.sort()\nfor i in range(len(num... | <|body_start_0|>
nums.sort()
results = []
for i in range(len(nums) - 3):
if i == 0 or nums[i] != nums[i - 1]:
threeResult = self.threeSum(nums[i + 1:], target - nums[i])
for item in threeResult:
results.append([nums[i]] + item)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] https://leetcode.com/problems/4sum/discuss/8545/Python-140ms-beats-100-and-works-for-N-sum-(Ngreater2)"""
<|body_0|>
def threeSum(self, nums, target):
"""第15... | stack_v2_sparse_classes_75kplus_train_072569 | 3,097 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]] https://leetcode.com/problems/4sum/discuss/8545/Python-140ms-beats-100-and-works-for-N-sum-(Ngreater2)",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": "第15题 :type nums: List[int]... | 2 | stack_v2_sparse_classes_30k_train_050905 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]] https://leetcode.com/problems/4sum/discuss/8545/Python-140ms-beats-100-and-works-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]] https://leetcode.com/problems/4sum/discuss/8545/Python-140ms-beats-100-and-works-... | 0b3bc77cbfe0e45e62c3c8f244e9e3d2421e6121 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] https://leetcode.com/problems/4sum/discuss/8545/Python-140ms-beats-100-and-works-for-N-sum-(Ngreater2)"""
<|body_0|>
def threeSum(self, nums, target):
"""第15... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]] https://leetcode.com/problems/4sum/discuss/8545/Python-140ms-beats-100-and-works-for-N-sum-(Ngreater2)"""
nums.sort()
results = []
for i in range(len(nums) - 3):
... | the_stack_v2_python_sparse | 18.py | lailianqi/LeetCodeByPython | train | 0 | |
78f27d147fc185cb5d0334b985a5246d1b087f53 | [
"if geotransform is None and wkt is not None or (geotransform is not None and wkt is None):\n raise RuntimeError('Must supply both geotransform and wkt or neither of them')\nelif geotransform is not None and wkt is not None:\n self._apply_transform = True\nelse:\n self._apply_transform = False\nself.mask =... | <|body_start_0|>
if geotransform is None and wkt is not None or (geotransform is not None and wkt is None):
raise RuntimeError('Must supply both geotransform and wkt or neither of them')
elif geotransform is not None and wkt is not None:
self._apply_transform = True
else:... | Pipeline item used for masking images | Mask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mask:
"""Pipeline item used for masking images"""
def __init__(self, str_description, mask, mask_value=math.nan, geotransform=None, wkt=None):
"""Initialize Mask item If geotransform and wkt are provided, then mask will be transformed before being applied @param str_description: Stri... | stack_v2_sparse_classes_75kplus_train_072570 | 4,453 | permissive | [
{
"docstring": "Initialize Mask item If geotransform and wkt are provided, then mask will be transformed before being applied @param str_description: String describing item @param mask: Array of zeros and ones with the same shape as the input images (1 for mask, 0 for no mask) @param mask_value: Value to set th... | 2 | stack_v2_sparse_classes_30k_train_042153 | Implement the Python class `Mask` described below.
Class description:
Pipeline item used for masking images
Method signatures and docstrings:
- def __init__(self, str_description, mask, mask_value=math.nan, geotransform=None, wkt=None): Initialize Mask item If geotransform and wkt are provided, then mask will be tran... | Implement the Python class `Mask` described below.
Class description:
Pipeline item used for masking images
Method signatures and docstrings:
- def __init__(self, str_description, mask, mask_value=math.nan, geotransform=None, wkt=None): Initialize Mask item If geotransform and wkt are provided, then mask will be tran... | 4d22e3ef90ef842d6b390074a8b5deedc7658a2b | <|skeleton|>
class Mask:
"""Pipeline item used for masking images"""
def __init__(self, str_description, mask, mask_value=math.nan, geotransform=None, wkt=None):
"""Initialize Mask item If geotransform and wkt are provided, then mask will be transformed before being applied @param str_description: Stri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Mask:
"""Pipeline item used for masking images"""
def __init__(self, str_description, mask, mask_value=math.nan, geotransform=None, wkt=None):
"""Initialize Mask item If geotransform and wkt are provided, then mask will be transformed before being applied @param str_description: String describing... | the_stack_v2_python_sparse | pyinsar/processing/discovery/mask.py | MITeaps/pyinsar | train | 11 |
35a247798dda4c42fc32f6d7ae28d37ed139a09e | [
"self.request_id = request_id\nself.status = status\nself.failed_telephone_numbers = failed_telephone_numbers\nself.result = result",
"if dictionary is None:\n return None\nrequest_id = dictionary.get('requestId')\nstatus = dictionary.get('status')\nfailed_telephone_numbers = dictionary.get('failedTelephoneNum... | <|body_start_0|>
self.request_id = request_id
self.status = status
self.failed_telephone_numbers = failed_telephone_numbers
self.result = result
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
request_id = dictionary.get('requestId')
... | Implementation of the 'OrderStatus' model. If requestId exists, the result for that request is returned. See the Examples for details on the various responses that you can receive. Generally, if you see a Response Code of 0 in a result for a TN, information will be available for it. Any other Response Code will indicat... | OrderStatus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderStatus:
"""Implementation of the 'OrderStatus' model. If requestId exists, the result for that request is returned. See the Examples for details on the various responses that you can receive. Generally, if you see a Response Code of 0 in a result for a TN, information will be available for i... | stack_v2_sparse_classes_75kplus_train_072571 | 2,840 | permissive | [
{
"docstring": "Constructor for the OrderStatus class",
"name": "__init__",
"signature": "def __init__(self, request_id=None, status=None, failed_telephone_numbers=None, result=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictiona... | 2 | null | Implement the Python class `OrderStatus` described below.
Class description:
Implementation of the 'OrderStatus' model. If requestId exists, the result for that request is returned. See the Examples for details on the various responses that you can receive. Generally, if you see a Response Code of 0 in a result for a ... | Implement the Python class `OrderStatus` described below.
Class description:
Implementation of the 'OrderStatus' model. If requestId exists, the result for that request is returned. See the Examples for details on the various responses that you can receive. Generally, if you see a Response Code of 0 in a result for a ... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class OrderStatus:
"""Implementation of the 'OrderStatus' model. If requestId exists, the result for that request is returned. See the Examples for details on the various responses that you can receive. Generally, if you see a Response Code of 0 in a result for a TN, information will be available for i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrderStatus:
"""Implementation of the 'OrderStatus' model. If requestId exists, the result for that request is returned. See the Examples for details on the various responses that you can receive. Generally, if you see a Response Code of 0 in a result for a TN, information will be available for it. Any other ... | the_stack_v2_python_sparse | bandwidth/phonenumberlookup/models/order_status.py | Bandwidth/python-sdk | train | 10 |
f637f9cb2a861f961b64d149d01f109268077f38 | [
"try:\n return states.index(state_name)\nexcept ValueError:\n raise StateException(\"Unknown state '%s'\" % state_name)",
"if state < 0 or state > len(states):\n raise StateException('Unknown state #%s' % state)\nreturn states[state]"
] | <|body_start_0|>
try:
return states.index(state_name)
except ValueError:
raise StateException("Unknown state '%s'" % state_name)
<|end_body_0|>
<|body_start_1|>
if state < 0 or state > len(states):
raise StateException('Unknown state #%s' % state)
ret... | Generic class for keeping track of the current state | AbstractState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractState:
"""Generic class for keeping track of the current state"""
def get_state(cls, states, state_name):
"""Return the numeric value of the named state state_name - named state"""
<|body_0|>
def state_string(cls, states, state):
"""Return the string asso... | stack_v2_sparse_classes_75kplus_train_072572 | 29,675 | no_license | [
{
"docstring": "Return the numeric value of the named state state_name - named state",
"name": "get_state",
"signature": "def get_state(cls, states, state_name)"
},
{
"docstring": "Return the string associated with a numeric state state - numeric state value",
"name": "state_string",
"si... | 2 | stack_v2_sparse_classes_30k_train_045093 | Implement the Python class `AbstractState` described below.
Class description:
Generic class for keeping track of the current state
Method signatures and docstrings:
- def get_state(cls, states, state_name): Return the numeric value of the named state state_name - named state
- def state_string(cls, states, state): R... | Implement the Python class `AbstractState` described below.
Class description:
Generic class for keeping track of the current state
Method signatures and docstrings:
- def get_state(cls, states, state_name): Return the numeric value of the named state state_name - named state
- def state_string(cls, states, state): R... | 718189be62907a6a8031980fe0c41fa7e06b898d | <|skeleton|>
class AbstractState:
"""Generic class for keeping track of the current state"""
def get_state(cls, states, state_name):
"""Return the numeric value of the named state state_name - named state"""
<|body_0|>
def state_string(cls, states, state):
"""Return the string asso... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbstractState:
"""Generic class for keeping track of the current state"""
def get_state(cls, states, state_name):
"""Return the numeric value of the named state state_name - named state"""
try:
return states.index(state_name)
except ValueError:
raise StateE... | the_stack_v2_python_sparse | liverun.py | dglo/dash | train | 0 |
0470920fe7a37fbe76239686a9695487c3953965 | [
"self.pre_trie = {}\nself.suf_trie = {}\nfor idx, w in enumerate(words):\n pre_cur = self.pre_trie\n suf_cur = self.suf_trie\n for i in range(len(w)):\n if w[i] not in pre_cur:\n pre_cur[w[i]] = {}\n pre_cur = pre_cur[w[i]]\n if w[len(w) - 1 - i] not in suf_cur:\n ... | <|body_start_0|>
self.pre_trie = {}
self.suf_trie = {}
for idx, w in enumerate(words):
pre_cur = self.pre_trie
suf_cur = self.suf_trie
for i in range(len(w)):
if w[i] not in pre_cur:
pre_cur[w[i]] = {}
pre_cu... | WordFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
"""two tie :type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pre_trie = {}
self.su... | stack_v2_sparse_classes_75kplus_train_072573 | 982 | no_license | [
{
"docstring": "two tie :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type prefix: str :type suffix: str :rtype: int",
"name": "f",
"signature": "def f(self, prefix, suffix)"
}
] | 2 | null | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): two tie :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): two tie :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
<|skeleton|>
class WordFilter:
... | e16702d2b3ec4e5054baad56f4320bc3b31676ad | <|skeleton|>
class WordFilter:
def __init__(self, words):
"""two tie :type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordFilter:
def __init__(self, words):
"""two tie :type words: List[str]"""
self.pre_trie = {}
self.suf_trie = {}
for idx, w in enumerate(words):
pre_cur = self.pre_trie
suf_cur = self.suf_trie
for i in range(len(w)):
if w[i] ... | the_stack_v2_python_sparse | leetcode/hard/Prefix_and_Suffix_Search.py | SuperMartinYang/learning_algorithm | train | 0 | |
c948f98914c2b348da01fcaab8b00dcbe224c950 | [
"try:\n res = questions.find({'q_id': id})\n return res[0]\nexcept Exception as e:\n print(e)",
"try:\n cursor = questions.find({'topics': topic})\n result = []\n for x in cursor:\n result.append(x)\n return result\nexcept Exception as e:\n print(e)",
"try:\n if st == None and ... | <|body_start_0|>
try:
res = questions.find({'q_id': id})
return res[0]
except Exception as e:
print(e)
<|end_body_0|>
<|body_start_1|>
try:
cursor = questions.find({'topics': topic})
result = []
for x in cursor:
... | QBank | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QBank:
def getQuestion(self, id):
"""Find question in database with given ID."""
<|body_0|>
def searchByTopic(self, topic):
"""Find Questions according to given topic. Returns an array of questions."""
<|body_1|>
def searchByAskDate(self, st, end):
... | stack_v2_sparse_classes_75kplus_train_072574 | 2,567 | no_license | [
{
"docstring": "Find question in database with given ID.",
"name": "getQuestion",
"signature": "def getQuestion(self, id)"
},
{
"docstring": "Find Questions according to given topic. Returns an array of questions.",
"name": "searchByTopic",
"signature": "def searchByTopic(self, topic)"
... | 5 | null | Implement the Python class `QBank` described below.
Class description:
Implement the QBank class.
Method signatures and docstrings:
- def getQuestion(self, id): Find question in database with given ID.
- def searchByTopic(self, topic): Find Questions according to given topic. Returns an array of questions.
- def sear... | Implement the Python class `QBank` described below.
Class description:
Implement the QBank class.
Method signatures and docstrings:
- def getQuestion(self, id): Find question in database with given ID.
- def searchByTopic(self, topic): Find Questions according to given topic. Returns an array of questions.
- def sear... | 59ae2e8628d148d3aadf9763ce5c1bebb41ee92d | <|skeleton|>
class QBank:
def getQuestion(self, id):
"""Find question in database with given ID."""
<|body_0|>
def searchByTopic(self, topic):
"""Find Questions according to given topic. Returns an array of questions."""
<|body_1|>
def searchByAskDate(self, st, end):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QBank:
def getQuestion(self, id):
"""Find question in database with given ID."""
try:
res = questions.find({'q_id': id})
return res[0]
except Exception as e:
print(e)
def searchByTopic(self, topic):
"""Find Questions according to given t... | the_stack_v2_python_sparse | phase1/QBank.py | KYurtseven/SoftDevWithScriptingLanguages_Ceng445 | train | 4 | |
ec9559f8d13490b602522f8d7715de56e696551b | [
"self.service = service\nself.profile_id = profile_id\nself.projection = projection\ngdata.service.Query.__init__(self, feed=feed, text_query=text_query, params=params, categories=categories)",
"old_feed = self.feed\nself.feed = '/'.join([self.service, old_feed, self.projection])\nif self.profile_id:\n self.fe... | <|body_start_0|>
self.service = service
self.profile_id = profile_id
self.projection = projection
gdata.service.Query.__init__(self, feed=feed, text_query=text_query, params=params, categories=categories)
<|end_body_0|>
<|body_start_1|>
old_feed = self.feed
self.feed = '... | Object used to construct a URI to query the Google Health profile feed. | HealthProfileQuery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HealthProfileQuery:
"""Object used to construct a URI to query the Google Health profile feed."""
def __init__(self, service='health', feed='feeds/profile', projection='default', profile_id=None, text_query=None, params=None, categories=None):
"""Constructor for Health profile feed q... | stack_v2_sparse_classes_75kplus_train_072575 | 10,007 | permissive | [
{
"docstring": "Constructor for Health profile feed query. Args: service: string (optional) The service to query. Either 'health' or 'h9'. feed: string (optional) The path for the feed. The default value is 'feeds/profile'. projection: string (optional) The visibility of the data. Possible values are 'default' ... | 2 | null | Implement the Python class `HealthProfileQuery` described below.
Class description:
Object used to construct a URI to query the Google Health profile feed.
Method signatures and docstrings:
- def __init__(self, service='health', feed='feeds/profile', projection='default', profile_id=None, text_query=None, params=None... | Implement the Python class `HealthProfileQuery` described below.
Class description:
Object used to construct a URI to query the Google Health profile feed.
Method signatures and docstrings:
- def __init__(self, service='health', feed='feeds/profile', projection='default', profile_id=None, text_query=None, params=None... | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | <|skeleton|>
class HealthProfileQuery:
"""Object used to construct a URI to query the Google Health profile feed."""
def __init__(self, service='health', feed='feeds/profile', projection='default', profile_id=None, text_query=None, params=None, categories=None):
"""Constructor for Health profile feed q... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HealthProfileQuery:
"""Object used to construct a URI to query the Google Health profile feed."""
def __init__(self, service='health', feed='feeds/profile', projection='default', profile_id=None, text_query=None, params=None, categories=None):
"""Constructor for Health profile feed query. Args: s... | the_stack_v2_python_sparse | python-build/python-libs/gdata/build/lib/gdata/health/service.py | kuri65536/python-for-android | train | 280 |
d6471002f682d9901d0deea45c4b78172f5285fd | [
"self.diphthongs_ipa = diphthongs_ipa\nself.diphthongs_ipa_class = diphthongs_ipa_class\nself.ipa_class = ipa_class\nself.rules = rules",
"phonemes = self.text_to_phonemes(word)\nphonetic_representation = self.phonemes_to_phonetic_representation(phonemes)\nif with_squared_brackets:\n return f'[{phonetic_repres... | <|body_start_0|>
self.diphthongs_ipa = diphthongs_ipa
self.diphthongs_ipa_class = diphthongs_ipa_class
self.ipa_class = ipa_class
self.rules = rules
<|end_body_0|>
<|body_start_1|>
phonemes = self.text_to_phonemes(word)
phonetic_representation = self.phonemes_to_phonetic... | There are two steps to transcribe words: - firstly, a greedy approximation of the pronunciation of word - then, use of rules to precise pronunciation of a preprocessed list of transcribed words | Transcriber | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transcriber:
"""There are two steps to transcribe words: - firstly, a greedy approximation of the pronunciation of word - then, use of rules to precise pronunciation of a preprocessed list of transcribed words"""
def __init__(self, diphthongs_ipa: dict, diphthongs_ipa_class: dict, ipa_class:... | stack_v2_sparse_classes_75kplus_train_072576 | 23,537 | permissive | [
{
"docstring": ":param diphthongs_ipa: dict whose keys are written diphthongs and and values IPA trasncription of them :param diphthongs_ipa_class: dict whose keys are written diphthongs and and values are Vowel instances :param ipa_class: dict whose keys are written characters and and values are Vowel or Conso... | 5 | stack_v2_sparse_classes_30k_train_047069 | Implement the Python class `Transcriber` described below.
Class description:
There are two steps to transcribe words: - firstly, a greedy approximation of the pronunciation of word - then, use of rules to precise pronunciation of a preprocessed list of transcribed words
Method signatures and docstrings:
- def __init_... | Implement the Python class `Transcriber` described below.
Class description:
There are two steps to transcribe words: - firstly, a greedy approximation of the pronunciation of word - then, use of rules to precise pronunciation of a preprocessed list of transcribed words
Method signatures and docstrings:
- def __init_... | 8a122113d2509aef85bebba8e2c303471c107ff4 | <|skeleton|>
class Transcriber:
"""There are two steps to transcribe words: - firstly, a greedy approximation of the pronunciation of word - then, use of rules to precise pronunciation of a preprocessed list of transcribed words"""
def __init__(self, diphthongs_ipa: dict, diphthongs_ipa_class: dict, ipa_class:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transcriber:
"""There are two steps to transcribe words: - firstly, a greedy approximation of the pronunciation of word - then, use of rules to precise pronunciation of a preprocessed list of transcribed words"""
def __init__(self, diphthongs_ipa: dict, diphthongs_ipa_class: dict, ipa_class: dict, rules:... | the_stack_v2_python_sparse | src/cltk/phonology/non/utils.py | cltk/cltk | train | 847 |
0bd47f621bdac3e959c85edc89a17f5300a0ad7e | [
"assert chunk_size % _CHUNK_SIZE_MULTIPLE == 0, 'chunk_size must be a multiple of %d B' % _CHUNK_SIZE_MULTIPLE\nself.chunk_size = chunk_size\nself.logger = logger\ncredentials = service_account.Credentials.from_service_account_file(json_key_path, scopes=(_GCS_SCOPE,))\nself.client = storage.Client(project='', crede... | <|body_start_0|>
assert chunk_size % _CHUNK_SIZE_MULTIPLE == 0, 'chunk_size must be a multiple of %d B' % _CHUNK_SIZE_MULTIPLE
self.chunk_size = chunk_size
self.logger = logger
credentials = service_account.Credentials.from_service_account_file(json_key_path, scopes=(_GCS_SCOPE,))
... | Wrapper to access Google Cloud Storage. | CloudStorage | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudStorage:
"""Wrapper to access Google Cloud Storage."""
def __init__(self, json_key_path, logger=logging, chunk_size=_CHUNK_SIZE):
"""Authenticates the connection to Cloud Storage. Args: json_key_path: Path to the private key (in JSON format) on disk. logger: A logging.logger obj... | stack_v2_sparse_classes_75kplus_train_072577 | 6,756 | permissive | [
{
"docstring": "Authenticates the connection to Cloud Storage. Args: json_key_path: Path to the private key (in JSON format) on disk. logger: A logging.logger object to record messages. chunk_size: Files uploaded to GCS are sent in chunks. Must be a multiple of _CHUNK_SIZE_MULTIPLE.",
"name": "__init__",
... | 4 | stack_v2_sparse_classes_30k_train_050134 | Implement the Python class `CloudStorage` described below.
Class description:
Wrapper to access Google Cloud Storage.
Method signatures and docstrings:
- def __init__(self, json_key_path, logger=logging, chunk_size=_CHUNK_SIZE): Authenticates the connection to Cloud Storage. Args: json_key_path: Path to the private k... | Implement the Python class `CloudStorage` described below.
Class description:
Wrapper to access Google Cloud Storage.
Method signatures and docstrings:
- def __init__(self, json_key_path, logger=logging, chunk_size=_CHUNK_SIZE): Authenticates the connection to Cloud Storage. Args: json_key_path: Path to the private k... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class CloudStorage:
"""Wrapper to access Google Cloud Storage."""
def __init__(self, json_key_path, logger=logging, chunk_size=_CHUNK_SIZE):
"""Authenticates the connection to Cloud Storage. Args: json_key_path: Path to the private key (in JSON format) on disk. logger: A logging.logger obj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudStorage:
"""Wrapper to access Google Cloud Storage."""
def __init__(self, json_key_path, logger=logging, chunk_size=_CHUNK_SIZE):
"""Authenticates the connection to Cloud Storage. Args: json_key_path: Path to the private key (in JSON format) on disk. logger: A logging.logger object to record... | the_stack_v2_python_sparse | py/utils/gcs_utils.py | bridder/factory | train | 0 |
97b2ba3de09fe1975cbba11a4e8bc609f6a23c5f | [
"self.max_atoms = max_atoms\nself.flatten = flatten\nself.scm: Any = None",
"if 'struct' in kwargs and datapoint is None:\n datapoint = kwargs.get('struct')\n raise DeprecationWarning('Struct is being phased out as a parameter, please pass \"datapoint\" instead.')\nif self.scm is None:\n try:\n fr... | <|body_start_0|>
self.max_atoms = max_atoms
self.flatten = flatten
self.scm: Any = None
<|end_body_0|>
<|body_start_1|>
if 'struct' in kwargs and datapoint is None:
datapoint = kwargs.get('struct')
raise DeprecationWarning('Struct is being phased out as a paramet... | Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are periodic in the dimensions of the crystal lattic... | SineCoulombMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SineCoulombMatrix:
"""Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are per... | stack_v2_sparse_classes_75kplus_train_072578 | 3,823 | permissive | [
{
"docstring": "Parameters ---------- max_atoms: int (default 100) Maximum number of atoms for any crystal in the dataset. Used to pad the Coulomb matrix. flatten: bool (default True) Return flattened vector of matrix eigenvalues.",
"name": "__init__",
"signature": "def __init__(self, max_atoms: int=100... | 2 | stack_v2_sparse_classes_30k_train_002559 | Implement the Python class `SineCoulombMatrix` described below.
Class description:
Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of... | Implement the Python class `SineCoulombMatrix` described below.
Class description:
Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class SineCoulombMatrix:
"""Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are per... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SineCoulombMatrix:
"""Calculate sine Coulomb matrix for crystals. A variant of Coulomb matrix for periodic crystals. The sine Coulomb matrix is identical to the Coulomb matrix, except that the inverse distance function is replaced by the inverse of sin**2 of the vector between sites which are periodic in the ... | the_stack_v2_python_sparse | deepchem/feat/material_featurizers/sine_coulomb_matrix.py | deepchem/deepchem | train | 4,876 |
463e654a298b6767d5c45a66863d525940a50de6 | [
"shib_checker = ShibChecker()\nshib_dct = shib_checker.grab_shib_info(request)\nvalidity = shib_checker.evaluate_shib_info(shib_dct, request)\nassert type(validity) == bool\nlog.debug('returning shib validity `%s`' % validity)\nreturn (validity, shib_dct)",
"request.session['shib_login_error'] = 'Problem on autho... | <|body_start_0|>
shib_checker = ShibChecker()
shib_dct = shib_checker.grab_shib_info(request)
validity = shib_checker.evaluate_shib_info(shib_dct, request)
assert type(validity) == bool
log.debug('returning shib validity `%s`' % validity)
return (validity, shib_dct)
<|end... | Contains helpers for views.shib_login() Called by views.shib_login() | ShibViewHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShibViewHelper:
"""Contains helpers for views.shib_login() Called by views.shib_login()"""
def check_shib_headers(self, request):
"""Grabs and checks shib headers, returns boolean. Called by views.shib_login_handler()"""
<|body_0|>
def prep_login_redirect(self, request):... | stack_v2_sparse_classes_75kplus_train_072579 | 10,892 | permissive | [
{
"docstring": "Grabs and checks shib headers, returns boolean. Called by views.shib_login_handler()",
"name": "check_shib_headers",
"signature": "def check_shib_headers(self, request)"
},
{
"docstring": "Prepares redirect response-object to views.problem() on bad authZ (p-type problem). Called ... | 3 | null | Implement the Python class `ShibViewHelper` described below.
Class description:
Contains helpers for views.shib_login() Called by views.shib_login()
Method signatures and docstrings:
- def check_shib_headers(self, request): Grabs and checks shib headers, returns boolean. Called by views.shib_login_handler()
- def pre... | Implement the Python class `ShibViewHelper` described below.
Class description:
Contains helpers for views.shib_login() Called by views.shib_login()
Method signatures and docstrings:
- def check_shib_headers(self, request): Grabs and checks shib headers, returns boolean. Called by views.shib_login_handler()
- def pre... | 0718b3e22485354b45eb27615aba05c56b2b833b | <|skeleton|>
class ShibViewHelper:
"""Contains helpers for views.shib_login() Called by views.shib_login()"""
def check_shib_headers(self, request):
"""Grabs and checks shib headers, returns boolean. Called by views.shib_login_handler()"""
<|body_0|>
def prep_login_redirect(self, request):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShibViewHelper:
"""Contains helpers for views.shib_login() Called by views.shib_login()"""
def check_shib_headers(self, request):
"""Grabs and checks shib headers, returns boolean. Called by views.shib_login_handler()"""
shib_checker = ShibChecker()
shib_dct = shib_checker.grab_sh... | the_stack_v2_python_sparse | easyrequest_hay_app/lib/shib_helper.py | Brown-University-Library/easyrequest_hay_project | train | 0 |
d8352a8e7b679ddf96237646a5208afbd8d3f931 | [
"dp = [[0] * n for _ in range(m)]\nfor j in range(n):\n dp[0][j] = 1\nfor i in range(m):\n dp[i][0] = 1\nfor i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\nreturn dp[m - 1][n - 1]",
"cur = [1] * n\nfor i in range(1, m):\n for j in range(1, n):\n cur[j... | <|body_start_0|>
dp = [[0] * n for _ in range(m)]
for j in range(n):
dp[0][j] = 1
for i in range(m):
dp[i][0] = 1
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
<|end_b... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def unique_paths(self, m: int, n: int) -> int:
"""动态规划。"""
<|body_0|>
def unique_paths_2(self, m: int, n: int) -> int:
"""动态规划 - 优化空间。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [[0] * n for _ in range(m)]
for j i... | stack_v2_sparse_classes_75kplus_train_072580 | 2,270 | no_license | [
{
"docstring": "动态规划。",
"name": "unique_paths",
"signature": "def unique_paths(self, m: int, n: int) -> int"
},
{
"docstring": "动态规划 - 优化空间。",
"name": "unique_paths_2",
"signature": "def unique_paths_2(self, m: int, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_032656 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def unique_paths(self, m: int, n: int) -> int: 动态规划。
- def unique_paths_2(self, m: int, n: int) -> int: 动态规划 - 优化空间。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def unique_paths(self, m: int, n: int) -> int: 动态规划。
- def unique_paths_2(self, m: int, n: int) -> int: 动态规划 - 优化空间。
<|skeleton|>
class OfficialSolution:
de... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def unique_paths(self, m: int, n: int) -> int:
"""动态规划。"""
<|body_0|>
def unique_paths_2(self, m: int, n: int) -> int:
"""动态规划 - 优化空间。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfficialSolution:
def unique_paths(self, m: int, n: int) -> int:
"""动态规划。"""
dp = [[0] * n for _ in range(m)]
for j in range(n):
dp[0][j] = 1
for i in range(m):
dp[i][0] = 1
for i in range(1, m):
for j in range(1, n):
... | the_stack_v2_python_sparse | 0062_unique-paths.py | Nigirimeshi/leetcode | train | 0 | |
d96fa37ee36a63e595afd47a210ab3f4847def36 | [
"self.scales = scales\nself.ratios = ratios\nself.feature_strides = feature_strides",
"anchors = [self._generate_anchors(0, feature_shape)]\nanchors = tf.concat(anchors, axis=0)\nimg_shapes = calc_img_shapes(img_metas)\nvalid_flags = [self._generate_valid_flags(anchors, img_shapes[i]) for i in range(img_shapes.sh... | <|body_start_0|>
self.scales = scales
self.ratios = ratios
self.feature_strides = feature_strides
<|end_body_0|>
<|body_start_1|>
anchors = [self._generate_anchors(0, feature_shape)]
anchors = tf.concat(anchors, axis=0)
img_shapes = calc_img_shapes(img_metas)
val... | AnchorGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnchorGenerator:
def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)):
"""Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the fe... | stack_v2_sparse_classes_75kplus_train_072581 | 6,009 | no_license | [
{
"docstring": "Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the feature map relative to the image in pixels.",
"name": "__init__",
"signature": "def __init__(self, scales=(32, 64, 128, 256, 512)... | 4 | null | Implement the Python class `AnchorGenerator` described below.
Class description:
Implement the AnchorGenerator class.
Method signatures and docstrings:
- def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)): Anchor Generator Attributes --- scales: 1D array of anch... | Implement the Python class `AnchorGenerator` described below.
Class description:
Implement the AnchorGenerator class.
Method signatures and docstrings:
- def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)): Anchor Generator Attributes --- scales: 1D array of anch... | ff1ecb407f33697b02f2f2061912841e168fd33f | <|skeleton|>
class AnchorGenerator:
def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)):
"""Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the fe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnchorGenerator:
def __init__(self, scales=(32, 64, 128, 256, 512), ratios=(0.5, 1, 2), feature_strides=(4, 8, 16, 32, 64)):
"""Anchor Generator Attributes --- scales: 1D array of anchor sizes in pixels. ratios: 1D array of anchor ratios of width/height. feature_strides: Stride of the feature map rela... | the_stack_v2_python_sparse | venv/Lib/site-packages/detecting/models/anchors/anchor_generator.py | RavinduAye/pythonProject | train | 0 | |
f5fb371455546935ae7302a5f4f8a8cb8b8182b2 | [
"logger.debug('----*---- setupclass %r', cls)\nTestCase.setUpClass()\nlogger.debug('in SetUpClass, refcnt : %d', LPBaseTest.ref_count)\nif not LPBaseTest.wrapper:\n LPBaseTest.wrapper = MHLinphoneWrapper(rc_config_file=os.path.join(LPConfig.get_default_lp_data_dir(), 'unit_test.linphonerc'))\n LPBaseTest.wrap... | <|body_start_0|>
logger.debug('----*---- setupclass %r', cls)
TestCase.setUpClass()
logger.debug('in SetUpClass, refcnt : %d', LPBaseTest.ref_count)
if not LPBaseTest.wrapper:
LPBaseTest.wrapper = MHLinphoneWrapper(rc_config_file=os.path.join(LPConfig.get_default_lp_data_dir(... | Base class for tests mhlinphone_wrapper | LPBaseTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LPBaseTest:
"""Base class for tests mhlinphone_wrapper"""
def setUpClass(cls):
"""setUp method for tests in this class"""
<|body_0|>
def tearDownClass(cls):
"""tearDown method for tests in this class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_072582 | 14,700 | no_license | [
{
"docstring": "setUp method for tests in this class",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "tearDown method for tests in this class",
"name": "tearDownClass",
"signature": "def tearDownClass(cls)"
}
] | 2 | null | Implement the Python class `LPBaseTest` described below.
Class description:
Base class for tests mhlinphone_wrapper
Method signatures and docstrings:
- def setUpClass(cls): setUp method for tests in this class
- def tearDownClass(cls): tearDown method for tests in this class | Implement the Python class `LPBaseTest` described below.
Class description:
Base class for tests mhlinphone_wrapper
Method signatures and docstrings:
- def setUpClass(cls): setUp method for tests in this class
- def tearDownClass(cls): tearDown method for tests in this class
<|skeleton|>
class LPBaseTest:
"""Bas... | 28be8176142b517dcd4f135c47190d053601d5e2 | <|skeleton|>
class LPBaseTest:
"""Base class for tests mhlinphone_wrapper"""
def setUpClass(cls):
"""setUp method for tests in this class"""
<|body_0|>
def tearDownClass(cls):
"""tearDown method for tests in this class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LPBaseTest:
"""Base class for tests mhlinphone_wrapper"""
def setUpClass(cls):
"""setUp method for tests in this class"""
logger.debug('----*---- setupclass %r', cls)
TestCase.setUpClass()
logger.debug('in SetUpClass, refcnt : %d', LPBaseTest.ref_count)
if not LPBa... | the_stack_v2_python_sparse | pylib/lp_tests/mhlinphone_wrapper.py | mhcomm/mh_linphone | train | 1 |
91f0b1ad868614320f65d62713e4db67ec6b3fda | [
"self.defect = defect\ntry:\n bv = BVAnalyzer()\n struct_valences = bv.get_valences(self.defect.bulk_structure)\n site_index = self.defect.bulk_structure.get_sites_in_sphere(self.defect.site.coords, 0.1, include_index=True)[0][2]\n def_site_valence = struct_valences[site_index]\nexcept Exception:\n d... | <|body_start_0|>
self.defect = defect
try:
bv = BVAnalyzer()
struct_valences = bv.get_valences(self.defect.bulk_structure)
site_index = self.defect.bulk_structure.get_sites_in_sphere(self.defect.site.coords, 0.1, include_index=True)[0][2]
def_site_valence ... | Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond valence method to assign oxidation states and consid... | SimpleChargeGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleChargeGenerator:
"""Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond val... | stack_v2_sparse_classes_75kplus_train_072583 | 10,935 | permissive | [
{
"docstring": "Args: defect(Defect): pymatgen Defect object",
"name": "__init__",
"signature": "def __init__(self, defect)"
},
{
"docstring": "Returns the next defect type with the correct charge appended raises StopIteration",
"name": "__next__",
"signature": "def __next__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000185 | Implement the Python class `SimpleChargeGenerator` described below.
Class description:
Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to t... | Implement the Python class `SimpleChargeGenerator` described below.
Class description:
Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to t... | 62ecae1c7382a41861e3a5d9b9c8dd1207472409 | <|skeleton|>
class SimpleChargeGenerator:
"""Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleChargeGenerator:
"""Does an extremely simple/limited charge generation scheme (only one charge generated) for vacancies: use bond valence method to assign oxidation states and consider negative of the vacant site's oxidation state as single charge to try for antisites and subs: use bond valence method t... | the_stack_v2_python_sparse | pymatgen/analysis/defects/generators.py | montoyjh/pymatgen | train | 2 |
819e54fe8972d5c5d211f5e4f8b371710c5d3531 | [
"self.top = tk.Toplevel()\nself.top.geometry('+550+200')\nself.top.resizable(0, 0)\nttk.Label(self.top, text='Введите имя файла').pack(pady=10)\nself.entry = ttk.Entry(self.top)\nself.entry.pack(padx=10, pady=10)\nbtn = ttk.Button(self.top, text='Готово', command=self.done)\nbtn.pack(pady=10)",
"filename = self.e... | <|body_start_0|>
self.top = tk.Toplevel()
self.top.geometry('+550+200')
self.top.resizable(0, 0)
ttk.Label(self.top, text='Введите имя файла').pack(pady=10)
self.entry = ttk.Entry(self.top)
self.entry.pack(padx=10, pady=10)
btn = ttk.Button(self.top, text='Готово'... | Класс, который создает окно ввода имени файла Автор: Умбрас Е.Д. БИВ182 | PopupFileName | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopupFileName:
"""Класс, который создает окно ввода имени файла Автор: Умбрас Е.Д. БИВ182"""
def __init__(self):
"""Функция инициализации, создает новое окно Toplevel"""
<|body_0|>
def done(self):
"""Функция нажатия на кнопку, получает имя файла из Entry Автор: У... | stack_v2_sparse_classes_75kplus_train_072584 | 5,323 | no_license | [
{
"docstring": "Функция инициализации, создает новое окно Toplevel",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Функция нажатия на кнопку, получает имя файла из Entry Автор: Умбрас Е.Д. БИВ182",
"name": "done",
"signature": "def done(self)"
}
] | 2 | null | Implement the Python class `PopupFileName` described below.
Class description:
Класс, который создает окно ввода имени файла Автор: Умбрас Е.Д. БИВ182
Method signatures and docstrings:
- def __init__(self): Функция инициализации, создает новое окно Toplevel
- def done(self): Функция нажатия на кнопку, получает имя фа... | Implement the Python class `PopupFileName` described below.
Class description:
Класс, который создает окно ввода имени файла Автор: Умбрас Е.Д. БИВ182
Method signatures and docstrings:
- def __init__(self): Функция инициализации, создает новое окно Toplevel
- def done(self): Функция нажатия на кнопку, получает имя фа... | 66aa20ba1c7121f77a75bc810a9ebca7ae6dba40 | <|skeleton|>
class PopupFileName:
"""Класс, который создает окно ввода имени файла Автор: Умбрас Е.Д. БИВ182"""
def __init__(self):
"""Функция инициализации, создает новое окно Toplevel"""
<|body_0|>
def done(self):
"""Функция нажатия на кнопку, получает имя файла из Entry Автор: У... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PopupFileName:
"""Класс, который создает окно ввода имени файла Автор: Умбрас Е.Д. БИВ182"""
def __init__(self):
"""Функция инициализации, создает новое окно Toplevel"""
self.top = tk.Toplevel()
self.top.geometry('+550+200')
self.top.resizable(0, 0)
ttk.Label(self.... | the_stack_v2_python_sparse | Library/library.py | EUmbr/hsePy | train | 0 |
34c0d5018b622d6ad02c691db28797eca484d3fa | [
"super(TwoLayerNet, self).__init__()\nself.linear1 = torch.nn.Linear(D_in, H)\nself.linear2 = torch.nn.Linear(H, D_out)",
"h_relu = self.linear1(x).clamp(min=0)\ny_pred = self.linear2(h_relu)\nreturn y_pred"
] | <|body_start_0|>
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
<|end_body_0|>
<|body_start_1|>
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
<|end_body_1|>
| TwoLayerNet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。"""
<|body_0|>
def forward(self, x):
"""在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modules和 其他任意的Tensors上的算子来完成前馈函数的任务逻辑。"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_072585 | 2,326 | permissive | [
{
"docstring": "在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modules和 其他任意的Tensors上的算子来完成前馈函数的任务逻辑。",
"name": "forward",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_050202 | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): 在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。
- def forward(self, x): 在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modu... | Implement the Python class `TwoLayerNet` described below.
Class description:
Implement the TwoLayerNet class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): 在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。
- def forward(self, x): 在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modu... | 631b817d2e98f351d1173b620d15c4a5efed11da | <|skeleton|>
class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。"""
<|body_0|>
def forward(self, x):
"""在前馈函数中,我们接受一个输入数据的 Tensor, 并且我们必须返回输出数据的Tensor。在这里 我们可以使用造函数中已经定义好的Modules和 其他任意的Tensors上的算子来完成前馈函数的任务逻辑。"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoLayerNet:
def __init__(self, D_in, H, D_out):
"""在构造函数中,我们实例化了两个nn.Linear模块, 并将它们赋值为成员变量。"""
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forward(self, x):
"""在前馈函数中,我们接受一个输入数据的 Tensor, ... | the_stack_v2_python_sparse | build/_downloads/2e3e83652169c85c0c0972d072ffa8a2/two_layer_net_module.py | ScorpioDoctor/antares02 | train | 0 | |
1a1454eacd3b957b84b294aec4651be266bb78b2 | [
"m, n = (len(word1), len(word2))\ndp = [[0] * (n + 1) for _ in range(m + 1)]\nfor j in range(1, n + 1):\n dp[0][j] = j\nfor i in range(1, m + 1):\n dp[i][0] = i\nfor i in range(1, m + 1):\n for j in range(1, n + 1):\n dp[i][j] = dp[i - 1][j - 1] if word1[i - 1] == word2[j - 1] else min(dp[i - 1][j -... | <|body_start_0|>
m, n = (len(word1), len(word2))
dp = [[0] * (n + 1) for _ in range(m + 1)]
for j in range(1, n + 1):
dp[0][j] = j
for i in range(1, m + 1):
dp[i][0] = i
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""dp[i][j] w1前i个,w2前j个 最少操作数 dp[i][j] = dp[i-1_最短回文串.py][j-1_最短回文串.py] if w1[i-1_最短回文串.py] == w2[j-1_最短回文串.py] = min(dp[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j], dp[i][j-1_最短回文串.py]) + 1_最短回文串.py dp[0][0] = 0 dp[0][... | stack_v2_sparse_classes_75kplus_train_072586 | 2,182 | no_license | [
{
"docstring": "dp[i][j] w1前i个,w2前j个 最少操作数 dp[i][j] = dp[i-1_最短回文串.py][j-1_最短回文串.py] if w1[i-1_最短回文串.py] == w2[j-1_最短回文串.py] = min(dp[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j], dp[i][j-1_最短回文串.py]) + 1_最短回文串.py dp[0][0] = 0 dp[0][j] = j dp[i][0] = i res = dp[-1_最短回文串.py][-1_最短回文串.py]",
"name": "minDi... | 2 | stack_v2_sparse_classes_30k_train_036670 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: dp[i][j] w1前i个,w2前j个 最少操作数 dp[i][j] = dp[i-1_最短回文串.py][j-1_最短回文串.py] if w1[i-1_最短回文串.py] == w2[j-1_最短回文串.py] = min(dp[i-1_最短... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance(self, word1: str, word2: str) -> int: dp[i][j] w1前i个,w2前j个 最少操作数 dp[i][j] = dp[i-1_最短回文串.py][j-1_最短回文串.py] if w1[i-1_最短回文串.py] == w2[j-1_最短回文串.py] = min(dp[i-1_最短... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""dp[i][j] w1前i个,w2前j个 最少操作数 dp[i][j] = dp[i-1_最短回文串.py][j-1_最短回文串.py] if w1[i-1_最短回文串.py] == w2[j-1_最短回文串.py] = min(dp[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j], dp[i][j-1_最短回文串.py]) + 1_最短回文串.py dp[0][0] = 0 dp[0][... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDistance(self, word1: str, word2: str) -> int:
"""dp[i][j] w1前i个,w2前j个 最少操作数 dp[i][j] = dp[i-1_最短回文串.py][j-1_最短回文串.py] if w1[i-1_最短回文串.py] == w2[j-1_最短回文串.py] = min(dp[i-1_最短回文串.py][j-1_最短回文串.py], dp[i-1_最短回文串.py][j], dp[i][j-1_最短回文串.py]) + 1_最短回文串.py dp[0][0] = 0 dp[0][j] = j dp[i][0... | the_stack_v2_python_sparse | 4_LEETCODE/2_DP/字符串匹配问题/72_编辑距离.py | fzingithub/SwordRefers2Offer | train | 1 | |
e27ed907252aa88bebc472207016219620ba87bb | [
"self.json_data = json_data\nself.status_code = status_code\nself.exception = exception",
"if self.exception:\n raise self.exception\nreturn self.json_data"
] | <|body_start_0|>
self.json_data = json_data
self.status_code = status_code
self.exception = exception
<|end_body_0|>
<|body_start_1|>
if self.exception:
raise self.exception
return self.json_data
<|end_body_1|>
| Mock response object for testing. | MockResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MockResponse:
"""Mock response object for testing."""
def __init__(self, json_data, status_code, exception=None):
"""Create object."""
<|body_0|>
def json(self):
"""Return json data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.json_data... | stack_v2_sparse_classes_75kplus_train_072587 | 17,261 | permissive | [
{
"docstring": "Create object.",
"name": "__init__",
"signature": "def __init__(self, json_data, status_code, exception=None)"
},
{
"docstring": "Return json data.",
"name": "json",
"signature": "def json(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011497 | Implement the Python class `MockResponse` described below.
Class description:
Mock response object for testing.
Method signatures and docstrings:
- def __init__(self, json_data, status_code, exception=None): Create object.
- def json(self): Return json data. | Implement the Python class `MockResponse` described below.
Class description:
Mock response object for testing.
Method signatures and docstrings:
- def __init__(self, json_data, status_code, exception=None): Create object.
- def json(self): Return json data.
<|skeleton|>
class MockResponse:
"""Mock response obje... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class MockResponse:
"""Mock response object for testing."""
def __init__(self, json_data, status_code, exception=None):
"""Create object."""
<|body_0|>
def json(self):
"""Return json data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MockResponse:
"""Mock response object for testing."""
def __init__(self, json_data, status_code, exception=None):
"""Create object."""
self.json_data = json_data
self.status_code = status_code
self.exception = exception
def json(self):
"""Return json data."""
... | the_stack_v2_python_sparse | koku/koku/test_rbac.py | project-koku/koku | train | 225 |
256d5909a6f2498f0013ecea215dc525009e74b1 | [
"self.id = id\nself.name = name\nself.status = status\nself.estimate_inclusion = estimate_inclusion\nself.confidence = confidence\nself.cadence = cadence\nself.net_monthly = net_monthly\nself.net_annual = net_annual\nself.projected_net_annual = projected_net_annual\nself.estimated_gross_annual = estimated_gross_ann... | <|body_start_0|>
self.id = id
self.name = name
self.status = status
self.estimate_inclusion = estimate_inclusion
self.confidence = confidence
self.cadence = cadence
self.net_monthly = net_monthly
self.net_annual = net_annual
self.projected_net_annu... | Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream status (StatusEnum): active or inactive estimate_inclusion... | VOIReportIncomeStreamRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VOIReportIncomeStreamRecord:
"""Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream sta... | stack_v2_sparse_classes_75kplus_train_072588 | 6,477 | permissive | [
{
"docstring": "Constructor for the VOIReportIncomeStreamRecord class",
"name": "__init__",
"signature": "def __init__(self, id=None, name=None, status=None, estimate_inclusion=None, confidence=None, cadence=None, net_monthly=None, net_annual=None, projected_net_annual=None, estimated_gross_annual=None,... | 2 | stack_v2_sparse_classes_30k_train_007992 | Implement the Python class `VOIReportIncomeStreamRecord` described below.
Class description:
Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the ... | Implement the Python class `VOIReportIncomeStreamRecord` described below.
Class description:
Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the ... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class VOIReportIncomeStreamRecord:
"""Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VOIReportIncomeStreamRecord:
"""Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream status (StatusEn... | the_stack_v2_python_sparse | finicityapi/models/voi_report_income_stream_record.py | monarchmoney/finicity-python | train | 0 |
0e2fd900048dbf2a986cde22ab1905e59e11abdc | [
"x, y = (0, 0)\ny -= self.g * self.list[i].m\ndxdy = self.list[i].difference(self.list[i - 1])\nd = dxdy.norme()\nif d > self.lo:\n dxdy.x = (d - self.lo) / d * dxdy.x\n dxdy.y = (d - self.lo) / d * dxdy.y\n x += self.k * dxdy.x\n y += self.k * dxdy.y\ndxdy = self.list[i].difference(self.list[i + 1])\nd... | <|body_start_0|>
x, y = (0, 0)
y -= self.g * self.list[i].m
dxdy = self.list[i].difference(self.list[i - 1])
d = dxdy.norme()
if d > self.lo:
dxdy.x = (d - self.lo) / d * dxdy.x
dxdy.y = (d - self.lo) / d * dxdy.y
x += self.k * dxdy.x
... | Définition d'une corde, une liste de masses reliées par des élastiques et attachées au deux extrémités. | Corde | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Corde:
"""Définition d'une corde, une liste de masses reliées par des élastiques et attachées au deux extrémités."""
def force_point(self, i):
"""calcule les forces qui s'exerce en un point, retourne un point x,y"""
<|body_0|>
def iteration(self, dt):
"""Calcule ... | stack_v2_sparse_classes_75kplus_train_072589 | 11,610 | permissive | [
{
"docstring": "calcule les forces qui s'exerce en un point, retourne un point x,y",
"name": "force_point",
"signature": "def force_point(self, i)"
},
{
"docstring": "Calcule les déplacements de chaque point et les met à jour, on ne déplace pas les points situés aux extrémités, retourne la somme... | 2 | null | Implement the Python class `Corde` described below.
Class description:
Définition d'une corde, une liste de masses reliées par des élastiques et attachées au deux extrémités.
Method signatures and docstrings:
- def force_point(self, i): calcule les forces qui s'exerce en un point, retourne un point x,y
- def iteratio... | Implement the Python class `Corde` described below.
Class description:
Définition d'une corde, une liste de masses reliées par des élastiques et attachées au deux extrémités.
Method signatures and docstrings:
- def force_point(self, i): calcule les forces qui s'exerce en un point, retourne un point x,y
- def iteratio... | 2abbc7a20c7437f9ab91d1ec83a6aecdefceb028 | <|skeleton|>
class Corde:
"""Définition d'une corde, une liste de masses reliées par des élastiques et attachées au deux extrémités."""
def force_point(self, i):
"""calcule les forces qui s'exerce en un point, retourne un point x,y"""
<|body_0|>
def iteration(self, dt):
"""Calcule ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Corde:
"""Définition d'une corde, une liste de masses reliées par des élastiques et attachées au deux extrémités."""
def force_point(self, i):
"""calcule les forces qui s'exerce en un point, retourne un point x,y"""
x, y = (0, 0)
y -= self.g * self.list[i].m
dxdy = self.li... | the_stack_v2_python_sparse | src/ensae_teaching_cs/special/corde.py | Pandinosaurus/ensae_teaching_cs | train | 1 |
c796d3edb6cd38582d66a322ddd40c5f0caf763f | [
"html = helpers.get_content(url)\nif not html:\n return None\nsoup = BeautifulSoup(html)\nheadline = None\npotential_classes = ['heading-story', 'articleOpinion-title']\nfor h1_class in potential_classes:\n try:\n headline = soup.find('h1', {'class': h1_class}).string\n break\n except Attribu... | <|body_start_0|>
html = helpers.get_content(url)
if not html:
return None
soup = BeautifulSoup(html)
headline = None
potential_classes = ['heading-story', 'articleOpinion-title']
for h1_class in potential_classes:
try:
headline = so... | Methods for interacting with the Al Jazeera website. | AlJazeera | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlJazeera:
"""Methods for interacting with the Al Jazeera website."""
def get_article(self, url):
"""Implementation for getting an article from Al Jazeera. Args: url: A URL in the aljazeera.* domain. Returns: The Article representing the article at that url, or None if unable to get ... | stack_v2_sparse_classes_75kplus_train_072590 | 2,606 | no_license | [
{
"docstring": "Implementation for getting an article from Al Jazeera. Args: url: A URL in the aljazeera.* domain. Returns: The Article representing the article at that url, or None if unable to get the Article.",
"name": "get_article",
"signature": "def get_article(self, url)"
},
{
"docstring":... | 2 | null | Implement the Python class `AlJazeera` described below.
Class description:
Methods for interacting with the Al Jazeera website.
Method signatures and docstrings:
- def get_article(self, url): Implementation for getting an article from Al Jazeera. Args: url: A URL in the aljazeera.* domain. Returns: The Article repres... | Implement the Python class `AlJazeera` described below.
Class description:
Methods for interacting with the Al Jazeera website.
Method signatures and docstrings:
- def get_article(self, url): Implementation for getting an article from Al Jazeera. Args: url: A URL in the aljazeera.* domain. Returns: The Article repres... | b1adf7d582eb78623a44611dc07749823da84d5f | <|skeleton|>
class AlJazeera:
"""Methods for interacting with the Al Jazeera website."""
def get_article(self, url):
"""Implementation for getting an article from Al Jazeera. Args: url: A URL in the aljazeera.* domain. Returns: The Article representing the article at that url, or None if unable to get ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AlJazeera:
"""Methods for interacting with the Al Jazeera website."""
def get_article(self, url):
"""Implementation for getting an article from Al Jazeera. Args: url: A URL in the aljazeera.* domain. Returns: The Article representing the article at that url, or None if unable to get the Article."... | the_stack_v2_python_sparse | analysis/scraping/aljazeera.py | pandrewhk/perspectives | train | 0 |
bf221a3d3e7ce7eb491cec9c43bdbb43ed36e4f5 | [
"self.timeout = timeout\ntry:\n self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=timeout)\nexcept Exception as e:\n self.errored(\"Section failed due to: '{e}'\".format(e=e))\nfor stp in steps.details:\n if stp.result.name == 'skipped':\n self.skipped('Canno... | <|body_start_0|>
self.timeout = timeout
try:
self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=timeout)
except Exception as e:
self.errored("Section failed due to: '{e}'".format(e=e))
for stp in steps.details:
i... | Trigger class for Modify action | TriggerModify | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerModify:
"""Trigger class for Modify action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`... | stack_v2_sparse_classes_75kplus_train_072591 | 5,499 | permissive | [
{
"docstring": "Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object timeout (`timeout obj`): Timeout Object Returns: None Raises: pyATS Res... | 6 | stack_v2_sparse_classes_30k_train_054000 | Implement the Python class `TriggerModify` described below.
Class description:
Trigger class for Modify action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next te... | Implement the Python class `TriggerModify` described below.
Class description:
Trigger class for Modify action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next te... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerModify:
"""Trigger class for Modify action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TriggerModify:
"""Trigger class for Modify action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract o... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/modify/modify.py | CiscoTestAutomation/genielibs | train | 109 |
752622abb905dcd4521f77c591f49e0521415456 | [
"FeatureSelection.__init__(self, **kwargs)\nself.__data_measure = data_measure\nself.__transfer_error = transfer_error\nself.__feature_selector = feature_selector\nself.__bestdetector = bestdetector\nself.__stopping_criterion = stopping_criterion",
"errors = []\n'Computed error for each tested features set.'\ncan... | <|body_start_0|>
FeatureSelection.__init__(self, **kwargs)
self.__data_measure = data_measure
self.__transfer_error = transfer_error
self.__feature_selector = feature_selector
self.__bestdetector = bestdetector
self.__stopping_criterion = stopping_criterion
<|end_body_0|>... | Incremental feature search. A scalar `DatasetMeasure` is computed multiple times on variations of a certain dataset. These measures are in turn used to incrementally select important features. Starting with an empty feature set the dataset measure is first computed for each single feature. A number of features is selec... | IFS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IFS:
"""Incremental feature search. A scalar `DatasetMeasure` is computed multiple times on variations of a certain dataset. These measures are in turn used to incrementally select important features. Starting with an empty feature set the dataset measure is first computed for each single feature... | stack_v2_sparse_classes_75kplus_train_072592 | 6,959 | permissive | [
{
"docstring": "Initialize incremental feature search :Parameters: data_measure : DatasetMeasure Computed for each candidate feature selection. transfer_error : TransferError Compute against a test dataset for each incremental feature set. bestdetector : Functor Given a list of error values it has to return a b... | 2 | null | Implement the Python class `IFS` described below.
Class description:
Incremental feature search. A scalar `DatasetMeasure` is computed multiple times on variations of a certain dataset. These measures are in turn used to incrementally select important features. Starting with an empty feature set the dataset measure is... | Implement the Python class `IFS` described below.
Class description:
Incremental feature search. A scalar `DatasetMeasure` is computed multiple times on variations of a certain dataset. These measures are in turn used to incrementally select important features. Starting with an empty feature set the dataset measure is... | 2a8fcaa57457c8994455144e9e69494d167204c4 | <|skeleton|>
class IFS:
"""Incremental feature search. A scalar `DatasetMeasure` is computed multiple times on variations of a certain dataset. These measures are in turn used to incrementally select important features. Starting with an empty feature set the dataset measure is first computed for each single feature... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IFS:
"""Incremental feature search. A scalar `DatasetMeasure` is computed multiple times on variations of a certain dataset. These measures are in turn used to incrementally select important features. Starting with an empty feature set the dataset measure is first computed for each single feature. A number of... | the_stack_v2_python_sparse | mvpa/featsel/ifs.py | gorlins/PyMVPA | train | 0 |
24be469660a08b08fc2b5e1a371e2bb81ce74374 | [
"self.config = configparser.ConfigParser()\nself.config.read(config_file)\nself.folder = self.config.get('generate-tasks', 'task_folder')\nself.hyperparams = self.config.get('generate-tasks', 'hyperparams')\nmodel = self.config.get('generate-tasks', 'mother_model')\nsolver = self.config.get('generate-tasks', 'mothe... | <|body_start_0|>
self.config = configparser.ConfigParser()
self.config.read(config_file)
self.folder = self.config.get('generate-tasks', 'task_folder')
self.hyperparams = self.config.get('generate-tasks', 'hyperparams')
model = self.config.get('generate-tasks', 'mother_model')
... | TaskCreator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskCreator:
def __init__(self, config_file):
"""New TaskCreator with given config file Arguments ---------- config_file : string filename of configuration file"""
<|body_0|>
def _verify(self):
"""Verify that this TaskCreator is valid, i.e. that our parameters match ... | stack_v2_sparse_classes_75kplus_train_072593 | 8,909 | permissive | [
{
"docstring": "New TaskCreator with given config file Arguments ---------- config_file : string filename of configuration file",
"name": "__init__",
"signature": "def __init__(self, config_file)"
},
{
"docstring": "Verify that this TaskCreator is valid, i.e. that our parameters match up, etc",
... | 6 | null | Implement the Python class `TaskCreator` described below.
Class description:
Implement the TaskCreator class.
Method signatures and docstrings:
- def __init__(self, config_file): New TaskCreator with given config file Arguments ---------- config_file : string filename of configuration file
- def _verify(self): Verify... | Implement the Python class `TaskCreator` described below.
Class description:
Implement the TaskCreator class.
Method signatures and docstrings:
- def __init__(self, config_file): New TaskCreator with given config file Arguments ---------- config_file : string filename of configuration file
- def _verify(self): Verify... | 0311caa8bec776fd78fd6860de2bdb26e32b1754 | <|skeleton|>
class TaskCreator:
def __init__(self, config_file):
"""New TaskCreator with given config file Arguments ---------- config_file : string filename of configuration file"""
<|body_0|>
def _verify(self):
"""Verify that this TaskCreator is valid, i.e. that our parameters match ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskCreator:
def __init__(self, config_file):
"""New TaskCreator with given config file Arguments ---------- config_file : string filename of configuration file"""
self.config = configparser.ConfigParser()
self.config.read(config_file)
self.folder = self.config.get('generate-ta... | the_stack_v2_python_sparse | scripts/generate_tasks.py | Mri-monitoring/Mri-app | train | 11 | |
fd3a5421c6b077979b0d2582b8df06bed5357aa1 | [
"super(TankSprite, self).__init__()\nself.tank_id = tank_id\nself.base_image = pygame.image.load(TANKS[tank_id % 5])\nself.image = self.base_image\nself.rect = self.image.get_bounding_rect()\nself.parent = parent",
"self.tank_id = tank_id % 4\nself.base_image = pygame.image.load(TANKS[tank_id % 5])\nself.image = ... | <|body_start_0|>
super(TankSprite, self).__init__()
self.tank_id = tank_id
self.base_image = pygame.image.load(TANKS[tank_id % 5])
self.image = self.base_image
self.rect = self.image.get_bounding_rect()
self.parent = parent
<|end_body_0|>
<|body_start_1|>
self.ta... | Tank Sprite for all tanks in game | TankSprite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TankSprite:
"""Tank Sprite for all tanks in game"""
def __init__(self, tank_id, parent):
""":param tank_id: number % available, of image that will represent tank :param parent: controller of tank"""
<|body_0|>
def change_image(self, tank_id):
"""changes image of ... | stack_v2_sparse_classes_75kplus_train_072594 | 3,586 | no_license | [
{
"docstring": ":param tank_id: number % available, of image that will represent tank :param parent: controller of tank",
"name": "__init__",
"signature": "def __init__(self, tank_id, parent)"
},
{
"docstring": "changes image of tank :param tank_id: number % available, of image that will represe... | 2 | stack_v2_sparse_classes_30k_train_032215 | Implement the Python class `TankSprite` described below.
Class description:
Tank Sprite for all tanks in game
Method signatures and docstrings:
- def __init__(self, tank_id, parent): :param tank_id: number % available, of image that will represent tank :param parent: controller of tank
- def change_image(self, tank_i... | Implement the Python class `TankSprite` described below.
Class description:
Tank Sprite for all tanks in game
Method signatures and docstrings:
- def __init__(self, tank_id, parent): :param tank_id: number % available, of image that will represent tank :param parent: controller of tank
- def change_image(self, tank_i... | 51a2f2ecc09a05672a2c3deb00ab8c273d3b756b | <|skeleton|>
class TankSprite:
"""Tank Sprite for all tanks in game"""
def __init__(self, tank_id, parent):
""":param tank_id: number % available, of image that will represent tank :param parent: controller of tank"""
<|body_0|>
def change_image(self, tank_id):
"""changes image of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TankSprite:
"""Tank Sprite for all tanks in game"""
def __init__(self, tank_id, parent):
""":param tank_id: number % available, of image that will represent tank :param parent: controller of tank"""
super(TankSprite, self).__init__()
self.tank_id = tank_id
self.base_image ... | the_stack_v2_python_sparse | game_core/actor.py | asmodeii/tanki | train | 0 |
ba859b4a9382086989644a62a40ed82277f9a727 | [
"super().__init__(root, train=train, transform=transform, target_transform=None, download=download)\nself.seed = seed\nself.targets = np.array(self.targets, dtype=np.int64)\nself.num_classes = np.unique(self.targets, return_counts=False).size\nself.num_samples = len(self.data)\nself.clean_targets = np.copy(self.tar... | <|body_start_0|>
super().__init__(root, train=train, transform=transform, target_transform=None, download=download)
self.seed = seed
self.targets = np.array(self.targets, dtype=np.int64)
self.num_classes = np.unique(self.targets, return_counts=False).size
self.num_samples = len(s... | Dataset class for the CIFAR10 dataset where target labels are sampled from a confusion matrix. | CIFAR10IDN | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CIFAR10IDN:
"""Dataset class for the CIFAR10 dataset where target labels are sampled from a confusion matrix."""
def __init__(self, root: str, train: bool, noise_rate: float, transform: Optional[Callable]=None, download: bool=True, use_fixed_labels: bool=True, seed: int=1) -> None:
"... | stack_v2_sparse_classes_75kplus_train_072595 | 7,066 | permissive | [
{
"docstring": ":param root: The directory in which the CIFAR10 images will be stored. :param train: If True, creates dataset from training set, otherwise creates from test set. :param transform: Transform to apply to the images. :param download: Whether to download the dataset if it is not already in the local... | 5 | stack_v2_sparse_classes_30k_train_004541 | Implement the Python class `CIFAR10IDN` described below.
Class description:
Dataset class for the CIFAR10 dataset where target labels are sampled from a confusion matrix.
Method signatures and docstrings:
- def __init__(self, root: str, train: bool, noise_rate: float, transform: Optional[Callable]=None, download: boo... | Implement the Python class `CIFAR10IDN` described below.
Class description:
Dataset class for the CIFAR10 dataset where target labels are sampled from a confusion matrix.
Method signatures and docstrings:
- def __init__(self, root: str, train: bool, noise_rate: float, transform: Optional[Callable]=None, download: boo... | 8495a2eec3903957e3e81f81a0d2ad842d41dfe2 | <|skeleton|>
class CIFAR10IDN:
"""Dataset class for the CIFAR10 dataset where target labels are sampled from a confusion matrix."""
def __init__(self, root: str, train: bool, noise_rate: float, transform: Optional[Callable]=None, download: bool=True, use_fixed_labels: bool=True, seed: int=1) -> None:
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CIFAR10IDN:
"""Dataset class for the CIFAR10 dataset where target labels are sampled from a confusion matrix."""
def __init__(self, root: str, train: bool, noise_rate: float, transform: Optional[Callable]=None, download: bool=True, use_fixed_labels: bool=True, seed: int=1) -> None:
""":param root... | the_stack_v2_python_sparse | InnerEye-DataQuality/InnerEyeDataQuality/datasets/cifar10_idn.py | RobinMarshall55/InnerEye-DeepLearning | train | 0 |
948ffe29b8b8074f41c005bffe66baa166b8545d | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | DeveloperServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeveloperServiceServicer:
"""Missing associated documentation comment in .proto file."""
def EditCheck(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Validate(self, request, context):
"""Missing associated d... | stack_v2_sparse_classes_75kplus_train_072596 | 11,293 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "EditCheck",
"signature": "def EditCheck(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Validate",
"signature": "def Validate(self, request,... | 6 | stack_v2_sparse_classes_30k_train_019481 | Implement the Python class `DeveloperServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def EditCheck(self, request, context): Missing associated documentation comment in .proto file.
- def Validate(self, request, context):... | Implement the Python class `DeveloperServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def EditCheck(self, request, context): Missing associated documentation comment in .proto file.
- def Validate(self, request, context):... | b94598eca5db7dd1746cc6f49c5cd0c76961b9c2 | <|skeleton|>
class DeveloperServiceServicer:
"""Missing associated documentation comment in .proto file."""
def EditCheck(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def Validate(self, request, context):
"""Missing associated d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeveloperServiceServicer:
"""Missing associated documentation comment in .proto file."""
def EditCheck(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemente... | the_stack_v2_python_sparse | authzed/api/v0/developer_pb2_grpc.py | hercules261188/authzed-py | train | 0 |
5eb8787aa8a9272bafde18b3fdbf4976b0bca0e2 | [
"if os.path.isfile(vcf) is False:\n raise Exception('File does not exist')\nself.vcf = vcf\nself.snptools_folder = snptools_folder",
"bamf = open(bamfiles, 'r')\nbams = list(set(bamf.read().splitlines()))\nbams = list(filter(None, bams))\nprogram_folder = ''\nif self.snptools_folder:\n program_folder += sel... | <|body_start_0|>
if os.path.isfile(vcf) is False:
raise Exception('File does not exist')
self.vcf = vcf
self.snptools_folder = snptools_folder
<|end_body_0|>
<|body_start_1|>
bamf = open(bamfiles, 'r')
bams = list(set(bamf.read().splitlines()))
bams = list(fi... | Class to operate on a VCF file at the population level and perform different SNPTools analysis on it | SNPTools | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SNPTools:
"""Class to operate on a VCF file at the population level and perform different SNPTools analysis on it"""
def __init__(self, vcf, snptools_folder=None):
"""Constructor Parameters ---------- vcf : str Path to vcf file. snptools_folder : str, optional Path to folder containi... | stack_v2_sparse_classes_75kplus_train_072597 | 6,663 | permissive | [
{
"docstring": "Constructor Parameters ---------- vcf : str Path to vcf file. snptools_folder : str, optional Path to folder containing the snptools binaries (bamodel, poprob, etc.).",
"name": "__init__",
"signature": "def __init__(self, vcf, snptools_folder=None)"
},
{
"docstring": "Method that... | 4 | stack_v2_sparse_classes_30k_test_000653 | Implement the Python class `SNPTools` described below.
Class description:
Class to operate on a VCF file at the population level and perform different SNPTools analysis on it
Method signatures and docstrings:
- def __init__(self, vcf, snptools_folder=None): Constructor Parameters ---------- vcf : str Path to vcf file... | Implement the Python class `SNPTools` described below.
Class description:
Class to operate on a VCF file at the population level and perform different SNPTools analysis on it
Method signatures and docstrings:
- def __init__(self, vcf, snptools_folder=None): Constructor Parameters ---------- vcf : str Path to vcf file... | ffea4885227c2299f886a4f41e70b6e1f6bb43da | <|skeleton|>
class SNPTools:
"""Class to operate on a VCF file at the population level and perform different SNPTools analysis on it"""
def __init__(self, vcf, snptools_folder=None):
"""Constructor Parameters ---------- vcf : str Path to vcf file. snptools_folder : str, optional Path to folder containi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SNPTools:
"""Class to operate on a VCF file at the population level and perform different SNPTools analysis on it"""
def __init__(self, vcf, snptools_folder=None):
"""Constructor Parameters ---------- vcf : str Path to vcf file. snptools_folder : str, optional Path to folder containing the snptoo... | the_stack_v2_python_sparse | VCF/VCFIntegration/SNPTools.py | igsr/igsr_analysis | train | 3 |
8cd1dde7a87bb9a255643fe12094d9cd4b2afa1c | [
"DocketGenerator.__init__(self)\nself.n_stimuli = n_stimuli\nself.n_reference = np.int32(n_reference)\nself.n_select = np.int32(n_select)\nself.is_ranked = True\nif max_unique_query is None:\n max_unique_query = n_stimuli\nelse:\n max_unique_query = np.minimum(max_unique_query, n_stimuli)\nself.max_unique_que... | <|body_start_0|>
DocketGenerator.__init__(self)
self.n_stimuli = n_stimuli
self.n_reference = np.int32(n_reference)
self.n_select = np.int32(n_select)
self.is_ranked = True
if max_unique_query is None:
max_unique_query = n_stimuli
else:
max... | A trial generator that uses approximate information gain. | ActiveRank | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveRank:
"""A trial generator that uses approximate information gain."""
def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128):
"""Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. ... | stack_v2_sparse_classes_75kplus_train_072598 | 15,132 | permissive | [
{
"docstring": "Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. n_reference (optional): An integer indicating the number of references for each trial. n_select (optional): An integer indicating the number of selections an agent must make. max_unique_query (optional): A ... | 4 | stack_v2_sparse_classes_30k_train_036681 | Implement the Python class `ActiveRank` described below.
Class description:
A trial generator that uses approximate information gain.
Method signatures and docstrings:
- def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128): Initialize. Arguments: n_stimuli:... | Implement the Python class `ActiveRank` described below.
Class description:
A trial generator that uses approximate information gain.
Method signatures and docstrings:
- def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128): Initialize. Arguments: n_stimuli:... | 4f05348cf43d2d53ff9cc6dee633de385df883e3 | <|skeleton|>
class ActiveRank:
"""A trial generator that uses approximate information gain."""
def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128):
"""Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActiveRank:
"""A trial generator that uses approximate information gain."""
def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128):
"""Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. n_reference (... | the_stack_v2_python_sparse | psiz/generators/similarity/rank/active_rank.py | asuiconlab/psiz | train | 0 |
1394907c23df171a6fb2629a74b6148492fbbbed | [
"self.driver.get(url)\nvalue = self.driver.find_element_by_id(requiredDom).is_enabled()\nreturn value",
"self.driver.get(url)\nps = self.driver.page_source\nreturn ps",
"if data is None:\n url = dc_url + '?ENV_OUTPUT_DATA_LIST={}'\n return url\nelse:\n url = dc_url + '?ENV_OUTPUT_DATA_LIST=' + json.dum... | <|body_start_0|>
self.driver.get(url)
value = self.driver.find_element_by_id(requiredDom).is_enabled()
return value
<|end_body_0|>
<|body_start_1|>
self.driver.get(url)
ps = self.driver.page_source
return ps
<|end_body_1|>
<|body_start_2|>
if data is None:
... | DataCleaningReceiver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCleaningReceiver:
def get_datacleaning_receiver_id(self, url, requiredDom):
"""数据清洗—接收器,访问url获取元素值 :param url: 接收器请求接口后,访问url地址 :param requiredDom: Dom树中id值 数据文件列表:'__data_source_list' 数据文件详情:'__data_source_detail' 模板列表:'__data_template-list' 模板详情:'__data_template-detail' :return: 布尔... | stack_v2_sparse_classes_75kplus_train_072599 | 3,422 | no_license | [
{
"docstring": "数据清洗—接收器,访问url获取元素值 :param url: 接收器请求接口后,访问url地址 :param requiredDom: Dom树中id值 数据文件列表:'__data_source_list' 数据文件详情:'__data_source_detail' 模板列表:'__data_template-list' 模板详情:'__data_template-detail' :return: 布尔,True/False;存在/不存在",
"name": "get_datacleaning_receiver_id",
"signature": "def get_... | 6 | stack_v2_sparse_classes_30k_train_036042 | Implement the Python class `DataCleaningReceiver` described below.
Class description:
Implement the DataCleaningReceiver class.
Method signatures and docstrings:
- def get_datacleaning_receiver_id(self, url, requiredDom): 数据清洗—接收器,访问url获取元素值 :param url: 接收器请求接口后,访问url地址 :param requiredDom: Dom树中id值 数据文件列表:'__data_sou... | Implement the Python class `DataCleaningReceiver` described below.
Class description:
Implement the DataCleaningReceiver class.
Method signatures and docstrings:
- def get_datacleaning_receiver_id(self, url, requiredDom): 数据清洗—接收器,访问url获取元素值 :param url: 接收器请求接口后,访问url地址 :param requiredDom: Dom树中id值 数据文件列表:'__data_sou... | 22927e1101efa219e526dcd9b70f519bb6bd9553 | <|skeleton|>
class DataCleaningReceiver:
def get_datacleaning_receiver_id(self, url, requiredDom):
"""数据清洗—接收器,访问url获取元素值 :param url: 接收器请求接口后,访问url地址 :param requiredDom: Dom树中id值 数据文件列表:'__data_source_list' 数据文件详情:'__data_source_detail' 模板列表:'__data_template-list' 模板详情:'__data_template-detail' :return: 布尔... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataCleaningReceiver:
def get_datacleaning_receiver_id(self, url, requiredDom):
"""数据清洗—接收器,访问url获取元素值 :param url: 接收器请求接口后,访问url地址 :param requiredDom: Dom树中id值 数据文件列表:'__data_source_list' 数据文件详情:'__data_source_detail' 模板列表:'__data_template-list' 模板详情:'__data_template-detail' :return: 布尔,True/False;存在... | the_stack_v2_python_sparse | apm_modules/data_cleaning_receiver.py | mentgmery/interface_testing | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.