blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8f7e0dec1976d6cb361cd35f86a6a7b12fd5184f | [
"super().__init__()\nself.candidate_data = candidate_data\nself.seed_data = seed_data\nself.n_query = n_query\nself.hull_distance = hull_distance\nself.pd = None\nself.parallel = parallel\nself.cv_score = np.nan",
"self.pd = PhaseData()\nif chemsys:\n total_comp = Composition(chemsys.replace('-', ''))\n fil... | <|body_start_0|>
super().__init__()
self.candidate_data = candidate_data
self.seed_data = seed_data
self.n_query = n_query
self.hull_distance = hull_distance
self.pd = None
self.parallel = parallel
self.cv_score = np.nan
<|end_body_0|>
<|body_start_1|>
... | The StabilityAgent is a mixin abstract class which contains initialization parameters and methods common to every agent which is responsible for making decisions about stability. | StabilityAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StabilityAgent:
"""The StabilityAgent is a mixin abstract class which contains initialization parameters and methods common to every agent which is responsible for making decisions about stability."""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, paral... | stack_v2_sparse_classes_36k_train_030200 | 38,060 | permissive | [
{
"docstring": "Args: candidate_data (DataFrame): data about the candidates seed_data (DataFrame): data which to fit the Agent to n_query (int): number of hypotheses to generate hull_distance (float): hull distance as a criteria for which to deem a given material as \"stable\" parallel (bool, int): whether to u... | 4 | stack_v2_sparse_classes_30k_train_007710 | Implement the Python class `StabilityAgent` described below.
Class description:
The StabilityAgent is a mixin abstract class which contains initialization parameters and methods common to every agent which is responsible for making decisions about stability.
Method signatures and docstrings:
- def __init__(self, cand... | Implement the Python class `StabilityAgent` described below.
Class description:
The StabilityAgent is a mixin abstract class which contains initialization parameters and methods common to every agent which is responsible for making decisions about stability.
Method signatures and docstrings:
- def __init__(self, cand... | 905f5d577513d1ca5a54fac3d381525e0fe3576a | <|skeleton|>
class StabilityAgent:
"""The StabilityAgent is a mixin abstract class which contains initialization parameters and methods common to every agent which is responsible for making decisions about stability."""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, paral... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StabilityAgent:
"""The StabilityAgent is a mixin abstract class which contains initialization parameters and methods common to every agent which is responsible for making decisions about stability."""
def __init__(self, candidate_data=None, seed_data=None, n_query=1, hull_distance=0.0, parallel=cpu_count... | the_stack_v2_python_sparse | camd/agent/stability.py | apalizha/CAMD | train | 0 |
af9810553acf759dbd93a8f9b4d513b0f4288ef1 | [
"key = self.request.get('key')\nif not key:\n self.RenderHtml('edit_site_config.html', {})\n return\nvalue = stored_object.Get(key)\nexternal_value = namespaced_stored_object.GetExternal(key)\ninternal_value = namespaced_stored_object.Get(key)\nself.RenderHtml('edit_site_config.html', {'key': key, 'value': _F... | <|body_start_0|>
key = self.request.get('key')
if not key:
self.RenderHtml('edit_site_config.html', {})
return
value = stored_object.Get(key)
external_value = namespaced_stored_object.GetExternal(key)
internal_value = namespaced_stored_object.Get(key)
... | Handles editing of site config values stored with stored_entity. FIXME: One confusing aspect of this page is: If a namespaced config is set, the non-namespaced configs are probably irrelevant bu tthe field is still shown. Similarly, if a non-namespaced config is set, the namespaced config fields are likely not needed, ... | EditSiteConfigHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditSiteConfigHandler:
"""Handles editing of site config values stored with stored_entity. FIXME: One confusing aspect of this page is: If a namespaced config is set, the non-namespaced configs are probably irrelevant bu tthe field is still shown. Similarly, if a non-namespaced config is set, the... | stack_v2_sparse_classes_36k_train_030201 | 5,181 | permissive | [
{
"docstring": "Renders the UI with the form.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Accepts posted values, makes changes, and shows the form again.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `EditSiteConfigHandler` described below.
Class description:
Handles editing of site config values stored with stored_entity. FIXME: One confusing aspect of this page is: If a namespaced config is set, the non-namespaced configs are probably irrelevant bu tthe field is still shown. Similarly,... | Implement the Python class `EditSiteConfigHandler` described below.
Class description:
Handles editing of site config values stored with stored_entity. FIXME: One confusing aspect of this page is: If a namespaced config is set, the non-namespaced configs are probably irrelevant bu tthe field is still shown. Similarly,... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class EditSiteConfigHandler:
"""Handles editing of site config values stored with stored_entity. FIXME: One confusing aspect of this page is: If a namespaced config is set, the non-namespaced configs are probably irrelevant bu tthe field is still shown. Similarly, if a non-namespaced config is set, the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditSiteConfigHandler:
"""Handles editing of site config values stored with stored_entity. FIXME: One confusing aspect of this page is: If a namespaced config is set, the non-namespaced configs are probably irrelevant bu tthe field is still shown. Similarly, if a non-namespaced config is set, the namespaced c... | the_stack_v2_python_sparse | dashboard/dashboard/edit_site_config.py | catapult-project/catapult | train | 2,032 |
806daf50ee7b7a5685c882889835f176dbba389e | [
"smach.State.__init__(self, outcomes=['done'])\nself.robot = robot\nself.breakout_id = breakout_id\nrospy.Subscriber('/amigo/persons', tue_msgs.msg.People, self._people_callback)\nrospy.Subscriber('/amigo/trigger', std_msgs.msg.String, self._trigger_callback)\nself._active = False\nself._requested_highlight = ''\ns... | <|body_start_0|>
smach.State.__init__(self, outcomes=['done'])
self.robot = robot
self.breakout_id = breakout_id
rospy.Subscriber('/amigo/persons', tue_msgs.msg.People, self._people_callback)
rospy.Subscriber('/amigo/trigger', std_msgs.msg.String, self._trigger_callback)
... | State to perform raytrace demo | RayTraceDemo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RayTraceDemo:
"""State to perform raytrace demo"""
def __init__(self, robot, breakout_id):
"""Constructor :param robot: robot object :param breakout_id: string identifying the breakout object. If the operator points to this object, the state will finish"""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_030202 | 7,153 | no_license | [
{
"docstring": "Constructor :param robot: robot object :param breakout_id: string identifying the breakout object. If the operator points to this object, the state will finish",
"name": "__init__",
"signature": "def __init__(self, robot, breakout_id)"
},
{
"docstring": "Execute function",
"n... | 5 | stack_v2_sparse_classes_30k_train_002321 | Implement the Python class `RayTraceDemo` described below.
Class description:
State to perform raytrace demo
Method signatures and docstrings:
- def __init__(self, robot, breakout_id): Constructor :param robot: robot object :param breakout_id: string identifying the breakout object. If the operator points to this obj... | Implement the Python class `RayTraceDemo` described below.
Class description:
State to perform raytrace demo
Method signatures and docstrings:
- def __init__(self, robot, breakout_id): Constructor :param robot: robot object :param breakout_id: string identifying the breakout object. If the operator points to this obj... | 189bd987822f9bd1c477769892e154964f97d2f0 | <|skeleton|>
class RayTraceDemo:
"""State to perform raytrace demo"""
def __init__(self, robot, breakout_id):
"""Constructor :param robot: robot object :param breakout_id: string identifying the breakout object. If the operator points to this object, the state will finish"""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RayTraceDemo:
"""State to perform raytrace demo"""
def __init__(self, robot, breakout_id):
"""Constructor :param robot: robot object :param breakout_id: string identifying the breakout object. If the operator points to this object, the state will finish"""
smach.State.__init__(self, outco... | the_stack_v2_python_sparse | challenge_open/src/raytrace_demo.py | sunarditay/tue_robocup | train | 0 |
2e4eb8e0e1ad902e2d792ebfb0f04a42e29c6d64 | [
"if not self.readonly:\n return True\nreturn obj.__class__.__name__ not in self._read_only_model_relationships",
"if value is None:\n return self.readonly\nif not isinstance(value, bool):\n raise ValidationError(\"Attribute 'readonly' has invalid value\")\nreturn value"
] | <|body_start_0|>
if not self.readonly:
return True
return obj.__class__.__name__ not in self._read_only_model_relationships
<|end_body_0|>
<|body_start_1|>
if value is None:
return self.readonly
if not isinstance(value, bool):
raise ValidationError("A... | Mixin for models which can be marked as read-only | WithReadOnlyAccess | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WithReadOnlyAccess:
"""Mixin for models which can be marked as read-only"""
def can_change_relationship_with(self, obj):
"""Check whether relationship from self to obj1 can be changed This function doesn't expect that another obj also has type WithReadOnlyAccess. In this case can_cha... | stack_v2_sparse_classes_36k_train_030203 | 2,150 | permissive | [
{
"docstring": "Check whether relationship from self to obj1 can be changed This function doesn't expect that another obj also has type WithReadOnlyAccess. In this case can_change_relationship_with() of another object have to be called also to ensure that relationship is not read-only. Final read-only flag can ... | 2 | stack_v2_sparse_classes_30k_train_003803 | Implement the Python class `WithReadOnlyAccess` described below.
Class description:
Mixin for models which can be marked as read-only
Method signatures and docstrings:
- def can_change_relationship_with(self, obj): Check whether relationship from self to obj1 can be changed This function doesn't expect that another o... | Implement the Python class `WithReadOnlyAccess` described below.
Class description:
Mixin for models which can be marked as read-only
Method signatures and docstrings:
- def can_change_relationship_with(self, obj): Check whether relationship from self to obj1 can be changed This function doesn't expect that another o... | f99bfdaa11ad30643d7bc9af67bd84436d298cfa | <|skeleton|>
class WithReadOnlyAccess:
"""Mixin for models which can be marked as read-only"""
def can_change_relationship_with(self, obj):
"""Check whether relationship from self to obj1 can be changed This function doesn't expect that another obj also has type WithReadOnlyAccess. In this case can_cha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WithReadOnlyAccess:
"""Mixin for models which can be marked as read-only"""
def can_change_relationship_with(self, obj):
"""Check whether relationship from self to obj1 can be changed This function doesn't expect that another obj also has type WithReadOnlyAccess. In this case can_change_relations... | the_stack_v2_python_sparse | src/ggrc/models/mixins/with_readonly_access.py | pavelglebov/ggrc-core | train | 1 |
05e51e2bbc093f36e603d9a832ba4b4c3ac55091 | [
"if element:\n self.reference = element.referanse\n self.reference_type = element.referanseType\n return\nself.reference = reference\nself.reference_type = reference_type",
"elem = melding.ctReferanse()\nelem.referanse = self.reference\nelem.referanseType = self.reference_type\nreturn elem"
] | <|body_start_0|>
if element:
self.reference = element.referanse
self.reference_type = element.referanseType
return
self.reference = reference
self.reference_type = reference_type
<|end_body_0|>
<|body_start_1|>
elem = melding.ctReferanse()
ele... | NEW brreg:EksternReferanse External (custom) reference for tracking in the client application. | BrregReference | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrregReference:
"""NEW brreg:EksternReferanse External (custom) reference for tracking in the client application."""
def __init__(self, reference=None, reference_type=None, element=None):
"""If element is supplied, all other arguments are ignored. :param reference: The reference valu... | stack_v2_sparse_classes_36k_train_030204 | 12,499 | permissive | [
{
"docstring": "If element is supplied, all other arguments are ignored. :param reference: The reference value :type reference: basestring :param reference_type: The type of reference, see documentation for valid values :type reference_type: basestring :param element: PyXB element of EksternReferanse :type elem... | 2 | stack_v2_sparse_classes_30k_train_016872 | Implement the Python class `BrregReference` described below.
Class description:
NEW brreg:EksternReferanse External (custom) reference for tracking in the client application.
Method signatures and docstrings:
- def __init__(self, reference=None, reference_type=None, element=None): If element is supplied, all other ar... | Implement the Python class `BrregReference` described below.
Class description:
NEW brreg:EksternReferanse External (custom) reference for tracking in the client application.
Method signatures and docstrings:
- def __init__(self, reference=None, reference_type=None, element=None): If element is supplied, all other ar... | ecb471065795ae4bba1d5b3466756df8e8db848e | <|skeleton|>
class BrregReference:
"""NEW brreg:EksternReferanse External (custom) reference for tracking in the client application."""
def __init__(self, reference=None, reference_type=None, element=None):
"""If element is supplied, all other arguments are ignored. :param reference: The reference valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrregReference:
"""NEW brreg:EksternReferanse External (custom) reference for tracking in the client application."""
def __init__(self, reference=None, reference_type=None, element=None):
"""If element is supplied, all other arguments are ignored. :param reference: The reference value :type refer... | the_stack_v2_python_sparse | pybrreg/models/new_inquiry.py | unicornis/pybrreg | train | 0 |
ae646cba6ce2f88c719c62c6020ebca6ee3af95f | [
"fig = Figure(figsize=(width, height), dpi=dpi)\nFigureCanvas.__init__(self, fig)\nself.setParent(parent)",
"ax = self.figure.add_subplot(111)\nax.bar(x, y, color='blue', width=0.2)\nax.set_ylim(0, 1)\nax.set_xlabel('Configurations title')\nax.set_ylabel(ylabel)\nself.draw()"
] | <|body_start_0|>
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
<|end_body_0|>
<|body_start_1|>
ax = self.figure.add_subplot(111)
ax.bar(x, y, color='blue', width=0.2)
ax.set_ylim(0, 1)
ax.set_xlabel('Config... | Figure Create the four charts and their layout. | Graph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
"""Figure Create the four charts and their layout."""
def __init__(self, parent=None, width=5, height=4, dpi=75):
"""Instantiate the canvas to plot the charts."""
<|body_0|>
def plot(self, x, y, ylabel):
"""Plot the charts in the canvas."""
<|body_... | stack_v2_sparse_classes_36k_train_030205 | 49,456 | no_license | [
{
"docstring": "Instantiate the canvas to plot the charts.",
"name": "__init__",
"signature": "def __init__(self, parent=None, width=5, height=4, dpi=75)"
},
{
"docstring": "Plot the charts in the canvas.",
"name": "plot",
"signature": "def plot(self, x, y, ylabel)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015894 | Implement the Python class `Graph` described below.
Class description:
Figure Create the four charts and their layout.
Method signatures and docstrings:
- def __init__(self, parent=None, width=5, height=4, dpi=75): Instantiate the canvas to plot the charts.
- def plot(self, x, y, ylabel): Plot the charts in the canva... | Implement the Python class `Graph` described below.
Class description:
Figure Create the four charts and their layout.
Method signatures and docstrings:
- def __init__(self, parent=None, width=5, height=4, dpi=75): Instantiate the canvas to plot the charts.
- def plot(self, x, y, ylabel): Plot the charts in the canva... | c0549695e9ee41842e6af0d9c6b3f75b75338eb7 | <|skeleton|>
class Graph:
"""Figure Create the four charts and their layout."""
def __init__(self, parent=None, width=5, height=4, dpi=75):
"""Instantiate the canvas to plot the charts."""
<|body_0|>
def plot(self, x, y, ylabel):
"""Plot the charts in the canvas."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graph:
"""Figure Create the four charts and their layout."""
def __init__(self, parent=None, width=5, height=4, dpi=75):
"""Instantiate the canvas to plot the charts."""
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
... | the_stack_v2_python_sparse | src/classes/GUI.py | mnarizzano/se20-project-16 | train | 0 |
b7f0ef9adf7c6c6f2684c36924a12a999b3ce5c9 | [
"bug_type = BugType()\nbug_type.label = request.data['label']\ntry:\n bug_type.save()\n serializer = BugTypeSerializer(bug_type, context={'request': request})\n return Response(serializer.data)\nexcept ValidationError as ex:\n return Response({'reason': ex.message}, status=status.HTTP_400_BAD_REQUEST)",... | <|body_start_0|>
bug_type = BugType()
bug_type.label = request.data['label']
try:
bug_type.save()
serializer = BugTypeSerializer(bug_type, context={'request': request})
return Response(serializer.data)
except ValidationError as ex:
return R... | Level up bug types | BugTypeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BugTypeView:
"""Level up bug types"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug_type instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug/ticket type Returns: Respon... | stack_v2_sparse_classes_36k_train_030206 | 3,392 | no_license | [
{
"docstring": "Handle POST operations Returns: Response -- JSON serialized bug_type instance",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle GET requests for single bug/ticket type Returns: Response -- JSON serialized bug/ticket type",
"name": "retriev... | 5 | stack_v2_sparse_classes_30k_train_000952 | Implement the Python class `BugTypeView` described below.
Class description:
Level up bug types
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug_type instance
- def retrieve(self, request, pk=None): Handle GET requests for single bug/ticket... | Implement the Python class `BugTypeView` described below.
Class description:
Level up bug types
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug_type instance
- def retrieve(self, request, pk=None): Handle GET requests for single bug/ticket... | 2a74a967bf891d5ddd212f371abef1bf72ebb327 | <|skeleton|>
class BugTypeView:
"""Level up bug types"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug_type instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug/ticket type Returns: Respon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BugTypeView:
"""Level up bug types"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug_type instance"""
bug_type = BugType()
bug_type.label = request.data['label']
try:
bug_type.save()
serializer = BugTyp... | the_stack_v2_python_sparse | bugboapi/views/bug_type.py | S-L-Murphey/Bugbo-server | train | 1 |
5622ee5bd3a50c072521453c8f8966ef5a5ce4d2 | [
"total = 0\nmax_value = -float('inf')\nfor a in A:\n if total < 0:\n total = 0\n total += a\n max_value = max(max_value, total)\ntotal = 0\nmin_value = float('inf')\nfor a in A:\n if total > 0:\n total = 0\n total += a\n min_value = min(min_value, total)\ntemp = sum(A) - min_value\nr... | <|body_start_0|>
total = 0
max_value = -float('inf')
for a in A:
if total < 0:
total = 0
total += a
max_value = max(max_value, total)
total = 0
min_value = float('inf')
for a in A:
if total > 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubarraySumCircular(self, A):
""":type A: List[int] :rtype: int 216 ms"""
<|body_0|>
def maxSubarraySumCircular_1(self, A):
""":type A: List[int] :rtype: int 116ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
total = 0
ma... | stack_v2_sparse_classes_36k_train_030207 | 3,145 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int 216 ms",
"name": "maxSubarraySumCircular",
"signature": "def maxSubarraySumCircular(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int 116ms",
"name": "maxSubarraySumCircular_1",
"signature": "def maxSubarraySumCircular_1(self, A)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubarraySumCircular(self, A): :type A: List[int] :rtype: int 216 ms
- def maxSubarraySumCircular_1(self, A): :type A: List[int] :rtype: int 116ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubarraySumCircular(self, A): :type A: List[int] :rtype: int 216 ms
- def maxSubarraySumCircular_1(self, A): :type A: List[int] :rtype: int 116ms
<|skeleton|>
class Solut... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def maxSubarraySumCircular(self, A):
""":type A: List[int] :rtype: int 216 ms"""
<|body_0|>
def maxSubarraySumCircular_1(self, A):
""":type A: List[int] :rtype: int 116ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubarraySumCircular(self, A):
""":type A: List[int] :rtype: int 216 ms"""
total = 0
max_value = -float('inf')
for a in A:
if total < 0:
total = 0
total += a
max_value = max(max_value, total)
total = 0
... | the_stack_v2_python_sparse | MaximumSumCircularSubarray_MID_918.py | 953250587/leetcode-python | train | 2 | |
a2e1ee8b35aaffa56758f3e39e10f81d8660b4bd | [
"self.SetStartDate(2013, 10, 7)\nself.SetEndDate(2013, 10, 8)\nself.AddEquity('SPY', Resolution.Minute)",
"try:\n self.MarketOrder('PEPE', 1)\nexcept Exception as exception:\n if 'This asset symbol (PEPE 0) was not found in your security list' in str(exception) and (not self.Portfolio.Invested):\n se... | <|body_start_0|>
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 8)
self.AddEquity('SPY', Resolution.Minute)
<|end_body_0|>
<|body_start_1|>
try:
self.MarketOrder('PEPE', 1)
except Exception as exception:
if 'This asset symbol (PEPE 0) was not fo... | StringToSymbolImplicitConversionRegressionAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringToSymbolImplicitConversionRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnData eve... | stack_v2_sparse_classes_36k_train_030208 | 1,785 | permissive | [
{
"docstring": "Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.",
"name": "Initialize",
"signature": "def Initialize(self)"
},
{
"docstring": "OnData event is the primary entry point for your algorithm. Eac... | 2 | null | Implement the Python class `StringToSymbolImplicitConversionRegressionAlgorithm` described below.
Class description:
Implement the StringToSymbolImplicitConversionRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and s... | Implement the Python class `StringToSymbolImplicitConversionRegressionAlgorithm` described below.
Class description:
Implement the StringToSymbolImplicitConversionRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and s... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class StringToSymbolImplicitConversionRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnData eve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringToSymbolImplicitConversionRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 8)
... | the_stack_v2_python_sparse | Algorithm.Python/StringToSymbolImplicitConversionRegressionAlgorithm.py | Capnode/Algoloop | train | 87 | |
f42487cd68137f31655bb1896769dd2e504c68b7 | [
"super().__init__(name)\nself._image = image\nself._command = command\nself._volumes = volumes\nself._devices = devices\nself._environment = environment\nself._network = network\nself._shm_size = shm_size\nself._triton_exec = None\nself._logging_thread = None\nself._log_file_path = pathlib.Path(log_file)",
"devic... | <|body_start_0|>
super().__init__(name)
self._image = image
self._command = command
self._volumes = volumes
self._devices = devices
self._environment = environment
self._network = network
self._shm_size = shm_size
self._triton_exec = None
s... | TritonServerContainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TritonServerContainer:
def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'):
"""Initialize Triton Server Container Args: name: Container name comma... | stack_v2_sparse_classes_36k_train_030209 | 5,403 | permissive | [
{
"docstring": "Initialize Triton Server Container Args: name: Container name command: Triton Server command to exec on container start image: Docker Image volumes: Volumes to mount inside container devices: Devices which has to be visible in container environment: Environment variables log_file: Path where log... | 5 | stack_v2_sparse_classes_30k_train_005763 | Implement the Python class `TritonServerContainer` described below.
Class description:
Implement the TritonServerContainer class.
Method signatures and docstrings:
- def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str],... | Implement the Python class `TritonServerContainer` described below.
Class description:
Implement the TritonServerContainer class.
Method signatures and docstrings:
- def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str],... | a5388a45f71a949639b35cc5b990bd130d2d8164 | <|skeleton|>
class TritonServerContainer:
def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'):
"""Initialize Triton Server Container Args: name: Container name comma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TritonServerContainer:
def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'):
"""Initialize Triton Server Container Args: name: Container name command: Triton Ser... | the_stack_v2_python_sparse | PyTorch/LanguageModeling/BERT/triton/runner/maintainer/docker/containers/triton_server_container.py | NVIDIA/DeepLearningExamples | train | 11,838 | |
054eb20e692179306f89a49307baa54c1531b78f | [
"sc.logger.info('拍摄-拍摄页放弃')\ntime.sleep(1)\nsc.logger.info('点击创作中心主按钮')\nsc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation').click()\nsc.logger.info('点击“拍摄”按钮')\nsc.driver.find_element_by_id('com.quvideo.xiaoying:id/icon2').click()\nel_capture = sc.driver.find_element_by_id('com.quvideo.xiaoying:id... | <|body_start_0|>
sc.logger.info('拍摄-拍摄页放弃')
time.sleep(1)
sc.logger.info('点击创作中心主按钮')
sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation').click()
sc.logger.info('点击“拍摄”按钮')
sc.driver.find_element_by_id('com.quvideo.xiaoying:id/icon2').click()
el_c... | camera取消操作相关的测试类. | TestCameraCancel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCameraCancel:
"""camera取消操作相关的测试类."""
def test_cancel_shot(self):
"""拍摄-拍摄页放弃."""
<|body_0|>
def test_cancel_save(self):
"""拍摄-拍摄页保存."""
<|body_1|>
def test_cancel_preview(self):
"""拍摄-预览页放弃."""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_030210 | 4,622 | no_license | [
{
"docstring": "拍摄-拍摄页放弃.",
"name": "test_cancel_shot",
"signature": "def test_cancel_shot(self)"
},
{
"docstring": "拍摄-拍摄页保存.",
"name": "test_cancel_save",
"signature": "def test_cancel_save(self)"
},
{
"docstring": "拍摄-预览页放弃.",
"name": "test_cancel_preview",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_017608 | Implement the Python class `TestCameraCancel` described below.
Class description:
camera取消操作相关的测试类.
Method signatures and docstrings:
- def test_cancel_shot(self): 拍摄-拍摄页放弃.
- def test_cancel_save(self): 拍摄-拍摄页保存.
- def test_cancel_preview(self): 拍摄-预览页放弃. | Implement the Python class `TestCameraCancel` described below.
Class description:
camera取消操作相关的测试类.
Method signatures and docstrings:
- def test_cancel_shot(self): 拍摄-拍摄页放弃.
- def test_cancel_save(self): 拍摄-拍摄页保存.
- def test_cancel_preview(self): 拍摄-预览页放弃.
<|skeleton|>
class TestCameraCancel:
"""camera取消操作相关的测试类... | b1190e3df62fa85562c14625c06a9794b8ce29a0 | <|skeleton|>
class TestCameraCancel:
"""camera取消操作相关的测试类."""
def test_cancel_shot(self):
"""拍摄-拍摄页放弃."""
<|body_0|>
def test_cancel_save(self):
"""拍摄-拍摄页保存."""
<|body_1|>
def test_cancel_preview(self):
"""拍摄-预览页放弃."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCameraCancel:
"""camera取消操作相关的测试类."""
def test_cancel_shot(self):
"""拍摄-拍摄页放弃."""
sc.logger.info('拍摄-拍摄页放弃')
time.sleep(1)
sc.logger.info('点击创作中心主按钮')
sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation').click()
sc.logger.info('点击“拍摄”按钮'... | the_stack_v2_python_sparse | Android/VivaVideo/test_creations/test_camera/test_cancel.py | hicheng/UItest | train | 0 |
47687f41a0e1d2f8c94640f37e24bb2b02dcd685 | [
"assert self.user_id, 'Login required'\nsupported_post_types = ('ALL', 'CAROUSEL_V2', 'IMAGE', 'SHOPPING', 'VIDEO')\nsupported_time_frames = ('ONE_WEEK', 'ONE_MONTH', 'THREE_MONTHS', 'SIX_MONTHS', 'ONE_YEAR', 'TWO_YEARS')\nassert post_type in supported_post_types, 'Unsupported post type'\nassert time_frame in suppo... | <|body_start_0|>
assert self.user_id, 'Login required'
supported_post_types = ('ALL', 'CAROUSEL_V2', 'IMAGE', 'SHOPPING', 'VIDEO')
supported_time_frames = ('ONE_WEEK', 'ONE_MONTH', 'THREE_MONTHS', 'SIX_MONTHS', 'ONE_YEAR', 'TWO_YEARS')
assert post_type in supported_post_types, 'Unsupport... | Helper class to get insights | InsightsMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsightsMixin:
"""Helper class to get insights"""
def insights_media_feed_all(self, post_type: str='ALL', time_frame: str='TWO_YEARS', data_ordering: str='REACH_COUNT', count: int=0, sleep: int=2) -> List[Dict]:
"""Get insights for all medias from feed with page iteration with cursor... | stack_v2_sparse_classes_36k_train_030211 | 5,987 | permissive | [
{
"docstring": "Get insights for all medias from feed with page iteration with cursor and sleep timeout Parameters ---------- post_type: str, optional Types of posts, default is \"ALL\" Options: (\"ALL\", \"CAROUSEL_V2\", \"IMAGE\", \"SHOPPING\", \"VIDEO\") time_frame: str, optional Time frame to pull media ins... | 3 | stack_v2_sparse_classes_30k_train_001718 | Implement the Python class `InsightsMixin` described below.
Class description:
Helper class to get insights
Method signatures and docstrings:
- def insights_media_feed_all(self, post_type: str='ALL', time_frame: str='TWO_YEARS', data_ordering: str='REACH_COUNT', count: int=0, sleep: int=2) -> List[Dict]: Get insights... | Implement the Python class `InsightsMixin` described below.
Class description:
Helper class to get insights
Method signatures and docstrings:
- def insights_media_feed_all(self, post_type: str='ALL', time_frame: str='TWO_YEARS', data_ordering: str='REACH_COUNT', count: int=0, sleep: int=2) -> List[Dict]: Get insights... | 14922b4038de0b693c6dd396c7ee0b57e626f32e | <|skeleton|>
class InsightsMixin:
"""Helper class to get insights"""
def insights_media_feed_all(self, post_type: str='ALL', time_frame: str='TWO_YEARS', data_ordering: str='REACH_COUNT', count: int=0, sleep: int=2) -> List[Dict]:
"""Get insights for all medias from feed with page iteration with cursor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsightsMixin:
"""Helper class to get insights"""
def insights_media_feed_all(self, post_type: str='ALL', time_frame: str='TWO_YEARS', data_ordering: str='REACH_COUNT', count: int=0, sleep: int=2) -> List[Dict]:
"""Get insights for all medias from feed with page iteration with cursor and sleep ti... | the_stack_v2_python_sparse | instagrapi/mixins/insights.py | bedefaced/instagrapi | train | 1 |
9b9d8e93d2af60dd2a57e4336d7344cb1f120ce8 | [
"super(BottleneckResidualUnit, self).__init__()\nself.bn1 = BatchNormalization()\nself.conv1 = Conv2D(n_filters, 1, padding='same', use_bias=False, kernel_regularizer=regularizers.l2(regularization))\nself.bn2 = BatchNormalization()\nself.conv2 = Conv2D(n_filters, 3, strides=strides, padding='same', use_bias=False,... | <|body_start_0|>
super(BottleneckResidualUnit, self).__init__()
self.bn1 = BatchNormalization()
self.conv1 = Conv2D(n_filters, 1, padding='same', use_bias=False, kernel_regularizer=regularizers.l2(regularization))
self.bn2 = BatchNormalization()
self.conv2 = Conv2D(n_filters, 3, ... | The fundamental module used to implement deep residual network. This module implement the bottleneck residual unit introduced in "Identity Mappings in Deep Residual Networks" (https://arxiv.org/pdf/1603.05027.pdf). | BottleneckResidualUnit | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottleneckResidualUnit:
"""The fundamental module used to implement deep residual network. This module implement the bottleneck residual unit introduced in "Identity Mappings in Deep Residual Networks" (https://arxiv.org/pdf/1603.05027.pdf)."""
def __init__(self, n_filters, strides=1, downsa... | stack_v2_sparse_classes_36k_train_030212 | 10,811 | permissive | [
{
"docstring": "Initialize the BottleneckResidualUnit module. Args: n_filters: (int) the number of output filters. strides: (int) the strides of the convolution. downsample: a function to down-sample the feature maps. regularization: L2 regularization factor for layer weights.",
"name": "__init__",
"sig... | 2 | null | Implement the Python class `BottleneckResidualUnit` described below.
Class description:
The fundamental module used to implement deep residual network. This module implement the bottleneck residual unit introduced in "Identity Mappings in Deep Residual Networks" (https://arxiv.org/pdf/1603.05027.pdf).
Method signatur... | Implement the Python class `BottleneckResidualUnit` described below.
Class description:
The fundamental module used to implement deep residual network. This module implement the bottleneck residual unit introduced in "Identity Mappings in Deep Residual Networks" (https://arxiv.org/pdf/1603.05027.pdf).
Method signatur... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class BottleneckResidualUnit:
"""The fundamental module used to implement deep residual network. This module implement the bottleneck residual unit introduced in "Identity Mappings in Deep Residual Networks" (https://arxiv.org/pdf/1603.05027.pdf)."""
def __init__(self, n_filters, strides=1, downsa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BottleneckResidualUnit:
"""The fundamental module used to implement deep residual network. This module implement the bottleneck residual unit introduced in "Identity Mappings in Deep Residual Networks" (https://arxiv.org/pdf/1603.05027.pdf)."""
def __init__(self, n_filters, strides=1, downsample=None, re... | the_stack_v2_python_sparse | direction_net/model.py | Jimmy-INL/google-research | train | 1 |
c4ecd1600a103e129b137ec874c25f3c6b86c7d1 | [
"excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])\nfor port_name, connector_list in self.inputPorts.iteritems():\n if port_name not in excluded_ports:\n for connector in connector_list:\n connector.obj.update()\nfor port_name, connectorList in copy.copy(sel... | <|body_start_0|>
excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])
for port_name, connector_list in self.inputPorts.iteritems():
if port_name not in excluded_ports:
for connector in connector_list:
connector.obj.update(... | The If Module alows the user to choose the part of the workflow to be executed through the use of a condition. | If | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def updateUpstream(self):
"""A modified version of the updateUpstream method."""
<|body_0|>
def compute(self):
"""The compute method for the I... | stack_v2_sparse_classes_36k_train_030213 | 5,146 | permissive | [
{
"docstring": "A modified version of the updateUpstream method.",
"name": "updateUpstream",
"signature": "def updateUpstream(self)"
},
{
"docstring": "The compute method for the If module.",
"name": "compute",
"signature": "def compute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003421 | Implement the Python class `If` described below.
Class description:
The If Module alows the user to choose the part of the workflow to be executed through the use of a condition.
Method signatures and docstrings:
- def updateUpstream(self): A modified version of the updateUpstream method.
- def compute(self): The com... | Implement the Python class `If` described below.
Class description:
The If Module alows the user to choose the part of the workflow to be executed through the use of a condition.
Method signatures and docstrings:
- def updateUpstream(self): A modified version of the updateUpstream method.
- def compute(self): The com... | 23ef56ec24b85c82416e1437a08381635328abe5 | <|skeleton|>
class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def updateUpstream(self):
"""A modified version of the updateUpstream method."""
<|body_0|>
def compute(self):
"""The compute method for the I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class If:
"""The If Module alows the user to choose the part of the workflow to be executed through the use of a condition."""
def updateUpstream(self):
"""A modified version of the updateUpstream method."""
excluded_ports = set(['TruePort', 'FalsePort', 'TrueOutputPorts', 'FalseOutputPorts'])
... | the_stack_v2_python_sparse | vistrails_current/vistrails/packages/controlflow/conditional.py | lumig242/VisTrailsRecommendation | train | 3 |
b04fd945061f57090941fd0c5021759af2ae09ba | [
"params = init_risky_asset.copy()\nparams.update(kwds)\nRiskyAssetConsumerType.__init__(self, verbose=verbose, quiet=quiet, **params)\nself.solve_one_period = make_one_period_oo_solver(ConsRiskyAssetLabeledSolver)\nself.update_labeled_type()",
"super().update_distributions()\nself.RiskyDstn = DiscreteDistribution... | <|body_start_0|>
params = init_risky_asset.copy()
params.update(kwds)
RiskyAssetConsumerType.__init__(self, verbose=verbose, quiet=quiet, **params)
self.solve_one_period = make_one_period_oo_solver(ConsRiskyAssetLabeledSolver)
self.update_labeled_type()
<|end_body_0|>
<|body_sta... | A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return. | RiskyAssetLabeledType | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiskyAssetLabeledType:
"""A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return."""
def __init__(self, verbose=1, quiet=False, **... | stack_v2_sparse_classes_36k_train_030214 | 40,507 | permissive | [
{
"docstring": "Initialize a labeled RiskyAssetConsumerType.",
"name": "__init__",
"signature": "def __init__(self, verbose=1, quiet=False, **kwds)"
},
{
"docstring": "Update the labeled distributions including the Risky distribution.",
"name": "update_distributions",
"signature": "def u... | 2 | stack_v2_sparse_classes_30k_train_001419 | Implement the Python class `RiskyAssetLabeledType` described below.
Class description:
A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return.
Method signat... | Implement the Python class `RiskyAssetLabeledType` described below.
Class description:
A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return.
Method signat... | 7ce7138b6d9617a28fd4448936be3d61acad21d8 | <|skeleton|>
class RiskyAssetLabeledType:
"""A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return."""
def __init__(self, verbose=1, quiet=False, **... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RiskyAssetLabeledType:
"""A labeled RiskyAssetConsumerType. This class is a subclass of RiskyAssetConsumerType, and inherits all of its methods and attributes. Risky asset consumers can only save on a risky asset that pays a stochastic return."""
def __init__(self, verbose=1, quiet=False, **kwds):
... | the_stack_v2_python_sparse | HARK/ConsumptionSaving/ConsLabeledModel.py | econ-ark/HARK | train | 315 |
d454c6e0331f685b99743ed36352ea689899d16a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MeetingTimeSuggestion()",
"from .attendee_availability import AttendeeAvailability\nfrom .free_busy_status import FreeBusyStatus\nfrom .location import Location\nfrom .time_slot import TimeSlot\nfrom .attendee_availability import Atten... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MeetingTimeSuggestion()
<|end_body_0|>
<|body_start_1|>
from .attendee_availability import AttendeeAvailability
from .free_busy_status import FreeBusyStatus
from .location import... | MeetingTimeSuggestion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeetingTimeSuggestion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingTimeSuggestion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_36k_train_030215 | 5,183 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: MeetingTimeSuggestion",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | stack_v2_sparse_classes_30k_train_014848 | Implement the Python class `MeetingTimeSuggestion` described below.
Class description:
Implement the MeetingTimeSuggestion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingTimeSuggestion: Creates a new instance of the appropriate class base... | Implement the Python class `MeetingTimeSuggestion` described below.
Class description:
Implement the MeetingTimeSuggestion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingTimeSuggestion: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MeetingTimeSuggestion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingTimeSuggestion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeetingTimeSuggestion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MeetingTimeSuggestion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | the_stack_v2_python_sparse | msgraph/generated/models/meeting_time_suggestion.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
b400466724d5e77c59e901ef330d6832237c1af8 | [
"data = {}\nself.parse_tables(soup.find_all('table'), data)\nreturn [data]",
"for table in tables:\n for td_element in table.find_all('td'):\n if 'Planned Work Notification' in td_element.text:\n groups = re.search('.+: ([0-9]+) - ([A-Z][a-z]+)', td_element.text.strip())\n if group... | <|body_start_0|>
data = {}
self.parse_tables(soup.find_all('table'), data)
return [data]
<|end_body_0|>
<|body_start_1|>
for table in tables:
for td_element in table.find_all('td'):
if 'Planned Work Notification' in td_element.text:
groups... | Notifications Parser for GTT notifications. | HtmlParserGTT1 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParserGTT1:
"""Notifications Parser for GTT notifications."""
def parse_html(self, soup):
"""Execute parsing."""
<|body_0|>
def parse_tables(self, tables, data):
"""Parse HTML tables."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = {}... | stack_v2_sparse_classes_36k_train_030216 | 2,541 | permissive | [
{
"docstring": "Execute parsing.",
"name": "parse_html",
"signature": "def parse_html(self, soup)"
},
{
"docstring": "Parse HTML tables.",
"name": "parse_tables",
"signature": "def parse_tables(self, tables, data)"
}
] | 2 | null | Implement the Python class `HtmlParserGTT1` described below.
Class description:
Notifications Parser for GTT notifications.
Method signatures and docstrings:
- def parse_html(self, soup): Execute parsing.
- def parse_tables(self, tables, data): Parse HTML tables. | Implement the Python class `HtmlParserGTT1` described below.
Class description:
Notifications Parser for GTT notifications.
Method signatures and docstrings:
- def parse_html(self, soup): Execute parsing.
- def parse_tables(self, tables, data): Parse HTML tables.
<|skeleton|>
class HtmlParserGTT1:
"""Notificatio... | 2f89d326a1dea49de24b47448549d1715dee189c | <|skeleton|>
class HtmlParserGTT1:
"""Notifications Parser for GTT notifications."""
def parse_html(self, soup):
"""Execute parsing."""
<|body_0|>
def parse_tables(self, tables, data):
"""Parse HTML tables."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlParserGTT1:
"""Notifications Parser for GTT notifications."""
def parse_html(self, soup):
"""Execute parsing."""
data = {}
self.parse_tables(soup.find_all('table'), data)
return [data]
def parse_tables(self, tables, data):
"""Parse HTML tables."""
... | the_stack_v2_python_sparse | circuit_maintenance_parser/parsers/gtt.py | NickCostadura/circuit-maintenance-parser | train | 0 |
aab86d3af7f45effafe1c3c08d3ab5c16c4218a8 | [
"super(DS2Scorer, self).__init__()\nself.infer = DS2Encoder()\nself.ckpt_filename = ckpt_filename\nself.is_restored = False\nself.collect_names = ['pooled_activations']",
"ckpt_filename = ckpt_filename or self.ckpt_filename\nself.infer(waves=tf.ones([16, 48000, 1]))\nreader = tf.train.load_checkpoint(ckpt_filenam... | <|body_start_0|>
super(DS2Scorer, self).__init__()
self.infer = DS2Encoder()
self.ckpt_filename = ckpt_filename
self.is_restored = False
self.collect_names = ['pooled_activations']
<|end_body_0|>
<|body_start_1|>
ckpt_filename = ckpt_filename or self.ckpt_filename
... | Speech scorer based on DeepSpeech2. | DS2Scorer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DS2Scorer:
"""Speech scorer based on DeepSpeech2."""
def __init__(self, ckpt_filename):
"""Constructor. Args: ckpt_filename: Str. Checkpoint filename."""
<|body_0|>
def restore(self, ckpt_filename=None):
"""Restore the model from a checkpoint. Args: ckpt_filename... | stack_v2_sparse_classes_36k_train_030217 | 7,341 | permissive | [
{
"docstring": "Constructor. Args: ckpt_filename: Str. Checkpoint filename.",
"name": "__init__",
"signature": "def __init__(self, ckpt_filename)"
},
{
"docstring": "Restore the model from a checkpoint. Args: ckpt_filename: Str. Checkpoint filename. Returns: Nothing.",
"name": "restore",
... | 3 | null | Implement the Python class `DS2Scorer` described below.
Class description:
Speech scorer based on DeepSpeech2.
Method signatures and docstrings:
- def __init__(self, ckpt_filename): Constructor. Args: ckpt_filename: Str. Checkpoint filename.
- def restore(self, ckpt_filename=None): Restore the model from a checkpoint... | Implement the Python class `DS2Scorer` described below.
Class description:
Speech scorer based on DeepSpeech2.
Method signatures and docstrings:
- def __init__(self, ckpt_filename): Constructor. Args: ckpt_filename: Str. Checkpoint filename.
- def restore(self, ckpt_filename=None): Restore the model from a checkpoint... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class DS2Scorer:
"""Speech scorer based on DeepSpeech2."""
def __init__(self, ckpt_filename):
"""Constructor. Args: ckpt_filename: Str. Checkpoint filename."""
<|body_0|>
def restore(self, ckpt_filename=None):
"""Restore the model from a checkpoint. Args: ckpt_filename... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DS2Scorer:
"""Speech scorer based on DeepSpeech2."""
def __init__(self, ckpt_filename):
"""Constructor. Args: ckpt_filename: Str. Checkpoint filename."""
super(DS2Scorer, self).__init__()
self.infer = DS2Encoder()
self.ckpt_filename = ckpt_filename
self.is_restored... | the_stack_v2_python_sparse | ged_tts/fdsd/eval/tts_scorer.py | Jimmy-INL/google-research | train | 1 |
a3791a17b18ff05cb6db872be03e904578063431 | [
"self.minLength = minLength\nself.maxLength = maxLength\nself.__inRangeValidator = IsInRange()",
"self.__inRangeValidator.minValue = self.minLength\nself.__inRangeValidator.maxValue = self.maxLength\nself.__inRangeValidator(len(value))"
] | <|body_start_0|>
self.minLength = minLength
self.maxLength = maxLength
self.__inRangeValidator = IsInRange()
<|end_body_0|>
<|body_start_1|>
self.__inRangeValidator.minValue = self.minLength
self.__inRangeValidator.maxValue = self.maxLength
self.__inRangeValidator(len(va... | Checks whether the length of a given value is in a specific range. The values that can be checked with this validation class have to support the "len" function. | IsLengthInRange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsLengthInRange:
"""Checks whether the length of a given value is in a specific range. The values that can be checked with this validation class have to support the "len" function."""
def __init__(self, minLength=None, maxLength=None):
"""@param minLength: The lower bound. @type minL... | stack_v2_sparse_classes_36k_train_030218 | 13,874 | no_license | [
{
"docstring": "@param minLength: The lower bound. @type minLength: C{int} @param maxLength: The upper bound. @type maxLength: C{int}",
"name": "__init__",
"signature": "def __init__(self, minLength=None, maxLength=None)"
},
{
"docstring": "Implements the validation. @param value: The value to c... | 2 | null | Implement the Python class `IsLengthInRange` described below.
Class description:
Checks whether the length of a given value is in a specific range. The values that can be checked with this validation class have to support the "len" function.
Method signatures and docstrings:
- def __init__(self, minLength=None, maxLe... | Implement the Python class `IsLengthInRange` described below.
Class description:
Checks whether the length of a given value is in a specific range. The values that can be checked with this validation class have to support the "len" function.
Method signatures and docstrings:
- def __init__(self, minLength=None, maxLe... | 958fda4f3064f9f6b2034da396a20ac9d9abd52f | <|skeleton|>
class IsLengthInRange:
"""Checks whether the length of a given value is in a specific range. The values that can be checked with this validation class have to support the "len" function."""
def __init__(self, minLength=None, maxLength=None):
"""@param minLength: The lower bound. @type minL... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsLengthInRange:
"""Checks whether the length of a given value is in a specific range. The values that can be checked with this validation class have to support the "len" function."""
def __init__(self, minLength=None, maxLength=None):
"""@param minLength: The lower bound. @type minLength: C{int}... | the_stack_v2_python_sparse | src/datafinder/core/configuration/properties/validators/base_validators.py | DLR-SC/DataFinder | train | 9 |
8204b4b8fac06e19c73d8cd08c3d4cac11595798 | [
"self.filename = DATA_PATH_FILE\nself.sheet = sheet\nself.wb = load_workbook(self.filename)\nif self.sheet is None:\n self.ws = self.wb.active\nelse:\n self.ws = self.wb[self.sheet]\nself.case = []\nself.first_row = tuple(self.ws.iter_rows(max_row=1, values_only=True))[0]",
"for rows in self.ws.iter_rows(mi... | <|body_start_0|>
self.filename = DATA_PATH_FILE
self.sheet = sheet
self.wb = load_workbook(self.filename)
if self.sheet is None:
self.ws = self.wb.active
else:
self.ws = self.wb[self.sheet]
self.case = []
self.first_row = tuple(self.ws.iter... | ReadExcel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadExcel:
def __init__(self, sheet=None):
""":param sheet: 表单名"""
<|body_0|>
def get_case(self):
"""获取全部Excel数据 :return: 返回嵌套字典的列表"""
<|body_1|>
def one_case(self, row):
"""获取某一行Excel数据 :param row: 需要返回的行号"""
<|body_2|>
def write_ca... | stack_v2_sparse_classes_36k_train_030219 | 2,319 | no_license | [
{
"docstring": ":param sheet: 表单名",
"name": "__init__",
"signature": "def __init__(self, sheet=None)"
},
{
"docstring": "获取全部Excel数据 :return: 返回嵌套字典的列表",
"name": "get_case",
"signature": "def get_case(self)"
},
{
"docstring": "获取某一行Excel数据 :param row: 需要返回的行号",
"name": "one_c... | 4 | stack_v2_sparse_classes_30k_train_020211 | Implement the Python class `ReadExcel` described below.
Class description:
Implement the ReadExcel class.
Method signatures and docstrings:
- def __init__(self, sheet=None): :param sheet: 表单名
- def get_case(self): 获取全部Excel数据 :return: 返回嵌套字典的列表
- def one_case(self, row): 获取某一行Excel数据 :param row: 需要返回的行号
- def write_c... | Implement the Python class `ReadExcel` described below.
Class description:
Implement the ReadExcel class.
Method signatures and docstrings:
- def __init__(self, sheet=None): :param sheet: 表单名
- def get_case(self): 获取全部Excel数据 :return: 返回嵌套字典的列表
- def one_case(self, row): 获取某一行Excel数据 :param row: 需要返回的行号
- def write_c... | 675962155a2e99aae81ddecd59e9b021ee665782 | <|skeleton|>
class ReadExcel:
def __init__(self, sheet=None):
""":param sheet: 表单名"""
<|body_0|>
def get_case(self):
"""获取全部Excel数据 :return: 返回嵌套字典的列表"""
<|body_1|>
def one_case(self, row):
"""获取某一行Excel数据 :param row: 需要返回的行号"""
<|body_2|>
def write_ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReadExcel:
def __init__(self, sheet=None):
""":param sheet: 表单名"""
self.filename = DATA_PATH_FILE
self.sheet = sheet
self.wb = load_workbook(self.filename)
if self.sheet is None:
self.ws = self.wb.active
else:
self.ws = self.wb[self.sheet... | the_stack_v2_python_sparse | script/rebulit_excel.py | yiruiwan/pytest-api-allure | train | 0 | |
56a0455a817f3a826b40815bfa69794b0c496e07 | [
"pre = ListNode(-1)\npre.next = head\ncurr = pre\nwhile curr.next and curr.next.next:\n forward = curr.next\n curr.next = forward.next\n forward.next = forward.next.next\n curr.next.next = forward\n curr = forward\nreturn pre.next",
"ret_head = head.next if head and head.next else head\npp_head = N... | <|body_start_0|>
pre = ListNode(-1)
pre.next = head
curr = pre
while curr.next and curr.next.next:
forward = curr.next
curr.next = forward.next
forward.next = forward.next.next
curr.next.next = forward
curr = forward
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode Fast solution, but hard to fathom."""
<|body_0|>
def rewrite(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def rewrite2(self, head):
""":type head... | stack_v2_sparse_classes_36k_train_030220 | 3,942 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode Fast solution, but hard to fathom.",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "rewrite",
"signature": "def rewrite(self, head)"
},
{
"docs... | 4 | stack_v2_sparse_classes_30k_train_010954 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode Fast solution, but hard to fathom.
- def rewrite(self, head): :type head: ListNode :rtype: ListNode
- def rewrite... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode Fast solution, but hard to fathom.
- def rewrite(self, head): :type head: ListNode :rtype: ListNode
- def rewrite... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode Fast solution, but hard to fathom."""
<|body_0|>
def rewrite(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def rewrite2(self, head):
""":type head... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode Fast solution, but hard to fathom."""
pre = ListNode(-1)
pre.next = head
curr = pre
while curr.next and curr.next.next:
forward = curr.next
curr.next = forward.next
... | the_stack_v2_python_sparse | co_fb/24_Swap_Nodes_in_Pairs.py | vsdrun/lc_public | train | 6 | |
ce289bfed1c54c6911f9154b50cc86921d290515 | [
"results = []\n\ndef solve(begin, current, tar):\n if tar == 0:\n results.append(current)\n return\n for i in range(begin, len(candidates)):\n c = candidates[i]\n if c <= tar:\n solve(i, current + [c], tar - c)\nsolve(0, [], target)\nreturn results",
"results = []\n\nd... | <|body_start_0|>
results = []
def solve(begin, current, tar):
if tar == 0:
results.append(current)
return
for i in range(begin, len(candidates)):
c = candidates[i]
if c <= tar:
solve(i, current +... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_36k_train_030221 | 2,216 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum",
"signature": "def combinationSum(self, candidates, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum2",
... | 2 | stack_v2_sparse_classes_30k_train_008237 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum2(self, candidates, target): :type candida... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum2(self, candidates, target): :type candida... | 763674fcbe271af3d21eed790c3968c4d33f7b09 | <|skeleton|>
class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
results = []
def solve(begin, current, tar):
if tar == 0:
results.append(current)
return
for i in... | the_stack_v2_python_sparse | 39_combination_sum/39.py | guzhoudiaoke/leetcode_python3 | train | 0 | |
3253ad287bab368239a9832c558801a90279b4d0 | [
"num = 1\nsubnum = 0\nif filename is None:\n filename = cls.DEFAULT_FILE\nif os.path.exists(filename):\n with open(filename, 'r') as fin:\n line = fin.readline()\n mtch = re.search('(\\\\d+)\\\\s+(\\\\d+)', line)\n if mtch is not None:\n try:\n num = int(mtch.gro... | <|body_start_0|>
num = 1
subnum = 0
if filename is None:
filename = cls.DEFAULT_FILE
if os.path.exists(filename):
with open(filename, 'r') as fin:
line = fin.readline()
mtch = re.search('(\\d+)\\s+(\\d+)', line)
if m... | RunNumber | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunNumber:
def get_last(cls, filename=None):
"""Return the last run and subrun numbers as a tuple"""
<|body_0|>
def set_last(cls, number, subrun=0, filename=None):
"""Set the last run and subrun numbers"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030222 | 4,402 | no_license | [
{
"docstring": "Return the last run and subrun numbers as a tuple",
"name": "get_last",
"signature": "def get_last(cls, filename=None)"
},
{
"docstring": "Set the last run and subrun numbers",
"name": "set_last",
"signature": "def set_last(cls, number, subrun=0, filename=None)"
}
] | 2 | null | Implement the Python class `RunNumber` described below.
Class description:
Implement the RunNumber class.
Method signatures and docstrings:
- def get_last(cls, filename=None): Return the last run and subrun numbers as a tuple
- def set_last(cls, number, subrun=0, filename=None): Set the last run and subrun numbers | Implement the Python class `RunNumber` described below.
Class description:
Implement the RunNumber class.
Method signatures and docstrings:
- def get_last(cls, filename=None): Return the last run and subrun numbers as a tuple
- def set_last(cls, number, subrun=0, filename=None): Set the last run and subrun numbers
<... | 718189be62907a6a8031980fe0c41fa7e06b898d | <|skeleton|>
class RunNumber:
def get_last(cls, filename=None):
"""Return the last run and subrun numbers as a tuple"""
<|body_0|>
def set_last(cls, number, subrun=0, filename=None):
"""Set the last run and subrun numbers"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunNumber:
def get_last(cls, filename=None):
"""Return the last run and subrun numbers as a tuple"""
num = 1
subnum = 0
if filename is None:
filename = cls.DEFAULT_FILE
if os.path.exists(filename):
with open(filename, 'r') as fin:
... | the_stack_v2_python_sparse | RunNumber.py | dglo/dash | train | 0 | |
bfd6773b3eb14fcf50864d84f4c32afc50579892 | [
"self.game_config = game_config\nself.unused_cpu = unused_cpu\nself.games = None\nself.batch_size = 0\nself.set_games()",
"if not games:\n self.games = [i + 1 for i in range(self.game_config.game.max_game_id)]\n self.batch_size = min(len(self.games), self.game_config.game.batch)\nelse:\n self.games = gam... | <|body_start_0|>
self.game_config = game_config
self.unused_cpu = unused_cpu
self.games = None
self.batch_size = 0
self.set_games()
<|end_body_0|>
<|body_start_1|>
if not games:
self.games = [i + 1 for i in range(self.game_config.game.max_game_id)]
... | This class is responsible evaluating and evolving the population across a set of games. | TrainingEnv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingEnv:
"""This class is responsible evaluating and evolving the population across a set of games."""
def __init__(self, game_config: Config, unused_cpu: int=0):
"""The evaluator is given a population which it then evaluates using the MultiEnvironment."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_030223 | 8,473 | permissive | [
{
"docstring": "The evaluator is given a population which it then evaluates using the MultiEnvironment.",
"name": "__init__",
"signature": "def __init__(self, game_config: Config, unused_cpu: int=0)"
},
{
"docstring": "Set the game-IDs that will be used to evaluate the population. The full game-... | 5 | stack_v2_sparse_classes_30k_train_006867 | Implement the Python class `TrainingEnv` described below.
Class description:
This class is responsible evaluating and evolving the population across a set of games.
Method signatures and docstrings:
- def __init__(self, game_config: Config, unused_cpu: int=0): The evaluator is given a population which it then evaluat... | Implement the Python class `TrainingEnv` described below.
Class description:
This class is responsible evaluating and evolving the population across a set of games.
Method signatures and docstrings:
- def __init__(self, game_config: Config, unused_cpu: int=0): The evaluator is given a population which it then evaluat... | 334d7b9cab0edb22d4670cfaf39fbed76c351758 | <|skeleton|>
class TrainingEnv:
"""This class is responsible evaluating and evolving the population across a set of games."""
def __init__(self, game_config: Config, unused_cpu: int=0):
"""The evaluator is given a population which it then evaluates using the MultiEnvironment."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainingEnv:
"""This class is responsible evaluating and evolving the population across a set of games."""
def __init__(self, game_config: Config, unused_cpu: int=0):
"""The evaluator is given a population which it then evaluates using the MultiEnvironment."""
self.game_config = game_conf... | the_stack_v2_python_sparse | environment/env_training.py | RubenPants/RobotSimulator2D | train | 0 |
84c8d220ac0c976eb936d2ff40d63525d790c683 | [
"_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_max_slope, bounding_matrix)\nif return_cost_matrix is True:\n\n @njit(cache=True)\n def numba_twe_distance_alignment_path(_x: np.ndarray, _y: np.ndarray) -> Tuple[List, float, np.ndarray]:\n cost_matrix = _twe_cost_matrix(_x, _y, _boundi... | <|body_start_0|>
_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_max_slope, bounding_matrix)
if return_cost_matrix is True:
@njit(cache=True)
def numba_twe_distance_alignment_path(_x: np.ndarray, _y: np.ndarray) -> Tuple[List, float, np.ndarray]:
... | Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE is a metric. Its computati... | _TweDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_36k_train_030224 | 11,583 | permissive | [
{
"docstring": "Create a no_python compiled twe distance callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array of shape (d,m2)). Second time series. return_cost... | 2 | stack_v2_sparse_classes_30k_train_009340 | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | fbe4af4d8419a01ada1e82da1aa63c0218d13edb | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE... | the_stack_v2_python_sparse | sktime/distances/_twe.py | jattenberg/sktime | train | 0 |
580714254fe1d9f3d61703dd554aa4920926446f | [
"self.text_field_key = text_field_key\nself.data = data\nself.cv = None\nself.ngrams_df = pd.DataFrame(['blank'], columns=['Index'])\nself.filtered_ngrams_df = pd.DataFrame(['blank'], columns=['Index'])\nself.ngram_word = None\nself.word_frequency_matrix = pd.DataFrame(['blank'], columns=['Index'])",
"if preproce... | <|body_start_0|>
self.text_field_key = text_field_key
self.data = data
self.cv = None
self.ngrams_df = pd.DataFrame(['blank'], columns=['Index'])
self.filtered_ngrams_df = pd.DataFrame(['blank'], columns=['Index'])
self.ngram_word = None
self.word_frequency_matrix... | The parent class for managing n-gram analysis | NGrams | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NGrams:
"""The parent class for managing n-gram analysis"""
def __init__(self, data, text_field_key='Snippet'):
""":param data: Pandas dataframe containing a text Snippet field and other metadata :param text_field_key: The name of the text field (by default Snippet)"""
<|body... | stack_v2_sparse_classes_36k_train_030225 | 4,267 | permissive | [
{
"docstring": ":param data: Pandas dataframe containing a text Snippet field and other metadata :param text_field_key: The name of the text field (by default Snippet)",
"name": "__init__",
"signature": "def __init__(self, data, text_field_key='Snippet')"
},
{
"docstring": "The primary function ... | 3 | stack_v2_sparse_classes_30k_train_011933 | Implement the Python class `NGrams` described below.
Class description:
The parent class for managing n-gram analysis
Method signatures and docstrings:
- def __init__(self, data, text_field_key='Snippet'): :param data: Pandas dataframe containing a text Snippet field and other metadata :param text_field_key: The name... | Implement the Python class `NGrams` described below.
Class description:
The parent class for managing n-gram analysis
Method signatures and docstrings:
- def __init__(self, data, text_field_key='Snippet'): :param data: Pandas dataframe containing a text Snippet field and other metadata :param text_field_key: The name... | b810c6e1a93a2ecaa9d6351449239d0a1833f971 | <|skeleton|>
class NGrams:
"""The parent class for managing n-gram analysis"""
def __init__(self, data, text_field_key='Snippet'):
""":param data: Pandas dataframe containing a text Snippet field and other metadata :param text_field_key: The name of the text field (by default Snippet)"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NGrams:
"""The parent class for managing n-gram analysis"""
def __init__(self, data, text_field_key='Snippet'):
""":param data: Pandas dataframe containing a text Snippet field and other metadata :param text_field_key: The name of the text field (by default Snippet)"""
self.text_field_key... | the_stack_v2_python_sparse | usherwood_ds/nlp/n_grams/main.py | Usherwood/usherwood_ds | train | 2 |
61366ce0f08dd8699d222602393dc75cdf913324 | [
"parser: OptionParser = super().make_parser(ctx)\noptions = set(parser._short_opt.values())\noptions |= set(parser._long_opt.values())\nfor option in options:\n if not isinstance(option.obj, DeprecatedOption):\n continue\n option.process = self._make_process(option)\nreturn parser",
"orig_process: Ca... | <|body_start_0|>
parser: OptionParser = super().make_parser(ctx)
options = set(parser._short_opt.values())
options |= set(parser._long_opt.values())
for option in options:
if not isinstance(option.obj, DeprecatedOption):
continue
option.process = s... | Allows to provide deprecated options for click's command. Works with `DeprecatedOption` (see above). Expects to be provided into standard `@click.command` as: * `@cli.command(cls=DeprecatedOptionsCommand)` | DeprecatedOptionsCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeprecatedOptionsCommand:
"""Allows to provide deprecated options for click's command. Works with `DeprecatedOption` (see above). Expects to be provided into standard `@click.command` as: * `@cli.command(cls=DeprecatedOptionsCommand)`"""
def make_parser(self, ctx: Context) -> OptionParser:
... | stack_v2_sparse_classes_36k_train_030226 | 3,624 | permissive | [
{
"docstring": "Hook 'make_parser' and during processing check the name. Used to invoke the option to see if it is preferred.",
"name": "make_parser",
"signature": "def make_parser(self, ctx: Context) -> OptionParser"
},
{
"docstring": "Construct a closure to the parser option processor.",
"... | 2 | stack_v2_sparse_classes_30k_train_021130 | Implement the Python class `DeprecatedOptionsCommand` described below.
Class description:
Allows to provide deprecated options for click's command. Works with `DeprecatedOption` (see above). Expects to be provided into standard `@click.command` as: * `@cli.command(cls=DeprecatedOptionsCommand)`
Method signatures and ... | Implement the Python class `DeprecatedOptionsCommand` described below.
Class description:
Allows to provide deprecated options for click's command. Works with `DeprecatedOption` (see above). Expects to be provided into standard `@click.command` as: * `@cli.command(cls=DeprecatedOptionsCommand)`
Method signatures and ... | a66da908907ee1eaf09d88a731025da29e7fca07 | <|skeleton|>
class DeprecatedOptionsCommand:
"""Allows to provide deprecated options for click's command. Works with `DeprecatedOption` (see above). Expects to be provided into standard `@click.command` as: * `@cli.command(cls=DeprecatedOptionsCommand)`"""
def make_parser(self, ctx: Context) -> OptionParser:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeprecatedOptionsCommand:
"""Allows to provide deprecated options for click's command. Works with `DeprecatedOption` (see above). Expects to be provided into standard `@click.command` as: * `@cli.command(cls=DeprecatedOptionsCommand)`"""
def make_parser(self, ctx: Context) -> OptionParser:
"""Hoo... | the_stack_v2_python_sparse | src/sqlfluff/cli/click_deprecated_option.py | sqlfluff/sqlfluff | train | 5,931 |
0ccbe8cf9e20ca38114ece312ac4aa7d55fb2611 | [
"super().__init__()\nself.embed, self.encoders, self.enc_out, self.conv_subsampling_factor = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwise_layer_type, positionwise... | <|body_start_0|>
super().__init__()
self.embed, self.encoders, self.enc_out, self.conv_subsampling_factor = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwi... | Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_type: Positional encoding type. positionwis... | CustomEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_ty... | stack_v2_sparse_classes_36k_train_030227 | 4,661 | permissive | [
{
"docstring": "Construct an CustomEncoder object.",
"name": "__init__",
"signature": "def __init__(self, idim: int, enc_arch: List, input_layer: str='linear', repeat_block: int=1, self_attn_type: str='selfattn', positional_encoding_type: str='abs_pos', positionwise_layer_type: str='linear', positionwis... | 2 | stack_v2_sparse_classes_30k_train_001770 | Implement the Python class `CustomEncoder` described below.
Class description:
Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self... | Implement the Python class `CustomEncoder` described below.
Class description:
Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomEncoder:
"""Custom encoder module for transducer models. Args: idim: Input dimension. enc_arch: Encoder block architecture (type and parameters). input_layer: Input layer type. repeat_block: Number of times blocks_arch is repeated. self_attn_type: Self-attention type. positional_encoding_type: Positiona... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/custom_encoder.py | espnet/espnet | train | 7,242 |
13191af415ebd2a0c3d124e91337c658c03c8e56 | [
"if len(args) == 2:\n maskedData, vbParam = args\n Khat = vbParam.rhat.shape[1]\n Ngroup, nfeature, nchannel = maskedData.sumY.shape\n self.Nhat = np.sum(vbParam.rhat * maskedData.weight[:, np.newaxis], axis=0)\n self.sumY = np.zeros([nfeature, Khat, nchannel])\n self.sumYSq = np.zeros([nfeature, ... | <|body_start_0|>
if len(args) == 2:
maskedData, vbParam = args
Khat = vbParam.rhat.shape[1]
Ngroup, nfeature, nchannel = maskedData.sumY.shape
self.Nhat = np.sum(vbParam.rhat * maskedData.weight[:, np.newaxis], axis=0)
self.sumY = np.zeros([nfeature, K... | Class to calculate precompute sufficient statistics for increased efficiency Attributes: ----------- Nhat : np.array K x 1 numpy array which stores pseudocounts for the number of elements in each cluster. K is the number of clusters sumY : np.array nfeature x K x nchannel which stores weighted sum of the maskData.sumY ... | suffStatistics | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class suffStatistics:
"""Class to calculate precompute sufficient statistics for increased efficiency Attributes: ----------- Nhat : np.array K x 1 numpy array which stores pseudocounts for the number of elements in each cluster. K is the number of clusters sumY : np.array nfeature x K x nchannel which... | stack_v2_sparse_classes_36k_train_030228 | 43,203 | permissive | [
{
"docstring": "Initializes the above attributes and calls calc_suffstat(). Parameters: ----------- maskedData: maskData object vbParam: vbPar object or suffStat: suffStatistics object",
"name": "__init__",
"signature": "def __init__(self, *args)"
},
{
"docstring": "Calcation of the above attrib... | 2 | stack_v2_sparse_classes_30k_train_001412 | Implement the Python class `suffStatistics` described below.
Class description:
Class to calculate precompute sufficient statistics for increased efficiency Attributes: ----------- Nhat : np.array K x 1 numpy array which stores pseudocounts for the number of elements in each cluster. K is the number of clusters sumY :... | Implement the Python class `suffStatistics` described below.
Class description:
Class to calculate precompute sufficient statistics for increased efficiency Attributes: ----------- Nhat : np.array K x 1 numpy array which stores pseudocounts for the number of elements in each cluster. K is the number of clusters sumY :... | 09b5984fe77fca69bbb8d42311ba690dd1d78c70 | <|skeleton|>
class suffStatistics:
"""Class to calculate precompute sufficient statistics for increased efficiency Attributes: ----------- Nhat : np.array K x 1 numpy array which stores pseudocounts for the number of elements in each cluster. K is the number of clusters sumY : np.array nfeature x K x nchannel which... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class suffStatistics:
"""Class to calculate precompute sufficient statistics for increased efficiency Attributes: ----------- Nhat : np.array K x 1 numpy array which stores pseudocounts for the number of elements in each cluster. K is the number of clusters sumY : np.array nfeature x K x nchannel which stores weigh... | the_stack_v2_python_sparse | src/yass/mfm.py | ShenghaoWu/yass | train | 0 |
ec9f0bb94ce660c0028aed21e1213c2ee9db8642 | [
"if not (is_local_folder(parent_dir) and os.path.isabs(parent_dir)):\n raise ValueError('parent_dir parameter must be an absolute path to a folder {0}'.format(parent_dir))\nabs_template_path = make_abs_path(parent_dir, template_path)\ntemplate_dir = os.path.dirname(abs_template_path)\nwith open(abs_template_path... | <|body_start_0|>
if not (is_local_folder(parent_dir) and os.path.isabs(parent_dir)):
raise ValueError('parent_dir parameter must be an absolute path to a folder {0}'.format(parent_dir))
abs_template_path = make_abs_path(parent_dir, template_path)
template_dir = os.path.dirname(abs_te... | Class to export a CloudFormation template | Template | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Template:
"""Class to export a CloudFormation template"""
def __init__(self, template_path, parent_dir, uploader, resources_to_export=RESOURCES_EXPORT_LIST, metadata_to_export=METADATA_EXPORT_LIST):
"""Reads the template and makes it ready for export"""
<|body_0|>
def ex... | stack_v2_sparse_classes_36k_train_030229 | 23,275 | permissive | [
{
"docstring": "Reads the template and makes it ready for export",
"name": "__init__",
"signature": "def __init__(self, template_path, parent_dir, uploader, resources_to_export=RESOURCES_EXPORT_LIST, metadata_to_export=METADATA_EXPORT_LIST)"
},
{
"docstring": "Template params such as AWS::Includ... | 4 | stack_v2_sparse_classes_30k_val_000270 | Implement the Python class `Template` described below.
Class description:
Class to export a CloudFormation template
Method signatures and docstrings:
- def __init__(self, template_path, parent_dir, uploader, resources_to_export=RESOURCES_EXPORT_LIST, metadata_to_export=METADATA_EXPORT_LIST): Reads the template and ma... | Implement the Python class `Template` described below.
Class description:
Class to export a CloudFormation template
Method signatures and docstrings:
- def __init__(self, template_path, parent_dir, uploader, resources_to_export=RESOURCES_EXPORT_LIST, metadata_to_export=METADATA_EXPORT_LIST): Reads the template and ma... | 147d16dfdb72dc9cf362b676a57e46a49375afbd | <|skeleton|>
class Template:
"""Class to export a CloudFormation template"""
def __init__(self, template_path, parent_dir, uploader, resources_to_export=RESOURCES_EXPORT_LIST, metadata_to_export=METADATA_EXPORT_LIST):
"""Reads the template and makes it ready for export"""
<|body_0|>
def ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Template:
"""Class to export a CloudFormation template"""
def __init__(self, template_path, parent_dir, uploader, resources_to_export=RESOURCES_EXPORT_LIST, metadata_to_export=METADATA_EXPORT_LIST):
"""Reads the template and makes it ready for export"""
if not (is_local_folder(parent_dir)... | the_stack_v2_python_sparse | awscli/customizations/cloudformation/artifact_exporter.py | aws/aws-cli | train | 13,038 |
ea0e3eafbbd443920d6add021877bd4d85b9d0bf | [
"self.exist = False\nif address is not None:\n self.exist = True\n if len(address) == 7:\n if address[0] == 1:\n self.universe, self.address_start, balance = ((address[4], address[5], cut_little_ledstrip), (address[1], address[2], 0))[idx_led < cut_little_ledstrip]\n self.address_... | <|body_start_0|>
self.exist = False
if address is not None:
self.exist = True
if len(address) == 7:
if address[0] == 1:
self.universe, self.address_start, balance = ((address[4], address[5], cut_little_ledstrip), (address[1], address[2], 0))[id... | Represent a led of the cube | Led | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Led:
"""Represent a led of the cube"""
def __init__(self, address, idx_led):
"""Constructor of led :param address: tuple of led address :param idx_led: led index"""
<|body_0|>
def show(self, brightness):
"""Illuminate the led with brightness :param brightness: in... | stack_v2_sparse_classes_36k_train_030230 | 3,537 | no_license | [
{
"docstring": "Constructor of led :param address: tuple of led address :param idx_led: led index",
"name": "__init__",
"signature": "def __init__(self, address, idx_led)"
},
{
"docstring": "Illuminate the led with brightness :param brightness: int between 0 and 15 include :raise exception",
... | 2 | stack_v2_sparse_classes_30k_train_005235 | Implement the Python class `Led` described below.
Class description:
Represent a led of the cube
Method signatures and docstrings:
- def __init__(self, address, idx_led): Constructor of led :param address: tuple of led address :param idx_led: led index
- def show(self, brightness): Illuminate the led with brightness ... | Implement the Python class `Led` described below.
Class description:
Represent a led of the cube
Method signatures and docstrings:
- def __init__(self, address, idx_led): Constructor of led :param address: tuple of led address :param idx_led: led index
- def show(self, brightness): Illuminate the led with brightness ... | de1408317d5071b7e0c6b2fea6f281660115d728 | <|skeleton|>
class Led:
"""Represent a led of the cube"""
def __init__(self, address, idx_led):
"""Constructor of led :param address: tuple of led address :param idx_led: led index"""
<|body_0|>
def show(self, brightness):
"""Illuminate the led with brightness :param brightness: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Led:
"""Represent a led of the cube"""
def __init__(self, address, idx_led):
"""Constructor of led :param address: tuple of led address :param idx_led: led index"""
self.exist = False
if address is not None:
self.exist = True
if len(address) == 7:
... | the_stack_v2_python_sparse | api/package/cube/led.py | HE-Arc/Extrusion---web-interface | train | 4 |
7839938c10c11e00708856e0dc9081aa58c7c434 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | AccionList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccionList:
def get(self):
"""Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una Acción"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
veri... | stack_v2_sparse_classes_36k_train_030231 | 6,129 | no_license | [
{
"docstring": "Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Crear una Acción",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005777 | Implement the Python class `AccionList` described below.
Class description:
Implement the AccionList class.
Method signatures and docstrings:
- def get(self): Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una Acción | Implement the Python class `AccionList` described below.
Class description:
Implement the AccionList class.
Method signatures and docstrings:
- def get(self): Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear una Acción
<|skeleton|>
class Acci... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class AccionList:
def get(self):
"""Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear una Acción"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccionList:
def get(self):
"""Listado de acciones. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset'... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/acciones.py | Telematica/knight-rider | train | 1 | |
cf626943f9d1dfe2a3ab12003a4564fea14ad99c | [
"if not root:\n return ''\ndq = deque([root])\nres = [root.val]\nres.append(None)\nwhile dq:\n node = dq.pop()\n for child in node.children:\n res.append(child.val)\n dq.appendleft(child)\n res.append(None)\nreturn ' '.join(map(str, res))",
"if not data:\n return None\ndata = data.spl... | <|body_start_0|>
if not root:
return ''
dq = deque([root])
res = [root.val]
res.append(None)
while dq:
node = dq.pop()
for child in node.children:
res.append(child.val)
dq.appendleft(child)
res.append... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_030232 | 1,439 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_016302 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if not root:
return ''
dq = deque([root])
res = [root.val]
res.append(None)
while dq:
node = dq.pop()
for c... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree _ tree.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
9bc2962bc478fc96722308ff373dddff682b8ba1 | [
"modify = True\nif modify and kwargs is not None:\n for key, value in kwargs.items():\n log('%s == %s' % (key, value))\nif modify:\n config = kwargs['config']\n inputdict = kwargs['inputdict']\n inputkeydict = kwargs['inputkeydict']",
"modify = True\nif modify and kwargs is not None:\n for k... | <|body_start_0|>
modify = True
if modify and kwargs is not None:
for key, value in kwargs.items():
log('%s == %s' % (key, value))
if modify:
config = kwargs['config']
inputdict = kwargs['inputdict']
inputkeydict = kwargs['inputkeydi... | ServiceDataCustomization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceDataCustomization:
def process_service_create_data(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the inputs"""
<|body_0|>
def process_service_device_bindings(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the device bindings or Call the ... | stack_v2_sparse_classes_36k_train_030233 | 30,627 | no_license | [
{
"docstring": "Custom API to modify the inputs",
"name": "process_service_create_data",
"signature": "def process_service_create_data(smodelctx, sdata, dev, **kwargs)"
},
{
"docstring": "Custom API to modify the device bindings or Call the Business Login Handlers",
"name": "process_service_... | 4 | null | Implement the Python class `ServiceDataCustomization` described below.
Class description:
Implement the ServiceDataCustomization class.
Method signatures and docstrings:
- def process_service_create_data(smodelctx, sdata, dev, **kwargs): Custom API to modify the inputs
- def process_service_device_bindings(smodelctx,... | Implement the Python class `ServiceDataCustomization` described below.
Class description:
Implement the ServiceDataCustomization class.
Method signatures and docstrings:
- def process_service_create_data(smodelctx, sdata, dev, **kwargs): Custom API to modify the inputs
- def process_service_device_bindings(smodelctx,... | 96de3a4fd4adbbc0d443620f0c53f397823a1cad | <|skeleton|>
class ServiceDataCustomization:
def process_service_create_data(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the inputs"""
<|body_0|>
def process_service_device_bindings(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the device bindings or Call the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceDataCustomization:
def process_service_create_data(smodelctx, sdata, dev, **kwargs):
"""Custom API to modify the inputs"""
modify = True
if modify and kwargs is not None:
for key, value in kwargs.items():
log('%s == %s' % (key, value))
if modi... | the_stack_v2_python_sparse | scripts/managed_cpe_services/customer/single_cpe_dual_wan_site/single_cpe_dual_wan_site_services/failover_fallback_service/failover_fallback/service_customization.py | lucabrasi83/anutacpedeployment | train | 0 | |
b6941a852d51fb4a92441a683ecbec3ce34e0ae2 | [
"if isinstance(decisions, Layer1Decisions):\n decisions = decisions._data\nif task_token is None:\n task_token = self.last_tasktoken\nreturn self._swf.respond_decision_task_completed(task_token, decisions, **kwargs)",
"task_list = self.task_list\nif 'task_list' in kwargs:\n task_list = kwargs.get('task_l... | <|body_start_0|>
if isinstance(decisions, Layer1Decisions):
decisions = decisions._data
if task_token is None:
task_token = self.last_tasktoken
return self._swf.respond_decision_task_completed(task_token, decisions, **kwargs)
<|end_body_0|>
<|body_start_1|>
task_... | Base class for SimpleWorkflow deciders. | Decider | [
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0",
"Unlicense",
"LGPL-3.0-only",
"CC0-1.0",
"LicenseRef-scancode-other-permissive",
"CNRI-Python",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"Python-2.0",
"GPL-3.0... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decider:
"""Base class for SimpleWorkflow deciders."""
def complete(self, task_token=None, decisions=None, **kwargs):
"""RespondDecisionTaskCompleted."""
<|body_0|>
def poll(self, **kwargs):
"""PollForDecisionTask."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_030234 | 13,056 | permissive | [
{
"docstring": "RespondDecisionTaskCompleted.",
"name": "complete",
"signature": "def complete(self, task_token=None, decisions=None, **kwargs)"
},
{
"docstring": "PollForDecisionTask.",
"name": "poll",
"signature": "def poll(self, **kwargs)"
}
] | 2 | null | Implement the Python class `Decider` described below.
Class description:
Base class for SimpleWorkflow deciders.
Method signatures and docstrings:
- def complete(self, task_token=None, decisions=None, **kwargs): RespondDecisionTaskCompleted.
- def poll(self, **kwargs): PollForDecisionTask. | Implement the Python class `Decider` described below.
Class description:
Base class for SimpleWorkflow deciders.
Method signatures and docstrings:
- def complete(self, task_token=None, decisions=None, **kwargs): RespondDecisionTaskCompleted.
- def poll(self, **kwargs): PollForDecisionTask.
<|skeleton|>
class Decider... | dccb9467675c67b9c3399fc76c5de6d31bfb8255 | <|skeleton|>
class Decider:
"""Base class for SimpleWorkflow deciders."""
def complete(self, task_token=None, decisions=None, **kwargs):
"""RespondDecisionTaskCompleted."""
<|body_0|>
def poll(self, **kwargs):
"""PollForDecisionTask."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decider:
"""Base class for SimpleWorkflow deciders."""
def complete(self, task_token=None, decisions=None, **kwargs):
"""RespondDecisionTaskCompleted."""
if isinstance(decisions, Layer1Decisions):
decisions = decisions._data
if task_token is None:
task_toke... | the_stack_v2_python_sparse | desktop/core/ext-py3/boto-2.49.0/boto/swf/layer2.py | cloudera/hue | train | 5,655 |
239fdce70b51f1475ea4ea87c4ef28f8802c43b0 | [
"while root:\n if target < root.val:\n root = root.left\n elif target > root.val:\n root = root.right\n else:\n return root\nreturn None",
"while root:\n if target < root.val:\n if not root.left:\n root.left = TreeNode(target)\n return\n root = ... | <|body_start_0|>
while root:
if target < root.val:
root = root.left
elif target > root.val:
root = root.right
else:
return root
return None
<|end_body_0|>
<|body_start_1|>
while root:
if target < roo... | BinarySearchTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySearchTree:
def find(self, root: TreeNode, target: int) -> TreeNode:
"""时间复杂度: O(logn) Args: root: target: Returns:"""
<|body_0|>
def insert(self, root: TreeNode, target: int):
"""插入 Args: root: target: Returns:"""
<|body_1|>
def delete(self, root:... | stack_v2_sparse_classes_36k_train_030235 | 2,628 | no_license | [
{
"docstring": "时间复杂度: O(logn) Args: root: target: Returns:",
"name": "find",
"signature": "def find(self, root: TreeNode, target: int) -> TreeNode"
},
{
"docstring": "插入 Args: root: target: Returns:",
"name": "insert",
"signature": "def insert(self, root: TreeNode, target: int)"
},
... | 3 | null | Implement the Python class `BinarySearchTree` described below.
Class description:
Implement the BinarySearchTree class.
Method signatures and docstrings:
- def find(self, root: TreeNode, target: int) -> TreeNode: 时间复杂度: O(logn) Args: root: target: Returns:
- def insert(self, root: TreeNode, target: int): 插入 Args: roo... | Implement the Python class `BinarySearchTree` described below.
Class description:
Implement the BinarySearchTree class.
Method signatures and docstrings:
- def find(self, root: TreeNode, target: int) -> TreeNode: 时间复杂度: O(logn) Args: root: target: Returns:
- def insert(self, root: TreeNode, target: int): 插入 Args: roo... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class BinarySearchTree:
def find(self, root: TreeNode, target: int) -> TreeNode:
"""时间复杂度: O(logn) Args: root: target: Returns:"""
<|body_0|>
def insert(self, root: TreeNode, target: int):
"""插入 Args: root: target: Returns:"""
<|body_1|>
def delete(self, root:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinarySearchTree:
def find(self, root: TreeNode, target: int) -> TreeNode:
"""时间复杂度: O(logn) Args: root: target: Returns:"""
while root:
if target < root.val:
root = root.left
elif target > root.val:
root = root.right
else:
... | the_stack_v2_python_sparse | 算法/二叉查找树.py | tenqaz/crazy_arithmetic | train | 0 | |
7ea30173fb869e0f3ec4f6ec587dd091c88d77e1 | [
"exists = os.path.exists(file_location)\ndata = {'exists': exists, 'file_location': file_location}\nif exists:\n local = pytz.timezone(timezone)\n utc = pytz.timezone('UTC')\n stats = os.stat(file_location)\n self.file_size = int(stats.st_size)\n self.mtime = datetime.datetime.fromtimestamp(stats.st_... | <|body_start_0|>
exists = os.path.exists(file_location)
data = {'exists': exists, 'file_location': file_location}
if exists:
local = pytz.timezone(timezone)
utc = pytz.timezone('UTC')
stats = os.stat(file_location)
self.file_size = int(stats.st_siz... | Status of the one-to-all propagator files | OneToAllStatus | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneToAllStatus:
"""Status of the one-to-all propagator files"""
def get_file_info(file_location: str, timezone='Etc/GMT-5') -> Dict[str, Any]:
"""Returns dict with keys ``file_size``, ``mtime``, ``exists`` and ``file_location`` Arguments: file_location: The file path to check timezon... | stack_v2_sparse_classes_36k_train_030236 | 3,491 | permissive | [
{
"docstring": "Returns dict with keys ``file_size``, ``mtime``, ``exists`` and ``file_location`` Arguments: file_location: The file path to check timezone: The local timezone",
"name": "get_file_info",
"signature": "def get_file_info(file_location: str, timezone='Etc/GMT-5') -> Dict[str, Any]"
},
{... | 2 | stack_v2_sparse_classes_30k_val_000765 | Implement the Python class `OneToAllStatus` described below.
Class description:
Status of the one-to-all propagator files
Method signatures and docstrings:
- def get_file_info(file_location: str, timezone='Etc/GMT-5') -> Dict[str, Any]: Returns dict with keys ``file_size``, ``mtime``, ``exists`` and ``file_location``... | Implement the Python class `OneToAllStatus` described below.
Class description:
Status of the one-to-all propagator files
Method signatures and docstrings:
- def get_file_info(file_location: str, timezone='Etc/GMT-5') -> Dict[str, Any]: Returns dict with keys ``file_size``, ``mtime``, ``exists`` and ``file_location``... | 75c06748f3d59332a84ec1b5794c215c5974a46f | <|skeleton|>
class OneToAllStatus:
"""Status of the one-to-all propagator files"""
def get_file_info(file_location: str, timezone='Etc/GMT-5') -> Dict[str, Any]:
"""Returns dict with keys ``file_size``, ``mtime``, ``exists`` and ``file_location`` Arguments: file_location: The file path to check timezon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OneToAllStatus:
"""Status of the one-to-all propagator files"""
def get_file_info(file_location: str, timezone='Etc/GMT-5') -> Dict[str, Any]:
"""Returns dict with keys ``file_size``, ``mtime``, ``exists`` and ``file_location`` Arguments: file_location: The file path to check timezone: The local ... | the_stack_v2_python_sparse | lattedb/project/ga_q2/models.py | callat-qcd/lattedb | train | 1 |
ac62548350bb2f5a43e01f83e7cc6183cf9055ee | [
"if not nums:\n return 0\ndp = [[0 for i in range(2)] for _ in range(len(nums))]\ndp[0][0] = 0\ndp[0][1] = nums[0]\nfor i in range(1, len(nums)):\n dp[i][0] = max(dp[i - 1][0], dp[i - 1][1])\n dp[i][1] = dp[i - 1][0] + nums[i]\nreturn max(dp[-1])",
"if not nums:\n return 0\nif len(nums) == 1:\n ret... | <|body_start_0|>
if not nums:
return 0
dp = [[0 for i in range(2)] for _ in range(len(nums))]
dp[0][0] = 0
dp[0][1] = nums[0]
for i in range(1, len(nums)):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1])
dp[i][1] = dp[i - 1][0] + nums[i]
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums: List[int]) -> int:
"""0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:"""
<|body_0|>
def rob1(self, nums: List[int]) -> int:
"""空间优化 o(n) 状态转移方程为dp[i] = max(dp[i - 2] + nums... | stack_v2_sparse_classes_36k_train_030237 | 2,431 | no_license | [
{
"docstring": "0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:",
"name": "rob",
"signature": "def rob(self, nums: List[int]) -> int"
},
{
"docstring": "空间优化 o(n) 状态转移方程为dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]),表示偷窃当前房间和不偷窃当前房间 ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:
- def rob1(self, nums: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:
- def rob1(self, nums: Lis... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def rob(self, nums: List[int]) -> int:
"""0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:"""
<|body_0|>
def rob1(self, nums: List[int]) -> int:
"""空间优化 o(n) 状态转移方程为dp[i] = max(dp[i - 2] + nums... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums: List[int]) -> int:
"""0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:"""
if not nums:
return 0
dp = [[0 for i in range(2)] for _ in range(len(nums))]
dp[0][0] = 0
... | the_stack_v2_python_sparse | datastructure/dp_exercise/Rob.py | yinhuax/leet_code | train | 0 | |
c273307560cddad80cd6009b73e0e2ac49685e4d | [
"super().__init__()\nself.dim = dim\nself.dim_out = dim_out\nself.norm1 = norm_layer(dim)\nself.norm1_is_batchnorm_1d = isinstance(self.norm1, BatchNorm1d)\nself.norm1.permute_input_output = True if self.norm1_is_batchnorm_1d else False\nkernel_skip = [s + 1 if s > 1 else s for s in stride_q]\nstride_skip = stride_... | <|body_start_0|>
super().__init__()
self.dim = dim
self.dim_out = dim_out
self.norm1 = norm_layer(dim)
self.norm1_is_batchnorm_1d = isinstance(self.norm1, BatchNorm1d)
self.norm1.permute_input_output = True if self.norm1_is_batchnorm_1d else False
kernel_skip = [s... | Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ | Mlp Proj ↓ | DropPath | ↓ | Summation ←---... | MultiScaleBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiScaleBlock:
"""Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ |... | stack_v2_sparse_classes_36k_train_030238 | 28,184 | permissive | [
{
"docstring": "Args: dim (int): Input feature dimension. dim_out (int): Output feature dimension. num_heads (int): Number of heads in the attention layer. mlp_ratio (float): Mlp ratio which controls the feature dimension in the hidden layer of the Mlp block. qkv_bias (bool): If set to False, the qkv layer will... | 2 | null | Implement the Python class `MultiScaleBlock` described below.
Class description:
Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+... | Implement the Python class `MultiScaleBlock` described below.
Class description:
Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+... | c60dc19788217556ba12ea378c02b9fd0aea9ffe | <|skeleton|>
class MultiScaleBlock:
"""Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ |... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiScaleBlock:
"""Implementation of a multiscale vision transformer block. Each block contains a multiscale attention layer and a Mlp layer. :: Input |-------------------+ ↓ | Norm | ↓ | MultiScaleAttention Pool ↓ | DropPath | ↓ | Summation ←-------------+ | |-------------------+ ↓ | Norm | ↓ | Mlp Proj ↓ |... | the_stack_v2_python_sparse | python/aitemplate/frontend/nn/multiscale_attention.py | facebookincubator/AITemplate | train | 4,065 |
2b022e9fa78a09ed512d34e2c746da312f8ada57 | [
"args = self._build_potential_args({'room_id': room_id, 'message': message, 'message_format': message_format, 'notify': notify, 'color': color, 'format': 'json'})\nurl = self._generate_escaped_url(API_MESSAGE_PATH, args)\nres = (yield self._fetch_wrapper(url))\nraise gen.Return(res)",
"self.log.info('Sending mess... | <|body_start_0|>
args = self._build_potential_args({'room_id': room_id, 'message': message, 'message_format': message_format, 'notify': notify, 'color': color, 'format': 'json'})
url = self._generate_escaped_url(API_MESSAGE_PATH, args)
res = (yield self._fetch_wrapper(url))
raise gen.Ret... | Sends a message to a room in HipChat. **Options** :room: (str) The string-name (or ID) of the room to send a message to :message: (str) Message to send **Examples** .. code-block:: json { "actor": "hipchat.Message", "desc": "Send a message!", "options": { "room": "Operations", "message": "Beginning Deploy: v1.2" } } **... | Message | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Message:
"""Sends a message to a room in HipChat. **Options** :room: (str) The string-name (or ID) of the room to send a message to :message: (str) Message to send **Examples** .. code-block:: json { "actor": "hipchat.Message", "desc": "Send a message!", "options": { "room": "Operations", "messag... | stack_v2_sparse_classes_36k_train_030239 | 10,230 | permissive | [
{
"docstring": "Posts a message to Hipchat. https://www.hipchat.com/docs/api/method/rooms/message Args: room_id: (Str/Int) Name or ID of the room to post to. message: (Str) Required. The message body. 10,000 characters max. message_format: (Str) 'html' or 'text'. notify: (0/1) Whether or not this message should... | 2 | stack_v2_sparse_classes_30k_train_003692 | Implement the Python class `Message` described below.
Class description:
Sends a message to a room in HipChat. **Options** :room: (str) The string-name (or ID) of the room to send a message to :message: (str) Message to send **Examples** .. code-block:: json { "actor": "hipchat.Message", "desc": "Send a message!", "op... | Implement the Python class `Message` described below.
Class description:
Sends a message to a room in HipChat. **Options** :room: (str) The string-name (or ID) of the room to send a message to :message: (str) Message to send **Examples** .. code-block:: json { "actor": "hipchat.Message", "desc": "Send a message!", "op... | d0abaf93ff321f12c0504c99eacb89f9288e892b | <|skeleton|>
class Message:
"""Sends a message to a room in HipChat. **Options** :room: (str) The string-name (or ID) of the room to send a message to :message: (str) Message to send **Examples** .. code-block:: json { "actor": "hipchat.Message", "desc": "Send a message!", "options": { "room": "Operations", "messag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Message:
"""Sends a message to a room in HipChat. **Options** :room: (str) The string-name (or ID) of the room to send a message to :message: (str) Message to send **Examples** .. code-block:: json { "actor": "hipchat.Message", "desc": "Send a message!", "options": { "room": "Operations", "message": "Beginnin... | the_stack_v2_python_sparse | kingpin/actors/hipchat.py | Nextdoor/kingpin | train | 29 |
47c0047efdc7219376c31b662c1461e701071671 | [
"conf = GlobalConfig.fetch()\nif not conf:\n conf = GlobalConfig()\nreturn GlobalConfigMessage(services_config_location=conf.services_config_location, services_config_storage_type=conf.services_config_storage_type)",
"conf = GlobalConfig.fetch()\nif not conf:\n conf = GlobalConfig()\nchanged = conf.modify(u... | <|body_start_0|>
conf = GlobalConfig.fetch()
if not conf:
conf = GlobalConfig()
return GlobalConfigMessage(services_config_location=conf.services_config_location, services_config_storage_type=conf.services_config_storage_type)
<|end_body_0|>
<|body_start_1|>
conf = GlobalCon... | Administration API accessible only by the service admins. | AdminApi | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminApi:
"""Administration API accessible only by the service admins."""
def read_global_config(self, _request):
"""Reads global configuration."""
<|body_0|>
def write_global_config(self, request):
"""Writes global configuration."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_030240 | 3,033 | permissive | [
{
"docstring": "Reads global configuration.",
"name": "read_global_config",
"signature": "def read_global_config(self, _request)"
},
{
"docstring": "Writes global configuration.",
"name": "write_global_config",
"signature": "def write_global_config(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006347 | Implement the Python class `AdminApi` described below.
Class description:
Administration API accessible only by the service admins.
Method signatures and docstrings:
- def read_global_config(self, _request): Reads global configuration.
- def write_global_config(self, request): Writes global configuration. | Implement the Python class `AdminApi` described below.
Class description:
Administration API accessible only by the service admins.
Method signatures and docstrings:
- def read_global_config(self, _request): Reads global configuration.
- def write_global_config(self, request): Writes global configuration.
<|skeleton... | 10cc5fdcca53e2a1690867acbe6fce099273f092 | <|skeleton|>
class AdminApi:
"""Administration API accessible only by the service admins."""
def read_global_config(self, _request):
"""Reads global configuration."""
<|body_0|>
def write_global_config(self, request):
"""Writes global configuration."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminApi:
"""Administration API accessible only by the service admins."""
def read_global_config(self, _request):
"""Reads global configuration."""
conf = GlobalConfig.fetch()
if not conf:
conf = GlobalConfig()
return GlobalConfigMessage(services_config_locatio... | the_stack_v2_python_sparse | appengine/config_service/admin.py | luci/luci-py | train | 84 |
c1e2c692a8af5a1edcf065bb85dddc2e1887244b | [
"self._unit_of_measurement = unit_of_measurement\nself._minimum_value = minimum_sensor_value\nself._maximum_value = maximum_sensor_value\nKNXGroupAddress.__init__(self, hass, config)",
"if self._data:\n from knxip.conversion import knx2_to_float\n value = knx2_to_float(self._data)\n if self._minimum_valu... | <|body_start_0|>
self._unit_of_measurement = unit_of_measurement
self._minimum_value = minimum_sensor_value
self._maximum_value = maximum_sensor_value
KNXGroupAddress.__init__(self, hass, config)
<|end_body_0|>
<|body_start_1|>
if self._data:
from knxip.conversion im... | Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10 | KNXSensorFloatClass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNXSensorFloatClass:
"""Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10"""
def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value):
"""Initialize a KNX Float Sensor."""
<|body_0|>
def state... | stack_v2_sparse_classes_36k_train_030241 | 4,164 | permissive | [
{
"docstring": "Initialize a KNX Float Sensor.",
"name": "__init__",
"signature": "def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value)"
},
{
"docstring": "Return the Value of the KNX Sensor.",
"name": "state",
"signature": "def state(self)"
... | 2 | stack_v2_sparse_classes_30k_train_001738 | Implement the Python class `KNXSensorFloatClass` described below.
Class description:
Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10
Method signatures and docstrings:
- def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value): Initialize... | Implement the Python class `KNXSensorFloatClass` described below.
Class description:
Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10
Method signatures and docstrings:
- def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value): Initialize... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class KNXSensorFloatClass:
"""Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10"""
def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value):
"""Initialize a KNX Float Sensor."""
<|body_0|>
def state... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KNXSensorFloatClass:
"""Base Implementation of a 2byte Floating Point KNX Telegram. Defined in KNX 3.7.2 - 3.10"""
def __init__(self, hass, config, unit_of_measurement, minimum_sensor_value, maximum_sensor_value):
"""Initialize a KNX Float Sensor."""
self._unit_of_measurement = unit_of_me... | the_stack_v2_python_sparse | homeassistant/components/sensor/knx.py | Smart-Torvy/torvy-home-assistant | train | 2 |
88d165f5fc315b95204ac15beefffaee1f79a6dd | [
"collateral = {'collateralId': self.id, 'addedDateTime': ''}\nif self.status and self.status == STATUS_ADDED:\n collateral['descriptionAdd'] = self.description\nelif self.status and self.status == STATUS_DELETED:\n collateral['descriptionDelete'] = self.description\nelse:\n collateral['description'] = self... | <|body_start_0|>
collateral = {'collateralId': self.id, 'addedDateTime': ''}
if self.status and self.status == STATUS_ADDED:
collateral['descriptionAdd'] = self.description
elif self.status and self.status == STATUS_DELETED:
collateral['descriptionDelete'] = self.descript... | This class manages all of the legacy application general collateral information. | GeneralCollateralLegacy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralCollateralLegacy:
"""This class manages all of the legacy application general collateral information."""
def current_json(self) -> dict:
"""Generate a Financing Statement current view of the general collateral as json/dict."""
<|body_0|>
def json(self) -> dict:
... | stack_v2_sparse_classes_36k_train_030242 | 4,718 | permissive | [
{
"docstring": "Generate a Financing Statement current view of the general collateral as json/dict.",
"name": "current_json",
"signature": "def current_json(self) -> dict"
},
{
"docstring": "Generate the default view of the general collateral as json/a dict.",
"name": "json",
"signature"... | 5 | stack_v2_sparse_classes_30k_train_009057 | Implement the Python class `GeneralCollateralLegacy` described below.
Class description:
This class manages all of the legacy application general collateral information.
Method signatures and docstrings:
- def current_json(self) -> dict: Generate a Financing Statement current view of the general collateral as json/di... | Implement the Python class `GeneralCollateralLegacy` described below.
Class description:
This class manages all of the legacy application general collateral information.
Method signatures and docstrings:
- def current_json(self) -> dict: Generate a Financing Statement current view of the general collateral as json/di... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class GeneralCollateralLegacy:
"""This class manages all of the legacy application general collateral information."""
def current_json(self) -> dict:
"""Generate a Financing Statement current view of the general collateral as json/dict."""
<|body_0|>
def json(self) -> dict:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneralCollateralLegacy:
"""This class manages all of the legacy application general collateral information."""
def current_json(self) -> dict:
"""Generate a Financing Statement current view of the general collateral as json/dict."""
collateral = {'collateralId': self.id, 'addedDateTime':... | the_stack_v2_python_sparse | ppr-api/src/ppr_api/models/general_collateral_legacy.py | bcgov/ppr | train | 4 |
05e7371c37288972b7c1426df6143b589e573695 | [
"self._target_init_lock = Lock()\nself._target_input_queue = Queue()\nself._target_output_queue = Queue()\nself._proc_list = []\nfor proc in range(n_procs):\n proc = Process(target=target_function, args=(self._target_init_lock, self._target_input_queue, self._target_output_queue, pass_through_args))\n self._p... | <|body_start_0|>
self._target_init_lock = Lock()
self._target_input_queue = Queue()
self._target_output_queue = Queue()
self._proc_list = []
for proc in range(n_procs):
proc = Process(target=target_function, args=(self._target_init_lock, self._target_input_queue, self... | LivingMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LivingMap:
def __init__(self, n_procs, target_function, pass_through_args):
"""start n_proc processes. Each one is the target_function with its pass_through_args. Maintain a list of the processes. Create two queues, one for passing work to the target_functions, and one for getting result... | stack_v2_sparse_classes_36k_train_030243 | 3,283 | no_license | [
{
"docstring": "start n_proc processes. Each one is the target_function with its pass_through_args. Maintain a list of the processes. Create two queues, one for passing work to the target_functions, and one for getting results back. Pass a lock to the target_functions so they can initialize themselves in serial... | 3 | stack_v2_sparse_classes_30k_train_006819 | Implement the Python class `LivingMap` described below.
Class description:
Implement the LivingMap class.
Method signatures and docstrings:
- def __init__(self, n_procs, target_function, pass_through_args): start n_proc processes. Each one is the target_function with its pass_through_args. Maintain a list of the proc... | Implement the Python class `LivingMap` described below.
Class description:
Implement the LivingMap class.
Method signatures and docstrings:
- def __init__(self, n_procs, target_function, pass_through_args): start n_proc processes. Each one is the target_function with its pass_through_args. Maintain a list of the proc... | 92622bce19dfd53e87a17e376a0e00c8f2f8f8cb | <|skeleton|>
class LivingMap:
def __init__(self, n_procs, target_function, pass_through_args):
"""start n_proc processes. Each one is the target_function with its pass_through_args. Maintain a list of the processes. Create two queues, one for passing work to the target_functions, and one for getting result... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LivingMap:
def __init__(self, n_procs, target_function, pass_through_args):
"""start n_proc processes. Each one is the target_function with its pass_through_args. Maintain a list of the processes. Create two queues, one for passing work to the target_functions, and one for getting results back. Pass a... | the_stack_v2_python_sparse | altsrc/LivingMapParallelism/livingmap.py | NingDaoguan/UQ | train | 0 | |
f305ddc1a75ca836d94d183268f24e723db473b8 | [
"self.id = id\nself.description = description\nself.cusip_no = cusip_no\nself.symbol = symbol\nself.quantity = quantity\nself.current_price = current_price\nself.fund_name = fund_name\nself.security_name = security_name\nself.transaction_type = transaction_type\nself.market_value = market_value\nself.cost_basis = c... | <|body_start_0|>
self.id = id
self.description = description
self.cusip_no = cusip_no
self.symbol = symbol
self.quantity = quantity
self.current_price = current_price
self.fund_name = fund_name
self.security_name = security_name
self.transaction_ty... | Implementation of the 'Customer Account Position' model. Details for investment account holdings Attributes: id (long|int): The id of the investment position description (string): The description of the holding cusip_no (long|int): Cusip number for the investment holding symbol (string): The symbol of the investment ho... | CustomerAccountPosition | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerAccountPosition:
"""Implementation of the 'Customer Account Position' model. Details for investment account holdings Attributes: id (long|int): The id of the investment position description (string): The description of the holding cusip_no (long|int): Cusip number for the investment holdi... | stack_v2_sparse_classes_36k_train_030244 | 5,672 | permissive | [
{
"docstring": "Constructor for the CustomerAccountPosition class",
"name": "__init__",
"signature": "def __init__(self, id=None, description=None, cusip_no=None, symbol=None, quantity=None, current_price=None, fund_name=None, security_name=None, transaction_type=None, market_value=None, cost_basis=None... | 2 | stack_v2_sparse_classes_30k_train_021604 | Implement the Python class `CustomerAccountPosition` described below.
Class description:
Implementation of the 'Customer Account Position' model. Details for investment account holdings Attributes: id (long|int): The id of the investment position description (string): The description of the holding cusip_no (long|int)... | Implement the Python class `CustomerAccountPosition` described below.
Class description:
Implementation of the 'Customer Account Position' model. Details for investment account holdings Attributes: id (long|int): The id of the investment position description (string): The description of the holding cusip_no (long|int)... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class CustomerAccountPosition:
"""Implementation of the 'Customer Account Position' model. Details for investment account holdings Attributes: id (long|int): The id of the investment position description (string): The description of the holding cusip_no (long|int): Cusip number for the investment holdi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerAccountPosition:
"""Implementation of the 'Customer Account Position' model. Details for investment account holdings Attributes: id (long|int): The id of the investment position description (string): The description of the holding cusip_no (long|int): Cusip number for the investment holding symbol (st... | the_stack_v2_python_sparse | finicityapi/models/customer_account_position.py | monarchmoney/finicity-python | train | 0 |
c1a4c4879b7bbd9f9be106559d2e3766c41ba87b | [
"val_arr = [[]]\n\ndef recursive(node):\n if not node:\n return\n val_arr[0] += (node.val,)\n recursive(node.left)\n recursive(node.right)\nrecursive(root)\npre_order = json.dumps(val_arr[0])\nreturn pre_order",
"pre_order = json.loads(data)\n\ndef gen_tree(order):\n length = len(order)\n ... | <|body_start_0|>
val_arr = [[]]
def recursive(node):
if not node:
return
val_arr[0] += (node.val,)
recursive(node.left)
recursive(node.right)
recursive(root)
pre_order = json.dumps(val_arr[0])
return pre_order
<|end... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_030245 | 1,715 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
val_arr = [[]]
def recursive(node):
if not node:
return
val_arr[0] += (node.val,)
recursive(node.left)
recursive(... | the_stack_v2_python_sparse | 449.Serialize-and-Deserialize-BST.py | mickey0524/leetcode | train | 27 | |
f772330b4859c29f7f3f79c72937393715315c84 | [
"nums, result, i = (sorted(nums), [], 0)\nif sum(nums[-3:]) < 0:\n return result\nif len(nums) >= 3 and nums[0] == nums[-1] == 0:\n return [[0, 0, 0]]\nwhile i < len(nums) - 2:\n if i == 0 or nums[i] != nums[i - 1]:\n if sum(nums[i:i + 2]) > 0:\n break\n if sum(nums[-2:]) + nums[i]... | <|body_start_0|>
nums, result, i = (sorted(nums), [], 0)
if sum(nums[-3:]) < 0:
return result
if len(nums) >= 3 and nums[0] == nums[-1] == 0:
return [[0, 0, 0]]
while i < len(nums) - 2:
if i == 0 or nums[i] != nums[i - 1]:
if sum(nums[i... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums, result, i = (sorted... | stack_v2_sparse_classes_36k_train_030246 | 12,477 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution1... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution1:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums, result, i = (sorted(nums), [], 0)
if sum(nums[-3:]) < 0:
return result
if len(nums) >= 3 and nums[0] == nums[-1] == 0:
return [[0, 0, 0]]
while i < len... | the_stack_v2_python_sparse | TwoPointers/q015_three_sum.py | sevenhe716/LeetCode | train | 0 | |
30cc6899eeebca39d6974a9cf1f251b627d138d4 | [
"import main\nmain.moteur_1_la.set(position)\nmoteur_left_arm_1(position)",
"import main\nmain.moteur_2_la.set(position)\nmoteur_left_arm_2(position)",
"import main\nmain.moteur_3_la.set(position)\nmoteur_left_arm_3(position)",
"import main\nmain.moteur_4_la.set(position)\nmoteur_left_arm_4(position)"
] | <|body_start_0|>
import main
main.moteur_1_la.set(position)
moteur_left_arm_1(position)
<|end_body_0|>
<|body_start_1|>
import main
main.moteur_2_la.set(position)
moteur_left_arm_2(position)
<|end_body_1|>
<|body_start_2|>
import main
main.moteur_3_la.se... | left_arm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class left_arm:
def shoulder_x(position: int):
"""position en % du mouvement total"""
<|body_0|>
def shoulder_y(position: int):
"""position en % du mouvement total"""
<|body_1|>
def shoulder_z(position: int):
"""position en % du mouvement total"""
... | stack_v2_sparse_classes_36k_train_030247 | 18,170 | no_license | [
{
"docstring": "position en % du mouvement total",
"name": "shoulder_x",
"signature": "def shoulder_x(position: int)"
},
{
"docstring": "position en % du mouvement total",
"name": "shoulder_y",
"signature": "def shoulder_y(position: int)"
},
{
"docstring": "position en % du mouve... | 4 | stack_v2_sparse_classes_30k_train_015211 | Implement the Python class `left_arm` described below.
Class description:
Implement the left_arm class.
Method signatures and docstrings:
- def shoulder_x(position: int): position en % du mouvement total
- def shoulder_y(position: int): position en % du mouvement total
- def shoulder_z(position: int): position en % d... | Implement the Python class `left_arm` described below.
Class description:
Implement the left_arm class.
Method signatures and docstrings:
- def shoulder_x(position: int): position en % du mouvement total
- def shoulder_y(position: int): position en % du mouvement total
- def shoulder_z(position: int): position en % d... | 68872f2845464b151ab0ddc809cef1d758e4a703 | <|skeleton|>
class left_arm:
def shoulder_x(position: int):
"""position en % du mouvement total"""
<|body_0|>
def shoulder_y(position: int):
"""position en % du mouvement total"""
<|body_1|>
def shoulder_z(position: int):
"""position en % du mouvement total"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class left_arm:
def shoulder_x(position: int):
"""position en % du mouvement total"""
import main
main.moteur_1_la.set(position)
moteur_left_arm_1(position)
def shoulder_y(position: int):
"""position en % du mouvement total"""
import main
main.moteur_2_la... | the_stack_v2_python_sparse | body.py | ppgg88/InMoov_app | train | 1 | |
0fb98998ddaeef5c4bbfdb856d3133c142f8a643 | [
"pk = kwargs.get('pk')\nqapp = Qapp.objects.filter(id=pk).first()\nif check_can_edit(qapp, request.user):\n qapp_approval = QappApproval.objects.filter(qapp_id=pk).first()\n return render(request, self.template_name, {'object': qapp_approval, 'qapp_id': pk, 'form': QappApprovalForm(instance=qapp_approval)})\n... | <|body_start_0|>
pk = kwargs.get('pk')
qapp = Qapp.objects.filter(id=pk).first()
if check_can_edit(qapp, request.user):
qapp_approval = QappApproval.objects.filter(qapp_id=pk).first()
return render(request, self.template_name, {'object': qapp_approval, 'qapp_id': pk, 'for... | View for editing the details of an existing Qapp Approval page. | ProjectApprovalEdit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectApprovalEdit:
"""View for editing the details of an existing Qapp Approval page."""
def get(self, request, *args, **kwargs):
"""GET Project Approval Edit page. Override default get request so we can verify the user has edit privileges, either through super status or team membe... | stack_v2_sparse_classes_36k_train_030248 | 36,787 | no_license | [
{
"docstring": "GET Project Approval Edit page. Override default get request so we can verify the user has edit privileges, either through super status or team membership.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Save the changes to the form.",
... | 2 | null | Implement the Python class `ProjectApprovalEdit` described below.
Class description:
View for editing the details of an existing Qapp Approval page.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): GET Project Approval Edit page. Override default get request so we can verify the user has e... | Implement the Python class `ProjectApprovalEdit` described below.
Class description:
View for editing the details of an existing Qapp Approval page.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): GET Project Approval Edit page. Override default get request so we can verify the user has e... | ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4 | <|skeleton|>
class ProjectApprovalEdit:
"""View for editing the details of an existing Qapp Approval page."""
def get(self, request, *args, **kwargs):
"""GET Project Approval Edit page. Override default get request so we can verify the user has edit privileges, either through super status or team membe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectApprovalEdit:
"""View for editing the details of an existing Qapp Approval page."""
def get(self, request, *args, **kwargs):
"""GET Project Approval Edit page. Override default get request so we can verify the user has edit privileges, either through super status or team membership."""
... | the_stack_v2_python_sparse | DataSearch/qar5/views.py | USEPA/FoodWaste | train | 1 |
d8a06be246e308f5c1ff503bc83a9e40eb19be3b | [
"tdc_Fields_Plotter.__init__(self, (f_e, f_p, f_g))\nself.plot_ylabel = '$n_{e,\\\\gamma}$'\nself.plot_idlabel = 'N_{e,p,g} : ' + self.data[0].calc_id\nif e_density_negative:\n self.e_sign = -1\nelse:\n self.e_sign = 1",
"self.lines[0], = ax.plot(self.data[0].x, self.e_sign * self.data[0].f, 'b', **kwargs)\... | <|body_start_0|>
tdc_Fields_Plotter.__init__(self, (f_e, f_p, f_g))
self.plot_ylabel = '$n_{e,\\gamma}$'
self.plot_idlabel = 'N_{e,p,g} : ' + self.data[0].calc_id
if e_density_negative:
self.e_sign = -1
else:
self.e_sign = 1
<|end_body_0|>
<|body_start_1|... | This class is plotter for (e)lectron, (p)ositron, (g)amma-rays number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label | tdc_EPG_Density_Plotter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tdc_EPG_Density_Plotter:
"""This class is plotter for (e)lectron, (p)ositron, (g)amma-rays number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label"""
def __init__(self, f_e, f_p, f_g, e_density_negative=True):
"""f_e -- field with electr... | stack_v2_sparse_classes_36k_train_030249 | 5,286 | no_license | [
{
"docstring": "f_e -- field with electron number density f_p -- field with positron number density f_g -- field with gamma-ray number density e_density_negative -- <True> if true Electron density is negative",
"name": "__init__",
"signature": "def __init__(self, f_e, f_p, f_g, e_density_negative=True)"... | 3 | null | Implement the Python class `tdc_EPG_Density_Plotter` described below.
Class description:
This class is plotter for (e)lectron, (p)ositron, (g)amma-rays number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label
Method signatures and docstrings:
- def __init__(self, f_e, f_p... | Implement the Python class `tdc_EPG_Density_Plotter` described below.
Class description:
This class is plotter for (e)lectron, (p)ositron, (g)amma-rays number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label
Method signatures and docstrings:
- def __init__(self, f_e, f_p... | 775dc841b1d8538584c8c68a5f75ae997191e685 | <|skeleton|>
class tdc_EPG_Density_Plotter:
"""This class is plotter for (e)lectron, (p)ositron, (g)amma-rays number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label"""
def __init__(self, f_e, f_p, f_g, e_density_negative=True):
"""f_e -- field with electr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class tdc_EPG_Density_Plotter:
"""This class is plotter for (e)lectron, (p)ositron, (g)amma-rays number densities =========== - it implements plot() function fron tdc_Fields_Plotter - sets plot label"""
def __init__(self, f_e, f_p, f_g, e_density_negative=True):
"""f_e -- field with electron number den... | the_stack_v2_python_sparse | Fields/tdc_ep_density_plotter.py | atimokhin/tdc_vis | train | 0 |
1bd825ce613bad884564da9386dde28c53bf75f6 | [
"if model._meta.app_label is 'manejador_contenido':\n return 'contenido'\nreturn None",
"if model._meta.app_label is 'manejador_contenido':\n return 'contenido'\nreturn None",
"if obj1._meta.app_label is 'manejador_contenido' or obj2._meta.app_label is 'manejador_contenido':\n return True\nreturn None"... | <|body_start_0|>
if model._meta.app_label is 'manejador_contenido':
return 'contenido'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label is 'manejador_contenido':
return 'contenido'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._... | ContenidoRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContenidoRouter:
def db_for_read(self, model, **hints):
"""Lee de la base de datos contenido"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Escribe la base de datos contenido"""
<|body_1|>
def allow_relation(self, obj1, obj2, **hints):
... | stack_v2_sparse_classes_36k_train_030250 | 1,007 | no_license | [
{
"docstring": "Lee de la base de datos contenido",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Escribe la base de datos contenido",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_017685 | Implement the Python class `ContenidoRouter` described below.
Class description:
Implement the ContenidoRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Lee de la base de datos contenido
- def db_for_write(self, model, **hints): Escribe la base de datos contenido
- def allow_re... | Implement the Python class `ContenidoRouter` described below.
Class description:
Implement the ContenidoRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Lee de la base de datos contenido
- def db_for_write(self, model, **hints): Escribe la base de datos contenido
- def allow_re... | 42956cf7ffcb121a4e0da9cf8d4e7d1b68820838 | <|skeleton|>
class ContenidoRouter:
def db_for_read(self, model, **hints):
"""Lee de la base de datos contenido"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Escribe la base de datos contenido"""
<|body_1|>
def allow_relation(self, obj1, obj2, **hints):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContenidoRouter:
def db_for_read(self, model, **hints):
"""Lee de la base de datos contenido"""
if model._meta.app_label is 'manejador_contenido':
return 'contenido'
return None
def db_for_write(self, model, **hints):
"""Escribe la base de datos contenido"""
... | the_stack_v2_python_sparse | manejador_estadisticas/manejador_estadisticas/db_routers/contenido_router.py | imsarmiento/ISIS2503-202020-S3-DISCigners | train | 0 | |
801eff9a5b6ec3a64e28bec2504b0a0104b4e3cb | [
"flag = 0\nfor i in range(len(digits) - 1, -1, -1):\n if i == len(digits) - 1:\n flag, mod = divmod(digits[i] + 1 + flag, 10)\n digits[i] = mod\n elif flag == 0:\n return digits\n else:\n flag, mod = divmod(digits[i] + flag, 10)\n digits[i] = mod\nif flag == 1:\n digit... | <|body_start_0|>
flag = 0
for i in range(len(digits) - 1, -1, -1):
if i == len(digits) - 1:
flag, mod = divmod(digits[i] + 1 + flag, 10)
digits[i] = mod
elif flag == 0:
return digits
else:
flag, mod = div... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
"""执行用时 :40 ms, 在所有 Python3 提交中击败了42.83%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.56%的用户 :param digits: :return:"""
<|body_0|>
def plusOne2(self, digits: List[int]) -> List[int]:
"""执行用时 :28 ms, 在所有 Python3 提... | stack_v2_sparse_classes_36k_train_030251 | 2,167 | no_license | [
{
"docstring": "执行用时 :40 ms, 在所有 Python3 提交中击败了42.83%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.56%的用户 :param digits: :return:",
"name": "plusOne",
"signature": "def plusOne(self, digits: List[int]) -> List[int]"
},
{
"docstring": "执行用时 :28 ms, 在所有 Python3 提交中击败了96.08%的用户 内存消耗 :13.5 MB, 在所有 Python3... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits: List[int]) -> List[int]: 执行用时 :40 ms, 在所有 Python3 提交中击败了42.83%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.56%的用户 :param digits: :return:
- def plusOne2(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits: List[int]) -> List[int]: 执行用时 :40 ms, 在所有 Python3 提交中击败了42.83%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.56%的用户 :param digits: :return:
- def plusOne2(self... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
"""执行用时 :40 ms, 在所有 Python3 提交中击败了42.83%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.56%的用户 :param digits: :return:"""
<|body_0|>
def plusOne2(self, digits: List[int]) -> List[int]:
"""执行用时 :28 ms, 在所有 Python3 提... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
"""执行用时 :40 ms, 在所有 Python3 提交中击败了42.83%的用户 内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.56%的用户 :param digits: :return:"""
flag = 0
for i in range(len(digits) - 1, -1, -1):
if i == len(digits) - 1:
flag, mo... | the_stack_v2_python_sparse | LeetCode/数组/66. Plus One.py | yiming1012/MyLeetCode | train | 2 | |
b9c9b20a6b7a08352e47725c61c8b6660f46c9f5 | [
"n = len(Arr)\nwhile j not in visited:\n visited.add(j)\n if Arr[j] * direction < 0:\n direction = Arr[j]\n numSet = set()\n numSet.add(j)\n j = (n + j + Arr[j]) % n\n else:\n numSet.add(j)\n j = (n + j + Arr[j]) % n\n if j in numSet and len(numSet) >= 2:\n ... | <|body_start_0|>
n = len(Arr)
while j not in visited:
visited.add(j)
if Arr[j] * direction < 0:
direction = Arr[j]
numSet = set()
numSet.add(j)
j = (n + j + Arr[j]) % n
else:
numSet.add(j)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkLoop(self, j, Arr, visited, numSet, direction):
"""双指针:以j为起点判断是否可能构成环形数组,direction存储着当前指针的方向,j表示另一个移动指针"""
<|body_0|>
def circularArrayLoop(self, Arr):
"""DFS:深度优先搜索"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(Arr)
... | stack_v2_sparse_classes_36k_train_030252 | 3,223 | no_license | [
{
"docstring": "双指针:以j为起点判断是否可能构成环形数组,direction存储着当前指针的方向,j表示另一个移动指针",
"name": "checkLoop",
"signature": "def checkLoop(self, j, Arr, visited, numSet, direction)"
},
{
"docstring": "DFS:深度优先搜索",
"name": "circularArrayLoop",
"signature": "def circularArrayLoop(self, Arr)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkLoop(self, j, Arr, visited, numSet, direction): 双指针:以j为起点判断是否可能构成环形数组,direction存储着当前指针的方向,j表示另一个移动指针
- def circularArrayLoop(self, Arr): DFS:深度优先搜索 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkLoop(self, j, Arr, visited, numSet, direction): 双指针:以j为起点判断是否可能构成环形数组,direction存储着当前指针的方向,j表示另一个移动指针
- def circularArrayLoop(self, Arr): DFS:深度优先搜索
<|skeleton|>
class S... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def checkLoop(self, j, Arr, visited, numSet, direction):
"""双指针:以j为起点判断是否可能构成环形数组,direction存储着当前指针的方向,j表示另一个移动指针"""
<|body_0|>
def circularArrayLoop(self, Arr):
"""DFS:深度优先搜索"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def checkLoop(self, j, Arr, visited, numSet, direction):
"""双指针:以j为起点判断是否可能构成环形数组,direction存储着当前指针的方向,j表示另一个移动指针"""
n = len(Arr)
while j not in visited:
visited.add(j)
if Arr[j] * direction < 0:
direction = Arr[j]
numSet... | the_stack_v2_python_sparse | leetcode/457、环形数组循环.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
1c9b79e1e15fb5127bd1f7aca347fe299e8307a9 | [
"super(deepSBD, self).__init__()\nself.conv1 = nn.Conv3d(3, 96, kernel_size=3, stride=(1, 2, 2), padding=(0, 0, 0), bias=True)\nself.relu1 = nn.ReLU(inplace=True)\nself.pool1 = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=(1, 2, 2), padding=0)\nself.conv2 = nn.Conv3d(96, 256, kernel_size=3, stride=(1, 2, 2), padding=... | <|body_start_0|>
super(deepSBD, self).__init__()
self.conv1 = nn.Conv3d(3, 96, kernel_size=3, stride=(1, 2, 2), padding=(0, 0, 0), bias=True)
self.relu1 = nn.ReLU(inplace=True)
self.pool1 = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=(1, 2, 2), padding=0)
self.conv2 = nn.Conv3d(96... | This class is represents the pytorch model architecture used for sbd candidate selection. It detects frames ranges of about 16 frames which includes an abrupt cut. The loaded model is pre-trained on the deepsbd dataset. | deepSBD | [
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class deepSBD:
"""This class is represents the pytorch model architecture used for sbd candidate selection. It detects frames ranges of about 16 frames which includes an abrupt cut. The loaded model is pre-trained on the deepsbd dataset."""
def __init__(self):
"""Constructor."""
<|... | stack_v2_sparse_classes_36k_train_030253 | 17,828 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This method is needed to calculate the foward pass of the model. :param x: this parameter must be a valid pytorch tensor. :return: This method returns a pytorch tensor with the specified shape... | 2 | stack_v2_sparse_classes_30k_train_011858 | Implement the Python class `deepSBD` described below.
Class description:
This class is represents the pytorch model architecture used for sbd candidate selection. It detects frames ranges of about 16 frames which includes an abrupt cut. The loaded model is pre-trained on the deepsbd dataset.
Method signatures and doc... | Implement the Python class `deepSBD` described below.
Class description:
This class is represents the pytorch model architecture used for sbd candidate selection. It detects frames ranges of about 16 frames which includes an abrupt cut. The loaded model is pre-trained on the deepsbd dataset.
Method signatures and doc... | f348e3aead7eff4f0a6df5235e53732955b4ff11 | <|skeleton|>
class deepSBD:
"""This class is represents the pytorch model architecture used for sbd candidate selection. It detects frames ranges of about 16 frames which includes an abrupt cut. The loaded model is pre-trained on the deepsbd dataset."""
def __init__(self):
"""Constructor."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class deepSBD:
"""This class is represents the pytorch model architecture used for sbd candidate selection. It detects frames ranges of about 16 frames which includes an abrupt cut. The loaded model is pre-trained on the deepsbd dataset."""
def __init__(self):
"""Constructor."""
super(deepSBD, ... | the_stack_v2_python_sparse | vhh_sbd/DeepSBD.py | dahe-cvl/vhh_sbd | train | 0 |
f3e8aa576d9170280eae5af567f15f8000251926 | [
"self.backup_type = backup_type\nself.copy_partially_successful_run = copy_partially_successful_run\nself.extended_retention_policy_vec = extended_retention_policy_vec\nself.granularity_bucket = granularity_bucket\nself.id = id\nself.num_days_to_keep = num_days_to_keep\nself.retention_policy = retention_policy\nsel... | <|body_start_0|>
self.backup_type = backup_type
self.copy_partially_successful_run = copy_partially_successful_run
self.extended_retention_policy_vec = extended_retention_policy_vec
self.granularity_bucket = granularity_bucket
self.id = id
self.num_days_to_keep = num_days... | Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified target. Attributes: backup_type (int): The backup typ... | SnapshotTargetPolicyProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapshotTargetPolicyProto:
"""Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified ... | stack_v2_sparse_classes_36k_train_030254 | 6,226 | permissive | [
{
"docstring": "Constructor for the SnapshotTargetPolicyProto class",
"name": "__init__",
"signature": "def __init__(self, backup_type=None, copy_partially_successful_run=None, extended_retention_policy_vec=None, granularity_bucket=None, id=None, num_days_to_keep=None, retention_policy=None, snapshot_ta... | 2 | stack_v2_sparse_classes_30k_train_020280 | Implement the Python class `SnapshotTargetPolicyProto` described below.
Class description:
Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after ... | Implement the Python class `SnapshotTargetPolicyProto` described below.
Class description:
Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SnapshotTargetPolicyProto:
"""Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnapshotTargetPolicyProto:
"""Implementation of the 'SnapshotTargetPolicyProto' model. Message that specifies the policy for copying backup snapshots to a target. This message also specifies the retention policy that should be applied to the snapshots after they have been copied to the specified target. Attri... | the_stack_v2_python_sparse | cohesity_management_sdk/models/snapshot_target_policy_proto.py | cohesity/management-sdk-python | train | 24 |
55bf3be67c5506a52b3163c99ad63b48446e3898 | [
"reg = Registration.objects.filter(trips_year=self.trips_year, user=request.user).first()\nif reg:\n return HttpResponseRedirect(reverse('incoming:edit_registration'))\nreturn super().dispatch(request, *args, **kwargs)",
"self.object = form.save(self.request.user)\nself.object.match()\nreturn HttpResponseRedir... | <|body_start_0|>
reg = Registration.objects.filter(trips_year=self.trips_year, user=request.user).first()
if reg:
return HttpResponseRedirect(reverse('incoming:edit_registration'))
return super().dispatch(request, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
self.object ... | Register for trips Redirect to the edit view if this incoming student has already registered. | Register | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Register:
"""Register for trips Redirect to the edit view if this incoming student has already registered."""
def dispatch(self, request, *args, **kwargs):
"""Redirect to edit existing application This is redundantly decorated with login_required to prevent user from being anonymous.... | stack_v2_sparse_classes_36k_train_030255 | 17,349 | no_license | [
{
"docstring": "Redirect to edit existing application This is redundantly decorated with login_required to prevent user from being anonymous. Otherwise this gets called first in the MRO order *then* passed to the LoginRequiredMixin, which doesn't work.",
"name": "dispatch",
"signature": "def dispatch(se... | 2 | stack_v2_sparse_classes_30k_train_003135 | Implement the Python class `Register` described below.
Class description:
Register for trips Redirect to the edit view if this incoming student has already registered.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Redirect to edit existing application This is redundantly decorated ... | Implement the Python class `Register` described below.
Class description:
Register for trips Redirect to the edit view if this incoming student has already registered.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Redirect to edit existing application This is redundantly decorated ... | 59c1ffc0bff1adb4f86f1dcfaa66d8970ff55b72 | <|skeleton|>
class Register:
"""Register for trips Redirect to the edit view if this incoming student has already registered."""
def dispatch(self, request, *args, **kwargs):
"""Redirect to edit existing application This is redundantly decorated with login_required to prevent user from being anonymous.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Register:
"""Register for trips Redirect to the edit view if this incoming student has already registered."""
def dispatch(self, request, *args, **kwargs):
"""Redirect to edit existing application This is redundantly decorated with login_required to prevent user from being anonymous. Otherwise th... | the_stack_v2_python_sparse | fyt/incoming/views.py | rlmv/doc-trips | train | 10 |
95f8d5cdb04db131eec782075bf3a3abf601f4e7 | [
"self.momentum = momentum\nvelocitys = dict()\nfor k, v in model.params.items():\n velocitys[k] = np.zeros_like(v)\nself.velocitys = velocitys",
"momentum = self.momentum\nvelocitys = self.velocitys\nparams = model.params\ngrads = model.grads\nfor k in grads:\n velocitys[k] = momentum * velocitys[k] + learn... | <|body_start_0|>
self.momentum = momentum
velocitys = dict()
for k, v in model.params.items():
velocitys[k] = np.zeros_like(v)
self.velocitys = velocitys
<|end_body_0|>
<|body_start_1|>
momentum = self.momentum
velocitys = self.velocitys
params = mode... | SGDmomentumOptim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SGDmomentumOptim:
def __init__(self, model, momentum=0.5):
"""Inputs: :param model: a neural netowrk class object :param momentum: (float)"""
<|body_0|>
def step(self, model, learning_rate):
"""Implement a one-step SGD+momentum update on network's parameters Inputs: ... | stack_v2_sparse_classes_36k_train_030256 | 9,004 | no_license | [
{
"docstring": "Inputs: :param model: a neural netowrk class object :param momentum: (float)",
"name": "__init__",
"signature": "def __init__(self, model, momentum=0.5)"
},
{
"docstring": "Implement a one-step SGD+momentum update on network's parameters Inputs: :param model: a neural network cla... | 2 | stack_v2_sparse_classes_30k_train_017373 | Implement the Python class `SGDmomentumOptim` described below.
Class description:
Implement the SGDmomentumOptim class.
Method signatures and docstrings:
- def __init__(self, model, momentum=0.5): Inputs: :param model: a neural netowrk class object :param momentum: (float)
- def step(self, model, learning_rate): Impl... | Implement the Python class `SGDmomentumOptim` described below.
Class description:
Implement the SGDmomentumOptim class.
Method signatures and docstrings:
- def __init__(self, model, momentum=0.5): Inputs: :param model: a neural netowrk class object :param momentum: (float)
- def step(self, model, learning_rate): Impl... | a401d09c28432109e9ced10e5011bff97dda05b9 | <|skeleton|>
class SGDmomentumOptim:
def __init__(self, model, momentum=0.5):
"""Inputs: :param model: a neural netowrk class object :param momentum: (float)"""
<|body_0|>
def step(self, model, learning_rate):
"""Implement a one-step SGD+momentum update on network's parameters Inputs: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SGDmomentumOptim:
def __init__(self, model, momentum=0.5):
"""Inputs: :param model: a neural netowrk class object :param momentum: (float)"""
self.momentum = momentum
velocitys = dict()
for k, v in model.params.items():
velocitys[k] = np.zeros_like(v)
self.v... | the_stack_v2_python_sparse | assignment2/E4040.2017.Assign2.xw2501/E4040.2017.Assign2.xw2501/ecbm4040/optimizers.py | xw2501/Deep_Learning_study | train | 7 | |
f78d5077c220c41307ab5955dc51869b353d56f1 | [
"logger.debug('In GET: reqid = %s', reqid)\nrequester = cherrypy.request.verified_user\nwith db_session() as session:\n user_requests = session.query(Requests).filter_by(requester_id=requester.id)\n if reqid is None:\n if requester.admin:\n all_requests = session.query(Requests, Users).join(... | <|body_start_0|>
logger.debug('In GET: reqid = %s', reqid)
requester = cherrypy.request.verified_user
with db_session() as session:
user_requests = session.query(Requests).filter_by(requester_id=requester.id)
if reqid is None:
if requester.admin:
... | RequestsDB Service. Service for checking the requests in the LZProd DB and for returning a given row. | RequestsDBAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestsDBAPI:
"""RequestsDB Service. Service for checking the requests in the LZProd DB and for returning a given row."""
def GET(self, reqid=None):
"""REST Get method."""
<|body_0|>
def POST(self, **kwargs):
"""REST Post method."""
<|body_1|>
def P... | stack_v2_sparse_classes_36k_train_030257 | 6,665 | permissive | [
{
"docstring": "REST Get method.",
"name": "GET",
"signature": "def GET(self, reqid=None)"
},
{
"docstring": "REST Post method.",
"name": "POST",
"signature": "def POST(self, **kwargs)"
},
{
"docstring": "REST Put method.",
"name": "PUT",
"signature": "def PUT(self, reqid... | 4 | stack_v2_sparse_classes_30k_train_003850 | Implement the Python class `RequestsDBAPI` described below.
Class description:
RequestsDB Service. Service for checking the requests in the LZProd DB and for returning a given row.
Method signatures and docstrings:
- def GET(self, reqid=None): REST Get method.
- def POST(self, **kwargs): REST Post method.
- def PUT(s... | Implement the Python class `RequestsDBAPI` described below.
Class description:
RequestsDB Service. Service for checking the requests in the LZProd DB and for returning a given row.
Method signatures and docstrings:
- def GET(self, reqid=None): REST Get method.
- def POST(self, **kwargs): REST Post method.
- def PUT(s... | de5b70ec195a9cd573da9d59807ff959358a5e37 | <|skeleton|>
class RequestsDBAPI:
"""RequestsDB Service. Service for checking the requests in the LZProd DB and for returning a given row."""
def GET(self, reqid=None):
"""REST Get method."""
<|body_0|>
def POST(self, **kwargs):
"""REST Post method."""
<|body_1|>
def P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestsDBAPI:
"""RequestsDB Service. Service for checking the requests in the LZProd DB and for returning a given row."""
def GET(self, reqid=None):
"""REST Get method."""
logger.debug('In GET: reqid = %s', reqid)
requester = cherrypy.request.verified_user
with db_session... | the_stack_v2_python_sparse | lzproduction/webapp/services/RequestsDBAPI.py | alexanderrichards/LZProduction | train | 2 |
cdb908bdbf0bc273437965f9e7fd0014c6233be9 | [
"self.name = name\nself.kernel_regularizer = kernel_regularizer\nself.bias_regularizer = bias_regularizer",
"func_name = 'get_fake_images'\nnetwork = Z\nprint_obj('\\n' + func_name, 'network', network)\nfinal_activation_dict = {'sigmoid': tf.nn.sigmoid, 'relu': tf.nn.relu, 'tanh': tf.nn.tanh}\nwith tf.variable_sc... | <|body_start_0|>
self.name = name
self.kernel_regularizer = kernel_regularizer
self.bias_regularizer = bias_regularizer
<|end_body_0|>
<|body_start_1|>
func_name = 'get_fake_images'
network = Z
print_obj('\n' + func_name, 'network', network)
final_activation_dict... | Generator that takes latent vector input and outputs image. Fields: name: str, name of `Generator`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. | Generator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Generator that takes latent vector input and outputs image. Fields: name: str, name of `Generator`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(se... | stack_v2_sparse_classes_36k_train_030258 | 5,185 | permissive | [
{
"docstring": "Instantiates and builds generator network. Args: kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. name: str, name of generator.",
"name": "__init__",
"signature": "def __init__(... | 3 | null | Implement the Python class `Generator` described below.
Class description:
Generator that takes latent vector input and outputs image. Fields: name: str, name of `Generator`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for ... | Implement the Python class `Generator` described below.
Class description:
Generator that takes latent vector input and outputs image. Fields: name: str, name of `Generator`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for ... | f7c21af221f366b075d351deeeb00a1b266ac3e3 | <|skeleton|>
class Generator:
"""Generator that takes latent vector input and outputs image. Fields: name: str, name of `Generator`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
"""Generator that takes latent vector input and outputs image. Fields: name: str, name of `Generator`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(self, kernel_re... | the_stack_v2_python_sparse | machine_learning/gan/vanilla_gan/tf_vanilla_gan/vanilla_gan_module/trainer/generator.py | ryangillard/artificial_intelligence | train | 4 |
7052fe44b6357995382f45cb0630e135eb4278de | [
"self.index = ref_index\nself.queries = queries\nself.k = k\nself.metrics = {'precision': Precision(), 'rappel': Rappel(), 'fmesure': FMesure(), 'avgp': AvgP(), 'rr': RR(), 'dcg': DCG(), 'ndcg': NDCG()}\nself.split = self.splitQueries()",
"idQueries = list(self.queries.keys())\nnp.random.shuffle(idQueries)\nispli... | <|body_start_0|>
self.index = ref_index
self.queries = queries
self.k = k
self.metrics = {'precision': Precision(), 'rappel': Rappel(), 'fmesure': FMesure(), 'avgp': AvgP(), 'rr': RR(), 'dcg': DCG(), 'ndcg': NDCG()}
self.split = self.splitQueries()
<|end_body_0|>
<|body_start_1|... | Classe permettant de trouver la combinaison de paramètres donnant la meilleure valeur de métrique pour un modèle. * self.queries: dict(int, Query), dictionnaire des requêtes | CrossValidation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossValidation:
"""Classe permettant de trouver la combinaison de paramètres donnant la meilleure valeur de métrique pour un modèle. * self.queries: dict(int, Query), dictionnaire des requêtes"""
def __init__(self, ref_index, queries, k=10):
"""Constructeur de la classe GridSearch."... | stack_v2_sparse_classes_36k_train_030259 | 3,841 | no_license | [
{
"docstring": "Constructeur de la classe GridSearch.",
"name": "__init__",
"signature": "def __init__(self, ref_index, queries, k=10)"
},
{
"docstring": "Partitionne la collection de requêtes en 2 ensembles (train-test). @param k: int, nombre de partitions (k-folds) @return split: list(dict(int... | 4 | stack_v2_sparse_classes_30k_train_007721 | Implement the Python class `CrossValidation` described below.
Class description:
Classe permettant de trouver la combinaison de paramètres donnant la meilleure valeur de métrique pour un modèle. * self.queries: dict(int, Query), dictionnaire des requêtes
Method signatures and docstrings:
- def __init__(self, ref_inde... | Implement the Python class `CrossValidation` described below.
Class description:
Classe permettant de trouver la combinaison de paramètres donnant la meilleure valeur de métrique pour un modèle. * self.queries: dict(int, Query), dictionnaire des requêtes
Method signatures and docstrings:
- def __init__(self, ref_inde... | 210bfc6b78e92fd3cc973ef64d6d91115b4f2c9b | <|skeleton|>
class CrossValidation:
"""Classe permettant de trouver la combinaison de paramètres donnant la meilleure valeur de métrique pour un modèle. * self.queries: dict(int, Query), dictionnaire des requêtes"""
def __init__(self, ref_index, queries, k=10):
"""Constructeur de la classe GridSearch."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossValidation:
"""Classe permettant de trouver la combinaison de paramètres donnant la meilleure valeur de métrique pour un modèle. * self.queries: dict(int, Query), dictionnaire des requêtes"""
def __init__(self, ref_index, queries, k=10):
"""Constructeur de la classe GridSearch."""
se... | the_stack_v2_python_sparse | RI/CrossValidation.py | celina-k/RITAL | train | 1 |
1ccd5f77c154b9eeebc9c7f8f5dac5df03681303 | [
"res = super(ResConfigInherit, self).get_values()\nparams = self.env['ir.config_parameter'].sudo().get_param\nproduct_restriction = params('sale_stock_restrict.product_restriction')\ncheck_stock = params('sale_stock_restrict.check_stock')\nres.update(product_restriction=product_restriction, check_stock=check_stock)... | <|body_start_0|>
res = super(ResConfigInherit, self).get_values()
params = self.env['ir.config_parameter'].sudo().get_param
product_restriction = params('sale_stock_restrict.product_restriction')
check_stock = params('sale_stock_restrict.check_stock')
res.update(product_restricti... | ResConfigInherit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResConfigInherit:
def get_values(self):
"""get values from the fields"""
<|body_0|>
def set_values(self):
"""Set values in the fields"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = super(ResConfigInherit, self).get_values()
params = s... | stack_v2_sparse_classes_36k_train_030260 | 2,286 | no_license | [
{
"docstring": "get values from the fields",
"name": "get_values",
"signature": "def get_values(self)"
},
{
"docstring": "Set values in the fields",
"name": "set_values",
"signature": "def set_values(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018275 | Implement the Python class `ResConfigInherit` described below.
Class description:
Implement the ResConfigInherit class.
Method signatures and docstrings:
- def get_values(self): get values from the fields
- def set_values(self): Set values in the fields | Implement the Python class `ResConfigInherit` described below.
Class description:
Implement the ResConfigInherit class.
Method signatures and docstrings:
- def get_values(self): get values from the fields
- def set_values(self): Set values in the fields
<|skeleton|>
class ResConfigInherit:
def get_values(self):... | 4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14 | <|skeleton|>
class ResConfigInherit:
def get_values(self):
"""get values from the fields"""
<|body_0|>
def set_values(self):
"""Set values in the fields"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResConfigInherit:
def get_values(self):
"""get values from the fields"""
res = super(ResConfigInherit, self).get_values()
params = self.env['ir.config_parameter'].sudo().get_param
product_restriction = params('sale_stock_restrict.product_restriction')
check_stock = para... | the_stack_v2_python_sparse | sale_stock_restrict/models/res_config.py | CybroOdoo/CybroAddons | train | 209 | |
b6c35a8577519638942f88bd0970dd66be54aa7a | [
"result = self.first_name\nif self.last_name is not None:\n result += ' ' + self.last_name\nreturn result",
"if not hasattr(self, '_avatar'):\n avatars = self._api.call('getUserProfilePhotos', {'user_id': self.id, 'limit': 1}, expect=UserProfilePhotos)\n self._avatar = None\n if len(avatars.photos):\n... | <|body_start_0|>
result = self.first_name
if self.last_name is not None:
result += ' ' + self.last_name
return result
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_avatar'):
avatars = self._api.call('getUserProfilePhotos', {'user_id': self.id, 'limit': 1... | Telegram API representation of an user https://core.telegram.org/bots/api#user | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""Telegram API representation of an user https://core.telegram.org/bots/api#user"""
def name(self):
"""Get the full name of the user"""
<|body_0|>
def avatar(self):
"""Get the avatar of the user"""
<|body_1|>
def avatar_history(self):
... | stack_v2_sparse_classes_36k_train_030261 | 17,248 | permissive | [
{
"docstring": "Get the full name of the user",
"name": "name",
"signature": "def name(self)"
},
{
"docstring": "Get the avatar of the user",
"name": "avatar",
"signature": "def avatar(self)"
},
{
"docstring": "Get all the avatars of the user",
"name": "avatar_history",
"... | 3 | stack_v2_sparse_classes_30k_train_000149 | Implement the Python class `User` described below.
Class description:
Telegram API representation of an user https://core.telegram.org/bots/api#user
Method signatures and docstrings:
- def name(self): Get the full name of the user
- def avatar(self): Get the avatar of the user
- def avatar_history(self): Get all the ... | Implement the Python class `User` described below.
Class description:
Telegram API representation of an user https://core.telegram.org/bots/api#user
Method signatures and docstrings:
- def name(self): Get the full name of the user
- def avatar(self): Get the avatar of the user
- def avatar_history(self): Get all the ... | 7daafc09cb8bbc27517e1febc5a6ca5a01cbc655 | <|skeleton|>
class User:
"""Telegram API representation of an user https://core.telegram.org/bots/api#user"""
def name(self):
"""Get the full name of the user"""
<|body_0|>
def avatar(self):
"""Get the avatar of the user"""
<|body_1|>
def avatar_history(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""Telegram API representation of an user https://core.telegram.org/bots/api#user"""
def name(self):
"""Get the full name of the user"""
result = self.first_name
if self.last_name is not None:
result += ' ' + self.last_name
return result
def avatar(s... | the_stack_v2_python_sparse | botogram/objects/chats.py | Ensenasty/botogram | train | 0 |
205748b941dfe8bdaa322345a11ceb5aa0b242b0 | [
"super().__init__(parent=parent)\nself.setTitle('XGM spectrum')\nself.setLabel('left', 'I0 (arb.)')\nself.setLabel('right', 'Count')\nself.setLabel('bottom', 'Energy (eV)')\nself._plot = self.plotScatter(brush=FColor.mkBrush('w'))\nself._count = self.plotBar(y2=True, brush=FColor.mkBrush('i', alpha=70))",
"stats,... | <|body_start_0|>
super().__init__(parent=parent)
self.setTitle('XGM spectrum')
self.setLabel('left', 'I0 (arb.)')
self.setLabel('right', 'Count')
self.setLabel('bottom', 'Energy (eV)')
self._plot = self.plotScatter(brush=FColor.mkBrush('w'))
self._count = self.plo... | XasTimXgmSpectrumPlot class. Visualize spectrum of I0 (XGM). | XasTimXgmSpectrumPlot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XasTimXgmSpectrumPlot:
"""XasTimXgmSpectrumPlot class. Visualize spectrum of I0 (XGM)."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def refresh(self):
"""Override."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(... | stack_v2_sparse_classes_36k_train_030262 | 13,999 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, *, parent=None)"
},
{
"docstring": "Override.",
"name": "refresh",
"signature": "def refresh(self)"
}
] | 2 | null | Implement the Python class `XasTimXgmSpectrumPlot` described below.
Class description:
XasTimXgmSpectrumPlot class. Visualize spectrum of I0 (XGM).
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def refresh(self): Override. | Implement the Python class `XasTimXgmSpectrumPlot` described below.
Class description:
XasTimXgmSpectrumPlot class. Visualize spectrum of I0 (XGM).
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def refresh(self): Override.
<|skeleton|>
class XasTimXgmSpectrumPlot:
"""X... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class XasTimXgmSpectrumPlot:
"""XasTimXgmSpectrumPlot class. Visualize spectrum of I0 (XGM)."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def refresh(self):
"""Override."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XasTimXgmSpectrumPlot:
"""XasTimXgmSpectrumPlot class. Visualize spectrum of I0 (XGM)."""
def __init__(self, *, parent=None):
"""Initialization."""
super().__init__(parent=parent)
self.setTitle('XGM spectrum')
self.setLabel('left', 'I0 (arb.)')
self.setLabel('right... | the_stack_v2_python_sparse | extra_foam/special_suite/xas_tim_w.py | European-XFEL/EXtra-foam | train | 8 |
9e5d077377c52228230fdf0b82f80448dc343b9b | [
"processed_dict = {}\nfor key, value in request.GET.items():\n processed_dict[key] = value\nsign = processed_dict.pop('sign', None)\nalipay = AliPay(appid=settings.ALIPAY_APP_ID, app_notify_url=settings.ALIPAY_APP_NOTIFY_URL, app_private_key_path=settings.ALIPAY_PRI_KEY_PATH, alipay_public_key_path=settings.ALIP... | <|body_start_0|>
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid=settings.ALIPAY_APP_ID, app_notify_url=settings.ALIPAY_APP_NOTIFY_URL, app_private_key_path=settings.ALIPAY_PR... | AlipayView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlipayView:
def get(self, request):
"""处理支付宝的 return_url 返回 :param request: :return:"""
<|body_0|>
def post(self, request):
"""处理支付宝的 notify_url :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
processed_dict = {}
for... | stack_v2_sparse_classes_36k_train_030263 | 8,287 | no_license | [
{
"docstring": "处理支付宝的 return_url 返回 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "处理支付宝的 notify_url :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011398 | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request): 处理支付宝的 return_url 返回 :param request: :return:
- def post(self, request): 处理支付宝的 notify_url :param request: :return: | Implement the Python class `AlipayView` described below.
Class description:
Implement the AlipayView class.
Method signatures and docstrings:
- def get(self, request): 处理支付宝的 return_url 返回 :param request: :return:
- def post(self, request): 处理支付宝的 notify_url :param request: :return:
<|skeleton|>
class AlipayView:
... | d77c00082e54a4d4bf3f4cfdf14581fb78dafeb6 | <|skeleton|>
class AlipayView:
def get(self, request):
"""处理支付宝的 return_url 返回 :param request: :return:"""
<|body_0|>
def post(self, request):
"""处理支付宝的 notify_url :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlipayView:
def get(self, request):
"""处理支付宝的 return_url 返回 :param request: :return:"""
processed_dict = {}
for key, value in request.GET.items():
processed_dict[key] = value
sign = processed_dict.pop('sign', None)
alipay = AliPay(appid=settings.ALIPAY_APP_I... | the_stack_v2_python_sparse | apps/trade/views.py | luoshanya/mxshop | train | 0 | |
e73680494b296e5ea6b7ce88b70562e7757b772f | [
"self._client = _utils.make_client(context)\nself._filter_string = filter_string\nself._descriptors = None",
"if self._descriptors is None:\n self._descriptors = self._client.list_resource_descriptors(filter_string=self._filter_string)\nreturn [resource for resource in self._descriptors if fnmatch.fnmatch(reso... | <|body_start_0|>
self._client = _utils.make_client(context)
self._filter_string = filter_string
self._descriptors = None
<|end_body_0|>
<|body_start_1|>
if self._descriptors is None:
self._descriptors = self._client.list_resource_descriptors(filter_string=self._filter_string... | ResourceDescriptors object for retrieving the resource descriptors. | ResourceDescriptors | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceDescriptors:
"""ResourceDescriptors object for retrieving the resource descriptors."""
def __init__(self, filter_string=None, context=None):
"""Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing th... | stack_v2_sparse_classes_36k_train_030264 | 2,837 | permissive | [
{
"docstring": "Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing the resource descriptors to be returned. context: An optional Context object to use instead of the global default.",
"name": "__init__",
"signature": "def __i... | 3 | stack_v2_sparse_classes_30k_train_009869 | Implement the Python class `ResourceDescriptors` described below.
Class description:
ResourceDescriptors object for retrieving the resource descriptors.
Method signatures and docstrings:
- def __init__(self, filter_string=None, context=None): Initializes the ResourceDescriptors based on the specified filters. Args: f... | Implement the Python class `ResourceDescriptors` described below.
Class description:
ResourceDescriptors object for retrieving the resource descriptors.
Method signatures and docstrings:
- def __init__(self, filter_string=None, context=None): Initializes the ResourceDescriptors based on the specified filters. Args: f... | 8bf007da3e43096aa3a3dca158fc56b286ba6f5c | <|skeleton|>
class ResourceDescriptors:
"""ResourceDescriptors object for retrieving the resource descriptors."""
def __init__(self, filter_string=None, context=None):
"""Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceDescriptors:
"""ResourceDescriptors object for retrieving the resource descriptors."""
def __init__(self, filter_string=None, context=None):
"""Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing the resource de... | the_stack_v2_python_sparse | google/datalab/stackdriver/monitoring/_resource.py | googledatalab/pydatalab | train | 200 |
45032a1c1b69910dcbbce3de9912c217ea8571e5 | [
"self.__exticon = dict()\nself.__exticon['.WAV'] = 'Audio'\nself.__exticon['.WAVE'] = 'Audio'\nfor ext in sppasRW.TRANSCRIPTION_SOFTWARE:\n software = sppasRW.TRANSCRIPTION_SOFTWARE[ext]\n if ext.startswith('.') is False:\n ext = '.' + ext\n self.__exticon[ext.upper()] = software",
"if ext.startsw... | <|body_start_0|>
self.__exticon = dict()
self.__exticon['.WAV'] = 'Audio'
self.__exticon['.WAVE'] = 'Audio'
for ext in sppasRW.TRANSCRIPTION_SOFTWARE:
software = sppasRW.TRANSCRIPTION_SOFTWARE[ext]
if ext.startswith('.') is False:
ext = '.' + ext
... | Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats of 'anndata' are linked to an icon file. | FileAnnotIcon | [
"GPL-3.0-only",
"GFDL-1.1-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileAnnotIcon:
"""Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats ... | stack_v2_sparse_classes_36k_train_030265 | 28,145 | permissive | [
{
"docstring": "Constructor of a FileAnnotIcon. Set the name of the icon for all known extensions of annotations. Create a dictionary linking a file extension to the name of the software it comes from. It is supposed this name is matching an an icon in PNG format.",
"name": "__init__",
"signature": "def... | 2 | null | Implement the Python class `FileAnnotIcon` described below.
Class description:
Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Br... | Implement the Python class `FileAnnotIcon` described below.
Class description:
Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Br... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class FileAnnotIcon:
"""Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileAnnotIcon:
"""Represents the link between a file extension and an icon name. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: contact@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi All supported file formats of 'anndata' ... | the_stack_v2_python_sparse | sppas/sppas/src/ui/phoenix/page_files/filesviewmodel.py | mirfan899/MTTS | train | 0 |
15e7688a3d649d704e3c1b87b7684c8c692ab325 | [
"try:\n driver = ContactElement(self.driver)\n driver.get(self.url)\n driver.contact_click()\n driver.full_windows_screen(self.screenshots_path, 1920, 980)\n self.first = driver.is_url_contain(url=self.data[0])\n self.is_asserts = True\nexcept Exception as exc:\n self.error = str(exc)",
"try:... | <|body_start_0|>
try:
driver = ContactElement(self.driver)
driver.get(self.url)
driver.contact_click()
driver.full_windows_screen(self.screenshots_path, 1920, 980)
self.first = driver.is_url_contain(url=self.data[0])
self.is_asserts = True
... | :param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法 | TestContact | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestContact:
""":param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法"""
def test_contact(self):
"""验证首页顶部CONTACT是否能正常跳转; 1、打开home; 2、点击顶部导航栏Contact; 3、断言跳转... | stack_v2_sparse_classes_36k_train_030266 | 3,171 | no_license | [
{
"docstring": "验证首页顶部CONTACT是否能正常跳转; 1、打开home; 2、点击顶部导航栏Contact; 3、断言跳转的url是否包含{/nav/24.html}",
"name": "test_contact",
"signature": "def test_contact(self)"
},
{
"docstring": "验证首页顶部CONTACT US是否能正常跳转; 1、打开Contact; 2、点击导航栏Contact us; 3、断言跳转的url是否包含{/intro/13.html}",
"name": "test_ContactUs"... | 3 | null | Implement the Python class `TestContact` described below.
Class description:
:param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法
Method signatures and docstrings:
- def test_contact(self):... | Implement the Python class `TestContact` described below.
Class description:
:param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法
Method signatures and docstrings:
- def test_contact(self):... | 86bb051e62abdf2ed5bbdbea4c9008a6c1f49060 | <|skeleton|>
class TestContact:
""":param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法"""
def test_contact(self):
"""验证首页顶部CONTACT是否能正常跳转; 1、打开home; 2、点击顶部导航栏Contact; 3、断言跳转... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestContact:
""":param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法"""
def test_contact(self):
"""验证首页顶部CONTACT是否能正常跳转; 1、打开home; 2、点击顶部导航栏Contact; 3、断言跳转的url是否包含{/nav... | the_stack_v2_python_sparse | Manufacture/contact/contact_st.py | yushu1987/UI | train | 0 |
8269c1ce29e78769d11083c2d0e86a680e9228ea | [
"super(DiscreteTransition, self).__init__(transition_id, label, firing_condition, consumption_speeds, production_speeds)\nself.delay = delay\nself.delay_counter = 0",
"input_place_tokens = self.get_input_place_tokens()\nif self.firing_condition(input_place_tokens) == True:\n if self.delay_counter == int(self.d... | <|body_start_0|>
super(DiscreteTransition, self).__init__(transition_id, label, firing_condition, consumption_speeds, production_speeds)
self.delay = delay
self.delay_counter = 0
<|end_body_0|>
<|body_start_1|>
input_place_tokens = self.get_input_place_tokens()
if self.firing_co... | DiscreteTransition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteTransition:
def __init__(self, transition_id, label, firing_condition, consumption_speeds, production_speeds, delay):
"""In addition to the arguments specified in the super class ContinuousTransition, a delay function must be specified for a discrete transition. Args: delay (int)... | stack_v2_sparse_classes_36k_train_030267 | 32,459 | permissive | [
{
"docstring": "In addition to the arguments specified in the super class ContinuousTransition, a delay function must be specified for a discrete transition. Args: delay (int): number of time-steps after which transition is fired if firing_condition still holds true.",
"name": "__init__",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_020551 | Implement the Python class `DiscreteTransition` described below.
Class description:
Implement the DiscreteTransition class.
Method signatures and docstrings:
- def __init__(self, transition_id, label, firing_condition, consumption_speeds, production_speeds, delay): In addition to the arguments specified in the super ... | Implement the Python class `DiscreteTransition` described below.
Class description:
Implement the DiscreteTransition class.
Method signatures and docstrings:
- def __init__(self, transition_id, label, firing_condition, consumption_speeds, production_speeds, delay): In addition to the arguments specified in the super ... | 8e9a3a8151069757475808c48511c9d7486ea334 | <|skeleton|>
class DiscreteTransition:
def __init__(self, transition_id, label, firing_condition, consumption_speeds, production_speeds, delay):
"""In addition to the arguments specified in the super class ContinuousTransition, a delay function must be specified for a discrete transition. Args: delay (int)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscreteTransition:
def __init__(self, transition_id, label, firing_condition, consumption_speeds, production_speeds, delay):
"""In addition to the arguments specified in the super class ContinuousTransition, a delay function must be specified for a discrete transition. Args: delay (int): number of ti... | the_stack_v2_python_sparse | HFPN model/utils/hfpn.py | PN-Alzheimers-Parkinsons/PN_Alzheimers_Parkinsons | train | 0 | |
ee3dfb1da1c999d470ab7730833414a009999f1d | [
"s_free = (depsf * (m + 1.0) * sV0 ** m / (2.0 * pi * r ** 2.0)) ** (1.0 / (m + 1.0))\nxi_free = s_free * (-np.log(1.0 - Pf)) ** (1.0 / (m + 1))\ns_fixed = (depsf * sV0 ** m / (2.0 * pi * r ** 2.0)) ** (1.0 / (m + 1.0))\nxi_fixed = s_fixed * (-np.log(1.0 - Pf)) ** (1.0 / (m + 1))\nreturn (xi_free, xi_fixed)",
"T ... | <|body_start_0|>
s_free = (depsf * (m + 1.0) * sV0 ** m / (2.0 * pi * r ** 2.0)) ** (1.0 / (m + 1.0))
xi_free = s_free * (-np.log(1.0 - Pf)) ** (1.0 / (m + 1))
s_fixed = (depsf * sV0 ** m / (2.0 * pi * r ** 2.0)) ** (1.0 / (m + 1.0))
xi_fixed = s_fixed * (-np.log(1.0 - Pf)) ** (1.0 / (m ... | Crack bridged by a fiber with constant frictional interface to rigid; free fiber end; | CBClamped | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBClamped:
"""Crack bridged by a fiber with constant frictional interface to rigid; free fiber end;"""
def e_broken(self, Pf, depsf, r, m, sV0, mask):
"""weibull_fibers_cdf_mc"""
<|body_0|>
def __call__(self, w, tau, E_f, V_f, r, m, sV0, lm, Pf):
"""free and fixe... | stack_v2_sparse_classes_36k_train_030268 | 4,458 | no_license | [
{
"docstring": "weibull_fibers_cdf_mc",
"name": "e_broken",
"signature": "def e_broken(self, Pf, depsf, r, m, sV0, mask)"
},
{
"docstring": "free and fixed fibers combined",
"name": "__call__",
"signature": "def __call__(self, w, tau, E_f, V_f, r, m, sV0, lm, Pf)"
},
{
"docstring... | 3 | null | Implement the Python class `CBClamped` described below.
Class description:
Crack bridged by a fiber with constant frictional interface to rigid; free fiber end;
Method signatures and docstrings:
- def e_broken(self, Pf, depsf, r, m, sV0, mask): weibull_fibers_cdf_mc
- def __call__(self, w, tau, E_f, V_f, r, m, sV0, l... | Implement the Python class `CBClamped` described below.
Class description:
Crack bridged by a fiber with constant frictional interface to rigid; free fiber end;
Method signatures and docstrings:
- def e_broken(self, Pf, depsf, r, m, sV0, mask): weibull_fibers_cdf_mc
- def __call__(self, w, tau, E_f, V_f, r, m, sV0, l... | acb2a8eb8b6caa57c1e9e15f724a2b43843c7b10 | <|skeleton|>
class CBClamped:
"""Crack bridged by a fiber with constant frictional interface to rigid; free fiber end;"""
def e_broken(self, Pf, depsf, r, m, sV0, mask):
"""weibull_fibers_cdf_mc"""
<|body_0|>
def __call__(self, w, tau, E_f, V_f, r, m, sV0, lm, Pf):
"""free and fixe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CBClamped:
"""Crack bridged by a fiber with constant frictional interface to rigid; free fiber end;"""
def e_broken(self, Pf, depsf, r, m, sV0, mask):
"""weibull_fibers_cdf_mc"""
s_free = (depsf * (m + 1.0) * sV0 ** m / (2.0 * pi * r ** 2.0)) ** (1.0 / (m + 1.0))
xi_free = s_free ... | the_stack_v2_python_sparse | quaducom/quaducom/micro/resp_func/CB_clamped.py | simvisage/simvisage | train | 0 |
94db26c0e6f1494dce6502b2df02607a9b711fc9 | [
"assert isinstance(calls, Iterable), 'Invalid calls %s' % calls\nself._calls = list(calls)\nassert self._calls, 'At least one call is required for processing'\nif __debug__:\n for call in self._calls:\n assert callable(call), 'Invalid call %s' % call\nself.ctx = Processing.Ctx()\nif contexts:\n assert ... | <|body_start_0|>
assert isinstance(calls, Iterable), 'Invalid calls %s' % calls
self._calls = list(calls)
assert self._calls, 'At least one call is required for processing'
if __debug__:
for call in self._calls:
assert callable(call), 'Invalid call %s' % call
... | Container for processor's, provides chains for their execution. !!! Attention, never ever use a processing in multiple threads, only one thread is allowed to execute a processing at one time. | Processing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Processing:
"""Container for processor's, provides chains for their execution. !!! Attention, never ever use a processing in multiple threads, only one thread is allowed to execute a processing at one time."""
def __init__(self, calls, contexts=None):
"""Construct the processing. @pa... | stack_v2_sparse_classes_36k_train_030269 | 21,295 | no_license | [
{
"docstring": "Construct the processing. @param calls: Iterable(callable) The iterable of calls that consists this processing. @param contexts: dictionary{string, ContextMetaClass}|None The initial contexts to be associated.",
"name": "__init__",
"signature": "def __init__(self, calls, contexts=None)"
... | 4 | null | Implement the Python class `Processing` described below.
Class description:
Container for processor's, provides chains for their execution. !!! Attention, never ever use a processing in multiple threads, only one thread is allowed to execute a processing at one time.
Method signatures and docstrings:
- def __init__(s... | Implement the Python class `Processing` described below.
Class description:
Container for processor's, provides chains for their execution. !!! Attention, never ever use a processing in multiple threads, only one thread is allowed to execute a processing at one time.
Method signatures and docstrings:
- def __init__(s... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class Processing:
"""Container for processor's, provides chains for their execution. !!! Attention, never ever use a processing in multiple threads, only one thread is allowed to execute a processing at one time."""
def __init__(self, calls, contexts=None):
"""Construct the processing. @pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Processing:
"""Container for processor's, provides chains for their execution. !!! Attention, never ever use a processing in multiple threads, only one thread is allowed to execute a processing at one time."""
def __init__(self, calls, contexts=None):
"""Construct the processing. @param calls: It... | the_stack_v2_python_sparse | components/ally/ally/design/processor/execution.py | cristidomsa/Ally-Py | train | 0 |
8d3c118a12c611f0920fa78ba72e8a550b9d02db | [
"cls.logger.debug('In GET: reqid = %r', request_id)\nif request_id is not None:\n with cherrypy.HTTPError.handle(ValueError, 400, 'Bad request_id: %r' % request_id):\n request_id = int(request_id)\nrequester = cherrypy.request.verified_user\nuser_id = requester.id\nif requester.admin:\n user_id = None\... | <|body_start_0|>
cls.logger.debug('In GET: reqid = %r', request_id)
if request_id is not None:
with cherrypy.HTTPError.handle(ValueError, 400, 'Bad request_id: %r' % request_id):
request_id = int(request_id)
requester = cherrypy.request.verified_user
user_id =... | Requests RESTful API. | RequestsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestsAPI:
"""Requests RESTful API."""
def GET(cls, request_id=None):
"""REST Get method."""
<|body_0|>
def DELETE(cls, request_id):
"""REST Delete method."""
<|body_1|>
def POST(cls):
"""REST Post method."""
<|body_2|>
def PUT... | stack_v2_sparse_classes_36k_train_030270 | 14,924 | permissive | [
{
"docstring": "REST Get method.",
"name": "GET",
"signature": "def GET(cls, request_id=None)"
},
{
"docstring": "REST Delete method.",
"name": "DELETE",
"signature": "def DELETE(cls, request_id)"
},
{
"docstring": "REST Post method.",
"name": "POST",
"signature": "def PO... | 4 | stack_v2_sparse_classes_30k_train_016380 | Implement the Python class `RequestsAPI` described below.
Class description:
Requests RESTful API.
Method signatures and docstrings:
- def GET(cls, request_id=None): REST Get method.
- def DELETE(cls, request_id): REST Delete method.
- def POST(cls): REST Post method.
- def PUT(cls, request_id, status): REST Put meth... | Implement the Python class `RequestsAPI` described below.
Class description:
Requests RESTful API.
Method signatures and docstrings:
- def GET(cls, request_id=None): REST Get method.
- def DELETE(cls, request_id): REST Delete method.
- def POST(cls): REST Post method.
- def PUT(cls, request_id, status): REST Put meth... | 43225a155a985a7a56402df23dd550e48e22b436 | <|skeleton|>
class RequestsAPI:
"""Requests RESTful API."""
def GET(cls, request_id=None):
"""REST Get method."""
<|body_0|>
def DELETE(cls, request_id):
"""REST Delete method."""
<|body_1|>
def POST(cls):
"""REST Post method."""
<|body_2|>
def PUT... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestsAPI:
"""Requests RESTful API."""
def GET(cls, request_id=None):
"""REST Get method."""
cls.logger.debug('In GET: reqid = %r', request_id)
if request_id is not None:
with cherrypy.HTTPError.handle(ValueError, 400, 'Bad request_id: %r' % request_id):
... | the_stack_v2_python_sparse | productionsystem/webapp/services/RESTfulAPI.py | alexanderrichards/ProductionSystem | train | 0 |
79fb3f0b20296bccdf26c0d15ea85e20af0fe998 | [
"super().__init__()\nself.sizes = sizes\ngroups = create_groupings(sizes)\nself.nn0, total = create_embedding_layers(groups=groups, sizes=sizes, dropout=dropout[0], norm=MODEL_NORM)\nif META in sizes['x']:\n hidden = HIDDEN_LARGE\nelif 'offer1' in sizes['x']:\n hidden = HIDDEN_SMALL\nelse:\n hidden = HIDDE... | <|body_start_0|>
super().__init__()
self.sizes = sizes
groups = create_groupings(sizes)
self.nn0, total = create_embedding_layers(groups=groups, sizes=sizes, dropout=dropout[0], norm=MODEL_NORM)
if META in sizes['x']:
hidden = HIDDEN_LARGE
elif 'offer1' in siz... | FeedForward | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedForward:
def __init__(self, sizes, dropout=(0.0, 0.0)):
""":param sizes: dictionary of scalar input sizes; sizes['x'] is an OrderedDict :param tuple dropout: pair of dropout rates."""
<|body_0|>
def forward(self, x):
"""x: OrderedDict()"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_030271 | 1,675 | permissive | [
{
"docstring": ":param sizes: dictionary of scalar input sizes; sizes['x'] is an OrderedDict :param tuple dropout: pair of dropout rates.",
"name": "__init__",
"signature": "def __init__(self, sizes, dropout=(0.0, 0.0))"
},
{
"docstring": "x: OrderedDict()",
"name": "forward",
"signature... | 2 | null | Implement the Python class `FeedForward` described below.
Class description:
Implement the FeedForward class.
Method signatures and docstrings:
- def __init__(self, sizes, dropout=(0.0, 0.0)): :param sizes: dictionary of scalar input sizes; sizes['x'] is an OrderedDict :param tuple dropout: pair of dropout rates.
- d... | Implement the Python class `FeedForward` described below.
Class description:
Implement the FeedForward class.
Method signatures and docstrings:
- def __init__(self, sizes, dropout=(0.0, 0.0)): :param sizes: dictionary of scalar input sizes; sizes['x'] is an OrderedDict :param tuple dropout: pair of dropout rates.
- d... | b40e9b147186ca04efd384d05b0f5e27ff8bd71a | <|skeleton|>
class FeedForward:
def __init__(self, sizes, dropout=(0.0, 0.0)):
""":param sizes: dictionary of scalar input sizes; sizes['x'] is an OrderedDict :param tuple dropout: pair of dropout rates."""
<|body_0|>
def forward(self, x):
"""x: OrderedDict()"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedForward:
def __init__(self, sizes, dropout=(0.0, 0.0)):
""":param sizes: dictionary of scalar input sizes; sizes['x'] is an OrderedDict :param tuple dropout: pair of dropout rates."""
super().__init__()
self.sizes = sizes
groups = create_groupings(sizes)
self.nn0, t... | the_stack_v2_python_sparse | nets/FeedForward.py | yuwei-cheng/eBay | train | 0 | |
6a666f5804ac00505ab358797d6e3182fd57620a | [
"tp = _QuadraticPlusSinProblem1D()\nquery_points, _, train_points, train_values = tp.get_problem(extrapolate=False, dtype='float64')\ninterpolation_order = 1\nwith ops.name_scope('interpolator'):\n interpolator = interpolate_spline.interpolate_spline(train_points, train_values, query_points, interpolation_order)... | <|body_start_0|>
tp = _QuadraticPlusSinProblem1D()
query_points, _, train_points, train_values = tp.get_problem(extrapolate=False, dtype='float64')
interpolation_order = 1
with ops.name_scope('interpolator'):
interpolator = interpolate_spline.interpolate_spline(train_points, ... | InterpolateSplineTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolateSplineTest:
def test_1d_linear_interpolation(self):
"""For 1d linear interpolation, we can compare directly to scipy."""
<|body_0|>
def test_1d_interpolation(self):
"""Regression test for interpolation with 1-D points."""
<|body_1|>
def test_n... | stack_v2_sparse_classes_36k_train_030272 | 10,269 | permissive | [
{
"docstring": "For 1d linear interpolation, we can compare directly to scipy.",
"name": "test_1d_linear_interpolation",
"signature": "def test_1d_linear_interpolation(self)"
},
{
"docstring": "Regression test for interpolation with 1-D points.",
"name": "test_1d_interpolation",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_005898 | Implement the Python class `InterpolateSplineTest` described below.
Class description:
Implement the InterpolateSplineTest class.
Method signatures and docstrings:
- def test_1d_linear_interpolation(self): For 1d linear interpolation, we can compare directly to scipy.
- def test_1d_interpolation(self): Regression tes... | Implement the Python class `InterpolateSplineTest` described below.
Class description:
Implement the InterpolateSplineTest class.
Method signatures and docstrings:
- def test_1d_linear_interpolation(self): For 1d linear interpolation, we can compare directly to scipy.
- def test_1d_interpolation(self): Regression tes... | 181bc2b37aa8a3eeb11a942d8f330b04abc804b3 | <|skeleton|>
class InterpolateSplineTest:
def test_1d_linear_interpolation(self):
"""For 1d linear interpolation, we can compare directly to scipy."""
<|body_0|>
def test_1d_interpolation(self):
"""Regression test for interpolation with 1-D points."""
<|body_1|>
def test_n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterpolateSplineTest:
def test_1d_linear_interpolation(self):
"""For 1d linear interpolation, we can compare directly to scipy."""
tp = _QuadraticPlusSinProblem1D()
query_points, _, train_points, train_values = tp.get_problem(extrapolate=False, dtype='float64')
interpolation_o... | the_stack_v2_python_sparse | tensorflow/contrib/image/python/kernel_tests/interpolate_spline_test.py | zylo117/tensorflow-gpu-macosx | train | 116 | |
532eafccbe97f5e7d7ea95e5bed5b0db32561816 | [
"from datasource import DataSource\nself.corot = DataSource(database='wifsip', user='sro', host='pina.aip.de')\nif type(param) is str:\n try:\n values = self._byname(param)[0]\n except IndexError:\n values = [None, None, None, None, None, None, None, None, None, None]\nif type(param) is tuple:\n... | <|body_start_0|>
from datasource import DataSource
self.corot = DataSource(database='wifsip', user='sro', host='pina.aip.de')
if type(param) is str:
try:
values = self._byname(param)[0]
except IndexError:
values = [None, None, None, None, N... | Class to inference the PPMXL table in the wifsip database on pina | Ppmxl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ppmxl:
"""Class to inference the PPMXL table in the wifsip database on pina"""
def __init__(self, param):
"""Constructor: initialize the database and query it according the parameter, if a string is given, then we assume, it is the name, if it is a tuple, then we take them as coordin... | stack_v2_sparse_classes_36k_train_030273 | 2,163 | no_license | [
{
"docstring": "Constructor: initialize the database and query it according the parameter, if a string is given, then we assume, it is the name, if it is a tuple, then we take them as coordinates",
"name": "__init__",
"signature": "def __init__(self, param)"
},
{
"docstring": "query the table by... | 3 | stack_v2_sparse_classes_30k_train_019538 | Implement the Python class `Ppmxl` described below.
Class description:
Class to inference the PPMXL table in the wifsip database on pina
Method signatures and docstrings:
- def __init__(self, param): Constructor: initialize the database and query it according the parameter, if a string is given, then we assume, it is... | Implement the Python class `Ppmxl` described below.
Class description:
Class to inference the PPMXL table in the wifsip database on pina
Method signatures and docstrings:
- def __init__(self, param): Constructor: initialize the database and query it according the parameter, if a string is given, then we assume, it is... | c2df6b5de8e94c3935768a8fb40b4f046c21afb4 | <|skeleton|>
class Ppmxl:
"""Class to inference the PPMXL table in the wifsip database on pina"""
def __init__(self, param):
"""Constructor: initialize the database and query it according the parameter, if a string is given, then we assume, it is the name, if it is a tuple, then we take them as coordin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ppmxl:
"""Class to inference the PPMXL table in the wifsip database on pina"""
def __init__(self, param):
"""Constructor: initialize the database and query it according the parameter, if a string is given, then we assume, it is the name, if it is a tuple, then we take them as coordinates"""
... | the_stack_v2_python_sparse | src/ppmxl.py | weingrill/SOCS | train | 0 |
26b210209b29dc797696bde6730d17bf5cd76a3b | [
"self.head = head\nself.size = 0\nwhile head:\n self.size += 1\n head = head.next",
"k = random.randrange(self.size)\ni = 0\nhead = self.head\nwhile i < k:\n head = head.next\n i += 1\nreturn head.val"
] | <|body_start_0|>
self.head = head
self.size = 0
while head:
self.size += 1
head = head.next
<|end_body_0|>
<|body_start_1|>
k = random.randrange(self.size)
i = 0
head = self.head
while i < k:
head = head.next
i += 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_030274 | 1,057 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.",
"name": "__init__",
"signature": "def __init__(self, head: ListNode)"
},
{
"docstring": "Returns a random node's value.",
"name": "getRandom",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_001232 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | 4f5f5124534bd4423356a5f5572b8a39b7828d80 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
self.head = head
self.size = 0
while head:
self.size += 1
head = head.next
def... | the_stack_v2_python_sparse | leetcode/linked-list-random-node/285257658.py | ausaki/data_structures_and_algorithms | train | 1 | |
4ee497b7f98bcf0a485b67feca2c4de1e5c8f359 | [
"self.insurance_policy_id = insurance_policy_id\nself.travel_duration_param = travel_duration_param\nself.passengers_count = passengers_count\nself.birth_date = birth_date\nself.birth_date_persian = birth_date_persian\nself.risk_level_discount = risk_level_discount\nself.base_premium = base_premium\nself.all_premiu... | <|body_start_0|>
self.insurance_policy_id = insurance_policy_id
self.travel_duration_param = travel_duration_param
self.passengers_count = passengers_count
self.birth_date = birth_date
self.birth_date_persian = birth_date_persian
self.risk_level_discount = risk_level_disc... | Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type description here. birth_date (string): TODO: type description ... | TravelInsurancePolicyExtend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TravelInsurancePolicyExtend:
"""Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type descrip... | stack_v2_sparse_classes_36k_train_030275 | 7,484 | permissive | [
{
"docstring": "Constructor for the TravelInsurancePolicyExtend class",
"name": "__init__",
"signature": "def __init__(self, insurance_policy_id=None, passengers_count=None, risk_level_discount=None, insurance_company_discount_rate=None, insurance_company_discount=None, insurance_centre_discount=None, c... | 2 | stack_v2_sparse_classes_30k_val_000975 | Implement the Python class `TravelInsurancePolicyExtend` described below.
Class description:
Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. pas... | Implement the Python class `TravelInsurancePolicyExtend` described below.
Class description:
Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. pas... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class TravelInsurancePolicyExtend:
"""Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type descrip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TravelInsurancePolicyExtend:
"""Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type description here. bi... | the_stack_v2_python_sparse | easybimehlanding/models/travel_insurance_policy_extend.py | kmelodi/EasyBimehLanding_Python | train | 0 |
8702a664fee7703c48db3aef5d829cd76fe8286f | [
"settings.addListsToRepository('skeinforge_tools.craft_plugins.lash.html', '', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Lash', self, '')\nself.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://www.bits... | <|body_start_0|>
settings.addListsToRepository('skeinforge_tools.craft_plugins.lash.html', '', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Lash', self, '')
self.openWikiManualHelpPage = settings.HelpPage().ge... | A class to handle the lash settings. | LashRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LashRepository:
"""A class to handle the lash settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Lash button has been clicked."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_030276 | 6,957 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Lash button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020006 | Implement the Python class `LashRepository` described below.
Class description:
A class to handle the lash settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Lash button has been clicked. | Implement the Python class `LashRepository` described below.
Class description:
A class to handle the lash settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Lash button has been clicked.
<|skeleton|>
class LashRepositor... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class LashRepository:
"""A class to handle the lash settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Lash button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LashRepository:
"""A class to handle the lash settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
settings.addListsToRepository('skeinforge_tools.craft_plugins.lash.html', '', self)
self.fileNameInput = settings.FileNameInput().getFr... | the_stack_v2_python_sparse | skeinforge_tools/craft_plugins/lash.py | bmander/skeinforge | train | 34 |
e98bf4021da2121edeb570d5d2dcbe43b5e391b5 | [
"can_activate, username = self._can_activate(data=data)\nif not can_activate or username is None:\n return\nlogger.info('\\t\\tRunning...')\nh_result: Dict = self.__get_gh_data(config=config, username=username)\nif 'github' not in data:\n data['github'] = {}\ndata['github'][username] = h_result\nif h_result['... | <|body_start_0|>
can_activate, username = self._can_activate(data=data)
if not can_activate or username is None:
return
logger.info('\t\tRunning...')
h_result: Dict = self.__get_gh_data(config=config, username=username)
if 'github' not in data:
data['githu... | Github Username Data Digger. | GithubUsernameDataDigger | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GithubUsernameDataDigger:
"""Github Username Data Digger."""
def run(self, config: ConfigParser, args: Dict, data: Dict) -> None:
"""Execute Module."""
<|body_0|>
def __get_gh_data(self, config: ConfigParser, username: str) -> Dict:
"""Download and Get GitHub Dat... | stack_v2_sparse_classes_36k_train_030277 | 8,676 | permissive | [
{
"docstring": "Execute Module.",
"name": "run",
"signature": "def run(self, config: ConfigParser, args: Dict, data: Dict) -> None"
},
{
"docstring": "Download and Get GitHub Data.",
"name": "__get_gh_data",
"signature": "def __get_gh_data(self, config: ConfigParser, username: str) -> Di... | 5 | stack_v2_sparse_classes_30k_train_005719 | Implement the Python class `GithubUsernameDataDigger` described below.
Class description:
Github Username Data Digger.
Method signatures and docstrings:
- def run(self, config: ConfigParser, args: Dict, data: Dict) -> None: Execute Module.
- def __get_gh_data(self, config: ConfigParser, username: str) -> Dict: Downlo... | Implement the Python class `GithubUsernameDataDigger` described below.
Class description:
Github Username Data Digger.
Method signatures and docstrings:
- def run(self, config: ConfigParser, args: Dict, data: Dict) -> None: Execute Module.
- def __get_gh_data(self, config: ConfigParser, username: str) -> Dict: Downlo... | 058714c1870bde0d794452b32ad0e62d544bdd90 | <|skeleton|>
class GithubUsernameDataDigger:
"""Github Username Data Digger."""
def run(self, config: ConfigParser, args: Dict, data: Dict) -> None:
"""Execute Module."""
<|body_0|>
def __get_gh_data(self, config: ConfigParser, username: str) -> Dict:
"""Download and Get GitHub Dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GithubUsernameDataDigger:
"""Github Username Data Digger."""
def run(self, config: ConfigParser, args: Dict, data: Dict) -> None:
"""Execute Module."""
can_activate, username = self._can_activate(data=data)
if not can_activate or username is None:
return
logger... | the_stack_v2_python_sparse | OSIx/modules/github_username_data_digger.py | guibacellar/OSIx | train | 2 |
1182abcc50f3e0c034cad51d33895663f1148fb0 | [
"self.app_data = {}\nfor pkg_index in app_dict:\n result = defaultdict(int)\n keywords = ','.join(app_dict[pkg_index][:2])\n for age, words_list in age_tags.items():\n for word in words_list:\n if keywords.find(word) >= 0:\n result[age] += 1\n break\n if l... | <|body_start_0|>
self.app_data = {}
for pkg_index in app_dict:
result = defaultdict(int)
keywords = ','.join(app_dict[pkg_index][:2])
for age, words_list in age_tags.items():
for word in words_list:
if keywords.find(word) >= 0:
... | 年龄预测 | AgePredict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgePredict:
"""年龄预测"""
def __init__(self, age_tags, app_dict):
"""初始化 :param age_tags: {"16-19": [], ....... ">45": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}"""
<|body_0|>
def check_user(self, user_pkg_index_list):
"""检查一个用户的年龄 :retur... | stack_v2_sparse_classes_36k_train_030278 | 1,918 | no_license | [
{
"docstring": "初始化 :param age_tags: {\"16-19\": [], ....... \">45\": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}",
"name": "__init__",
"signature": "def __init__(self, age_tags, app_dict)"
},
{
"docstring": "检查一个用户的年龄 :return result: {age: \"16-19\", rate: 1.0}",
... | 2 | stack_v2_sparse_classes_30k_train_007839 | Implement the Python class `AgePredict` described below.
Class description:
年龄预测
Method signatures and docstrings:
- def __init__(self, age_tags, app_dict): 初始化 :param age_tags: {"16-19": [], ....... ">45": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}
- def check_user(self, user_pkg_index_li... | Implement the Python class `AgePredict` described below.
Class description:
年龄预测
Method signatures and docstrings:
- def __init__(self, age_tags, app_dict): 初始化 :param age_tags: {"16-19": [], ....... ">45": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}
- def check_user(self, user_pkg_index_li... | 2693b1262a15b66365ec6f1ffc3b6673a9d9760d | <|skeleton|>
class AgePredict:
"""年龄预测"""
def __init__(self, age_tags, app_dict):
"""初始化 :param age_tags: {"16-19": [], ....... ">45": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}"""
<|body_0|>
def check_user(self, user_pkg_index_list):
"""检查一个用户的年龄 :retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgePredict:
"""年龄预测"""
def __init__(self, age_tags, app_dict):
"""初始化 :param age_tags: {"16-19": [], ....... ">45": []} :param app_dict: {pkg_index: [app_name, app_tags, word, ...], ...}"""
self.app_data = {}
for pkg_index in app_dict:
result = defaultdict(int)
... | the_stack_v2_python_sparse | predict/predict_age.py | walleleung/DemoGraphy | train | 0 |
c6190809a6a1b826e35fece80e89d6b72d38b44a | [
"self.app = app\nself.client_prefix = client_prefix\nself.repo_prefix = repo_prefix\nself.pb = PubSub(self.app, self.client_prefix)",
"file = File()\nfile.file_name = file_name\nfile.desired_copies = desired_copies\nfile.packets = packets\nfile.size = size\nfetch_path = FetchPath()\nfetch_path.prefix = fetch_pref... | <|body_start_0|>
self.app = app
self.client_prefix = client_prefix
self.repo_prefix = repo_prefix
self.pb = PubSub(self.app, self.client_prefix)
<|end_body_0|>
<|body_start_1|>
file = File()
file.file_name = file_name
file.desired_copies = desired_copies
... | InsertClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsertClient:
def __init__(self, app: NDNApp, client_prefix: FormalName, repo_prefix: FormalName):
"""This client inserts data packets from the remote repo. :param app: NDNApp. :param repo_name: NonStrictName. Routable name to remote repo."""
<|body_0|>
async def insert_file... | stack_v2_sparse_classes_36k_train_030279 | 2,215 | permissive | [
{
"docstring": "This client inserts data packets from the remote repo. :param app: NDNApp. :param repo_name: NonStrictName. Routable name to remote repo.",
"name": "__init__",
"signature": "def __init__(self, app: NDNApp, client_prefix: FormalName, repo_prefix: FormalName)"
},
{
"docstring": "In... | 2 | stack_v2_sparse_classes_30k_train_013501 | Implement the Python class `InsertClient` described below.
Class description:
Implement the InsertClient class.
Method signatures and docstrings:
- def __init__(self, app: NDNApp, client_prefix: FormalName, repo_prefix: FormalName): This client inserts data packets from the remote repo. :param app: NDNApp. :param rep... | Implement the Python class `InsertClient` described below.
Class description:
Implement the InsertClient class.
Method signatures and docstrings:
- def __init__(self, app: NDNApp, client_prefix: FormalName, repo_prefix: FormalName): This client inserts data packets from the remote repo. :param app: NDNApp. :param rep... | 4377074833a3515666a5ddeaaba15f4972e5d812 | <|skeleton|>
class InsertClient:
def __init__(self, app: NDNApp, client_prefix: FormalName, repo_prefix: FormalName):
"""This client inserts data packets from the remote repo. :param app: NDNApp. :param repo_name: NonStrictName. Routable name to remote repo."""
<|body_0|>
async def insert_file... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsertClient:
def __init__(self, app: NDNApp, client_prefix: FormalName, repo_prefix: FormalName):
"""This client inserts data packets from the remote repo. :param app: NDNApp. :param repo_name: NonStrictName. Routable name to remote repo."""
self.app = app
self.client_prefix = client_... | the_stack_v2_python_sparse | client/insert.py | daniel-achee/ndn-distributed-repo | train | 1 | |
d9e65f2deae8aa58a79aa81f6582ca953949d7e2 | [
"os.makedirs(os.path.dirname(cls.path_token), exist_ok=True)\nwith open(cls.path_token, 'w+') as f:\n f.write(token)",
"try:\n with open(cls.path_token, 'r') as f:\n return f.read()\nexcept FileNotFoundError:\n pass",
"try:\n os.remove(cls.path_token)\nexcept FileNotFoundError:\n pass"
] | <|body_start_0|>
os.makedirs(os.path.dirname(cls.path_token), exist_ok=True)
with open(cls.path_token, 'w+') as f:
f.write(token)
<|end_body_0|>
<|body_start_1|>
try:
with open(cls.path_token, 'r') as f:
return f.read()
except FileNotFoundError:
... | HfFolder | [
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HfFolder:
def save_token(cls, token):
"""Save token, creating folder as needed."""
<|body_0|>
def get_token(cls):
"""Get token or None if not existent."""
<|body_1|>
def delete_token(cls):
"""Delete token. Do not fail if token does not exist."""
... | stack_v2_sparse_classes_36k_train_030280 | 5,878 | permissive | [
{
"docstring": "Save token, creating folder as needed.",
"name": "save_token",
"signature": "def save_token(cls, token)"
},
{
"docstring": "Get token or None if not existent.",
"name": "get_token",
"signature": "def get_token(cls)"
},
{
"docstring": "Delete token. Do not fail if ... | 3 | stack_v2_sparse_classes_30k_train_014759 | Implement the Python class `HfFolder` described below.
Class description:
Implement the HfFolder class.
Method signatures and docstrings:
- def save_token(cls, token): Save token, creating folder as needed.
- def get_token(cls): Get token or None if not existent.
- def delete_token(cls): Delete token. Do not fail if ... | Implement the Python class `HfFolder` described below.
Class description:
Implement the HfFolder class.
Method signatures and docstrings:
- def save_token(cls, token): Save token, creating folder as needed.
- def get_token(cls): Get token or None if not existent.
- def delete_token(cls): Delete token. Do not fail if ... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class HfFolder:
def save_token(cls, token):
"""Save token, creating folder as needed."""
<|body_0|>
def get_token(cls):
"""Get token or None if not existent."""
<|body_1|>
def delete_token(cls):
"""Delete token. Do not fail if token does not exist."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HfFolder:
def save_token(cls, token):
"""Save token, creating folder as needed."""
os.makedirs(os.path.dirname(cls.path_token), exist_ok=True)
with open(cls.path_token, 'w+') as f:
f.write(token)
def get_token(cls):
"""Get token or None if not existent."""
... | the_stack_v2_python_sparse | xtune/src/transformers/hf_api.py | microsoft/unilm | train | 15,313 | |
8af38bc258b027642cf1db7d75621e7c25c195eb | [
"self.model = KNeighborsClassifier(n_neighbors=3)\nself.X = X\nself.Y = Y",
"if params is None:\n params = [{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20], 'weights': ['uniform', 'distance']}]\nself.CV = KFoldCrossVal(self.X, self.Y, folds=kfold)\nself.CV.tune_and_evaluate(self.model, parameters=param... | <|body_start_0|>
self.model = KNeighborsClassifier(n_neighbors=3)
self.X = X
self.Y = Y
<|end_body_0|>
<|body_start_1|>
if params is None:
params = [{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20], 'weights': ['uniform', 'distance']}]
self.CV = KFoldCrossVal(... | K-nearest neighbor classifier | KNN | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNN:
"""K-nearest neighbor classifier"""
def __init__(self, X, Y):
""":param X: :param Y:"""
<|body_0|>
def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10):
""":param results_file: :param params: :param njobs: :param kfold: :return:"""
... | stack_v2_sparse_classes_36k_train_030281 | 10,404 | permissive | [
{
"docstring": ":param X: :param Y:",
"name": "__init__",
"signature": "def __init__(self, X, Y)"
},
{
"docstring": ":param results_file: :param params: :param njobs: :param kfold: :return:",
"name": "tune_and_eval",
"signature": "def tune_and_eval(self, results_file, params=None, njobs=... | 3 | stack_v2_sparse_classes_30k_train_017140 | Implement the Python class `KNN` described below.
Class description:
K-nearest neighbor classifier
Method signatures and docstrings:
- def __init__(self, X, Y): :param X: :param Y:
- def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10): :param results_file: :param params: :param njobs: :param kfold:... | Implement the Python class `KNN` described below.
Class description:
K-nearest neighbor classifier
Method signatures and docstrings:
- def __init__(self, X, Y): :param X: :param Y:
- def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10): :param results_file: :param params: :param njobs: :param kfold:... | 127177deb630ad66520a2fdae1793417cd77ee99 | <|skeleton|>
class KNN:
"""K-nearest neighbor classifier"""
def __init__(self, X, Y):
""":param X: :param Y:"""
<|body_0|>
def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10):
""":param results_file: :param params: :param njobs: :param kfold: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KNN:
"""K-nearest neighbor classifier"""
def __init__(self, X, Y):
""":param X: :param Y:"""
self.model = KNeighborsClassifier(n_neighbors=3)
self.X = X
self.Y = Y
def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10):
""":param results_file: ... | the_stack_v2_python_sparse | classifier/classical_classifiers.py | seedpcseed/DiTaxa | train | 0 |
8d9f8115f73f107c3518ba43e252a79208fee7a8 | [
"super(AbstractBlockFileIO, self).__init__(**args)\nself.token = token\nself.wise_opener = self.get_opener()",
"with self.wise_opener(input_file, 'r') as fh:\n for head, body, start, next in self.gen_block_sequences(self.token, fh):\n self.data.append((head, body, start, next))",
"with self.wise_opene... | <|body_start_0|>
super(AbstractBlockFileIO, self).__init__(**args)
self.token = token
self.wise_opener = self.get_opener()
<|end_body_0|>
<|body_start_1|>
with self.wise_opener(input_file, 'r') as fh:
for head, body, start, next in self.gen_block_sequences(self.token, fh):
... | Working with file with data organized in block, where each block starts with same token. Public methods: - get_block_sequence(self, head_start, next_head, fh) - get_blocks(self, token, fh) - gen_block_sequences(self, token, fh) Inherited public properties: - data - iterable data, each item is tuple (head, body) - N - a... | AbstractBlockFileIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractBlockFileIO:
"""Working with file with data organized in block, where each block starts with same token. Public methods: - get_block_sequence(self, head_start, next_head, fh) - get_blocks(self, token, fh) - gen_block_sequences(self, token, fh) Inherited public properties: - data - iterabl... | stack_v2_sparse_classes_36k_train_030282 | 5,074 | permissive | [
{
"docstring": "Overrided. Set token velue.",
"name": "__init__",
"signature": "def __init__(self, token, **args)"
},
{
"docstring": "Overrided. Read data from given input_file.",
"name": "read_from_file",
"signature": "def read_from_file(self, input_file)"
},
{
"docstring": "Ove... | 6 | stack_v2_sparse_classes_30k_train_008878 | Implement the Python class `AbstractBlockFileIO` described below.
Class description:
Working with file with data organized in block, where each block starts with same token. Public methods: - get_block_sequence(self, head_start, next_head, fh) - get_blocks(self, token, fh) - gen_block_sequences(self, token, fh) Inheri... | Implement the Python class `AbstractBlockFileIO` described below.
Class description:
Working with file with data organized in block, where each block starts with same token. Public methods: - get_block_sequence(self, head_start, next_head, fh) - get_blocks(self, token, fh) - gen_block_sequences(self, token, fh) Inheri... | 8c0a186e32d61189f073401152c52a89bfed46ed | <|skeleton|>
class AbstractBlockFileIO:
"""Working with file with data organized in block, where each block starts with same token. Public methods: - get_block_sequence(self, head_start, next_head, fh) - get_blocks(self, token, fh) - gen_block_sequences(self, token, fh) Inherited public properties: - data - iterabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractBlockFileIO:
"""Working with file with data organized in block, where each block starts with same token. Public methods: - get_block_sequence(self, head_start, next_head, fh) - get_blocks(self, token, fh) - gen_block_sequences(self, token, fh) Inherited public properties: - data - iterable data, each ... | the_stack_v2_python_sparse | trseeker/seqio/block_file.py | ad3002/Lyrebird | train | 1 |
1db78f74b1a8f786c670ec15a504b466ec5f2571 | [
"self.number_resources = parameters.number_resources\nself.t = parameters.t\nself.r = parameters.r\nself.small_jobs_probability = 0.8\nself.big_jobs_probability = 1 - self.small_jobs_probability\nself.big_jobs_lower_time_limit = 10 * self.t\nself.big_jobs_upper_time_limit = 15 * self.t\nself.small_jobs_lower_time_l... | <|body_start_0|>
self.number_resources = parameters.number_resources
self.t = parameters.t
self.r = parameters.r
self.small_jobs_probability = 0.8
self.big_jobs_probability = 1 - self.small_jobs_probability
self.big_jobs_lower_time_limit = 10 * self.t
self.big_job... | DataGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataGenerator:
def __init__(self, parameters):
"""Initializes the parameters of the data generator"""
<|body_0|>
def generate_job(self):
"""Generates a single job with the initialized parameters."""
<|body_1|>
def generate_sequence(self, debug=False):
... | stack_v2_sparse_classes_36k_train_030283 | 3,132 | no_license | [
{
"docstring": "Initializes the parameters of the data generator",
"name": "__init__",
"signature": "def __init__(self, parameters)"
},
{
"docstring": "Generates a single job with the initialized parameters.",
"name": "generate_job",
"signature": "def generate_job(self)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_020965 | Implement the Python class `DataGenerator` described below.
Class description:
Implement the DataGenerator class.
Method signatures and docstrings:
- def __init__(self, parameters): Initializes the parameters of the data generator
- def generate_job(self): Generates a single job with the initialized parameters.
- def... | Implement the Python class `DataGenerator` described below.
Class description:
Implement the DataGenerator class.
Method signatures and docstrings:
- def __init__(self, parameters): Initializes the parameters of the data generator
- def generate_job(self): Generates a single job with the initialized parameters.
- def... | 21162545b95f6222539ccdf1dfdc03e2f3aac9f6 | <|skeleton|>
class DataGenerator:
def __init__(self, parameters):
"""Initializes the parameters of the data generator"""
<|body_0|>
def generate_job(self):
"""Generates a single job with the initialized parameters."""
<|body_1|>
def generate_sequence(self, debug=False):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataGenerator:
def __init__(self, parameters):
"""Initializes the parameters of the data generator"""
self.number_resources = parameters.number_resources
self.t = parameters.t
self.r = parameters.r
self.small_jobs_probability = 0.8
self.big_jobs_probability = 1 ... | the_stack_v2_python_sparse | data_generator.py | angelbeshirov/resource-management | train | 8 | |
3647ca005d614a7fcc09565bc38ff0b4ae188c0f | [
"User = get_user_model()\ntry:\n return User.objects.get(pk=user_id)\nexcept User.DoesNotExist:\n return None",
"try:\n data = Signer().unsign(token)\nexcept BadSignature:\n return\ndata = json.loads(base64.b64decode(data).decode('utf8'))\nif data['t'] < time.time() - settings.AUTH_TOKEN_DURATION:\n ... | <|body_start_0|>
User = get_user_model()
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
try:
data = Signer().unsign(token)
except BadSignature:
return
data = j... | EmailTokenBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailTokenBackend:
def get_user(self, user_id):
"""Get a user by their email address."""
<|body_0|>
def authenticate(self, token=None):
"""Authenticate a user given a signed token."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
User = get_user_mode... | stack_v2_sparse_classes_36k_train_030284 | 923 | no_license | [
{
"docstring": "Get a user by their email address.",
"name": "get_user",
"signature": "def get_user(self, user_id)"
},
{
"docstring": "Authenticate a user given a signed token.",
"name": "authenticate",
"signature": "def authenticate(self, token=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004688 | Implement the Python class `EmailTokenBackend` described below.
Class description:
Implement the EmailTokenBackend class.
Method signatures and docstrings:
- def get_user(self, user_id): Get a user by their email address.
- def authenticate(self, token=None): Authenticate a user given a signed token. | Implement the Python class `EmailTokenBackend` described below.
Class description:
Implement the EmailTokenBackend class.
Method signatures and docstrings:
- def get_user(self, user_id): Get a user by their email address.
- def authenticate(self, token=None): Authenticate a user given a signed token.
<|skeleton|>
cl... | a75a4251a3dd14a9a8a61867ded2ec39a0ae997f | <|skeleton|>
class EmailTokenBackend:
def get_user(self, user_id):
"""Get a user by their email address."""
<|body_0|>
def authenticate(self, token=None):
"""Authenticate a user given a signed token."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailTokenBackend:
def get_user(self, user_id):
"""Get a user by their email address."""
User = get_user_model()
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def authenticate(self, token=None):
"""Authentica... | the_stack_v2_python_sparse | main/auth_backends.py | sirodoht/avocado-jobs | train | 1 | |
43bc742e88650eb5c8cbe3c29336985cf2a8c8c7 | [
"super(FarChamferDist, self).__init__()\nself.num_add = num_add\nself.far_dist = FarthestDist()\nself.chamfer_dist = ChamferDist(method=chamfer_method)\nself.cd_w = chamfer_weight",
"B = adv_pc.shape[0]\nchamfer_loss = self.chamfer_dist(adv_pc, ori_pc, weights=weights, batch_avg=batch_avg)\nadv_clusters = adv_pc.... | <|body_start_0|>
super(FarChamferDist, self).__init__()
self.num_add = num_add
self.far_dist = FarthestDist()
self.chamfer_dist = ChamferDist(method=chamfer_method)
self.cd_w = chamfer_weight
<|end_body_0|>
<|body_start_1|>
B = adv_pc.shape[0]
chamfer_loss = self... | FarChamferDist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FarChamferDist:
def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.1):
"""Distance function used in generating adv clusters. Consisting of a Farthest dist and a chamfer dist. Args: num_add (int): number of added clusters. chamfer_method (str, optional): chamfer. Defau... | stack_v2_sparse_classes_36k_train_030285 | 11,583 | permissive | [
{
"docstring": "Distance function used in generating adv clusters. Consisting of a Farthest dist and a chamfer dist. Args: num_add (int): number of added clusters. chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. chamfer_weight (float, optional): weight factor. Defaults to 0.1.",
"name": "__i... | 2 | stack_v2_sparse_classes_30k_train_006755 | Implement the Python class `FarChamferDist` described below.
Class description:
Implement the FarChamferDist class.
Method signatures and docstrings:
- def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.1): Distance function used in generating adv clusters. Consisting of a Farthest dist and a cham... | Implement the Python class `FarChamferDist` described below.
Class description:
Implement the FarChamferDist class.
Method signatures and docstrings:
- def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.1): Distance function used in generating adv clusters. Consisting of a Farthest dist and a cham... | 4e2462b66fa1eac90cfbf61fa0dc635d223fdf2f | <|skeleton|>
class FarChamferDist:
def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.1):
"""Distance function used in generating adv clusters. Consisting of a Farthest dist and a chamfer dist. Args: num_add (int): number of added clusters. chamfer_method (str, optional): chamfer. Defau... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FarChamferDist:
def __init__(self, num_add, chamfer_method='adv2ori', chamfer_weight=0.1):
"""Distance function used in generating adv clusters. Consisting of a Farthest dist and a chamfer dist. Args: num_add (int): number of added clusters. chamfer_method (str, optional): chamfer. Defaults to 'adv2or... | the_stack_v2_python_sparse | baselines/attack/util/dist_utils.py | code-roamer/IF-Defense | train | 0 | |
0165a4237cbe7017e0aa4f13135bb3cda7dfabd0 | [
"result = {}\nfor name, field in cls.fields.items():\n representation = field.api_representation()\n if not representation['config']['editable']:\n continue\n result[name] = representation\nreturn result",
"instance = cls()\ninstance.validated_data = {}\nfor key, field in cls.fields.items():\n ... | <|body_start_0|>
result = {}
for name, field in cls.fields.items():
representation = field.api_representation()
if not representation['config']['editable']:
continue
result[name] = representation
return result
<|end_body_0|>
<|body_start_1|>
... | BaseConfigurator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseConfigurator:
def get_fields_representation(cls) -> DictFields:
"""Return fields config without values."""
<|body_0|>
def parse(cls, data: DictFields):
"""Parse API data."""
<|body_1|>
def exclude(self, key: str, equal=True):
"""Mutate `.vali... | stack_v2_sparse_classes_36k_train_030286 | 1,432 | no_license | [
{
"docstring": "Return fields config without values.",
"name": "get_fields_representation",
"signature": "def get_fields_representation(cls) -> DictFields"
},
{
"docstring": "Parse API data.",
"name": "parse",
"signature": "def parse(cls, data: DictFields)"
},
{
"docstring": "Mut... | 3 | stack_v2_sparse_classes_30k_train_004158 | Implement the Python class `BaseConfigurator` described below.
Class description:
Implement the BaseConfigurator class.
Method signatures and docstrings:
- def get_fields_representation(cls) -> DictFields: Return fields config without values.
- def parse(cls, data: DictFields): Parse API data.
- def exclude(self, key... | Implement the Python class `BaseConfigurator` described below.
Class description:
Implement the BaseConfigurator class.
Method signatures and docstrings:
- def get_fields_representation(cls) -> DictFields: Return fields config without values.
- def parse(cls, data: DictFields): Parse API data.
- def exclude(self, key... | 82a2537c2ae841edec591a36c3f76da97f99701b | <|skeleton|>
class BaseConfigurator:
def get_fields_representation(cls) -> DictFields:
"""Return fields config without values."""
<|body_0|>
def parse(cls, data: DictFields):
"""Parse API data."""
<|body_1|>
def exclude(self, key: str, equal=True):
"""Mutate `.vali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseConfigurator:
def get_fields_representation(cls) -> DictFields:
"""Return fields config without values."""
result = {}
for name, field in cls.fields.items():
representation = field.api_representation()
if not representation['config']['editable']:
... | the_stack_v2_python_sparse | servers/helpers/configurator/base.py | donkey-engine/donkey-engine | train | 7 | |
1f58eac5a11cc19335da627c6e79501c9d54d021 | [
"self.local_redis = RedisWrapper(host_name=AthenaConfig.redis_host_local, port=AthenaConfig.redis_port, db=AthenaConfig.hermes_db_index)\nself.remote_redis = RedisWrapper(host_name=AthenaConfig.redis_host_remote_1, port=AthenaConfig.redis_port, db=AthenaConfig.hermes_db_index)\nself.sub = self.remote_redis.connecti... | <|body_start_0|>
self.local_redis = RedisWrapper(host_name=AthenaConfig.redis_host_local, port=AthenaConfig.redis_port, db=AthenaConfig.hermes_db_index)
self.remote_redis = RedisWrapper(host_name=AthenaConfig.redis_host_remote_1, port=AthenaConfig.redis_port, db=AthenaConfig.hermes_db_index)
sel... | HermesPipe class acts as a pipeline between local redis server and remote redis server (deployed on the PC to store historical data) It simply pipes hermes data to that PC. | HermesPipe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HermesPipe:
"""HermesPipe class acts as a pipeline between local redis server and remote redis server (deployed on the PC to store historical data) It simply pipes hermes data to that PC."""
def __init__(self):
""":return:"""
<|body_0|>
def add_instrument(self, instrumen... | stack_v2_sparse_classes_36k_train_030287 | 3,532 | no_license | [
{
"docstring": ":return:",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Begin to listen to one single instrument. :param instrument: string :param kline_dur_specifiers: tuple of strings. Default is ('1m'), subscribe 1 minute kline only. :return:",
"name": "add_ins... | 3 | stack_v2_sparse_classes_30k_val_000998 | Implement the Python class `HermesPipe` described below.
Class description:
HermesPipe class acts as a pipeline between local redis server and remote redis server (deployed on the PC to store historical data) It simply pipes hermes data to that PC.
Method signatures and docstrings:
- def __init__(self): :return:
- de... | Implement the Python class `HermesPipe` described below.
Class description:
HermesPipe class acts as a pipeline between local redis server and remote redis server (deployed on the PC to store historical data) It simply pipes hermes data to that PC.
Method signatures and docstrings:
- def __init__(self): :return:
- de... | dd191a9830ecfa7a8bef646854bbce3c7b7c07bf | <|skeleton|>
class HermesPipe:
"""HermesPipe class acts as a pipeline between local redis server and remote redis server (deployed on the PC to store historical data) It simply pipes hermes data to that PC."""
def __init__(self):
""":return:"""
<|body_0|>
def add_instrument(self, instrumen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HermesPipe:
"""HermesPipe class acts as a pipeline between local redis server and remote redis server (deployed on the PC to store historical data) It simply pipes hermes data to that PC."""
def __init__(self):
""":return:"""
self.local_redis = RedisWrapper(host_name=AthenaConfig.redis_ho... | the_stack_v2_python_sparse | data_handler/data_pipe.py | wenhangz/Athena | train | 0 |
e346410063ec8c9d423e2c6b30be8162f842040f | [
"try:\n payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])\nexcept jwt.ExpiredSignatureError:\n raise serializers.ValidationError('Verification link has expired')\nexcept jwt.PyJWTError:\n raise serializers.ValidationError('Invalid token')\nif payload['type'] != 'email_confirmation':\n ... | <|body_start_0|>
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.ValidationError('Verification link has expired')
except jwt.PyJWTError:
raise serializers.ValidationError('Invalid t... | Acount verification serializer. | AccountVerificationSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountVerificationSerializer:
"""Acount verification serializer."""
def validate_token(self, data):
"""Verifiy token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_030288 | 30,238 | no_license | [
{
"docstring": "Verifiy token is valid.",
"name": "validate_token",
"signature": "def validate_token(self, data)"
},
{
"docstring": "Update user's verified status.",
"name": "save",
"signature": "def save(self)"
}
] | 2 | null | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Acount verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verifiy token is valid.
- def save(self): Update user's verified status. | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Acount verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verifiy token is valid.
- def save(self): Update user's verified status.
<|skeleton|>
class AccountVerificationSerializer:... | 49fcf0c6d735a56eaebc17d04be52dab91ca4c3a | <|skeleton|>
class AccountVerificationSerializer:
"""Acount verification serializer."""
def validate_token(self, data):
"""Verifiy token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountVerificationSerializer:
"""Acount verification serializer."""
def validate_token(self, data):
"""Verifiy token is valid."""
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers... | the_stack_v2_python_sparse | api/users/serializers/users.py | alexhernandez-git/django-classline | train | 0 |
312886165729fab5ae2f720e07cf7d7a1b0feada | [
"assert not element.findall('.//node')\nself.element = element\nself._screen_width = screen_width\nself._screen_height = screen_height\nbbox = _build_bounding_box(element.get('bounds'))\nself.uiobject = UIObject(obj_type=_build_object_type(element.get('class')), obj_name=_build_object_name(element.get('text'), elem... | <|body_start_0|>
assert not element.findall('.//node')
self.element = element
self._screen_width = screen_width
self._screen_height = screen_height
bbox = _build_bounding_box(element.get('bounds'))
self.uiobject = UIObject(obj_type=_build_object_type(element.get('class'))... | Represents a leaf node in the view hierarchy data from xml. | LeafNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeafNode:
"""Represents a leaf node in the view hierarchy data from xml."""
def __init__(self, element, dom_location=None, screen_width=config.SCREEN_WIDTH, screen_height=config.SCREEN_HEIGHT):
"""Constructor. Args: element: The etree.Element object. dom_location: [depth, preorder-in... | stack_v2_sparse_classes_36k_train_030289 | 21,100 | permissive | [
{
"docstring": "Constructor. Args: element: The etree.Element object. dom_location: [depth, preorder-index, postorder-index] of element. screen_width: The width of the screen associated with the element. screen_height: The height of the screen associated with the element.",
"name": "__init__",
"signatur... | 3 | null | Implement the Python class `LeafNode` described below.
Class description:
Represents a leaf node in the view hierarchy data from xml.
Method signatures and docstrings:
- def __init__(self, element, dom_location=None, screen_width=config.SCREEN_WIDTH, screen_height=config.SCREEN_HEIGHT): Constructor. Args: element: Th... | Implement the Python class `LeafNode` described below.
Class description:
Represents a leaf node in the view hierarchy data from xml.
Method signatures and docstrings:
- def __init__(self, element, dom_location=None, screen_width=config.SCREEN_WIDTH, screen_height=config.SCREEN_HEIGHT): Constructor. Args: element: Th... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class LeafNode:
"""Represents a leaf node in the view hierarchy data from xml."""
def __init__(self, element, dom_location=None, screen_width=config.SCREEN_WIDTH, screen_height=config.SCREEN_HEIGHT):
"""Constructor. Args: element: The etree.Element object. dom_location: [depth, preorder-in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeafNode:
"""Represents a leaf node in the view hierarchy data from xml."""
def __init__(self, element, dom_location=None, screen_width=config.SCREEN_WIDTH, screen_height=config.SCREEN_HEIGHT):
"""Constructor. Args: element: The etree.Element object. dom_location: [depth, preorder-index, postorde... | the_stack_v2_python_sparse | seq2act/data_generation/view_hierarchy.py | Ayoob7/google-research | train | 2 |
308e2384af6fe6d7e3f1738f30e6175879c6fe2b | [
"houses.sort()\nheaters.sort()\nr = 0\ni = 0\nfor h in houses:\n i = bisect.bisect(heaters, h)\n left = max(0, i - 1)\n right = min(len(heaters) - 1, i)\n r_cur = min(abs(heaters[left] - h), abs(heaters[right] - h))\n r = max(r, r_cur)\nreturn r",
"houses.sort()\nheaters.sort()\nheaters.append(floa... | <|body_start_0|>
houses.sort()
heaters.sort()
r = 0
i = 0
for h in houses:
i = bisect.bisect(heaters, h)
left = max(0, i - 1)
right = min(len(heaters) - 1, i)
r_cur = min(abs(heaters[left] - h), abs(heaters[right] - h))
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRadius(self, houses, heaters):
"""check the responsibility use bisect :type houses: List[int] :type heaters: List[int] :rtype: int"""
<|body_0|>
def findRadius_naive(self, houses, heaters):
"""check the responsibility :type houses: List[int] :type h... | stack_v2_sparse_classes_36k_train_030290 | 2,057 | permissive | [
{
"docstring": "check the responsibility use bisect :type houses: List[int] :type heaters: List[int] :rtype: int",
"name": "findRadius",
"signature": "def findRadius(self, houses, heaters)"
},
{
"docstring": "check the responsibility :type houses: List[int] :type heaters: List[int] :rtype: int",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRadius(self, houses, heaters): check the responsibility use bisect :type houses: List[int] :type heaters: List[int] :rtype: int
- def findRadius_naive(self, houses, heate... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRadius(self, houses, heaters): check the responsibility use bisect :type houses: List[int] :type heaters: List[int] :rtype: int
- def findRadius_naive(self, houses, heate... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def findRadius(self, houses, heaters):
"""check the responsibility use bisect :type houses: List[int] :type heaters: List[int] :rtype: int"""
<|body_0|>
def findRadius_naive(self, houses, heaters):
"""check the responsibility :type houses: List[int] :type h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findRadius(self, houses, heaters):
"""check the responsibility use bisect :type houses: List[int] :type heaters: List[int] :rtype: int"""
houses.sort()
heaters.sort()
r = 0
i = 0
for h in houses:
i = bisect.bisect(heaters, h)
... | the_stack_v2_python_sparse | 475 Heaters.py | Aminaba123/LeetCode | train | 1 | |
565970a3c45e839a28cf0c8db663722dd98bca10 | [
"this_matrix, these_means, these_standard_deviations = novelty_detection._normalize_features(feature_matrix=FEATURE_MATRIX_DENORM + 0.0)\nself.assertTrue(numpy.allclose(this_matrix, FEATURE_MATRIX_NORM, atol=TOLERANCE))\nself.assertTrue(numpy.allclose(these_means, FEATURE_MEANS, atol=TOLERANCE))\nself.assertTrue(nu... | <|body_start_0|>
this_matrix, these_means, these_standard_deviations = novelty_detection._normalize_features(feature_matrix=FEATURE_MATRIX_DENORM + 0.0)
self.assertTrue(numpy.allclose(this_matrix, FEATURE_MATRIX_NORM, atol=TOLERANCE))
self.assertTrue(numpy.allclose(these_means, FEATURE_MEANS, at... | Each method is a unit test for novelty_detection.py. | NoveltyDetectionTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoveltyDetectionTests:
"""Each method is a unit test for novelty_detection.py."""
def test_normalize_features(self):
"""Ensures correct output from _normalize_features."""
<|body_0|>
def test_fit_and_apply_svd(self):
"""Ensures correct output from _fit_svd and _a... | stack_v2_sparse_classes_36k_train_030291 | 2,930 | permissive | [
{
"docstring": "Ensures correct output from _normalize_features.",
"name": "test_normalize_features",
"signature": "def test_normalize_features(self)"
},
{
"docstring": "Ensures correct output from _fit_svd and _apply_svd.",
"name": "test_fit_and_apply_svd",
"signature": "def test_fit_an... | 2 | null | Implement the Python class `NoveltyDetectionTests` described below.
Class description:
Each method is a unit test for novelty_detection.py.
Method signatures and docstrings:
- def test_normalize_features(self): Ensures correct output from _normalize_features.
- def test_fit_and_apply_svd(self): Ensures correct output... | Implement the Python class `NoveltyDetectionTests` described below.
Class description:
Each method is a unit test for novelty_detection.py.
Method signatures and docstrings:
- def test_normalize_features(self): Ensures correct output from _normalize_features.
- def test_fit_and_apply_svd(self): Ensures correct output... | 1835a71ababb7ad7e47bfa19e62948d466559d56 | <|skeleton|>
class NoveltyDetectionTests:
"""Each method is a unit test for novelty_detection.py."""
def test_normalize_features(self):
"""Ensures correct output from _normalize_features."""
<|body_0|>
def test_fit_and_apply_svd(self):
"""Ensures correct output from _fit_svd and _a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoveltyDetectionTests:
"""Each method is a unit test for novelty_detection.py."""
def test_normalize_features(self):
"""Ensures correct output from _normalize_features."""
this_matrix, these_means, these_standard_deviations = novelty_detection._normalize_features(feature_matrix=FEATURE_MA... | the_stack_v2_python_sparse | gewittergefahr/deep_learning/novelty_detection_test.py | thunderhoser/GewitterGefahr | train | 29 |
ed0af6b1fc923c0c58411385cac89997e2a9a99c | [
"self.log = logging.getLogger('lapis.gyazo')\nself.headers = {'User-Agent': useragent}\nself.regex = re.compile('^(.*?\\\\.)?gyazo\\\\.com$')",
"try:\n if not self.regex.match(urlsplit(submission.url).netloc):\n return None\n data = {'author': 'a gyazo.com user', 'source': submission.url, 'importer_d... | <|body_start_0|>
self.log = logging.getLogger('lapis.gyazo')
self.headers = {'User-Agent': useragent}
self.regex = re.compile('^(.*?\\.)?gyazo\\.com$')
<|end_body_0|>
<|body_start_1|>
try:
if not self.regex.match(urlsplit(submission.url).netloc):
return None
... | A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots. | GyazoPlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GyazoPlugin:
"""A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots."""
def __init__(self, useragent: str, **options):
"""Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the con... | stack_v2_sparse_classes_36k_train_030292 | 2,843 | permissive | [
{
"docstring": "Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the configuration. Ignored.",
"name": "__init__",
"signature": "def __init__(self, useragent: str, **options)"
},
{
"docstring": "Import a submission from ... | 2 | stack_v2_sparse_classes_30k_val_001035 | Implement the Python class `GyazoPlugin` described below.
Class description:
A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots.
Method signatures and docstrings:
- def __init__(self, useragent: str, **options): Initialize the gyazo import API. :param useragent: The useragent to use for... | Implement the Python class `GyazoPlugin` described below.
Class description:
A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots.
Method signatures and docstrings:
- def __init__(self, useragent: str, **options): Initialize the gyazo import API. :param useragent: The useragent to use for... | 29503bb70b7b9e47a5cea1ea03098543b1a01efb | <|skeleton|>
class GyazoPlugin:
"""A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots."""
def __init__(self, useragent: str, **options):
"""Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GyazoPlugin:
"""A gyazo.com import plugin. gyazo.com is a site for quickly uploading screen shots."""
def __init__(self, useragent: str, **options):
"""Initialize the gyazo import API. :param useragent: The useragent to use for querying gyazo. :param options: Other options in the configuration. I... | the_stack_v2_python_sparse | plugins/gyazo.py | spiral6/VelvetBot | train | 0 |
fabe7a434ec485e953176a31b9c49f7aea655746 | [
"if node.op_type in OP_TYPES_WITH_PARAMS:\n if len(node.input) >= param_index + 1:\n param_name = node.input[param_index]\n for param in model.graph.initializer:\n if param.name == param_name:\n return param.dims\n assert 'Param not present in the node'\nelse:\n asse... | <|body_start_0|>
if node.op_type in OP_TYPES_WITH_PARAMS:
if len(node.input) >= param_index + 1:
param_name = node.input[param_index]
for param in model.graph.initializer:
if param.name == param_name:
return param.dims
... | Param utilities | ParamUtils | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at w... | stack_v2_sparse_classes_36k_train_030293 | 17,157 | permissive | [
{
"docstring": "Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at which param feeds to the ONNX node",
"name": "get_shape",
"signature": "def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProt... | 2 | stack_v2_sparse_classes_30k_train_013638 | Implement the Python class `ParamUtils` described below.
Class description:
Param utilities
Method signatures and docstrings:
- def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List: Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node t... | Implement the Python class `ParamUtils` described below.
Class description:
Param utilities
Method signatures and docstrings:
- def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List: Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node t... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at which param fe... | the_stack_v2_python_sparse | TrainingExtensions/onnx/src/python/aimet_onnx/utils.py | quic/aimet | train | 1,676 |
3f0f5c8fccb7fefc63bf8f37f99443721a659ad8 | [
"l = heap.left(i)\nr = heap.right(i)\nlargest = 0\nif l <= heap.heapsize(A) and A[l] >= A[i]:\n largest = l\nelse:\n largest = i\nif r <= heap.heapsize(A) and A[r] >= A[largest]:\n largest = r\nif largest != i:\n A[i], A[largest] = (A[largest], A[i])\n self.maxheapify(A, largest)\nreturn A",
"count... | <|body_start_0|>
l = heap.left(i)
r = heap.right(i)
largest = 0
if l <= heap.heapsize(A) and A[l] >= A[i]:
largest = l
else:
largest = i
if r <= heap.heapsize(A) and A[r] >= A[largest]:
largest = r
if largest != i:
A... | CLRS 第六章 6.2 算法函数和笔记 | Chapter6_2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chapter6_2:
"""CLRS 第六章 6.2 算法函数和笔记"""
def maxheapify(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_0|>
def maxheapify_quick(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_1|>
def minheapify(self, A, i):
"""保持堆:使某一个结点i成为最小堆... | stack_v2_sparse_classes_36k_train_030294 | 4,741 | permissive | [
{
"docstring": "保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)",
"name": "maxheapify",
"signature": "def maxheapify(self, A, i)"
},
{
"docstring": "保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)",
"name": "maxheapify_quick",
"signature": "def maxheapify_quick(self, A, i)"
},
{
"docstring": "保持堆:使某一个结点i成为最小堆(其子树本身... | 4 | null | Implement the Python class `Chapter6_2` described below.
Class description:
CLRS 第六章 6.2 算法函数和笔记
Method signatures and docstrings:
- def maxheapify(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def maxheapify_quick(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def minheapify(self, A, i): 保持堆:使某一个结点i成为最小堆(其子树本身已经为最小堆)
-... | Implement the Python class `Chapter6_2` described below.
Class description:
CLRS 第六章 6.2 算法函数和笔记
Method signatures and docstrings:
- def maxheapify(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def maxheapify_quick(self, A, i): 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)
- def minheapify(self, A, i): 保持堆:使某一个结点i成为最小堆(其子树本身已经为最小堆)
-... | 33662f46dc346203b220d7481d1a4439feda05d2 | <|skeleton|>
class Chapter6_2:
"""CLRS 第六章 6.2 算法函数和笔记"""
def maxheapify(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_0|>
def maxheapify_quick(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
<|body_1|>
def minheapify(self, A, i):
"""保持堆:使某一个结点i成为最小堆... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Chapter6_2:
"""CLRS 第六章 6.2 算法函数和笔记"""
def maxheapify(self, A, i):
"""保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆)"""
l = heap.left(i)
r = heap.right(i)
largest = 0
if l <= heap.heapsize(A) and A[l] >= A[i]:
largest = l
else:
largest = i
if... | the_stack_v2_python_sparse | src/chapter6/chapter6_2.py | HideLakitu/IntroductionToAlgorithm.Python | train | 1 |
6d7ee50ab2d4a7a866292407fe8ff1a1c88a84b8 | [
"super(CoarseMaskHead, self).__init__()\nself.num_classes = num_classes\nconv_dim = 256\nself.fc_dim = 1024\nnum_fc = 2\nself.output_side_resolution = 7\nself.input_channels = input_channel\nself.input_h = input_height\nself.input_w = input_width\nself.relu = ops.ReLU()\nself.flatten = ops.Flatten()\nself.conv_laye... | <|body_start_0|>
super(CoarseMaskHead, self).__init__()
self.num_classes = num_classes
conv_dim = 256
self.fc_dim = 1024
num_fc = 2
self.output_side_resolution = 7
self.input_channels = input_channel
self.input_h = input_height
self.input_w = input... | A mask head with fully connected layers. Given pooled features it first reduces channels and spatial dimensions with conv layers and then uses FC layers to predict coarse masks analogously to the standard box head. | CoarseMaskHead | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoarseMaskHead:
"""A mask head with fully connected layers. Given pooled features it first reduces channels and spatial dimensions with conv layers and then uses FC layers to predict coarse masks analogously to the standard box head."""
def __init__(self, num_classes, input_channel=256, inpu... | stack_v2_sparse_classes_36k_train_030295 | 7,797 | permissive | [
{
"docstring": "The following attributes are parsed from config: conv_dim: the output dimension of the conv layers fc_dim: the feature dimension of the FC layers num_fc: the number of FC layers output_side_resolution: side resolution of the output square mask prediction",
"name": "__init__",
"signature"... | 2 | null | Implement the Python class `CoarseMaskHead` described below.
Class description:
A mask head with fully connected layers. Given pooled features it first reduces channels and spatial dimensions with conv layers and then uses FC layers to predict coarse masks analogously to the standard box head.
Method signatures and d... | Implement the Python class `CoarseMaskHead` described below.
Class description:
A mask head with fully connected layers. Given pooled features it first reduces channels and spatial dimensions with conv layers and then uses FC layers to predict coarse masks analogously to the standard box head.
Method signatures and d... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class CoarseMaskHead:
"""A mask head with fully connected layers. Given pooled features it first reduces channels and spatial dimensions with conv layers and then uses FC layers to predict coarse masks analogously to the standard box head."""
def __init__(self, num_classes, input_channel=256, inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoarseMaskHead:
"""A mask head with fully connected layers. Given pooled features it first reduces channels and spatial dimensions with conv layers and then uses FC layers to predict coarse masks analogously to the standard box head."""
def __init__(self, num_classes, input_channel=256, input_height=14, ... | the_stack_v2_python_sparse | community/cv/pointrend/maskrcnn_pointrend/src/point_rend/coarse_mask_head.py | mindspore-ai/models | train | 301 |
2f1e175857e81e35d2c3ddc3c8b320ead636ff10 | [
"self.dummy = Node(None)\nself.length = 0\nself.tail = self.dummy",
"if index < 0 or index >= self.length:\n return -1\np = self.dummy.next\nfor _ in range(index):\n p = p.next\nreturn p.val",
"node = Node(val)\nnode.next = self.dummy.next\nself.dummy.next = node\nif node.next is None:\n self.tail = no... | <|body_start_0|>
self.dummy = Node(None)
self.length = 0
self.tail = self.dummy
<|end_body_0|>
<|body_start_1|>
if index < 0 or index >= self.length:
return -1
p = self.dummy.next
for _ in range(index):
p = p.next
return p.val
<|end_body_1... | Notes 0 - dummy node for convenience 1 - update attributes after operations 1.1 - self.length += 1, self.length -= 1 1.2 - IMPORTANT: self.tail = node if node.next is None 2 - delete/add, p = dummy get, p = dummy.next p and index ranges are different in each case When operating link lists, be very careful about pointer... | MyLinkedList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyLinkedList:
"""Notes 0 - dummy node for convenience 1 - update attributes after operations 1.1 - self.length += 1, self.length -= 1 1.2 - IMPORTANT: self.tail = node if node.next is None 2 - delete/add, p = dummy get, p = dummy.next p and index ranges are different in each case When operating l... | stack_v2_sparse_classes_36k_train_030296 | 3,665 | permissive | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get the value of the index-th node in the linked list. If the index is invalid, return -1.",
"name": "get",
"signature": "def get(self, index: int) -> int"
},... | 6 | stack_v2_sparse_classes_30k_train_019455 | Implement the Python class `MyLinkedList` described below.
Class description:
Notes 0 - dummy node for convenience 1 - update attributes after operations 1.1 - self.length += 1, self.length -= 1 1.2 - IMPORTANT: self.tail = node if node.next is None 2 - delete/add, p = dummy get, p = dummy.next p and index ranges are ... | Implement the Python class `MyLinkedList` described below.
Class description:
Notes 0 - dummy node for convenience 1 - update attributes after operations 1.1 - self.length += 1, self.length -= 1 1.2 - IMPORTANT: self.tail = node if node.next is None 2 - delete/add, p = dummy get, p = dummy.next p and index ranges are ... | 3c18b8809c5a21a62903060eef659654e0595036 | <|skeleton|>
class MyLinkedList:
"""Notes 0 - dummy node for convenience 1 - update attributes after operations 1.1 - self.length += 1, self.length -= 1 1.2 - IMPORTANT: self.tail = node if node.next is None 2 - delete/add, p = dummy get, p = dummy.next p and index ranges are different in each case When operating l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyLinkedList:
"""Notes 0 - dummy node for convenience 1 - update attributes after operations 1.1 - self.length += 1, self.length -= 1 1.2 - IMPORTANT: self.tail = node if node.next is None 2 - delete/add, p = dummy get, p = dummy.next p and index ranges are different in each case When operating link lists, be... | the_stack_v2_python_sparse | OOD/707. Design Linked List.py | xli1110/LC | train | 2 |
f6e8af73b7a652f4b3fb5e71106e32379ced8efa | [
"size = 0\ncur_node = head\nwhile cur_node:\n size += 1\n cur_node = cur_node.next\nself.size = size\nself.head = head",
"idx = randint(0, self.size - 1)\ncur_node = self.head\nfor _ in range(idx):\n cur_node = cur_node.next\nreturn cur_node.val"
] | <|body_start_0|>
size = 0
cur_node = head
while cur_node:
size += 1
cur_node = cur_node.next
self.size = size
self.head = head
<|end_body_0|>
<|body_start_1|>
idx = randint(0, self.size - 1)
cur_node = self.head
for _ in range(idx)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_030297 | 1,449 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.",
"name": "__init__",
"signature": "def __init__(self, head: ListNode)"
},
{
"docstring": "Returns a random node's value.",
"name": "getRandom",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_021356 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | ea6aa0cffb55b2d88f71f108f16c34e9779da9c7 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
size = 0
cur_node = head
while cur_node:
size += 1
cur_node = cur_node.next
... | the_stack_v2_python_sparse | linked_list_random_node.py | charliedmiller/coding_challenges | train | 0 | |
cc5ab1aaf9dca2627793290b85057c2845a6ed16 | [
"user = get_object_or_404(self.queryset, pk=pk)\nserializer = self.get_serializer(user)\nreturn Response(serializer.data)",
"print(request.version)\nusers = self.queryset.values('id', 'username', 'is_staff')\nreturn Response({'data': users})",
"username = request.data.get('username', None)\npassword = request.d... | <|body_start_0|>
user = get_object_or_404(self.queryset, pk=pk)
serializer = self.get_serializer(user)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
print(request.version)
users = self.queryset.values('id', 'username', 'is_staff')
return Response({'dat... | 通过session确定认证,这个viewset下面的api需要session认证通过才能访问 | UsersViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersViewSet:
"""通过session确定认证,这个viewset下面的api需要session认证通过才能访问"""
def retrieve(self, request, pk=None):
"""指定用户信息"""
<|body_0|>
def list(self, request):
"""users列表"""
<|body_1|>
def create(self, request):
"""创建用户"""
<|body_2|>
d... | stack_v2_sparse_classes_36k_train_030298 | 5,186 | no_license | [
{
"docstring": "指定用户信息",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "users列表",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "创建用户",
"name": "create",
"signature": "def create(self, request)"
},
... | 5 | stack_v2_sparse_classes_30k_test_000264 | Implement the Python class `UsersViewSet` described below.
Class description:
通过session确定认证,这个viewset下面的api需要session认证通过才能访问
Method signatures and docstrings:
- def retrieve(self, request, pk=None): 指定用户信息
- def list(self, request): users列表
- def create(self, request): 创建用户
- def destroy(self, request, pk=None): 删除用户... | Implement the Python class `UsersViewSet` described below.
Class description:
通过session确定认证,这个viewset下面的api需要session认证通过才能访问
Method signatures and docstrings:
- def retrieve(self, request, pk=None): 指定用户信息
- def list(self, request): users列表
- def create(self, request): 创建用户
- def destroy(self, request, pk=None): 删除用户... | 28a0b04ee3b9ca7e2d6e84e522047c63b0d19c8f | <|skeleton|>
class UsersViewSet:
"""通过session确定认证,这个viewset下面的api需要session认证通过才能访问"""
def retrieve(self, request, pk=None):
"""指定用户信息"""
<|body_0|>
def list(self, request):
"""users列表"""
<|body_1|>
def create(self, request):
"""创建用户"""
<|body_2|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersViewSet:
"""通过session确定认证,这个viewset下面的api需要session认证通过才能访问"""
def retrieve(self, request, pk=None):
"""指定用户信息"""
user = get_object_or_404(self.queryset, pk=pk)
serializer = self.get_serializer(user)
return Response(serializer.data)
def list(self, request):
... | the_stack_v2_python_sparse | mysite/users/views/users.py | 26huitailang/django-tutorial | train | 1 |
8c8b62d0b482efe039d52744a0a3ada53669821e | [
"from .services import get_mentee_mentors_dict\nuser_id = current_user.get_id()\ntry:\n mentors = get_mentee_mentors_dict(user_id)\n return {'mentors': mentors, 'success': True}\nexcept SQLAlchemyError:\n return {'success': False}",
"from .services import add_mentor\nparser = reqparse.RequestParser()\npa... | <|body_start_0|>
from .services import get_mentee_mentors_dict
user_id = current_user.get_id()
try:
mentors = get_mentee_mentors_dict(user_id)
return {'mentors': mentors, 'success': True}
except SQLAlchemyError:
return {'success': False}
<|end_body_0|>... | MporterAPIMentor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MporterAPIMentor:
def get(self):
"""get logged in mentee's mentors :return: {'mentors': [list of mentors]"""
<|body_0|>
def post(self):
"""create or add mentor under the authorized user"""
<|body_1|>
def delete(self):
"""delete a mentor from unde... | stack_v2_sparse_classes_36k_train_030299 | 4,700 | permissive | [
{
"docstring": "get logged in mentee's mentors :return: {'mentors': [list of mentors]",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "create or add mentor under the authorized user",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "delete a mentor... | 3 | stack_v2_sparse_classes_30k_train_002920 | Implement the Python class `MporterAPIMentor` described below.
Class description:
Implement the MporterAPIMentor class.
Method signatures and docstrings:
- def get(self): get logged in mentee's mentors :return: {'mentors': [list of mentors]
- def post(self): create or add mentor under the authorized user
- def delete... | Implement the Python class `MporterAPIMentor` described below.
Class description:
Implement the MporterAPIMentor class.
Method signatures and docstrings:
- def get(self): get logged in mentee's mentors :return: {'mentors': [list of mentors]
- def post(self): create or add mentor under the authorized user
- def delete... | 3014131fe480604319555319662e5c20d2abb125 | <|skeleton|>
class MporterAPIMentor:
def get(self):
"""get logged in mentee's mentors :return: {'mentors': [list of mentors]"""
<|body_0|>
def post(self):
"""create or add mentor under the authorized user"""
<|body_1|>
def delete(self):
"""delete a mentor from unde... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MporterAPIMentor:
def get(self):
"""get logged in mentee's mentors :return: {'mentors': [list of mentors]"""
from .services import get_mentee_mentors_dict
user_id = current_user.get_id()
try:
mentors = get_mentee_mentors_dict(user_id)
return {'mentors': ... | the_stack_v2_python_sparse | app/api.py | abhn/Mporter | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.