uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1767481253c5c0ac92713727 | train | function | def test_add_condition():
attr = Attribute("name", definition_id="code")
group = InputGroup(id_="id", attribute=attr)
c1 = Condition("INCLUDE", SqlColumn("public", "patients", "gender"), "EQ", "M")
group.add_condition(c1)
assert len(group.conditions) == 1
assert group.conditions[0] == c1
c... | def test_add_condition():
| attr = Attribute("name", definition_id="code")
group = InputGroup(id_="id", attribute=attr)
c1 = Condition("INCLUDE", SqlColumn("public", "patients", "gender"), "EQ", "M")
group.add_condition(c1)
assert len(group.conditions) == 1
assert group.conditions[0] == c1
c2 = Condition("EXCLUDE", S... | from river.common.analyzer.attribute import Attribute
from river.common.analyzer.condition import Condition
from river.common.analyzer.input_group import InputGroup
from river.common.analyzer.sql_column import SqlColumn
def test_add_condition():
| 45 | 64 | 140 | 5 | 39 | arkhn/fhir-river | tests/river/unit/analyzer/test_input_groups.py | Python | test_add_condition | test_add_condition | 7 | 19 | 7 | 7 | 2f5fa4a58f6038ba22c698f84e5614d46a89a245 | bigcode/the-stack | train |
04df6aab30e0866a345a319d | train | function | def test_add_static_input():
attr = Attribute("name", definition_id="code")
group = InputGroup(id_="id", attribute=attr)
i1 = "bob"
group.add_static_input(i1)
assert len(group.static_inputs) == 1
assert group.static_inputs[0] == i1
i2 = "alice"
group.add_static_input(i2)
assert len... | def test_add_static_input():
| attr = Attribute("name", definition_id="code")
group = InputGroup(id_="id", attribute=attr)
i1 = "bob"
group.add_static_input(i1)
assert len(group.static_inputs) == 1
assert group.static_inputs[0] == i1
i2 = "alice"
group.add_static_input(i2)
assert len(group.static_inputs) == 2
... | c1
c2 = Condition("EXCLUDE", SqlColumn("public", "patients", "subject_id"), "EQ", "123")
group.add_column(c2)
assert len(group.columns) == 2
assert group.columns[1] == c2
def test_add_static_input():
| 64 | 64 | 108 | 6 | 57 | arkhn/fhir-river | tests/river/unit/analyzer/test_input_groups.py | Python | test_add_static_input | test_add_static_input | 37 | 49 | 37 | 37 | b42e01700040f07709b99bcbbc81e95d2f3f78e8 | bigcode/the-stack | train |
a0fb379dd8107dcf224fc9af | train | class | class SAHPGen(SeqGenerator):
# sequence generator for the SAHP model
def __init__(self,model, record_intensity = True):
super(SAHPGen, self).__init__(model, record_intensity)
self.lbda_ub = []
def _restart_sequence(self):
super(SAHPGen, self)._restart_sequence()
self.lbda_u... | class SAHPGen(SeqGenerator):
# sequence generator for the SAHP model
| def __init__(self,model, record_intensity = True):
super(SAHPGen, self).__init__(model, record_intensity)
self.lbda_ub = []
def _restart_sequence(self):
super(SAHPGen, self)._restart_sequence()
self.lbda_ub = []
| _points):#
x_intensity = np.linspace(sample_times.min(), sample_times.max(), n_points)
y_intensity = intensity_i
ax.plot(x_intensity, y_intensity)
ax.set_title(label)
class SAHPGen(SeqGenerator):
# sequence generator for the SAHP model
| 64 | 64 | 85 | 18 | 46 | yangalan123/anhp-andtt | sahp/sahp_training/models/sahp.py | Python | SAHPGen | SAHPGen | 311 | 320 | 311 | 313 | a7cd3575c527aef364a74c6bff734e06236c7f11 | bigcode/the-stack | train |
c683bf12871e659b8adee42e | train | class | class SAHP(nn.Module):
"Generic N layer attentive Hawkes with masking"
def __init__(self, nLayers, d_model, atten_heads, dropout, process_dim, device, max_sequence_length):
super(SAHP, self).__init__()
self.nLayers = nLayers
self.process_dim = process_dim
self.input_size = proce... | class SAHP(nn.Module):
| "Generic N layer attentive Hawkes with masking"
def __init__(self, nLayers, d_model, atten_heads, dropout, process_dim, device, max_sequence_length):
super(SAHP, self).__init__()
self.nLayers = nLayers
self.process_dim = process_dim
self.input_size = process_dim + 1
self... | '''
self-attentive Hawkes process
'''
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import math, copy
from models.embedding.event_type import TypeEmbedding
from models.embedding.position import PositionalEmbedding,BiasedPositionalEmbedding
fr... | 143 | 256 | 2,681 | 6 | 136 | yangalan123/anhp-andtt | sahp/sahp_training/models/sahp.py | Python | SAHP | SAHP | 23 | 308 | 23 | 23 | 36e7cf828eaab18146fb12b8d705e54f06d7a072 | bigcode/the-stack | train |
dc669ea81a957d10d238bbb4 | train | class | class ApplicationCommand(_BaseCommand):
cog = None
def __repr__(self):
return f"<discord.application.{self.__class__.__name__} name={self.name}>"
def __eq__(self, other):
return isinstance(other, self.__class__)
async def __call__(self, ctx, *args, **kwargs):
"""|coro|
... | class ApplicationCommand(_BaseCommand):
| cog = None
def __repr__(self):
return f"<discord.application.{self.__class__.__name__} name={self.name}>"
def __eq__(self, other):
return isinstance(other, self.__class__)
async def __call__(self, ctx, *args, **kwargs):
"""|coro|
Calls the command's callback.
... | ",
"slash_command",
"application_command",
"user_command",
"message_command",
"command",
"SlashCommandGroup",
"ContextMenuCommand",
"UserCommand",
"MessageCommand",
)
if TYPE_CHECKING:
from ..interactions import Interaction
def wrap_callback(coro):
@functools.wraps(coro)
... | 255 | 256 | 1,679 | 7 | 248 | alexyy802/Texus | discord/application/commands.py | Python | ApplicationCommand | ApplicationCommand | 106 | 328 | 106 | 106 | 3794b717e36e91ccf11d7869c275fb5a1ce3aeff | bigcode/the-stack | train |
5ae563885754c4ad6895b884 | train | function | def option(name, type=None, **kwargs):
"""A decorator that can be used instead of typehinting Option"""
def decor(func):
nonlocal type
type = type or func.__annotations__.get(name, str)
func.__annotations__[name] = Option(type, **kwargs)
return func
return decor
| def option(name, type=None, **kwargs):
| """A decorator that can be used instead of typehinting Option"""
def decor(func):
nonlocal type
type = type or func.__annotations__.get(name, str)
func.__annotations__[name] = Option(type, **kwargs)
return func
return decor
| [str, int, float]] = None):
self.name = name
self.value = value or name
def to_dict(self) -> Dict[str, Union[str, int, float]]:
return {"name": self.name, "value": self.value}
def option(name, type=None, **kwargs):
| 64 | 64 | 71 | 10 | 54 | alexyy802/Texus | discord/application/commands.py | Python | option | option | 710 | 719 | 710 | 710 | 5d4282bb712e4f73c27e9e9ae2838e0d7d2742d9 | bigcode/the-stack | train |
1fd40756f2bdfb1c0f9d03b9 | train | class | class UserCommand(ContextMenuCommand):
type = 2
def __new__(cls, *args, **kwargs) -> UserCommand:
self = super().__new__(cls)
self.__original_kwargs__ = kwargs.copy()
return self
async def _invoke(self, ctx: ApplicationContext) -> None:
if "members" not in ctx.interaction.... | class UserCommand(ContextMenuCommand):
| type = 2
def __new__(cls, *args, **kwargs) -> UserCommand:
self = super().__new__(cls)
self.__original_kwargs__ = kwargs.copy()
return self
async def _invoke(self, ctx: ApplicationContext) -> None:
if "members" not in ctx.interaction.data["resolved"]:
_data = c... | " parameter.'
)
# next we have the 'user/message' as the next parameter
try:
next(params)
except StopIteration:
cmd = "user" if type(self) == UserCommand else "message"
raise ClientException(
f'Callback for {self.name} command is m... | 173 | 173 | 579 | 7 | 166 | alexyy802/Texus | discord/application/commands.py | Python | UserCommand | UserCommand | 937 | 1,009 | 937 | 937 | d02e53953e0ec4a54aa2c5540b689c27da543a92 | bigcode/the-stack | train |
d5e2ddc31fb1521b8ceacd58 | train | class | class SlashCommandGroup(ApplicationCommand, Option):
r"""A class that implements the protocol for a slash command group.
These can be created manually, but they should be created via the
decorator or functional interface.
Attributes
-----------
name: :class:`str`
The name of the comman... | class SlashCommandGroup(ApplicationCommand, Option):
| r"""A class that implements the protocol for a slash command group.
These can be created manually, but they should be created via the
decorator or functional interface.
Attributes
-----------
name: :class:`str`
The name of the command.
description: Optional[:class:`str`]
Th... | ),
}
if self.channel_types:
as_dict["channel_types"] = [t.value for t in self.channel_types]
if self.min_value is not None:
as_dict["min_value"] = self.min_value
if self.max_value is not None:
as_dict["max_value"] = self.max_value
return as_di... | 256 | 256 | 882 | 9 | 246 | alexyy802/Texus | discord/application/commands.py | Python | SlashCommandGroup | SlashCommandGroup | 722 | 828 | 722 | 722 | f73ba3c20c660bb44967c814914d2793ddf83c2f | bigcode/the-stack | train |
12acdbb0be012d5f945d799d | train | class | class OptionChoice:
def __init__(self, name: str, value: Optional[Union[str, int, float]] = None):
self.name = name
self.value = value or name
def to_dict(self) -> Dict[str, Union[str, int, float]]:
return {"name": self.name, "value": self.value}
| class OptionChoice:
| def __init__(self, name: str, value: Optional[Union[str, int, float]] = None):
self.name = name
self.value = value or name
def to_dict(self) -> Dict[str, Union[str, int, float]]:
return {"name": self.name, "value": self.value}
| "] = self.min_value
if self.max_value is not None:
as_dict["max_value"] = self.max_value
return as_dict
def __repr__(self):
return f"<discord.application.{self.__class__.__name__} name={self.name}>"
class OptionChoice:
| 63 | 64 | 74 | 4 | 59 | alexyy802/Texus | discord/application/commands.py | Python | OptionChoice | OptionChoice | 701 | 707 | 701 | 701 | 2e149566c9a96639164bf495350e48c918bc2167 | bigcode/the-stack | train |
dae481fb13678d2c168d27fa | train | class | class MessageCommand(ContextMenuCommand):
type = 3
def __new__(cls, *args, **kwargs) -> MessageCommand:
self = super().__new__(cls)
self.__original_kwargs__ = kwargs.copy()
return self
async def _invoke(self, ctx: ApplicationContext):
_data = ctx.interaction.data["resolved... | class MessageCommand(ContextMenuCommand):
| type = 3
def __new__(cls, *args, **kwargs) -> MessageCommand:
self = super().__new__(cls)
self.__original_kwargs__ = kwargs.copy()
return self
async def _invoke(self, ctx: ApplicationContext):
_data = ctx.interaction.data["resolved"]["messages"]
for i, v in _data.i... | buckets.copy()
# if self._max_concurrency != other._max_concurrency:
# # _max_concurrency won't be None at this point
# other._max_concurrency = self._max_concurrency.copy() # type: ignore
try:
other.on_error = self.on_error
except AttributeError:
... | 150 | 150 | 502 | 7 | 143 | alexyy802/Texus | discord/application/commands.py | Python | MessageCommand | MessageCommand | 1,012 | 1,075 | 1,012 | 1,012 | 133f7b74893eac4524a4e0645a97be4aea9edd34 | bigcode/the-stack | train |
6baefc05fce9e798a7a98607 | train | class | class SlashCommand(ApplicationCommand):
r"""A class that implements the protocol for a slash command.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
-----------
name: :class:`str`
The name of the command.
callback: :re... | class SlashCommand(ApplicationCommand):
| r"""A class that implements the protocol for a slash command.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
-----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
The co... | class__._get_overridden_method(cog.cog_after_invoke)
if hook is not None:
await hook(ctx)
hook = ctx.bot._after_invoke
if hook is not None:
await hook(ctx)
@property
def full_parent_name(self) -> str:
""":class:`str`: Retrieves the fully qualifie... | 256 | 256 | 2,127 | 6 | 249 | alexyy802/Texus | discord/application/commands.py | Python | SlashCommand | SlashCommand | 331 | 614 | 331 | 331 | 7a437632490b2ebb71ac9374302132d191c505a2 | bigcode/the-stack | train |
9b4317524a1e51259a8fd502 | train | function | def validate_chat_input_description(description: Any):
if not isinstance(description, str):
raise TypeError("Description of a command must be a string.")
if len(description) > 100 or len(description) < 1:
raise ValidationError(
"Description of a chat input command must be less than 1... | def validate_chat_input_description(description: Any):
| if not isinstance(description, str):
raise TypeError("Description of a command must be a string.")
if len(description) > 100 or len(description) < 1:
raise ValidationError(
"Description of a chat input command must be less than 100 characters and non empty."
)
| ValidationError("Name of a chat input command must be lowercase.")
if len(name) > 32 or len(name) < 1:
raise ValidationError(
"Name of a chat input command must be less than 32 characters and non empty."
)
def validate_chat_input_description(description: Any):
| 64 | 64 | 73 | 9 | 55 | alexyy802/Texus | discord/application/commands.py | Python | validate_chat_input_description | validate_chat_input_description | 1,174 | 1,180 | 1,174 | 1,174 | 546dc094ae703dcd25d5ea684468e0d7de970062 | bigcode/the-stack | train |
bea2ed3260b917d36c79a44a | train | class | class _BaseCommand:
__slots__ = ()
| class _BaseCommand:
| __slots__ = ()
| await coro(arg)
except ApplicationCommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise ApplicationCommandInvokeError(exc) from exc
finally:
await command.call_after_hooks(ctx)
return ret
ret... | 64 | 64 | 11 | 5 | 58 | alexyy802/Texus | discord/application/commands.py | Python | _BaseCommand | _BaseCommand | 102 | 103 | 102 | 102 | 092b186f9f15cf089667af313ad51ee950f7fe4b | bigcode/the-stack | train |
67f1d6590f7f1e99e041e3b6 | train | function | def user_command(**kwargs):
"""Decorator for user commands that invokes :func:`application_command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`UserCommand`]
A decorator that converts the provided method into a :class:`.UserCommand`.
"""
return application_command(c... | def user_command(**kwargs):
| """Decorator for user commands that invokes :func:`application_command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`UserCommand`]
A decorator that converts the provided method into a :class:`.UserCommand`.
"""
return application_command(cls=UserCommand, **kwargs)
| `.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`SlashCommand`]
A decorator that converts the provided method into a :class:`.SlashCommand`.
"""
return application_command(cls=SlashCommand, **kwargs)
def user_command(**kwargs):
| 64 | 64 | 77 | 6 | 58 | alexyy802/Texus | discord/application/commands.py | Python | user_command | user_command | 1,089 | 1,097 | 1,089 | 1,089 | 75d281737f330761ffdee73610ea92b77ab54d5f | bigcode/the-stack | train |
3ef697cf23735676357aa3a3 | train | function | def message_command(**kwargs):
"""Decorator for message commands that invokes :func:`application_command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`MessageCommand`]
A decorator that converts the provided method into a :class:`.MessageCommand`.
"""
return applicati... | def message_command(**kwargs):
| """Decorator for message commands that invokes :func:`application_command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`MessageCommand`]
A decorator that converts the provided method into a :class:`.MessageCommand`.
"""
return application_command(cls=MessageCommand, ... | `.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`UserCommand`]
A decorator that converts the provided method into a :class:`.UserCommand`.
"""
return application_command(cls=UserCommand, **kwargs)
def message_command(**kwargs):
| 64 | 64 | 77 | 6 | 58 | alexyy802/Texus | discord/application/commands.py | Python | message_command | message_command | 1,100 | 1,108 | 1,100 | 1,100 | 3ed082ca41ff0fa98ac0316d6c22c715991fe61f | bigcode/the-stack | train |
3725fbec4ba9aace813dc9b6 | train | function | def application_command(cls=SlashCommand, **attrs):
"""A decorator that transforms a function into an :class:`.ApplicationCommand`. More specifically,
usually one of :class:`.SlashCommand`, :class:`.UserCommand`, or :class:`.MessageCommand`. The exact class
depends on the ``cls`` parameter.
By default t... | def application_command(cls=SlashCommand, **attrs):
| """A decorator that transforms a function into an :class:`.ApplicationCommand`. More specifically,
usually one of :class:`.SlashCommand`, :class:`.UserCommand`, or :class:`.MessageCommand`. The exact class
depends on the ``cls`` parameter.
By default the ``description`` attribute is received automatical... | Command, **kwargs)
def message_command(**kwargs):
"""Decorator for message commands that invokes :func:`application_command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`MessageCommand`]
A decorator that converts the provided method into a :class:`.MessageCommand`.
"""... | 93 | 93 | 313 | 11 | 82 | alexyy802/Texus | discord/application/commands.py | Python | application_command | application_command | 1,111 | 1,144 | 1,111 | 1,111 | e96de9bbc7f9707e74725ec8404b5641f61f795c | bigcode/the-stack | train |
65e842b6194e92de8f4b4761 | train | function | def slash_command(**kwargs):
"""Decorator for slash commands that invokes :func:`application_command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`SlashCommand`]
A decorator that converts the provided method into a :class:`.SlashCommand`.
"""
return application_comma... | def slash_command(**kwargs):
| """Decorator for slash commands that invokes :func:`application_command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`SlashCommand`]
A decorator that converts the provided method into a :class:`.SlashCommand`.
"""
return application_command(cls=SlashCommand, **kwargs... | (self, kwargs: Dict[str, Any]):
if kwargs:
kw = kwargs.copy()
kw.update(self.__original_kwargs__)
copy = self.__class__(self.callback, **kw)
return self._ensure_assignment_on_copy(copy)
else:
return self.copy()
def slash_command(**kwargs):
| 64 | 64 | 77 | 6 | 58 | alexyy802/Texus | discord/application/commands.py | Python | slash_command | slash_command | 1,078 | 1,086 | 1,078 | 1,078 | 48eb2623b4220432c4c8de0c36ac4c5cb9fb2b91 | bigcode/the-stack | train |
f4a1c18c79f4c93ec3aa62e2 | train | function | def validate_chat_input_name(name: Any):
if not isinstance(name, str):
raise TypeError("Name of a command must be a string.")
if " " in name:
raise ValidationError("Name of a chat input command cannot have spaces.")
if not name.islower():
raise ValidationError("Name of a chat input c... | def validate_chat_input_name(name: Any):
| if not isinstance(name, str):
raise TypeError("Name of a command must be a string.")
if " " in name:
raise ValidationError("Name of a chat input command cannot have spaces.")
if not name.islower():
raise ValidationError("Name of a chat input command must be lowercase.")
if len(na... | .. versionadded:: 2.0
Returns
--------
Callable[..., :class:`ApplicationCommand`]
A decorator that converts the provided method into an :class:`.ApplicationCommand`.
"""
return application_command(**kwargs)
# Validation
def validate_chat_input_name(name: Any):
| 64 | 64 | 117 | 9 | 54 | alexyy802/Texus | discord/application/commands.py | Python | validate_chat_input_name | validate_chat_input_name | 1,161 | 1,171 | 1,161 | 1,161 | 4e32f9b9c04d8cb5071f09091978f07237551778 | bigcode/the-stack | train |
d3df1566cfc1ee3b012064e4 | train | function | def command(**kwargs):
"""There is an alias for :meth:`application_command`.
.. note::
This decorator is overridden by :func:`commands.command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`ApplicationCommand`]
A decorator that converts the provided method into an... | def command(**kwargs):
| """There is an alias for :meth:`application_command`.
.. note::
This decorator is overridden by :func:`commands.command`.
.. versionadded:: 2.0
Returns
--------
Callable[..., :class:`ApplicationCommand`]
A decorator that converts the provided method into an :class:`.ApplicationCo... | Callable) -> cls:
if isinstance(func, ApplicationCommand):
func = func.callback
elif not callable(func):
raise TypeError(
"func needs to be a callable or a subclass of ApplicationCommand."
)
return cls(func, **attrs)
return decorator
def ... | 64 | 64 | 86 | 5 | 58 | alexyy802/Texus | discord/application/commands.py | Python | command | command | 1,147 | 1,157 | 1,147 | 1,147 | 536de9b903411e26516af3ffdfe32f886bd3417c | bigcode/the-stack | train |
5c23f5336aa41be25e0e24d0 | train | function | def hooked_wrapped_callback(command, ctx, coro):
@functools.wraps(coro)
async def wrapped(arg):
try:
ret = await coro(arg)
except ApplicationCommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise Ap... | def hooked_wrapped_callback(command, ctx, coro):
@functools.wraps(coro)
| async def wrapped(arg):
try:
ret = await coro(arg)
except ApplicationCommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise ApplicationCommandInvokeError(exc) from exc
finally:
await... | except ApplicationCommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise ApplicationCommandInvokeError(exc) from exc
return ret
return wrapped
def hooked_wrapped_callback(command, ctx, coro):
@functools.wraps(coro)
| 64 | 64 | 92 | 21 | 42 | alexyy802/Texus | discord/application/commands.py | Python | hooked_wrapped_callback | hooked_wrapped_callback | 84 | 99 | 84 | 85 | 747ce30e8df81983c32b1e0083c462d6fe04f3f9 | bigcode/the-stack | train |
843267825740fa62963b9806 | train | class | class ContextMenuCommand(ApplicationCommand):
r"""A class that implements the protocol for context menu commands.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
-----------
name: :class:`str`
The name of the command.
c... | class ContextMenuCommand(ApplicationCommand):
| r"""A class that implements the protocol for context menu commands.
These are not created manually, instead they are created via the
decorator or functional interface.
Attributes
-----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
... | Command:
command = SlashCommand(func, parent=self, **kwargs)
self.subcommands.append(command)
return command
return wrap
def command_group(self, name, description) -> SlashCommandGroup:
if self.parent is not None:
# TODO: Improve this error message
... | 235 | 235 | 786 | 7 | 228 | alexyy802/Texus | discord/application/commands.py | Python | ContextMenuCommand | ContextMenuCommand | 831 | 934 | 831 | 831 | 51e7fa8f61a459ea1a0d96d31cd51be57a52a8ba | bigcode/the-stack | train |
1877caf79450351dbbacfc4f | train | function | def wrap_callback(coro):
@functools.wraps(coro)
async def wrapped(*args, **kwargs):
try:
ret = await coro(*args, **kwargs)
except ApplicationCommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise Ap... | def wrap_callback(coro):
@functools.wraps(coro)
| async def wrapped(*args, **kwargs):
try:
ret = await coro(*args, **kwargs)
except ApplicationCommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise ApplicationCommandInvokeError(exc) from exc
re... | user_command",
"message_command",
"command",
"SlashCommandGroup",
"ContextMenuCommand",
"UserCommand",
"MessageCommand",
)
if TYPE_CHECKING:
from ..interactions import Interaction
def wrap_callback(coro):
@functools.wraps(coro)
| 64 | 64 | 84 | 16 | 47 | alexyy802/Texus | discord/application/commands.py | Python | wrap_callback | wrap_callback | 68 | 81 | 68 | 69 | 04acc16375ac8b95b27c39107e39c68a49034e93 | bigcode/the-stack | train |
e8f0f835125365c13a00cc98 | train | class | class Option:
def __init__(self, input_type: Any, /, description: str = None, **kwargs) -> None:
self.name: Optional[str] = kwargs.pop("name", None)
self.description = description or "No description provided"
self._converter = None
self.channel_types: List[SlashCommandOptionType] = k... | class Option:
| def __init__(self, input_type: Any, /, description: str = None, **kwargs) -> None:
self.name: Optional[str] = kwargs.pop("name", None)
self.description = description or "No description provided"
self._converter = None
self.channel_types: List[SlashCommandOptionType] = kwargs.pop(
... | and not other._buckets.valid:
# other._buckets = self._buckets.copy()
# if self._max_concurrency != other._max_concurrency:
# # _max_concurrency won't be None at this point
# other._max_concurrency = self._max_concurrency.copy() # type: ignore
try:
other.o... | 207 | 207 | 692 | 3 | 204 | alexyy802/Texus | discord/application/commands.py | Python | Option | Option | 625 | 698 | 625 | 625 | 073efdcc59d904c0d7528ab6435a5c596f585094 | bigcode/the-stack | train |
9eaa2a0b00084f071fa91b7b | train | class | class BoundingBoxDecode(nn.Cell):
"""
BoundintBox Decoder.
Returns:
pred_box(Tensor): decoder bounding boxes.
"""
def __init__(self):
super(BoundingBoxDecode, self).__init__()
self.split = P.Split(axis=1, output_num=4)
self.ones = 1.0
self.half = 0.5
... | class BoundingBoxDecode(nn.Cell):
| """
BoundintBox Decoder.
Returns:
pred_box(Tensor): decoder bounding boxes.
"""
def __init__(self):
super(BoundingBoxDecode, self).__init__()
self.split = P.Split(axis=1, output_num=4)
self.ones = 1.0
self.half = 0.5
self.log = P.Log()
self.ex... | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permis... | 103 | 103 | 345 | 7 | 95 | leelige/mindspore | official/cv/ctpn/src/CTPN/BoundingBoxDecode.py | Python | BoundingBoxDecode | BoundingBoxDecode | 18 | 55 | 18 | 18 | 104c2e3f32da088f2acc5a187d0ef99dc76c77c9 | bigcode/the-stack | train |
851d21448632313d9cdc0a81 | train | class | class ThumbnailBackend(object):
"""
The main class for sorl-thumbnail, you can subclass this if you for example
want to change the way destination filename is generated.
"""
default_options = {
'format': settings.THUMBNAIL_FORMAT,
'quality': settings.THUMBNAIL_QUALITY,
'colo... | class ThumbnailBackend(object):
| """
The main class for sorl-thumbnail, you can subclass this if you for example
want to change the way destination filename is generated.
"""
default_options = {
'format': settings.THUMBNAIL_FORMAT,
'quality': settings.THUMBNAIL_QUALITY,
'colorspace': settings.THUMBNAIL_COLO... | from __future__ import unicode_literals
import logging
import os
import re
from django.utils.six import string_types
from sorl.thumbnail.conf import settings, defaults as default_settings
from sorl.thumbnail.helpers import tokey, serialize
from sorl.thumbnail.images import ImageFile, DummyImageFile
from sorl.thumbna... | 127 | 256 | 1,538 | 5 | 122 | frmdstryr/sorl-thumbnail | sorl/thumbnail/base.py | Python | ThumbnailBackend | ThumbnailBackend | 26 | 208 | 26 | 26 | 7e3f3196c3a9524b828674123c5e0592e181c66f | bigcode/the-stack | train |
dfd000433dd293040b4fb69e | train | function | @pytest.mark.asyncio
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
@mock.patch("google.cloud.dataproc_v1.ClusterControllerAsyncClient.get_cluster")
async def test_get_cluster(mock_get_cluster, mock_get_cluster_client):
"""assert that get_cluster called with correct... | @pytest.mark.asyncio
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
@mock.patch("google.cloud.dataproc_v1.ClusterControllerAsyncClient.get_cluster")
async def test_get_cluster(mock_get_cluster, mock_get_cluster_client):
| """assert that get_cluster called with correct param"""
mock_get_cluster_client.return_value = ga_credentials.AnonymousCredentials()
hook = DataprocHookAsync()
await hook.get_cluster(region="us-west", cluster_name="test_cluster", project_id="test_project")
mock_get_cluster.assert_called_once_with(
... | -west"), JobControllerAsyncClient)
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
@mock.patch("google.cloud.dataproc_v1.ClusterControllerAsyncClient.get_cluster")
async def test_get_cluster(mock_get_cluster, mock_get_cluster_client):
| 64 | 64 | 158 | 57 | 7 | astronomer/astronomer-providers | tests/google/cloud/hooks/test_dataproc.py | Python | test_get_cluster | test_get_cluster | 30 | 45 | 30 | 33 | fcd64db884d4d55331181b47390c648f57dfca9f | bigcode/the-stack | train |
154c0f7abdc8a32aefe533e1 | train | function | @mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
def test_get_cluster_client(mock_get_credentials):
"""assert that get_cluster_client return ClusterControllerAsyncClient"""
mock_get_credentials.return_value = ga_credentials.AnonymousCredentials()
hook = Datapr... | @mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
def test_get_cluster_client(mock_get_credentials):
| """assert that get_cluster_client return ClusterControllerAsyncClient"""
mock_get_credentials.return_value = ga_credentials.AnonymousCredentials()
hook = DataprocHookAsync()
assert isinstance(hook.get_cluster_client(location="us-west"), ClusterControllerAsyncClient)
| _v1 import (
ClusterControllerAsyncClient,
JobControllerAsyncClient,
)
from astronomer.providers.google.cloud.hooks.dataproc import DataprocHookAsync
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
def test_get_cluster_client(mock_get_credentials):
| 64 | 64 | 82 | 29 | 34 | astronomer/astronomer-providers | tests/google/cloud/hooks/test_dataproc.py | Python | test_get_cluster_client | test_get_cluster_client | 14 | 19 | 14 | 15 | 66da34e8cd34d7ac658e4dbd8195d334763a1914 | bigcode/the-stack | train |
9195181f01d7398a8028820b | train | function | @mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
def test_get_job_client(mock_get_credentials):
"""assert that get_job_client return JobControllerAsyncClient"""
mock_get_credentials.return_value = ga_credentials.AnonymousCredentials()
hook = DataprocHookAsync(... | @mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
def test_get_job_client(mock_get_credentials):
| """assert that get_job_client return JobControllerAsyncClient"""
mock_get_credentials.return_value = ga_credentials.AnonymousCredentials()
hook = DataprocHookAsync()
assert isinstance(hook.get_job_client(location="us-west"), JobControllerAsyncClient)
| _value = ga_credentials.AnonymousCredentials()
hook = DataprocHookAsync()
assert isinstance(hook.get_cluster_client(location="us-west"), ClusterControllerAsyncClient)
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
def test_get_job_client(mock_get_credentials):
| 64 | 64 | 82 | 29 | 35 | astronomer/astronomer-providers | tests/google/cloud/hooks/test_dataproc.py | Python | test_get_job_client | test_get_job_client | 22 | 27 | 22 | 23 | 042c0aa4a60b6c9495d0bf2b525a8723a4fb42ee | bigcode/the-stack | train |
c218ce9a4ee2b54f29dc3a57 | train | function | @pytest.mark.asyncio
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
@mock.patch("google.cloud.dataproc_v1.JobControllerAsyncClient.get_job")
async def test_get_job(mock_get_job, mock_get_cred):
"""Test to get the job from Google cloud dataproc"""
mock_get_cred.r... | @pytest.mark.asyncio
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
@mock.patch("google.cloud.dataproc_v1.JobControllerAsyncClient.get_job")
async def test_get_job(mock_get_job, mock_get_cred):
| """Test to get the job from Google cloud dataproc"""
mock_get_cred.return_value = ga_credentials.AnonymousCredentials()
hook = DataprocHookAsync()
await hook.get_job(region="us-west", job_id="test-id", project_id="test-project")
mock_get_job.assert_called_once_with(
request={
"re... | ,
metadata=(),
)
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.common.hooks.base_google.GoogleBaseHook._get_credentials")
@mock.patch("google.cloud.dataproc_v1.JobControllerAsyncClient.get_job")
async def test_get_job(mock_get_job, mock_get_cred):
| 64 | 64 | 176 | 57 | 7 | astronomer/astronomer-providers | tests/google/cloud/hooks/test_dataproc.py | Python | test_get_job | test_get_job | 48 | 65 | 48 | 51 | a52db828e0989b070aba2b2e025a18aa3a8e61d4 | bigcode/the-stack | train |
e49acc4e9a618732a823d516 | train | function | def run_example(device_id, monitor_length=4000, num_averages=2**8, do_plot=True):
""" Run a combined test of the monitor and result units.
The example applies a simple square wave to the instrument using the AWG. The
integration functions use the full length of the integrators, and each
integration fun... | def run_example(device_id, monitor_length=4000, num_averages=2**8, do_plot=True):
| """ Run a combined test of the monitor and result units.
The example applies a simple square wave to the instrument using the AWG. The
integration functions use the full length of the integrators, and each
integration function is basically just a constant value through the entire
integration window... | # -*- coding: utf-8 -*-
""" Run a combined test of the monitor and result units.
"""
# Copyright 2018 Zurich Instruments AG
from __future__ import print_function
import sys
import time
import textwrap
import numpy as np
import zhinst.utils
from .common import initialize_device, acquisition_poll
from .common import ... | 101 | 256 | 2,488 | 25 | 75 | tempstabilizer2018group/mfli_labber_dynamic_integration | Drivers/python_libs/linux/zhinst/examples/uhfqa/example_delay.py | Python | run_example | run_example | 19 | 254 | 19 | 19 | 9a9c68460307f05f73cc36dddedc7de06c4925e8 | bigcode/the-stack | train |
3503b6af0251f5dc5771f788 | train | class | class Login(object):
logger = Logger().logger
driver = None
# username = Location("用户名输入框", "input[type=text]")
# passwd = Location("密码输入框", "input[type=password]")
# submit = Location("登录按钮", ".btn-login")
# logo = Location("大后台管理系统图标", "#leftpanel .img")
def __init__(self):
# 启动dr... | class Login(object):
| logger = Logger().logger
driver = None
# username = Location("用户名输入框", "input[type=text]")
# passwd = Location("密码输入框", "input[type=password]")
# submit = Location("登录按钮", ".btn-login")
# logo = Location("大后台管理系统图标", "#leftpanel .img")
def __init__(self):
# 启动driver
try:
... | from util.decorator import Log
from util.driver import ChromeDriver
from util.logger import Logger
from config import Config
class Login(object):
| 29 | 93 | 312 | 4 | 24 | wuranxu/webTest | page/login.py | Python | Login | Login | 7 | 38 | 7 | 7 | 93b3f9e248d388ed1eac2b0f9b437306fbd5df42 | bigcode/the-stack | train |
b3a87f456c9a14ea0de09399 | train | function | def fbcode_builder_spec(builder):
return {
'steps': [
# on macOS the filesystem is typically case insensitive.
# We need to ensure that the CWD is not the folly source
# dir when we build, otherwise the system will decide
# that `folly/String.h` is the file it... | def fbcode_builder_spec(builder):
| return {
'steps': [
# on macOS the filesystem is typically case insensitive.
# We need to ensure that the CWD is not the folly source
# dir when we build, otherwise the system will decide
# that `folly/String.h` is the file it wants when including
... | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
def fbcode_builder_spec(builder):
| 44 | 64 | 115 | 7 | 36 | jamesbj/openr | build/fbcode_builder/specs/folly.py | Python | fbcode_builder_spec | fbcode_builder_spec | 8 | 19 | 8 | 8 | 8f19adaf0afbc9dc750a31eb88b27f7da4487fc5 | bigcode/the-stack | train |
904eb9cb175aab7f509fc03b | train | function | def create_app():
app = Flask(__name__)
@app.route('/')
def root():
return 'airbnb predictive project'
@app.route('/predict', methods=['POST'])
def predict(message=""):
try:
# find authorization header
content = request.get_json(force=True)
messa... | def create_app():
| app = Flask(__name__)
@app.route('/')
def root():
return 'airbnb predictive project'
@app.route('/predict', methods=['POST'])
def predict(message=""):
try:
# find authorization header
content = request.get_json(force=True)
message = f'POST respon... | from flask import Flask, request
def create_app():
| 11 | 64 | 109 | 4 | 6 | serinamarie/Saltiest-Hackers | airbnb/app.py | Python | create_app | create_app | 3 | 21 | 3 | 3 | 77660085c95ad9eecde519b5597009abee1b67e9 | bigcode/the-stack | train |
30952c7d2e8afddcd0903938 | train | function | def getBodyPart(Collection):
'''Provides the body part affected in a collection dataset'''
baseurl = 'https://services.cancerimagingarchive.net/services/v3/TCIA'
queryEndpoint = '/query/getBodyPartValues?'
queryParams = f'Collection={Collection}&'
form = 'format=json'
url = baseurl+queryEndpoint... | def getBodyPart(Collection):
| '''Provides the body part affected in a collection dataset'''
baseurl = 'https://services.cancerimagingarchive.net/services/v3/TCIA'
queryEndpoint = '/query/getBodyPartValues?'
queryParams = f'Collection={Collection}&'
form = 'format=json'
url = baseurl+queryEndpoint+queryParams+form
respons... | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import requests
import json
from tqdm import tqdm
pbar = tqdm(total=96)
def getBodyPart(Collection):
| 43 | 64 | 163 | 6 | 37 | deeprob/Predicting-the-survival-rate-of-patients-with-brain-cancer | gbp.py | Python | getBodyPart | getBodyPart | 11 | 29 | 11 | 11 | f3421586bf7c3f138ab207356e4bf751d6b0e37f | bigcode/the-stack | train |
27dbfcfc832af197310696e7 | train | function | def required_if(
depend_name=None,
op=None,
value=None,
checks=[],
error_msg="This field is required",
):
def check_field(form, field):
data = field.data
if isinstance(data, six.string_types):
data = data.strip()
if data:
return
checks_ =... | def required_if(
depend_name=None,
op=None,
value=None,
checks=[],
error_msg="This field is required",
):
| def check_field(form, field):
data = field.data
if isinstance(data, six.string_types):
data = data.strip()
if data:
return
checks_ = checks or [(depend_name, op, value)]
logics = 0
for dep_name, op_, val in checks_:
depend_data = ... | Error:
from flask_wtf import Form as FlaskForm
from wtforms.validators import ValidationError
__version__ = "2021.11.03"
def required_if(
depend_name=None,
op=None,
value=None,
checks=[],
error_msg="This field is required",
):
| 64 | 64 | 215 | 31 | 33 | lixxu/flask_wtf_top | flask_wtf_top/__init__.py | Python | required_if | required_if | 21 | 53 | 21 | 27 | 663dd0855cac4193d121bfd32d2d1b5981299b2a | bigcode/the-stack | train |
ec499996627115f181cf2b91 | train | class | class ToppingForm(FlaskForm):
__lowers__ = []
__uppers__ = []
__nostrips__ = []
__excludes__ = []
__aliases__ = {}
def parse_form(self, box_wrap=False):
lowers = self.get_attrs("lowers")
uppers = self.get_attrs("uppers")
nostrips = self.get_attrs("nostrips")
excl... | class ToppingForm(FlaskForm):
| __lowers__ = []
__uppers__ = []
__nostrips__ = []
__excludes__ = []
__aliases__ = {}
def parse_form(self, box_wrap=False):
lowers = self.get_attrs("lowers")
uppers = self.get_attrs("uppers")
nostrips = self.get_attrs("nostrips")
excludes = self.get_attrs("exclude... | dep_name).data
if isinstance(depend_data, six.string_types):
depend_data = depend_data.strip()
if depend_data:
func = getattr(operator, op_, None)
logic1 = func and func(depend_data, val)
logic2 = (not func) and getattr(depend_dat... | 117 | 117 | 393 | 9 | 107 | lixxu/flask_wtf_top | flask_wtf_top/__init__.py | Python | ToppingForm | ToppingForm | 56 | 112 | 56 | 56 | f8f2fe0f598235b0c0cc5b806deb60453f617bb8 | bigcode/the-stack | train |
9d39e68ce8143204411cf334 | train | class | class TestGet:
@pytest.fixture(autouse=True)
def setup(self, db):
self.last_example = Example.objects.last()
def test_get_all(self, client: TestClient):
response = client.get('/examples/')
assert response.status_code == 200
response_json: List[dict] = response.json()
... | class TestGet:
@pytest.fixture(autouse=True)
| def setup(self, db):
self.last_example = Example.objects.last()
def test_get_all(self, client: TestClient):
response = client.get('/examples/')
assert response.status_code == 200
response_json: List[dict] = response.json()
example_ids = [example.pop('id') for example in ... | import pytest
from typing import List
from fastapi.testclient import TestClient
from example.models import Example
class TestGet:
@pytest.fixture(autouse=True)
| 36 | 155 | 518 | 13 | 22 | vitornere/django-orm-async-adapter | example/example/tests/test_get.py | Python | TestGet | TestGet | 7 | 70 | 7 | 8 | 6c2043924dd94ab1129ee85dda61b459fb4363d1 | bigcode/the-stack | train |
574d7ece6c9f256b8a81853c | train | function | def get_package(data_dir):
if not isinstance(data_dir, six.string_types):
raise RuntimeError('data_dir must be a string')
return DirPackage(data_dir)
| def get_package(data_dir):
| if not isinstance(data_dir, six.string_types):
raise RuntimeError('data_dir must be a string')
return DirPackage(data_dir)
| import sputnik
from sputnik.dir_package import DirPackage
from sputnik.package_list import (PackageNotFoundException,
CompatiblePackageNotFoundException)
from . import about
def get_package(data_dir):
| 43 | 64 | 36 | 6 | 36 | jumbojett/sense2vec | sense2vec/util.py | Python | get_package | get_package | 9 | 12 | 9 | 9 | 882219512cf4fbc2d1a89cf9fa745c118f124a38 | bigcode/the-stack | train |
ae4880e210335071d98f602b | train | function | def get_package_by_name(name=None, via=None):
try:
return sputnik.package(about.title, about.version,
name or about.default_model, data_path=via)
except PackageNotFoundException as e:
raise RuntimeError("Model not installed. Please run 'python -m "
... | def get_package_by_name(name=None, via=None):
| try:
return sputnik.package(about.title, about.version,
name or about.default_model, data_path=via)
except PackageNotFoundException as e:
raise RuntimeError("Model not installed. Please run 'python -m "
"sense2vec.download' to install lat... | PackageNotFoundException,
CompatiblePackageNotFoundException)
from . import about
def get_package(data_dir):
if not isinstance(data_dir, six.string_types):
raise RuntimeError('data_dir must be a string')
return DirPackage(data_dir)
def get_package_by_name(name=None, ... | 64 | 64 | 129 | 11 | 53 | jumbojett/sense2vec | sense2vec/util.py | Python | get_package_by_name | get_package_by_name | 15 | 26 | 15 | 15 | 0bd9fceacf90f4e6cf3b8879a3280823d480e8de | bigcode/the-stack | train |
84ae35bd378c2475b25f2499 | train | function | @pytest.fixture(scope="module")
def newsCrawler():
logger.warning("Init News Crawler ...")
return ttv.TTVNewsCrawler()
| @pytest.fixture(scope="module")
def newsCrawler():
| logger.warning("Init News Crawler ...")
return ttv.TTVNewsCrawler()
| 2021-08-17T15:17:19+08:00",
link="https://news.ttv.com.tw/news/11008170002600W",
),
)
TEST_DATA_LIST = [TEST_DATA_1, TEST_DATA_2]
@pytest.fixture(scope="module")
def newsCrawler():
| 64 | 64 | 29 | 10 | 54 | allenyummy/GoodInfo | tests/crawler/media/test_ttv.py | Python | newsCrawler | newsCrawler | 54 | 57 | 54 | 55 | 9a581d95fe225e3230fa2a782dbf9fd2209e0f35 | bigcode/the-stack | train |
ebcffa068907b38456756113 | train | function | @pytest.mark.parametrize(
argnames="name, link, expected_output",
argvalues=[tuple(t) for t in TEST_DATA_LIST],
ids=[
f"{t.name}, {t.link[:50]+'...' if len(t.link) > 50 else t.link}"
for t in TEST_DATA_LIST
],
)
def test_get_info(
newsCrawler,
name,
link,
expected_output,... | @pytest.mark.parametrize(
argnames="name, link, expected_output",
argvalues=[tuple(t) for t in TEST_DATA_LIST],
ids=[
f"{t.name}, {t.link[:50]+'...' if len(t.link) > 50 else t.link}"
for t in TEST_DATA_LIST
],
)
def test_get_info(
newsCrawler,
name,
link,
expected_output,... | output = newsCrawler.getInfo(link=link)
assert NewsStruct.__2dict__(output) == NewsStruct.__2dict__(expected_output)
| @pytest.mark.parametrize(
argnames="name, link, expected_output",
argvalues=[tuple(t) for t in TEST_DATA_LIST],
ids=[
f"{t.name}, {t.link[:50]+'...' if len(t.link) > 50 else t.link}"
for t in TEST_DATA_LIST
],
)
def test_get_info(
newsCrawler,
name,
link,
expected_output,... | 89 | 64 | 120 | 89 | 0 | allenyummy/GoodInfo | tests/crawler/media/test_ttv.py | Python | test_get_info | test_get_info | 60 | 75 | 60 | 73 | dcf966348ccf7d3386e22dde9831a7d3b06f6688 | bigcode/the-stack | train |
a15dc923f809e7878b477b44 | train | function | def try_import_dataset(dataset):
if dataset not in DATASET_REGISTRY:
if dataset in SUPPORTED_DATASETS:
importlib.import_module(SUPPORTED_DATASETS[dataset])
else:
print(f"Failed to import {dataset} dataset.")
return False
return True
| def try_import_dataset(dataset):
| if dataset not in DATASET_REGISTRY:
if dataset in SUPPORTED_DATASETS:
importlib.import_module(SUPPORTED_DATASETS[dataset])
else:
print(f"Failed to import {dataset} dataset.")
return False
return True
| g and not issubclass(cls, torch_geometric.data.Dataset)):
raise ValueError("Dataset ({}: {}) must extend cogdl.data.Dataset".format(name, cls.__name__))
DATASET_REGISTRY[name] = cls
return cls
return register_dataset_cls
def try_import_dataset(dataset):
| 64 | 64 | 61 | 6 | 57 | cenyk1230/cogdl | cogdl/datasets/__init__.py | Python | try_import_dataset | try_import_dataset | 43 | 50 | 43 | 43 | 42e028db39167b2e5d48b20a123237a23c9c7f57 | bigcode/the-stack | train |
f91e3af1638a10d19402b4f1 | train | function | def build_dataset(args):
if not try_import_dataset(args.dataset):
assert hasattr(args, "task")
dataset = build_dataset_from_path(args.dataset, args.task)
if dataset is not None:
return dataset
exit(1)
return DATASET_REGISTRY[args.dataset]()
| def build_dataset(args):
| if not try_import_dataset(args.dataset):
assert hasattr(args, "task")
dataset = build_dataset_from_path(args.dataset, args.task)
if dataset is not None:
return dataset
exit(1)
return DATASET_REGISTRY[args.dataset]()
| _import_dataset(dataset):
if dataset not in DATASET_REGISTRY:
if dataset in SUPPORTED_DATASETS:
importlib.import_module(SUPPORTED_DATASETS[dataset])
else:
print(f"Failed to import {dataset} dataset.")
return False
return True
def build_dataset(args):
| 64 | 64 | 61 | 5 | 58 | cenyk1230/cogdl | cogdl/datasets/__init__.py | Python | build_dataset | build_dataset | 53 | 60 | 53 | 53 | 05cdc95aee046bb382039e262b34d9df4734da40 | bigcode/the-stack | train |
6f4a159f5e0ced85cd64c3d3 | train | function | def register_dataset(name):
"""
New dataset types can be added to cogdl with the :func:`register_dataset`
function decorator.
For example::
@register_dataset('my_dataset')
class MyDataset():
(...)
Args:
name (str): the name of the dataset
"""
def regis... | def register_dataset(name):
| """
New dataset types can be added to cogdl with the :func:`register_dataset`
function decorator.
For example::
@register_dataset('my_dataset')
class MyDataset():
(...)
Args:
name (str): the name of the dataset
"""
def register_dataset_cls(cls):
... | import importlib
from cogdl.data.dataset import Dataset
from .customized_data import NodeDataset, GraphDataset
try:
import torch_geometric
except ImportError:
pyg = False
else:
pyg = True
DATASET_REGISTRY = {}
def register_dataset(name):
| 59 | 64 | 169 | 5 | 54 | cenyk1230/cogdl | cogdl/datasets/__init__.py | Python | register_dataset | register_dataset | 17 | 40 | 17 | 17 | 7c697bcb96fee336ad841950344d2e083adfb388 | bigcode/the-stack | train |
9199f1c0e83b82467037f455 | train | function | def build_dataset_from_name(dataset):
if not try_import_dataset(dataset):
exit(1)
return DATASET_REGISTRY[dataset]()
| def build_dataset_from_name(dataset):
| if not try_import_dataset(dataset):
exit(1)
return DATASET_REGISTRY[dataset]()
| if not try_import_dataset(args.dataset):
assert hasattr(args, "task")
dataset = build_dataset_from_path(args.dataset, args.task)
if dataset is not None:
return dataset
exit(1)
return DATASET_REGISTRY[args.dataset]()
def build_dataset_from_name(dataset):
| 63 | 64 | 29 | 7 | 56 | cenyk1230/cogdl | cogdl/datasets/__init__.py | Python | build_dataset_from_name | build_dataset_from_name | 63 | 66 | 63 | 63 | 8c291ce7e02a6d292735c521828287a2e2380cc1 | bigcode/the-stack | train |
e94a2537f8de60e48d048543 | train | function | def build_dataset_from_path(data_path, task=None, dataset=None):
if dataset is not None and dataset in SUPPORTED_DATASETS:
if try_import_dataset(dataset):
return DATASET_REGISTRY[dataset](data_path=data_path)
if task is None:
return None
if "node_classification" in task:
... | def build_dataset_from_path(data_path, task=None, dataset=None):
| if dataset is not None and dataset in SUPPORTED_DATASETS:
if try_import_dataset(dataset):
return DATASET_REGISTRY[dataset](data_path=data_path)
if task is None:
return None
if "node_classification" in task:
return NodeDataset(data_path)
elif "graph_classification" in... | return dataset
exit(1)
return DATASET_REGISTRY[args.dataset]()
def build_dataset_from_name(dataset):
if not try_import_dataset(dataset):
exit(1)
return DATASET_REGISTRY[dataset]()
def build_dataset_from_path(data_path, task=None, dataset=None):
| 63 | 64 | 100 | 14 | 49 | cenyk1230/cogdl | cogdl/datasets/__init__.py | Python | build_dataset_from_path | build_dataset_from_path | 69 | 81 | 69 | 69 | 65f45be3b742723e2a769fd9b1db4b8aa01c9b5d | bigcode/the-stack | train |
684eb6280837554fdbe809f9 | train | function | def get_favorite_status(article_id):
article_not_found(article_id)
if models.FavoriteArticle.objects.filter(article=article_id).exists():
favorite_status = models.FavoriteArticle.objects.filter(
article=article_id)
favorite_statuses = serializers.FavoriteStatusSerializer(
... | def get_favorite_status(article_id):
| article_not_found(article_id)
if models.FavoriteArticle.objects.filter(article=article_id).exists():
favorite_status = models.FavoriteArticle.objects.filter(
article=article_id)
favorite_statuses = serializers.FavoriteStatusSerializer(
favorite_status, many=True)
... | _data.title,
"favorite_status": favorite_status,
"user": user
}
serializer = self.serializer_class(data=new_like_status)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
def get_favorite_status(article_id):
| 64 | 64 | 97 | 8 | 56 | andela/ah-backend-thanos | authors/apps/articles/favorites_crud.py | Python | get_favorite_status | get_favorite_status | 40 | 48 | 40 | 40 | 5eebeb558a3c205bad7658167f71c28705df7e81 | bigcode/the-stack | train |
b569863bb1142697e43a9073 | train | function | def favorite_an_article(self, request, article_pk):
user = validate_article_get_user(request, article_pk)
favorite_status = request.data.get('favorite_status')
if models.FavoriteArticle.objects.filter(user=user)\
.filter(article=article_pk)\
.exists... | def favorite_an_article(self, request, article_pk):
| user = validate_article_get_user(request, article_pk)
favorite_status = request.data.get('favorite_status')
if models.FavoriteArticle.objects.filter(user=user)\
.filter(article=article_pk)\
.exists():
raise NotAcceptable(detail="You have alr... | current_user_favorites = models.FavoriteArticle.objects.filter(
user=request.user, favorite_status=True)
serializer = serializers.GetFavoriteArticleSerializer(
current_user_favorites, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def favorite_an_article(self, request... | 64 | 64 | 161 | 11 | 53 | andela/ah-backend-thanos | authors/apps/articles/favorites_crud.py | Python | favorite_an_article | favorite_an_article | 19 | 37 | 19 | 19 | f8967cab5ed3bfa4bb5dca5b50e10326695126dc | bigcode/the-stack | train |
914046920542896268c0099f | train | function | def udpate_favorite(request, article_pk):
user = validate_article_get_user(request, article_pk)
current_favorite_status = models.FavoriteArticle.objects.filter(
user=user).get(article=article_pk)
favorite_status_update = request.data.get(
'favorite_status', current_favorite_status.favorite_... | def udpate_favorite(request, article_pk):
| user = validate_article_get_user(request, article_pk)
current_favorite_status = models.FavoriteArticle.objects.filter(
user=user).get(article=article_pk)
favorite_status_update = request.data.get(
'favorite_status', current_favorite_status.favorite_status)
if not models.FavoriteArticle.... | =article_id)
favorite_statuses = serializers.FavoriteStatusSerializer(
favorite_status, many=True)
return Response(favorite_statuses.data, status=status.HTTP_200_OK)
raise ParseError(detail="This article has not been favorited yet",)
def udpate_favorite(request, article_pk):
| 64 | 64 | 171 | 10 | 54 | andela/ah-backend-thanos | authors/apps/articles/favorites_crud.py | Python | udpate_favorite | udpate_favorite | 51 | 66 | 51 | 51 | efed3af28e11d108ffed10069c1ad3bc4471a40f | bigcode/the-stack | train |
8f5d98615cdf1a9277c3c598 | train | function | def list_favorites(request):
current_user_favorites = models.FavoriteArticle.objects.filter(
user=request.user, favorite_status=True)
serializer = serializers.GetFavoriteArticleSerializer(
current_user_favorites, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
| def list_favorites(request):
| current_user_favorites = models.FavoriteArticle.objects.filter(
user=request.user, favorite_status=True)
serializer = serializers.GetFavoriteArticleSerializer(
current_user_favorites, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
| .response import Response
from rest_framework import status
from rest_framework.exceptions import NotAcceptable, ParseError
from authors.apps.core.utils.article_management import (
validate_article_get_user)
from authors.apps.core.utils.article_management import (
article_not_found)
from . import models, serial... | 64 | 64 | 59 | 6 | 57 | andela/ah-backend-thanos | authors/apps/articles/favorites_crud.py | Python | list_favorites | list_favorites | 11 | 16 | 11 | 11 | f752a96ad51b8566c5e4ab5501e1a50688c9d52e | bigcode/the-stack | train |
1b9c2d2a09a397acbc33c263 | train | function | def get_redoc_html(title: str) -> str:
"""Gets the HTML template for rendering the ReDoc interactive documentation."""
redoc_script = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"
google_fonts = (
"https://fonts.googleapis.com/css?family=Montserrat:300,400,700|"
"Robo... | def get_redoc_html(title: str) -> str:
| """Gets the HTML template for rendering the ReDoc interactive documentation."""
redoc_script = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"
google_fonts = (
"https://fonts.googleapis.com/css?family=Montserrat:300,400,700|"
"Roboto:300,400,700"
)
html = f"""
... | """
A module for the interactive documentation renderers.
"""
from asymmetric.constants import OPENAPI_SPEC_ROUTE
def get_redoc_html(title: str) -> str:
| 32 | 72 | 241 | 12 | 19 | ink-splatters/asymmetric | asymmetric/openapi/docs.py | Python | get_redoc_html | get_redoc_html | 8 | 42 | 8 | 8 | 0dc57e422cbfb1dfe25e3d48397db6eb48d963be | bigcode/the-stack | train |
4b09dc3632c89ede7258c5b8 | train | function | def get_swagger_html(title: str) -> str:
"""Gets the HTML template for rendering the Swagger interactive documentation."""
swagger_js_url = (
"https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui-bundle.js"
)
swagger_css_url = (
"https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.3... | def get_swagger_html(title: str) -> str:
| """Gets the HTML template for rendering the Swagger interactive documentation."""
swagger_js_url = (
"https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui-bundle.js"
)
swagger_css_url = (
"https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui.css"
)
html = f""... | body {{
margin: 0;
padding: 0;
}}
</style>
</head>
<body>
<redoc spec-url="{OPENAPI_SPEC_ROUTE}">
</redoc>
<script src="{redoc_script}"></script>
</body>
</html>
"""
return html
def get_s... | 83 | 83 | 277 | 12 | 70 | ink-splatters/asymmetric | asymmetric/openapi/docs.py | Python | get_swagger_html | get_swagger_html | 45 | 82 | 45 | 45 | f547d516fb39f5c9444a14e5d235e468ea755694 | bigcode/the-stack | train |
733022ab34274090df1aaaf6 | train | function | def test_basic() -> None:
intermediate = build_intermediate_representation(get_test_case_path("basic"), GenerationConfiguration())
assert intermediate
| def test_basic() -> None:
| intermediate = build_intermediate_representation(get_test_case_path("basic"), GenerationConfiguration())
assert intermediate
| from json_schema_for_humans.intermediate_representation import build_intermediate_representation
from json_schema_for_humans.generation_configuration import GenerationConfiguration
from tests.test_utils import get_test_case_path
def test_basic() -> None:
| 49 | 64 | 29 | 7 | 41 | fchastanet/json-schema-for-humans | tests/intermediate_test.py | Python | test_basic | test_basic | 6 | 9 | 6 | 6 | 4516fdc9a9f08a8702f5dfb321835b5853425006 | bigcode/the-stack | train |
cc64448600c985a362467252 | train | function | def test_references() -> None:
intermediate = build_intermediate_representation(get_test_case_path("references"), GenerationConfiguration())
assert intermediate
| def test_references() -> None:
| intermediate = build_intermediate_representation(get_test_case_path("references"), GenerationConfiguration())
assert intermediate
| _representation
from json_schema_for_humans.generation_configuration import GenerationConfiguration
from tests.test_utils import get_test_case_path
def test_basic() -> None:
intermediate = build_intermediate_representation(get_test_case_path("basic"), GenerationConfiguration())
assert intermediate
def test_r... | 64 | 64 | 30 | 8 | 55 | fchastanet/json-schema-for-humans | tests/intermediate_test.py | Python | test_references | test_references | 12 | 15 | 12 | 12 | 4268fb5c0bad010d89dc80a351326a8ca2056537 | bigcode/the-stack | train |
62af663441d6561036bf07c9 | train | function | def main() -> None:
conf = OmegaConf.load(Path(__file__).parent / "configs" / "language_config.yaml")
conf.model_type = ModelType(conf.model_type)
writer = create_writer(Path("language-modeling"), conf.model_type, conf.seed)
device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
torch... | def main() -> None:
| conf = OmegaConf.load(Path(__file__).parent / "configs" / "language_config.yaml")
conf.model_type = ModelType(conf.model_type)
writer = create_writer(Path("language-modeling"), conf.model_type, conf.seed)
device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
torch.random.manual_seed(... | import math
from pathlib import Path
import sys
import traceback
import warnings
from omegaconf import OmegaConf
import torch
import torch.nn as nn
from torch.optim import AdamW
from torchtext.data import BPTTIterator
from torchtext.datasets import WikiText103
import tqdm
from models.language_model import LanguageMod... | 119 | 161 | 539 | 6 | 113 | r0mainK/ur-lstm | experiments/language_task.py | Python | main | main | 24 | 75 | 24 | 24 | 5d060243f26f2f0fd7a65c676cd8e52b469a2202 | bigcode/the-stack | train |
29228cbd5138011e2665c645 | train | function | def evaluate(model: nn.Module, generator: BPTTIterator, loss_fn: nn.CrossEntropyLoss):
model.eval()
total_loss = 0
n = 0
with torch.no_grad():
for batch in tqdm.tqdm(generator, desc="eval batch", leave=False):
output, _ = model(batch.text, None)
loss = loss_fn(output.view... | def evaluate(model: nn.Module, generator: BPTTIterator, loss_fn: nn.CrossEntropyLoss):
| model.eval()
total_loss = 0
n = 0
with torch.no_grad():
for batch in tqdm.tqdm(generator, desc="eval batch", leave=False):
output, _ = model(batch.text, None)
loss = loss_fn(output.view(-1, output.size(-1)), batch.target.view(-1))
total_loss += loss.item() * l... | model.state_dict())
file_name = output_dir / f"{conf.model_type}-{conf.seed}-vocab.pt"
torch.save(file_name, train_generator.dataset.fields["text"].vocab.itos)
def evaluate(model: nn.Module, generator: BPTTIterator, loss_fn: nn.CrossEntropyLoss):
| 64 | 64 | 128 | 22 | 42 | r0mainK/ur-lstm | experiments/language_task.py | Python | evaluate | evaluate | 78 | 89 | 78 | 78 | 5a7b210aa1984ff1c70051fe0cde476df543cd2c | bigcode/the-stack | train |
ed66f1307c816ffb47ee0567 | train | class | class Migration(migrations.Migration):
dependencies = [
("peeldb", "0009_agencyworklog"),
]
operations = [
migrations.AddField(
model_name="agencyworklog",
name="timegap",
field=models.CharField(default="", max_length=100),
preserve_default=F... | class Migration(migrations.Migration):
| dependencies = [
("peeldb", "0009_agencyworklog"),
]
operations = [
migrations.AddField(
model_name="agencyworklog",
name="timegap",
field=models.CharField(default="", max_length=100),
preserve_default=False,
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-02-14 18:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 71 | 7 | 46 | sanjay051099/try2- | peeldb/migrations/0010_agencyworklog_timegap.py | Python | Migration | Migration | 8 | 21 | 8 | 9 | e9faf353fbf3fc10eddd94b0c4f2806e95d51bdc | bigcode/the-stack | train |
68e8176b9bb5f9f6060e8369 | train | class | @register_api(provider='sina')
class StockMoneyFlow(MoneyFlowBase, Mixin):
__tablename__ = 'stock_money_flow'
code = Column(String(length=32))
name = Column(String(length=32))
# 收盘价
close = Column(Float)
change_pct = Column(Float)
turnover_rate = Column(Float)
# 净流入
net_inflows = ... | @register_api(provider='sina')
class StockMoneyFlow(MoneyFlowBase, Mixin):
| __tablename__ = 'stock_money_flow'
code = Column(String(length=32))
name = Column(String(length=32))
# 收盘价
close = Column(Float)
change_pct = Column(Float)
turnover_rate = Column(Float)
# 净流入
net_inflows = Column(Float)
# 净流入率
net_inflow_rate = Column(Float)
# 主力=超大单+... | (Float)
# 中单
net_medium_inflows = Column(Float)
net_medium_inflow_rate = Column(Float)
# 小单
net_small_inflows = Column(Float)
net_small_inflow_rate = Column(Float)
@register_api(provider='sina')
class StockMoneyFlow(MoneyFlowBase, Mixin):
| 70 | 70 | 236 | 20 | 50 | Evergreen2020/zvt | zvt/domain/misc/money_flow.py | Python | StockMoneyFlow | StockMoneyFlow | 47 | 79 | 47 | 48 | 816023194c553881149c66e7139590d7cb209039 | bigcode/the-stack | train |
e4b2cef8f3c0831d30d29743 | train | class | @register_api(provider='sina')
class BlockMoneyFlow(MoneyFlowBase, Mixin):
__tablename__ = 'block_money_flow'
code = Column(String(length=32))
name = Column(String(length=32))
# 收盘价
close = Column(Float)
change_pct = Column(Float)
turnover_rate = Column(Float)
# 净流入
net_inflows = ... | @register_api(provider='sina')
class BlockMoneyFlow(MoneyFlowBase, Mixin):
| __tablename__ = 'block_money_flow'
code = Column(String(length=32))
name = Column(String(length=32))
# 收盘价
close = Column(Float)
change_pct = Column(Float)
turnover_rate = Column(Float)
# 净流入
net_inflows = Column(Float)
# 净流入率
net_inflow_rate = Column(Float)
# 主力=超大单+... | , String, Float
from sqlalchemy.ext.declarative import declarative_base
from zvdata import Mixin
from zvdata.contract import register_schema, register_api
MoneyFlowBase = declarative_base()
# 板块资金流向
@register_api(provider='sina')
class BlockMoneyFlow(MoneyFlowBase, Mixin):
| 70 | 70 | 236 | 20 | 49 | Evergreen2020/zvt | zvt/domain/misc/money_flow.py | Python | BlockMoneyFlow | BlockMoneyFlow | 12 | 44 | 12 | 13 | 4ff53eae847383cc3203bb95e06a22155c8223a1 | bigcode/the-stack | train |
58fd68d0489b6efd33f4d8d7 | train | class | class ActivityUser(models.Model):
title = models.CharField(blank=True, null=True,
max_length=3, choices=TITLE_CHOICES)
name = models.CharField("Given Name", blank=True,
null=True, max_length=100)
employee_number = models.IntegerField(
"Employe... | class ActivityUser(models.Model):
| title = models.CharField(blank=True, null=True,
max_length=3, choices=TITLE_CHOICES)
name = models.CharField("Given Name", blank=True,
null=True, max_length=100)
employee_number = models.IntegerField(
"Employee Number", blank=True, null=True)
... | _plural = "Countries"
app_label = 'workflow'
# on save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Country, self).save()
# displayed in ... | 125 | 125 | 417 | 6 | 119 | michaelbukachi/Activity | workflow/models.py | Python | ActivityUser | ActivityUser | 232 | 278 | 232 | 232 | 3f346facae7d7bbf894e2059aca69e0101553c26 | bigcode/the-stack | train |
538f8537df5876018edfe4df | train | class | class AdminLevelThree(models.Model):
name = models.CharField("Admin Level 3", max_length=255, blank=True)
district = models.ForeignKey(
District, verbose_name="Admin Level 2", blank=True, null=True,
on_delete=models.SET_NULL)
create_date = models.DateTimeField(null=True, blank=True)
edit... | class AdminLevelThree(models.Model):
| name = models.CharField("Admin Level 3", max_length=255, blank=True)
district = models.ForeignKey(
District, verbose_name="Admin Level 2", blank=True, null=True,
on_delete=models.SET_NULL)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=Tru... | args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(District, self).save()
# displayed in admin templates
def __str__(self):
return self.name
class AdminLevelThree(models.Model):
| 64 | 64 | 194 | 7 | 56 | michaelbukachi/Activity | workflow/models.py | Python | AdminLevelThree | AdminLevelThree | 539 | 561 | 539 | 539 | 414d948d561f47c7f87675a34a78e72fb342322a | bigcode/the-stack | train |
fd73844982e3b45466424221 | train | class | class ProjectAgreement(models.Model):
agreement_key = models.UUIDField(default=uuid.uuid4, unique=True),
short = models.BooleanField(
default=True, verbose_name="Short Form (recommended)")
program = models.ForeignKey(
Program, verbose_name="Program", related_name="agreement",
on_dele... | class ProjectAgreement(models.Model):
| agreement_key = models.UUIDField(default=uuid.uuid4, unique=True),
short = models.BooleanField(
default=True, verbose_name="Short Form (recommended)")
program = models.ForeignKey(
Program, verbose_name="Program", related_name="agreement",
on_delete=models.CASCADE)
date_of_request... | Meta:
ordering = ('country', 'name', 'type')
verbose_name_plural = "Stakeholders"
# on save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
su... | 256 | 256 | 2,795 | 6 | 250 | michaelbukachi/Activity | workflow/models.py | Python | ProjectAgreement | ProjectAgreement | 1,020 | 1,293 | 1,020 | 1,020 | 907a8377e54f79b96cbd6f9bcd9884b26e1a61fb | bigcode/the-stack | train |
4aaaf45b10e7f5a8ee4c712f | train | class | class Currency(models.Model):
name = models.CharField("Currency Name", max_length=255)
symbol = models.CharField("Currency Symbol", max_length=10, blank=True)
code = models.CharField("Currency Code", max_length=20, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = mod... | class Currency(models.Model):
| name = models.CharField("Currency Name", max_length=255)
symbol = models.CharField("Currency Symbol", max_length=10, blank=True)
code = models.CharField("Currency Code", max_length=20, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, b... | , *args, **kwargs):
""" On save, update timestamps as appropriate """
if kwargs.pop('new_entry', True):
self.created = datetime.now()
else:
self.updated = datetime.now()
return super(ActivitySites, self).save(*args, **kwargs)
class Currency(models.Model):
| 64 | 64 | 159 | 5 | 59 | michaelbukachi/Activity | workflow/models.py | Python | Currency | Currency | 78 | 96 | 78 | 78 | f09a4dc8aad740273a7b38204a0e440524a45fdc | bigcode/the-stack | train |
d1d5294556f8b88ea05fe071 | train | class | class District(models.Model):
name = models.CharField("Admin Level 2", max_length=255, blank=True)
province = models.ForeignKey(
Province, verbose_name="Admin Level 1", on_delete=models.CASCADE)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True,... | class District(models.Model):
| name = models.CharField("Admin Level 2", max_length=255, blank=True)
province = models.ForeignKey(
Province, verbose_name="Admin Level 1", on_delete=models.CASCADE)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
... | , *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Province, self).save()
# displayed in admin templates
def __str__(self):
return self.name
class District(models.Model):
| 64 | 64 | 183 | 5 | 58 | michaelbukachi/Activity | workflow/models.py | Python | District | District | 515 | 536 | 515 | 515 | adb15b070992d06db1491f0b32545e01951eb833 | bigcode/the-stack | train |
ef94890276fe53490df02175 | train | class | class FormGuidance(models.Model):
form = models.CharField(max_length=135, null=True, blank=True)
guidance_link = models.URLField(max_length=200, null=True, blank=True)
guidance = models.TextField(null=True, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
class Meta:
or... | class FormGuidance(models.Model):
| form = models.CharField(max_length=135, null=True, blank=True)
guidance_link = models.URLField(max_length=200, null=True, blank=True)
guidance = models.TextField(null=True, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('create_date',)
def... | save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(ActivityBookmarks, self).save()
# Form Guidance
class FormGuidance(models.Model):
| 64 | 64 | 123 | 7 | 56 | michaelbukachi/Activity | workflow/models.py | Python | FormGuidance | FormGuidance | 307 | 322 | 307 | 307 | 6b3a7c0f531fef2564a0c9d2033800c213e87571 | bigcode/the-stack | train |
39b16752db6c90f0c8df68e5 | train | class | class Office(models.Model):
name = models.CharField("Office Name", max_length=255, blank=True)
code = models.CharField("Office Code", max_length=255, blank=True)
province = models.ForeignKey(
Province, verbose_name="Admin Level 1", on_delete=models.CASCADE)
create_date = models.DateTimeField(nul... | class Office(models.Model):
| name = models.CharField("Office Name", max_length=255, blank=True)
code = models.CharField("Office Code", max_length=255, blank=True)
province = models.ForeignKey(
Province, verbose_name="Admin Level 1", on_delete=models.CASCADE)
create_date = models.DateTimeField(null=True, blank=True)
edit... | , *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Village, self).save()
# displayed in admin templates
def __str__(self):
return self.name
class Office(models.Model):
| 64 | 64 | 192 | 5 | 58 | michaelbukachi/Activity | workflow/models.py | Python | Office | Office | 591 | 612 | 591 | 591 | a50cb6b51d8aced83b30218127580114298ec0e3 | bigcode/the-stack | train |
5dcfe05daada5562bdb0a8f5 | train | function | @receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
| @receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
| if created:
Token.objects.create(user=instance)
| progress'),
('awaiting approval', 'awaiting approval'),
('approved', 'approved'),
('rejected', 'rejected'),
)
# New user created generate a token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
| 64 | 64 | 38 | 26 | 37 | michaelbukachi/Activity | workflow/models.py | Python | create_auth_token | create_auth_token | 39 | 42 | 39 | 40 | 92cea3e44e8dbfb1e5d41b9a405c5fdd1136ae77 | bigcode/the-stack | train |
6363567555d2824daf7348f8 | train | class | class LoggedUser(models.Model):
username = models.CharField(max_length=30, primary_key=True)
country = models.CharField(max_length=100, blank=False)
email = models.CharField(max_length=100, blank=False,
default='user@hikaya.io')
def __str__(self):
return self.userna... | class LoggedUser(models.Model):
| username = models.CharField(max_length=30, primary_key=True)
country = models.CharField(max_length=100, blank=False)
email = models.CharField(max_length=100, blank=False,
default='user@hikaya.io')
def __str__(self):
return self.username
def login_user(sender, r... | on save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(ChecklistItem, self).save()
# displayed in admin templates
def __str__(self):
return... | 84 | 84 | 280 | 6 | 77 | michaelbukachi/Activity | workflow/models.py | Python | LoggedUser | LoggedUser | 1,643 | 1,687 | 1,643 | 1,643 | b86fe50905dbb7f489366bb7a3358758d26bb7e9 | bigcode/the-stack | train |
d84f51fb553e6f25fd54f5c4 | train | class | class ActivitySites(models.Model):
name = models.CharField(blank=True, null=True, max_length=255)
agency_name = models.CharField(blank=True, null=True, max_length=255)
agency_url = models.CharField(blank=True, null=True, max_length=255)
activity_report_url = models.CharField(blank=True, null=True,
... | class ActivitySites(models.Model):
| name = models.CharField(blank=True, null=True, max_length=255)
agency_name = models.CharField(blank=True, null=True, max_length=255)
agency_url = models.CharField(blank=True, null=True, max_length=255)
activity_report_url = models.CharField(blank=True, null=True,
... | new'),
('in progress', 'in progress'),
('awaiting approval', 'awaiting approval'),
('approved', 'approved'),
('rejected', 'rejected'),
)
# New user created generate a token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
... | 91 | 91 | 304 | 6 | 85 | michaelbukachi/Activity | workflow/models.py | Python | ActivitySites | ActivitySites | 45 | 75 | 45 | 45 | 7a7a5a1bacb4c7b4204ed2047a1f6fe275660f40 | bigcode/the-stack | train |
ca4f6f00fb8f2dbd4273a910 | train | function | def validate_image(image, width=IMAGE_SPEC['width'],
height=IMAGE_SPEC['height'],
limit_kb=IMAGE_SPEC['limit_kb']):
file_size = image.file.size
if file_size > limit_kb * 1024:
raise ValidationError("Max size of file is %s KB" % limit_kb)
w, h = get_image_dimensi... | def validate_image(image, width=IMAGE_SPEC['width'],
height=IMAGE_SPEC['height'],
limit_kb=IMAGE_SPEC['limit_kb']):
| file_size = image.file.size
if file_size > limit_kb * 1024:
raise ValidationError("Max size of file is %s KB" % limit_kb)
w, h = get_image_dimensions(image)
if w < width:
raise ValidationError("Min width is %s" % width)
if h < height:
raise ValidationError("Min height is %s" ... | self.name
IMAGE_SPEC = {
"width": 2000,
"height": 500,
"limit_kb": 100
}
def validate_image(image, width=IMAGE_SPEC['width'],
height=IMAGE_SPEC['height'],
limit_kb=IMAGE_SPEC['limit_kb']):
| 64 | 64 | 122 | 32 | 32 | michaelbukachi/Activity | workflow/models.py | Python | validate_image | validate_image | 106 | 116 | 106 | 108 | a4c2b94a24d4fb03a40361bd4cf9b5d3ab784b07 | bigcode/the-stack | train |
8a6d425d47c4158ea29df1d4 | train | class | class ProjectAgreementManager(models.Manager):
def get_approved(self):
return self.filter(approval="approved")
def get_open(self):
return self.filter(approval="")
def get_inprogress(self):
return self.filter(approval="in progress")
def get_awaiting_approval(self):
retu... | class ProjectAgreementManager(models.Manager):
| def get_approved(self):
return self.filter(approval="approved")
def get_open(self):
return self.filter(approval="")
def get_inprogress(self):
return self.filter(approval="in progress")
def get_awaiting_approval(self):
return self.filter(approval="awaiting approval")
... | , **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Stakeholder, self).save()
# displayed in admin templates
def __str__(self):
return self.name
class ProjectAgreementManager(models.Manager):
| 64 | 64 | 151 | 7 | 56 | michaelbukachi/Activity | workflow/models.py | Python | ProjectAgreementManager | ProjectAgreementManager | 993 | 1,017 | 993 | 993 | dfb6831eb6fdc8a0c43f43fea64dc21c8b9cee7d | bigcode/the-stack | train |
7980c02e14b46c45bda51ebd | train | class | class ProjectComplete(models.Model):
short = models.BooleanField(
default=True, verbose_name="Short Form (recommended)")
program = models.ForeignKey(
Program, null=True, blank=True, related_name="complete",
on_delete=models.SET_NULL)
project_agreement = models.OneToOneField(
... | class ProjectComplete(models.Model):
| short = models.BooleanField(
default=True, verbose_name="Short Form (recommended)")
program = models.ForeignKey(
Program, null=True, blank=True, related_name="complete",
on_delete=models.SET_NULL)
project_agreement = models.OneToOneField(
ProjectAgreement, verbose_name="Proje... | ")
if self.mc_estimated_budget is None:
self.mc_estimated_budget = Decimal("0.00")
if self.local_total_estimated_budget is None:
self.local_total_estimated_budget = Decimal("0.00")
if self.local_mc_estimated_budget is None:
self.local_mc_estimated_budget = Dec... | 256 | 256 | 1,969 | 6 | 249 | michaelbukachi/Activity | workflow/models.py | Python | ProjectComplete | ProjectComplete | 1,296 | 1,483 | 1,296 | 1,296 | 9ffcec4704d34ddda081fdd8d15917501abeca1e | bigcode/the-stack | train |
9c81817453a4bdce105013dd | train | class | class ApprovalAuthority(models.Model):
approval_user = models.ForeignKey(ActivityUser,
help_text='User with Approval Authority',
blank=True, null=True,
related_name="auth_approving",
... | class ApprovalAuthority(models.Model):
| approval_user = models.ForeignKey(ActivityUser,
help_text='User with Approval Authority',
blank=True, null=True,
related_name="auth_approving",
on_delete=models.SET... | = datetime.now()
self.edit_date = datetime.now()
super(Program, self).save()
@property
def countries(self):
return ', '.join([x.country for x in self.country.all()])
# displayed in admin templates
def __str__(self):
return str(self.name) or ''
class ApprovalAuthority(m... | 74 | 75 | 250 | 6 | 68 | michaelbukachi/Activity | workflow/models.py | Python | ApprovalAuthority | ApprovalAuthority | 462 | 489 | 462 | 462 | b32a581b10d27e11feb7027d2c3a8bc152d0fe18 | bigcode/the-stack | train |
05203baf10dab24d1aea6d12 | train | class | class ChecklistItem(models.Model):
item = models.CharField(max_length=255)
checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE)
in_file = models.BooleanField(default=False)
not_applicable = models.BooleanField(default=False)
global_item = models.BooleanField(default=False)
owner = ... | class ChecklistItem(models.Model):
| item = models.CharField(max_length=255)
checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE)
in_file = models.BooleanField(default=False)
not_applicable = models.BooleanField(default=False)
global_item = models.BooleanField(default=False)
owner = models.ForeignKey(
Activity... | args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Checklist, self).save()
# displayed in admin templates
def __str__(self):
return self.agreement
class ChecklistItem(models.Model):
| 64 | 64 | 200 | 6 | 57 | michaelbukachi/Activity | workflow/models.py | Python | ChecklistItem | ChecklistItem | 1,616 | 1,639 | 1,616 | 1,616 | 239ea393dee5a6adf83ae3a073e5d8cb190fd90e | bigcode/the-stack | train |
04120aa3f1fb30180ec13c77 | train | class | class Country(models.Model):
country = models.CharField("Country Name", max_length=255, blank=True)
organization = models.ForeignKey(
Organization, blank=True, null=True, on_delete=models.SET_NULL)
code = models.CharField("2 Letter Country Code", max_length=4, blank=True)
description = models.Te... | class Country(models.Model):
| country = models.CharField("Country Name", max_length=255, blank=True)
organization = models.ForeignKey(
Organization, blank=True, null=True, on_delete=models.SET_NULL)
code = models.CharField("2 Letter Country Code", max_length=4, blank=True)
description = models.TextField(
"Description... | # on save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Organization, self).save()
# displayed in admin templates
def __str__(self):
retur... | 80 | 81 | 273 | 5 | 75 | michaelbukachi/Activity | workflow/models.py | Python | Country | Country | 193 | 222 | 193 | 193 | caa45f433cf18c2e438bbccdcbd6c0264e3c5595 | bigcode/the-stack | train |
a014670cc02d2c138467eca3 | train | class | class SiteProfileManager(models.Manager):
def get_queryset(self):
return super(SiteProfileManager,
self).get_queryset().prefetch_related() \
.select_related('country', 'province', 'district',
'admin_level_three', 'type')
| class SiteProfileManager(models.Manager):
| def get_queryset(self):
return super(SiteProfileManager,
self).get_queryset().prefetch_related() \
.select_related('country', 'province', 'district',
'admin_level_three', 'type')
| kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(LandType, self).save()
# displayed in admin templates
def __str__(self):
return self.classify_land
class SiteProfileManager(models.Manager):
| 64 | 64 | 54 | 7 | 56 | michaelbukachi/Activity | workflow/models.py | Python | SiteProfileManager | SiteProfileManager | 657 | 662 | 657 | 657 | 8a46216a94b5da5b40a67a9a241162eea2791ce8 | bigcode/the-stack | train |
95469ab82b8a7d3d435d3102 | train | class | class Budget(models.Model):
contributor = models.CharField(max_length=135, blank=True, null=True)
description_of_contribution = models.CharField(
max_length=255, blank=True, null=True)
proposed_value = models.IntegerField(
"Value", default=0, blank=True, null=True)
agreement = models.For... | class Budget(models.Model):
| contributor = models.CharField(max_length=135, blank=True, null=True)
description_of_contribution = models.CharField(
max_length=255, blank=True, null=True)
proposed_value = models.IntegerField(
"Value", default=0, blank=True, null=True)
agreement = models.ForeignKey(ProjectAgreement, bl... |
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Benchmarks, self).save()
# displayed in admin templates
def __str__(self):
return self.description
class Budget(models.Model):
| 70 | 70 | 234 | 5 | 64 | michaelbukachi/Activity | workflow/models.py | Python | Budget | Budget | 1,560 | 1,587 | 1,560 | 1,560 | 71e2f12956a9140c0b06b564f90f46a416e55e4c | bigcode/the-stack | train |
11e7b2939d4b9e1616cd7a6f | train | class | class ProjectType(models.Model):
name = models.CharField("Type of Activity", max_length=135)
description = models.CharField(max_length=765)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
# on save add create date or update edit date... | class ProjectType(models.Model):
| name = models.CharField("Type of Activity", max_length=135)
description = models.CharField(max_length=765)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
# on save add create date or update edit date
def save(self, *args, **kwar... | *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Evaluate, self).save()
# displayed in admin templates
def __str__(self):
return self.evaluate
class ProjectType(models.Model):
| 64 | 64 | 140 | 6 | 57 | michaelbukachi/Activity | workflow/models.py | Python | ProjectType | ProjectType | 882 | 899 | 882 | 882 | 3d2aa987e2a72f1cd1e5acd731b66d9cfdd42c12 | bigcode/the-stack | train |
becfe9b8dd0d5051f6ef6c88 | train | class | class SiteProfile(models.Model):
profile_key = models.UUIDField(default=uuid.uuid4, unique=True),
name = models.CharField("Site Name", max_length=255, blank=False)
type = models.ForeignKey(ProfileType, blank=True,
null=True, on_delete=models.SET_NULL)
office = models.Foreign... | class SiteProfile(models.Model):
| profile_key = models.UUIDField(default=uuid.uuid4, unique=True),
name = models.CharField("Site Name", max_length=255, blank=False)
type = models.ForeignKey(ProfileType, blank=True,
null=True, on_delete=models.SET_NULL)
office = models.ForeignKey(
Office, blank=True, ... | self.edit_date = datetime.now()
super(ProfileType, self).save()
# displayed in admin templates
def __str__(self):
return self.profile
class LandType(models.Model):
classify_land = models.CharField(
"Land Classification", help_text="Rural, Urban, Peri-Urban",
max_le... | 256 | 256 | 1,689 | 6 | 250 | michaelbukachi/Activity | workflow/models.py | Python | SiteProfile | SiteProfile | 665 | 812 | 665 | 665 | 91d643b13484eec5b6992ae30d6d5335f9c7d5e2 | bigcode/the-stack | train |
13c3297c3a5ce4d167fb1843 | train | class | class Sector(models.Model):
sector = models.CharField("Sector Name", max_length=255, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('sector',)
# on save add create date or update edit dat... | class Sector(models.Model):
| sector = models.CharField("Sector Name", max_length=255, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('sector',)
# on save add create date or update edit date
def save(self, *args, ... | , blank=True)
class Meta:
ordering = ('create_date',)
def save(self):
if self.create_date is None:
self.create_date = datetime.now()
super(FormGuidance, self).save()
def __str__(self):
return self.form
class Sector(models.Model):
| 64 | 64 | 139 | 5 | 58 | michaelbukachi/Activity | workflow/models.py | Python | Sector | Sector | 325 | 342 | 325 | 325 | 98c57f667bfc009d30f0624b54090441246eacdd | bigcode/the-stack | train |
4207d503e543ba501bb75383 | train | class | class ActivityUserOrganizationGroup(models.Model):
"""
This models tracks user permissions for all organizations they have access to
"""
uuid = models.UUIDField('ActivityUser Organization Group UUUID',
unique=True, editable=False, default=uuid.uuid4)
activity_user = model... | class ActivityUserOrganizationGroup(models.Model):
| """
This models tracks user permissions for all organizations they have access to
"""
uuid = models.UUIDField('ActivityUser Organization Group UUUID',
unique=True, editable=False, default=uuid.uuid4)
activity_user = models.ForeignKey(ActivityUser, related_name='activity_u... | )
status = models.CharField(
'Invitation Status', max_length=35, choices=INVITE_STATUSES, default='pending')
invite_date = models.DateTimeField('Invitation DAte', auto_now_add=True)
class Meta:
ordering = ('invite_date',)
def __str__(self):
return '{}'.format(self.email)
class ... | 82 | 82 | 274 | 8 | 74 | michaelbukachi/Activity | workflow/models.py | Python | ActivityUserOrganizationGroup | ActivityUserOrganizationGroup | 1,731 | 1,759 | 1,731 | 1,731 | 91f1472b9c72484d54e4ebff34b648be9f3b4d23 | bigcode/the-stack | train |
0d02075dc06cbd0fd25d2ffb | train | class | class Program(models.Model):
FUNDING_STATUSES = (
('open', 'Open'),
('in_negotiation', 'In Negotiation'),
('signed', 'Signed'),
('Awarded', 'Awarded'),
('Closed', 'Closed'),
)
program_uuid = models.UUIDField(
editable=False, verbose_name='Program UUID', defau... | class Program(models.Model):
| FUNDING_STATUSES = (
('open', 'Open'),
('in_negotiation', 'In Negotiation'),
('signed', 'Signed'),
('Awarded', 'Awarded'),
('Closed', 'Closed'),
)
program_uuid = models.UUIDField(
editable=False, verbose_name='Program UUID', default=uuid.uuid4, unique=True)
... | stakeholder = models.ForeignKey(
'Stakeholder', related_name='stakeholder', null=True, blank=True,
on_delete=models.SET_NULL)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('name',)
#... | 154 | 154 | 515 | 5 | 149 | michaelbukachi/Activity | workflow/models.py | Python | Program | Program | 404 | 459 | 404 | 404 | d04cb566f663a299adfc154ca9d12d854dfc9382 | bigcode/the-stack | train |
711c581dba618a865eaf3e5f | train | class | class Evaluate(models.Model):
evaluate = models.CharField(
"How will you evaluate the outcome or impact of the project?",
max_length=255, blank=True, null=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
... | class Evaluate(models.Model):
| evaluate = models.CharField(
"How will you evaluate the outcome or impact of the project?",
max_length=255, blank=True, null=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('evaluate'... | args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(StakeholderType, self).save()
# displayed in admin templates
def __str__(self):
return self.name
class Evaluate(models.Model):
| 64 | 64 | 160 | 5 | 58 | michaelbukachi/Activity | workflow/models.py | Python | Evaluate | Evaluate | 859 | 879 | 859 | 859 | 64ad5014fe101ec1f19d9822361d12334db9dd47 | bigcode/the-stack | train |
975d302d322aa70673573000 | train | class | class Documentation(models.Model):
name = models.CharField(
'Document Name', max_length=135, blank=True, null=True)
url = models.CharField(
'URL (Link to document or folder)', blank=True, null=True,
max_length=135)
description = models.TextField(max_length=255, blank=True, null=True)... | class Documentation(models.Model):
| name = models.CharField(
'Document Name', max_length=135, blank=True, null=True)
url = models.CharField(
'URL (Link to document or folder)', blank=True, null=True,
max_length=135)
description = models.TextField(max_length=255, blank=True, null=True)
template = models.ForeignKey(
... | self.edit_date = datetime.now()
super(ProjectComplete, self).save()
# displayed in admin templates
def __str__(self):
new_name = "{} - {}".format(self.office, self.project_name)
return new_name
@property
def project_name_clean(self):
return self.project_name.encode('as... | 90 | 90 | 300 | 5 | 84 | michaelbukachi/Activity | workflow/models.py | Python | Documentation | Documentation | 1,487 | 1,520 | 1,487 | 1,487 | 3e0470937157c7b65817b6a1297fae7c9e2b23ed | bigcode/the-stack | train |
ad5d2d2c6bde9f719e47ddd4 | train | class | class StakeholderType(models.Model):
name = models.CharField(
"Stakeholder Type", max_length=255, blank=True, null=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('name',)
verbose_nam... | class StakeholderType(models.Model):
| name = models.CharField(
"Stakeholder Type", max_length=255, blank=True, null=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('name',)
verbose_name_plural = "Stakeholder Types"
#... | , **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Capacity, self).save()
# displayed in admin templates
def __str__(self):
return self.capacity
class StakeholderType(models.Model):
| 64 | 64 | 157 | 7 | 56 | michaelbukachi/Activity | workflow/models.py | Python | StakeholderType | StakeholderType | 837 | 856 | 837 | 837 | ae1559d86f79af27e6da0bb20901bbd2be551cf3 | bigcode/the-stack | train |
06e82975b518a81758feb351 | train | class | class Village(models.Model):
name = models.CharField("Admin Level 4", max_length=255, blank=True)
district = models.ForeignKey(
District, null=True, blank=True, on_delete=models.SET_NULL)
admin_3 = models.ForeignKey(AdminLevelThree, verbose_name="Admin Level 3",
null=... | class Village(models.Model):
| name = models.CharField("Admin Level 4", max_length=255, blank=True)
district = models.ForeignKey(
District, null=True, blank=True, on_delete=models.SET_NULL)
admin_3 = models.ForeignKey(AdminLevelThree, verbose_name="Admin Level 3",
null=True, blank=True,
... | *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(AdminLevelThree, self).save()
# displayed in admin templates
def __str__(self):
return self.name
class Village(models.Model):
| 64 | 64 | 216 | 5 | 58 | michaelbukachi/Activity | workflow/models.py | Python | Village | Village | 564 | 588 | 564 | 564 | d719671bb199f54c05980bea345f90f8f59daff0 | bigcode/the-stack | train |
d259ed058403d1d74810746a | train | class | class Template(models.Model):
name = models.CharField("Name of Document", max_length=135)
documentation_type = models.CharField("Type (File or URL)", max_length=135)
description = models.CharField(max_length=765)
file_field = models.FileField(upload_to="uploads", blank=True, null=True)
create_date =... | class Template(models.Model):
| name = models.CharField("Name of Document", max_length=135)
documentation_type = models.CharField("Type (File or URL)", max_length=135)
description = models.CharField(max_length=765)
file_field = models.FileField(upload_to="uploads", blank=True, null=True)
create_date = models.DateTimeField(null=Tru... | **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(ProjectType, self).save()
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
class Template(models.Model):
| 64 | 64 | 176 | 5 | 59 | michaelbukachi/Activity | workflow/models.py | Python | Template | Template | 902 | 921 | 902 | 902 | 9cf5ca6b4ad5eab8362dc7815993a030d2c8989a | bigcode/the-stack | train |
01e0e36e66066ec6bd318a3e | train | class | class Province(models.Model):
name = models.CharField("Admin Level 1", max_length=255, blank=True)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ord... | class Province(models.Model):
| name = models.CharField("Admin Level 1", max_length=255, blank=True)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('name',)
verb... | .now()
self.edit_date = datetime.now()
super(ApprovalAuthority, self).save()
# displayed in admin templates
def __str__(self):
return self.approval_user.user.first_name + " " + \
self.approval_user.user.last_name
class Province(models.Model):
| 64 | 64 | 174 | 5 | 58 | michaelbukachi/Activity | workflow/models.py | Python | Province | Province | 492 | 512 | 492 | 492 | 0ade443bc794dbd995a57ba29e65d0821ed63a16 | bigcode/the-stack | train |
e0955cad0a9ff9ddffe7679e | train | class | class Checklist(models.Model):
name = models.CharField(max_length=255, null=True,
blank=True, default="Checklist")
agreement = models.ForeignKey(ProjectAgreement, null=True, blank=True,
verbose_name="Project Initiation",
... | class Checklist(models.Model):
| name = models.CharField(max_length=255, null=True,
blank=True, default="Checklist")
agreement = models.ForeignKey(ProjectAgreement, null=True, blank=True,
verbose_name="Project Initiation",
on_delete=models.SET_NULL)... | ):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Budget, self).save()
def __str__(self):
return self.contributor
class Meta:
ordering = ('contributor',)
class Checklist(models.Model):
| 64 | 64 | 194 | 5 | 59 | michaelbukachi/Activity | workflow/models.py | Python | Checklist | Checklist | 1,590 | 1,613 | 1,590 | 1,590 | 4d1c59631944295bc322e7a00195cf349e74a3e4 | bigcode/the-stack | train |
8aabbfc5ec5c298f76788534 | train | class | class FundCode(models.Model):
name = models.CharField('Fund Code', max_length=255, blank=True)
stakeholder = models.ForeignKey(
'Stakeholder', related_name='stakeholder', null=True, blank=True,
on_delete=models.SET_NULL)
create_date = models.DateTimeField(null=True, blank=True)
edit_date... | class FundCode(models.Model):
| name = models.CharField('Fund Code', max_length=255, blank=True)
stakeholder = models.ForeignKey(
'Stakeholder', related_name='stakeholder', null=True, blank=True,
on_delete=models.SET_NULL)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=T... | , self).save()
# displayed in admin templates
def __str__(self):
return u'%s, %s' % (self.name, self.title)
# For programs that have custom dashboards. The default dashboard for all
# other programs is 'Program Dashboard'
class FundCode(models.Model):
| 64 | 64 | 173 | 6 | 58 | michaelbukachi/Activity | workflow/models.py | Python | FundCode | FundCode | 381 | 401 | 381 | 381 | 684d4cc46d73c3da01ec0036d8d2ecf31529ff67 | bigcode/the-stack | train |
708e6af39c124706d53cc5f7 | train | class | class ProfileType(models.Model):
profile = models.CharField("Profile Type", max_length=255, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('profile',)
# on save add create date or update ... | class ProfileType(models.Model):
| profile = models.CharField("Profile Type", max_length=255, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('profile',)
# on save add create date or update edit date
def save(self, *arg... | self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Office, self).save()
# displayed in admin templates
def __str__(self):
new_name = self.name + " - " + self.code
return new_name
class ProfileType(models.Model):
| 64 | 64 | 138 | 6 | 57 | michaelbukachi/Activity | workflow/models.py | Python | ProfileType | ProfileType | 615 | 632 | 615 | 615 | ace13b9088fd19c46530bbc0d666de8fc2921ca0 | bigcode/the-stack | train |
4c1bf8adc17f6c3d017599e5 | train | class | class Capacity(models.Model):
capacity = models.CharField(
"Capacity", max_length=255, blank=True, null=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('capacity',)
verbose_name_plura... | class Capacity(models.Model):
| capacity = models.CharField(
"Capacity", max_length=255, blank=True, null=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('capacity',)
verbose_name_plural = "Capacity"
# on save ... | if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(SiteProfile, self).save()
# displayed in admin templates
def __str__(self):
new_name = self.name
return new_name
class Capacity(models.Model):
| 64 | 64 | 150 | 5 | 58 | michaelbukachi/Activity | workflow/models.py | Python | Capacity | Capacity | 815 | 834 | 815 | 815 | 62741f07f8d730151dd7e153d3c0171b5f40b5a6 | bigcode/the-stack | train |
b4ee3c17ae092a0e9ecdf7d3 | train | class | class Organization(models.Model):
name = models.CharField("Organization Name",
max_length=255, blank=True, default="Hikaya")
description = models.TextField(
"Description/Notes", max_length=765, null=True, blank=True)
organization_url = models.CharField(
'URL', bla... | class Organization(models.Model):
| name = models.CharField("Organization Name",
max_length=255, blank=True, default="Hikaya")
description = models.TextField(
"Description/Notes", max_length=765, null=True, blank=True)
organization_url = models.CharField(
'URL', blank=True, null=True, max_length=255... | , *args, **kwargs):
if self.create_date is None:
self.create_date = timezone.now()
self.edit_date = timezone.now()
super(Currency, self).save()
def __unicode__(self):
return self.name
IMAGE_SPEC = {
"width": 2000,
"height": 500,
"limit_kb": 100
}
def vali... | 208 | 208 | 695 | 5 | 203 | michaelbukachi/Activity | workflow/models.py | Python | Organization | Organization | 119 | 190 | 119 | 119 | 9b0141a739ad7c42fe188ecc838a7980f27b9d89 | bigcode/the-stack | train |
90229e84f090fd0c0b8df187 | train | class | class Benchmarks(models.Model):
percent_complete = models.IntegerField("% complete", blank=True, null=True)
percent_cumulative = models.IntegerField(
"% cumulative completion", blank=True, null=True)
est_start_date = models.DateTimeField(null=True, blank=True)
est_end_date = models.DateTimeField... | class Benchmarks(models.Model):
| percent_complete = models.IntegerField("% complete", blank=True, null=True)
percent_cumulative = models.IntegerField(
"% cumulative completion", blank=True, null=True)
est_start_date = models.DateTimeField(null=True, blank=True)
est_end_date = models.DateTimeField(null=True, blank=True)
actu... | save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Documentation, self).save()
def __str__(self):
return self.name
@property
def name_n_url(self):
return "%s %s" % (self.name... | 105 | 105 | 351 | 6 | 99 | michaelbukachi/Activity | workflow/models.py | Python | Benchmarks | Benchmarks | 1,523 | 1,557 | 1,523 | 1,523 | c719147ab202f7c0843bde6adb1e488e8c41be73 | bigcode/the-stack | train |
5d2071de3d4393013437cd37 | train | class | class Contact(models.Model):
name = models.CharField("Name", max_length=255, blank=True, null=True)
title = models.CharField("Title", max_length=255, blank=True, null=True)
city = models.CharField("City/Town", max_length=255, blank=True, null=True)
address = models.TextField(
"Address", max_leng... | class Contact(models.Model):
| name = models.CharField("Name", max_length=255, blank=True, null=True)
title = models.CharField("Title", max_length=255, blank=True, null=True)
city = models.CharField("City/Town", max_length=255, blank=True, null=True)
address = models.TextField(
"Address", max_length=255, blank=True, null=True... | .DateTimeField(null=True, blank=True)
class Meta:
ordering = ('sector',)
# on save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Sector, s... | 102 | 103 | 344 | 5 | 97 | michaelbukachi/Activity | workflow/models.py | Python | Contact | Contact | 345 | 376 | 345 | 345 | dfce558b3e3a370f6cd1ac2902e55b30a4373b36 | bigcode/the-stack | train |
894a3049166c01fffbb68f8d | train | class | class Stakeholder(models.Model):
name = models.CharField("Stakeholder/Organization Name",
max_length=255, blank=True, null=True)
type = models.ForeignKey(StakeholderType, blank=True,
null=True, on_delete=models.SET_NULL)
contact = models.ManyToManyFie... | class Stakeholder(models.Model):
| name = models.CharField("Stakeholder/Organization Name",
max_length=255, blank=True, null=True)
type = models.ForeignKey(StakeholderType, blank=True,
null=True, on_delete=models.SET_NULL)
contact = models.ManyToManyField(
Contact, related_name... | )
edit_date = models.DateTimeField(null=True, blank=True)
# on save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Template, self).save()
def _... | 158 | 158 | 528 | 6 | 152 | michaelbukachi/Activity | workflow/models.py | Python | Stakeholder | Stakeholder | 932 | 990 | 932 | 932 | f699d20af29d172e2781ba9f953235f7452ca1af | bigcode/the-stack | train |
162227ddf9c33e07535c913f | train | function | def get_user_country(request):
# Automatically geolocate the connecting IP
ip = request.META.get('REMOTE_ADDR')
try:
response = urlopen('http://ipinfo.io/' + ip + '/json').read()
response = json.loads(response)
return response['country'].lower()
except Exception as e:
re... | def get_user_country(request):
# Automatically geolocate the connecting IP
| ip = request.META.get('REMOTE_ADDR')
try:
response = urlopen('http://ipinfo.io/' + ip + '/json').read()
response = json.loads(response)
return response['country'].lower()
except Exception as e:
response = "undefined"
return response
| kwargs):
try:
user = LoggedUser.objects.get(pk=user.username)
user.delete()
except LoggedUser.DoesNotExist:
pass
user_logged_in.connect(login_user)
user_logged_out.connect(logout_user)
def get_user_country(request):
# Automatically geolocate the connect... | 64 | 64 | 81 | 16 | 48 | michaelbukachi/Activity | workflow/models.py | Python | get_user_country | get_user_country | 1,690 | 1,700 | 1,690 | 1,691 | 08288c0e730958cba74b6c31a40a7725066403f8 | bigcode/the-stack | train |
151c3b15b1aa46b0f01567e2 | train | class | class StakeholderManager(models.Manager):
def get_queryset(self):
return super(StakeholderManager, self).get_queryset().prefetch_related(
'contact', 'sectors').select_related('country', 'type',
'formal_relationship_document',
... | class StakeholderManager(models.Manager):
| def get_queryset(self):
return super(StakeholderManager, self).get_queryset().prefetch_related(
'contact', 'sectors').select_related('country', 'type',
'formal_relationship_document',
'vetting_docum... | ):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(Template, self).save()
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
class StakeholderManager(models.Manager):
| 64 | 64 | 58 | 7 | 57 | michaelbukachi/Activity | workflow/models.py | Python | StakeholderManager | StakeholderManager | 924 | 929 | 924 | 924 | 0c29b357a7d3327207261f625f771ba7853b753f | bigcode/the-stack | train |
c6ea92b1fe091d0400fe30b2 | train | class | class UserInvite(models.Model):
"""
store user invitations
"""
invite_uuid = models.UUIDField(
'Invite UUUID', unique=True, editable=False, default=uuid.uuid4)
email = models.CharField('Email Address', max_length=255)
organization = models.ForeignKey(
Organization, verbose_name='... | class UserInvite(models.Model):
| """
store user invitations
"""
invite_uuid = models.UUIDField(
'Invite UUUID', unique=True, editable=False, default=uuid.uuid4)
email = models.CharField('Email Address', max_length=255)
organization = models.ForeignKey(
Organization, verbose_name='Organization', on_delete=models.... | return response['country'].lower()
except Exception as e:
response = "undefined"
return response
# invitation statuse
INVITE_STATUSES = (
('accepted', 'Accepted'),
('pending', 'pending'),
('rejected', 'Rejected')
)
class UserInvite(models.Model):
| 64 | 64 | 149 | 6 | 58 | michaelbukachi/Activity | workflow/models.py | Python | UserInvite | UserInvite | 1,711 | 1,728 | 1,711 | 1,711 | a6fff5e7dad3f153d77ac996b948171830127439 | bigcode/the-stack | train |
7b54ab23a7862c5e95ede7c5 | train | class | class ActivityBookmarks(models.Model):
user = models.ForeignKey(
ActivityUser, related_name='activitybookmark',
on_delete=models.CASCADE)
name = models.CharField(blank=True, null=True, max_length=255)
bookmark_url = models.CharField(blank=True, null=True, max_length=255)
program = models... | class ActivityBookmarks(models.Model):
| user = models.ForeignKey(
ActivityUser, related_name='activitybookmark',
on_delete=models.CASCADE)
name = models.CharField(blank=True, null=True, max_length=255)
bookmark_url = models.CharField(blank=True, null=True, max_length=255)
program = models.ForeignKey(
"Program", blank=T... | ()])
# on save add create date or update edit date
def save(self, *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(ActivityUser, self).save()
class ActivityBookmarks(models.Model):
| 64 | 64 | 194 | 6 | 58 | michaelbukachi/Activity | workflow/models.py | Python | ActivityBookmarks | ActivityBookmarks | 281 | 303 | 281 | 281 | fa4ff8912659e1d349f4dfdae8b6233f5a68d53e | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.