code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class ConfigureAction(argparse.Action): <NEW_LINE> <INDENT> def __init__(self, option_strings, dest, **kwargs): <NEW_LINE> <INDENT> kwargs['nargs'] = 1 <NEW_LINE> kwargs['const'] = None <NEW_LINE> kwargs.setdefault('default','cauldron.cfg') <NEW_LINE> kwargs['type'] = str <NEW_LINE> kwargs['choices'] = None <NEW_LINE> kwargs.setdefault('required', False) <NEW_LINE> kwargs.setdefault('help', "The Cauldron configuration file.") <NEW_LINE> kwargs.setdefault('metavar', 'configuration') <NEW_LINE> super(ConfigureAction, self).__init__(option_strings, dest, **kwargs) <NEW_LINE> <DEDENT> def __call__(self, parser, namespace, values, option_string): <NEW_LINE> <INDENT> setattr(namespace, self.dest, values[0]) | An action to configure Cauldron. | 62598f9e6fb2d068a7693d2a |
class MinSavingPercent(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(MinSavingPercent, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MinSavingPercent): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598f9ea17c0f6771d5c027 |
class TarotUserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Tarotuser <NEW_LINE> fields = ("username", ) | JSON serializer for Tarotuser info in profile detail view | 62598f9e60cbc95b06364139 |
class ItemView(widgetset.TableView): <NEW_LINE> <INDENT> def __init__(self, model, custom_headers=False): <NEW_LINE> <INDENT> widgetset.TableView.__init__(self, model, custom_headers=custom_headers) <NEW_LINE> self.set_fixed_height(True) <NEW_LINE> self.allow_multiple_select = True <NEW_LINE> self.create_signal('scroll-position-changed') | TableView that displays a list of items. | 62598f9ee5267d203ee6b6fa |
class Typename: <NEW_LINE> <INDENT> namespaces_name_rule = delimitedList(IDENT, "::") <NEW_LINE> instantiation_name_rule = delimitedList(IDENT, "::") <NEW_LINE> rule = ( namespaces_name_rule("namespaces_and_name") ).setParseAction(lambda t: Typename(t)) <NEW_LINE> def __init__(self, t: ParseResults, instantiations: Sequence[ParseResults] = ()): <NEW_LINE> <INDENT> self.name = t[-1] <NEW_LINE> self.namespaces = t[:-1] <NEW_LINE> if self.namespaces and self.namespaces[0] == '': <NEW_LINE> <INDENT> self.namespaces.pop(0) <NEW_LINE> <DEDENT> if instantiations: <NEW_LINE> <INDENT> if isinstance(instantiations, Sequence): <NEW_LINE> <INDENT> self.instantiations = instantiations <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.instantiations = instantiations.asList() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.instantiations = [] <NEW_LINE> <DEDENT> if self.name in ["Matrix", "Vector"] and not self.namespaces: <NEW_LINE> <INDENT> self.namespaces = ["gtsam"] <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def from_parse_result(parse_result: Union[str, list]): <NEW_LINE> <INDENT> return parse_result[0] <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return self.to_cpp() <NEW_LINE> <DEDENT> def instantiated_name(self) -> str: <NEW_LINE> <INDENT> res = self.name <NEW_LINE> for instantiation in self.instantiations: <NEW_LINE> <INDENT> res += instantiation.instantiated_name() <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def qualified_name(self): <NEW_LINE> <INDENT> return "::".join(self.namespaces + [self.name]) <NEW_LINE> <DEDENT> def to_cpp(self) -> str: <NEW_LINE> <INDENT> idx = 1 if self.namespaces and not self.namespaces[0] else 0 <NEW_LINE> if self.instantiations: <NEW_LINE> <INDENT> cpp_name = self.name + "<{}>".format(", ".join( [inst.to_cpp() for inst in self.instantiations])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cpp_name = self.name <NEW_LINE> <DEDENT> return '{}{}{}'.format( "::".join(self.namespaces), "::" if self.namespaces else "", cpp_name, ) <NEW_LINE> <DEDENT> def __eq__(self, other) -> bool: <NEW_LINE> <INDENT> if isinstance(other, Typename): <NEW_LINE> <INDENT> return str(self) == str(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other) -> bool: <NEW_LINE> <INDENT> res = self.__eq__(other) <NEW_LINE> return not res | Generic type which can be either a basic type or a class type,
similar to C++'s `typename` aka a qualified dependent type.
Contains type name with full namespace and template arguments.
E.g.
```
gtsam::PinholeCamera<gtsam::Cal3S2>
```
will give the name as `PinholeCamera`, namespace as `gtsam`,
and template instantiations as `[gtsam::Cal3S2]`.
Args:
namespaces_and_name: A list representing the namespaces of the type
with the type being the last element.
instantiations: Template parameters to the type. | 62598f9e67a9b606de545db6 |
class HPMSSectorObjectProperties(bpy.types.PropertyGroup): <NEW_LINE> <INDENT> sector: bpy.props.BoolProperty( name="Activate HPMS Sector", description="Toggle for mark this object as HPMS sector") | Group of properties representing an sector configuration. | 62598f9e0a50d4780f7051c6 |
class Point: <NEW_LINE> <INDENT> def __init__(self, x=0, y=0): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.move(0,0) <NEW_LINE> <DEDENT> def move(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def calculate_distance(self, other_point): <NEW_LINE> <INDENT> return math.sqrt( (self.x - other_point.x)**2 + (self.y - other_point.y)**2) | Represents a point in 2-D geometric space | 62598f9ea219f33f346c6606 |
class JsonRpcTypeError(JsonRpcInvalidRequest): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> self.name = 'TypeError' | Generic JSON-RPC error class for requests with parameters of invalid type
Example:
The JSON representation of this error looks like this::
{"name": "TypeError", "message": "Your error message"} | 62598f9e91f36d47f2230d96 |
class NormalizedEqualHGBeam(NormalizedHGBeam): <NEW_LINE> <INDENT> name = 'NormalizedEqualHGBeam' <NEW_LINE> modifiable_properties = ('wavelength', 'p0', 'omega0', 'mx', 'my') <NEW_LINE> def __init__(self, name="NormalizedEqualHGBeam", **kwargs): <NEW_LINE> <INDENT> omega0 = kwargs.get('omega0', None) <NEW_LINE> kwargs['omega0x'] = kwargs['omega0y'] = omega0 <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.property_set.add_required('omega0') <NEW_LINE> self.property_set['omega0'] = kwargs.get('omega0', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def omega0(self): <NEW_LINE> <INDENT> return self.get_property('omega0') <NEW_LINE> <DEDENT> @property <NEW_LINE> def z0(self): <NEW_LINE> <INDENT> return self.get_property('z0', lambda: self.z0x) <NEW_LINE> <DEDENT> def omega_f(self, z): <NEW_LINE> <INDENT> return self.omegax_f(z) <NEW_LINE> <DEDENT> def r_f(self, z): <NEW_LINE> <INDENT> return self.rx_f(z) <NEW_LINE> <DEDENT> def phi_f(self, z): <NEW_LINE> <INDENT> return self.phix_f(z) <NEW_LINE> <DEDENT> def preprocess_properties(self, **propdict): <NEW_LINE> <INDENT> if 'omega0' in propdict: <NEW_LINE> <INDENT> propdict['omega0x'] = propdict['omega0y'] = propdict['omega0'] <NEW_LINE> <DEDENT> propdict = super().preprocess_properties(**propdict) <NEW_LINE> return propdict | 此类描述了x、y方向等价基模束腰半径相等的归一化Herimite-Gaussian光。
在轴对称的模型结构中,x、y方向等价基模束腰半径是相等的。
此类可以通过以下属性构建:
wavelength - 波长
p0 - 束腰的位置
omega0 - 等价基模的束腰半径
mx - x方向模式数
my - y方向模式数 | 62598f9e460517430c431f51 |
class ConstantKernel(StationaryKernelMixin, GenericKernelMixin, Kernel): <NEW_LINE> <INDENT> def __init__(self, constant_value=1.0, constant_value_bounds=(1e-5, 1e5)): <NEW_LINE> <INDENT> self.constant_value = constant_value <NEW_LINE> self.constant_value_bounds = constant_value_bounds <NEW_LINE> <DEDENT> @property <NEW_LINE> def hyperparameter_constant_value(self): <NEW_LINE> <INDENT> return Hyperparameter( "constant_value", "numeric", self.constant_value_bounds) <NEW_LINE> <DEDENT> def __call__(self, X, Y=None, eval_gradient=False): <NEW_LINE> <INDENT> if Y is None: <NEW_LINE> <INDENT> Y = X <NEW_LINE> <DEDENT> elif eval_gradient: <NEW_LINE> <INDENT> raise ValueError("Gradient can only be evaluated when Y is None.") <NEW_LINE> <DEDENT> K = np.full((_num_samples(X), _num_samples(Y)), self.constant_value, dtype=np.array(self.constant_value).dtype) <NEW_LINE> if eval_gradient: <NEW_LINE> <INDENT> if not self.hyperparameter_constant_value.fixed: <NEW_LINE> <INDENT> return (K, np.full((_num_samples(X), _num_samples(X), 1), self.constant_value, dtype=np.array(self.constant_value).dtype)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return K, np.empty((_num_samples(X), _num_samples(X), 0)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return K <NEW_LINE> <DEDENT> <DEDENT> def diag(self, X): <NEW_LINE> <INDENT> return np.full(_num_samples(X), self.constant_value, dtype=np.array(self.constant_value).dtype) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{0:.3g}**2".format(np.sqrt(self.constant_value)) | Constant kernel.
Can be used as part of a product-kernel where it scales the magnitude of
the other factor (kernel) or as part of a sum-kernel, where it modifies
the mean of the Gaussian process.
.. math::
k(x_1, x_2) = constant\_value \;\forall\; x_1, x_2
Adding a constant kernel is equivalent to adding a constant::
kernel = RBF() + ConstantKernel(constant_value=2)
is the same as::
kernel = RBF() + 2
Read more in the :ref:`User Guide <gp_kernels>`.
.. versionadded:: 0.18
Parameters
----------
constant_value : float, default=1.0
The constant value which defines the covariance:
k(x_1, x_2) = constant_value
constant_value_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5)
The lower and upper bound on `constant_value`.
If set to "fixed", `constant_value` cannot be changed during
hyperparameter tuning.
Examples
--------
>>> from sklearn.datasets import make_friedman2
>>> from sklearn.gaussian_process import GaussianProcessRegressor
>>> from sklearn.gaussian_process.kernels import RBF, ConstantKernel
>>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0)
>>> kernel = RBF() + ConstantKernel(constant_value=2)
>>> gpr = GaussianProcessRegressor(kernel=kernel, alpha=5,
... random_state=0).fit(X, y)
>>> gpr.score(X, y)
0.3696...
>>> gpr.predict(X[:1,:], return_std=True)
(array([606.1...]), array([0.24...])) | 62598f9e236d856c2adc9330 |
class Main(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.f=open('data.txt','r') <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> lists=[] <NEW_LINE> for line in self.f: <NEW_LINE> <INDENT> item=line.split('----') <NEW_LINE> lists.append(item) <NEW_LINE> <DEDENT> users=[] <NEW_LINE> for item in lists: <NEW_LINE> <INDENT> users.append(item) <NEW_LINE> if len(users)<100: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.qiandao(users) <NEW_LINE> users=[] <NEW_LINE> <DEDENT> self.qiandao(users) <NEW_LINE> <DEDENT> def qiandao(self,items): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> work=multiprocessing.Process(target=Qiandao,args=(item[0],item[1].replace('\n',''),)) <NEW_LINE> work.start() | docstring for Main | 62598f9e4f6381625f1993b2 |
class AddressDataProperty(davcommon.SubbedProperty): <NEW_LINE> <INDENT> name = "{%s}address-data" % NAMESPACE <NEW_LINE> def supported_on(self, resource): <NEW_LINE> <INDENT> return resource.get_content_type() == "text/vcard" <NEW_LINE> <DEDENT> async def get_value_ext(self, href, resource, el, environ, requested): <NEW_LINE> <INDENT> el.text = b"".join(await resource.get_body()).decode("utf-8") | address-data property
See https://tools.ietf.org/html/rfc6352, section 10.4
Note that this is not technically a DAV property, and
it is thus not registered in the regular webdav server. | 62598f9e0c0af96317c5616f |
class User(BaseModel): <NEW_LINE> <INDENT> email = CharField(128, null = False, unique = True) <NEW_LINE> password = CharField(128, null = False) <NEW_LINE> first_name = CharField(128, null = False) <NEW_LINE> last_name = CharField(128, null = False) <NEW_LINE> is_admin = BooleanField(default = False) <NEW_LINE> def set_password(self, clear_password): <NEW_LINE> <INDENT> self.password = md5(clear_password).hexdigest() <NEW_LINE> <DEDENT> def to_hash(self): <NEW_LINE> <INDENT> user = { 'email' : self.email, 'first_name' : self.first_name, 'last_name' : self.last_name, 'is_admin' : self.is_admin } <NEW_LINE> return super(User, self).to_hash(self, user) | User model definition | 62598f9e10dbd63aa1c709a3 |
class Solution: <NEW_LINE> <INDENT> def numberOfLines(self, widths, S): <NEW_LINE> <INDENT> line = 0 <NEW_LINE> width = 100 <NEW_LINE> for s in S: <NEW_LINE> <INDENT> w = widths[ord(s)-ord('a')] <NEW_LINE> if width + w <= 100: <NEW_LINE> <INDENT> width = width + w <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> width = w <NEW_LINE> line += 1 <NEW_LINE> <DEDENT> <DEDENT> return [line, width] | @param widths: an array
@param S: a string
@return: how many lines have at least one character from S, and what is the width used by the last such line | 62598f9eeab8aa0e5d30bb73 |
class ITopAboveNavManager(IViewletManager): <NEW_LINE> <INDENT> pass | A viewlet manager that sits at the top of the rendered table,
above the batching navigation. | 62598f9e85dfad0860cbf96b |
class Solution: <NEW_LINE> <INDENT> def maxTree(self, nums): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> node = TreeNode(num) <NEW_LINE> if stack and num > stack[-1].val: <NEW_LINE> <INDENT> node.left = stack.pop() <NEW_LINE> <DEDENT> if stack: <NEW_LINE> <INDENT> stack[-1].right = node <NEW_LINE> <DEDENT> stack.append(node) <NEW_LINE> <DEDENT> return stack[0] <NEW_LINE> <DEDENT> def maxTree_dfs(self, A): <NEW_LINE> <INDENT> if not A or len(A) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return self.maxTree_dfs(A, 0 , len(A)) <NEW_LINE> <DEDENT> def maxTree_dfs_helper(self, A, left, right): <NEW_LINE> <INDENT> if left >= right: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> max_value, max_idx = float('-inf'), None <NEW_LINE> for i in range(left, right): <NEW_LINE> <INDENT> if A[i] >= max_value: <NEW_LINE> <INDENT> max_value = A[i] <NEW_LINE> max_idx = i <NEW_LINE> <DEDENT> <DEDENT> root = TreeNode(max_value) <NEW_LINE> left_node = self.maxTree_dfs_helper(A, left, max_idx) <NEW_LINE> right_node = self.maxTree_dfs_helper(A, max_idx + 1, right) <NEW_LINE> root.left = left_node <NEW_LINE> root.right = right_node <NEW_LINE> return root | @param: A: Given an integer array with no duplicates.
@return: The root of max tree. | 62598f9ef7d966606f747dd5 |
class RatioFormat(Format): <NEW_LINE> <INDENT> def _ComputeFloat(self, cell): <NEW_LINE> <INDENT> cell.string_value = '%+1.1f%%' % ((cell.value - 1) * 100) <NEW_LINE> cell.color = self._GetColor(cell.value, Color(255, 0, 0, 0), Color(0, 0, 0, 0), Color(0, 255, 0, 0)) | Format the cell as a ratio.
Example:
If the cell contains a value of 1.5642, the string_value will be 1.56. | 62598f9edd821e528d6d8d22 |
@python_2_unicode_compatible <NEW_LINE> @jsontags.register_tag <NEW_LINE> class DefaultTagger(SequentialBackoffTagger): <NEW_LINE> <INDENT> json_tag = 'nltk.tag.sequential.DefaultTagger' <NEW_LINE> def __init__(self, tag): <NEW_LINE> <INDENT> self._tag = tag <NEW_LINE> SequentialBackoffTagger.__init__(self, None) <NEW_LINE> <DEDENT> def encode_json_obj(self): <NEW_LINE> <INDENT> return self._tag <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def decode_json_obj(cls, obj): <NEW_LINE> <INDENT> tag = obj <NEW_LINE> return cls(tag) <NEW_LINE> <DEDENT> def choose_tag(self, tokens, index, history): <NEW_LINE> <INDENT> return self._tag <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<DefaultTagger: tag=%s>' % self._tag | A tagger that assigns the same tag to every token.
>>> from nltk.tag import DefaultTagger
>>> default_tagger = DefaultTagger('NN')
>>> list(default_tagger.tag('This is a test'.split()))
[('This', 'NN'), ('is', 'NN'), ('a', 'NN'), ('test', 'NN')]
This tagger is recommended as a backoff tagger, in cases where
a more powerful tagger is unable to assign a tag to the word
(e.g. because the word was not seen during training).
:param tag: The tag to assign to each token
:type tag: str | 62598f9e8c0ade5d55dc3586 |
class RemoteLocationWristbandFence(messages.Message): <NEW_LINE> <INDENT> wbid = messages.StringField(1, required=True) <NEW_LINE> latitude = messages.FloatField(2, required=True) <NEW_LINE> longitude = messages.FloatField(3, required=True) <NEW_LINE> radius = messages.FloatField(4, required=True) | Message used to describe fence for wristbands | 62598f9e4e4d562566372212 |
class Options(Builtin): <NEW_LINE> <INDENT> def apply(self, f, evaluation): <NEW_LINE> <INDENT> name = f.get_name() <NEW_LINE> if not name: <NEW_LINE> <INDENT> if isinstance(f, Image): <NEW_LINE> <INDENT> options = f.metadata <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> evaluation.message("Options", "sym", f, 1) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> options = evaluation.definitions.get_options(name) <NEW_LINE> <DEDENT> result = [] <NEW_LINE> for option, value in sorted(options.items(), key=lambda item: item[0]): <NEW_LINE> <INDENT> result.append(Expression("RuleDelayed", Symbol(option), value)) <NEW_LINE> <DEDENT> return Expression("List", *result) | <dl>
<dt>'Options[$f$]'
<dd>gives a list of optional arguments to $f$ and their
default values.
</dl>
You can assign values to 'Options' to specify options.
>> Options[f] = {n -> 2}
= {n -> 2}
>> Options[f]
= {n :> 2}
>> f[x_, OptionsPattern[f]] := x ^ OptionValue[n]
>> f[x]
= x ^ 2
>> f[x, n -> 3]
= x ^ 3
#> f[x_, OptionsPattern[f]] := x ^ OptionValue["m"];
#> Options[f] = {"m" -> 7};
#> f[x]
= x ^ 7
Delayed option rules are evaluated just when the corresponding 'OptionValue' is called:
>> f[a :> Print["value"]] /. f[OptionsPattern[{}]] :> (OptionValue[a]; Print["between"]; OptionValue[a]);
| value
| between
| value
In contrast to that, normal option rules are evaluated immediately:
>> f[a -> Print["value"]] /. f[OptionsPattern[{}]] :> (OptionValue[a]; Print["between"]; OptionValue[a]);
| value
| between
Options must be rules or delayed rules:
>> Options[f] = {a}
: {a} is not a valid list of option rules.
= {a}
A single rule need not be given inside a list:
>> Options[f] = a -> b
= a -> b
>> Options[f]
= {a :> b}
Options can only be assigned to symbols:
>> Options[a + b] = {a -> b}
: Argument a + b at position 1 is expected to be a symbol.
= {a -> b}
#> f /: Options[f] = {a -> b}
= {a -> b}
#> Options[f]
= {a :> b}
#> f /: Options[g] := {a -> b}
: Rule for Options can only be attached to g.
= $Failed
#> Options[f] = a /; True
: a /; True is not a valid list of option rules.
= a /; True | 62598f9ee5267d203ee6b6fb |
class State(ABC): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.__name = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name: str) -> None: <NEW_LINE> <INDENT> assert isinstance(name, str), TypeError(f"name must is str, not {type(name)}") <NEW_LINE> self.__name = name <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def behavior(self, water: "Water"): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def is_match(self, context: Context) -> bool: <NEW_LINE> <INDENT> pass | 状态抽象类 | 62598f9ed99f1b3c44d0549e |
class Stream(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.boundary = None <NEW_LINE> self.header = bytes() <NEW_LINE> self.file_count = 0 <NEW_LINE> self.state = 0 <NEW_LINE> self.tail = bytes() <NEW_LINE> self.working_dir = None | The stream state
This is used to store the state of the streaming data.
Attributes:
boundary (str): The request boundary. Used to determine the metadata from the content.
header (bytes): The header.
file_count (int): Number of files in the request.
state (int): The state of the state machine used for live parsing.
tail (bytes): The tail of the previous chunk.
working_dir (obj): The `TemporaryDirectory` where the data is being saved to. | 62598f9ed486a94d0ba2bdc3 |
class SemanticMapping: <NEW_LINE> <INDENT> map_type = None <NEW_LINE> levels = None <NEW_LINE> lookup_table = None <NEW_LINE> def __init__(self, plotter): <NEW_LINE> <INDENT> self.plotter = plotter <NEW_LINE> <DEDENT> def map(cls, plotter, *args, **kwargs): <NEW_LINE> <INDENT> method_name = "_{}_map".format(cls.__name__[:-7].lower()) <NEW_LINE> setattr(plotter, method_name, cls(plotter, *args, **kwargs)) <NEW_LINE> return plotter <NEW_LINE> <DEDENT> def _lookup_single(self, key): <NEW_LINE> <INDENT> return self.lookup_table[key] <NEW_LINE> <DEDENT> def __call__(self, key, *args, **kwargs): <NEW_LINE> <INDENT> if isinstance(key, (list, np.ndarray, pd.Series)): <NEW_LINE> <INDENT> return [self._lookup_single(k, *args, **kwargs) for k in key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._lookup_single(key, *args, **kwargs) | Base class for mapping data values to plot attributes. | 62598f9e796e427e5384e581 |
class InventoryDoesNotHaveItem(WotwGameException): <NEW_LINE> <INDENT> def __init__(self, inventory, item): <NEW_LINE> <INDENT> self.inventory = inventory <NEW_LINE> self.item = item <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> err = "The inventory %s does not have any items %s"%( self.inventory, self.item.name) <NEW_LINE> return err | The inventory from which the items were being removed does not have
that item | 62598f9eb7558d589546341d |
class propertyplugin(property): <NEW_LINE> <INDENT> def __init__(self, cls): <NEW_LINE> <INDENT> def plugin_instatiator(project): <NEW_LINE> <INDENT> if hasattr(project, 'project'): <NEW_LINE> <INDENT> project = project.project <NEW_LINE> <DEDENT> return cls(project) <NEW_LINE> <DEDENT> super(propertyplugin, self).__init__(plugin_instatiator) <NEW_LINE> self.__doc__ = cls.__doc__ <NEW_LINE> self.__name__ = cls.__name__ <NEW_LINE> self.__module__ = getattr(cls, '__module__', None) <NEW_LINE> self.plugin = cls <NEW_LINE> return | Class decorator to create a plugin that is instantiated and returned when
the project attribute is used to conveniently combine class + constructor.
Like all plugins, the propertyplugin __init__ method must only accept one
positional argument, i.e. the project.
Usage:
------
```
@propertyplugin
class result:
def __init__(self, project):
pass
project = swim.Project()
project.result -> result instance
``` | 62598f9e76e4537e8c3ef3a4 |
class DispatchingConfig(object): <NEW_LINE> <INDENT> _constructor_lock = threading.Lock() <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._constructor_lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> self.dispatching_id = 0 <NEW_LINE> while 1: <NEW_LINE> <INDENT> self._local_key = 'paste.processconfig_%i' % self.dispatching_id <NEW_LINE> if not self._local_key in local_dict(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.dispatching_id += 1 <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._constructor_lock.release() <NEW_LINE> <DEDENT> self._process_configs = [] <NEW_LINE> <DEDENT> def push_thread_config(self, conf): <NEW_LINE> <INDENT> local_dict().setdefault(self._local_key, []).append(conf) <NEW_LINE> <DEDENT> def pop_thread_config(self, conf=None): <NEW_LINE> <INDENT> self._pop_from(local_dict()[self._local_key], conf) <NEW_LINE> <DEDENT> def _pop_from(self, lst, conf): <NEW_LINE> <INDENT> popped = lst.pop() <NEW_LINE> if conf is not None and popped is not conf: <NEW_LINE> <INDENT> raise AssertionError( "The config popped (%s) is not the same as the config " "expected (%s)" % (popped, conf)) <NEW_LINE> <DEDENT> <DEDENT> def push_process_config(self, conf): <NEW_LINE> <INDENT> self._process_configs.append(conf) <NEW_LINE> <DEDENT> def pop_process_config(self, conf=None): <NEW_LINE> <INDENT> self._pop_from(self._process_configs, conf) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> conf = self.current_conf() <NEW_LINE> if conf is None: <NEW_LINE> <INDENT> raise AttributeError( "No configuration has been registered for this process " "or thread") <NEW_LINE> <DEDENT> return getattr(conf, attr) <NEW_LINE> <DEDENT> def current_conf(self): <NEW_LINE> <INDENT> thread_configs = local_dict().get(self._local_key) <NEW_LINE> if thread_configs: <NEW_LINE> <INDENT> return thread_configs[-1] <NEW_LINE> <DEDENT> elif self._process_configs: <NEW_LINE> <INDENT> return self._process_configs[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> conf = self.current_conf() <NEW_LINE> if conf is None: <NEW_LINE> <INDENT> raise TypeError( "No configuration has been registered for this process " "or thread") <NEW_LINE> <DEDENT> return conf[key] <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> conf = self.current_conf() <NEW_LINE> conf[key] = value | This is a configuration object that can be used globally,
imported, have references held onto. The configuration may differ
by thread (or may not).
Specific configurations are registered (and deregistered) either
for the process or for threads. | 62598f9e60cbc95b0636413b |
class MobileAuthenticationBackend(ModelBackend): <NEW_LINE> <INDENT> def authenticate(self, *args, **credentials): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(phone=credentials["username"]) <NEW_LINE> <DEDENT> except (User.DoesNotExist, KeyError): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if user.check_password(credentials["password"]): <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None | 手机登录 | 62598f9ebaa26c4b54d4f09c |
class Movie(object): <NEW_LINE> <INDENT> valid_ratings = ["G", "PG", "PG-13", "R"] <NEW_LINE> def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.storyline = movie_storyline <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube <NEW_LINE> <DEDENT> def show_trailer(self): <NEW_LINE> <INDENT> webbrowser.open(self.trailer_youtube_url) | This class provides a way to store movie related information.
Attributes:
title: A string to store the title of the movie.
storyline: A string to store the basic plot of the movie.
poster_image_url: A string to store the URL of the movie poster.
trailer_youtube_url: A string to store the URL of the movie trailer.
release_date: A string to store the release date of the movie.
| 62598f9e498bea3a75a5790f |
class LombScargleMultibandFast(PeriodicModelerMultiband): <NEW_LINE> <INDENT> def __init__(self, optimizer=None, Nterms=1, BaseModel=LombScargle): <NEW_LINE> <INDENT> self.Nterms = Nterms <NEW_LINE> self.BaseModel = BaseModel <NEW_LINE> PeriodicModelerMultiband.__init__(self, optimizer) <NEW_LINE> <DEDENT> def _fit(self, t, y, dy, filts): <NEW_LINE> <INDENT> masks = [(filts == f) for f in self.unique_filts_] <NEW_LINE> self.models_ = [self.BaseModel(Nterms=self.Nterms, center_data=True, fit_offset=True).fit(t[m], y[m], dy[m]) for m in masks] <NEW_LINE> <DEDENT> def _score(self, periods): <NEW_LINE> <INDENT> powers = np.array([model.score(periods) for model in self.models_]) <NEW_LINE> chi2_0 = np.array([np.sum(model.yw_ ** 2) for model in self.models_]) <NEW_LINE> return np.dot(chi2_0 / chi2_0.sum(), powers) <NEW_LINE> <DEDENT> def _best_params(self, omega): <NEW_LINE> <INDENT> return np.asarray([model._best_params(omega) for model in self.models_]) <NEW_LINE> <DEDENT> def _predict(self, t, filts, period): <NEW_LINE> <INDENT> t, filts = np.broadcast_arrays(t, filts) <NEW_LINE> result = np.zeros(t.shape, dtype=float) <NEW_LINE> masks = ((filts == f) for f in self.unique_filts_) <NEW_LINE> for model, mask in zip(self.models_, masks): <NEW_LINE> <INDENT> result[mask] = model.predict(t[mask], period=period) <NEW_LINE> <DEDENT> return result | Fast Multiband Periodogram Implementation
This implements the specialized multi-band periodogram described in
VanderPlas & Ivezic 2015 (with Nbase=0 and Nband=1) which is essentially
a weighted sum of the standard periodograms for each band.
Parameters
----------
optimizer : PeriodicOptimizer instance
Optimizer to use to find the best period. If not specified, the
LinearScanOptimizer will be used.
Nterms : integer (default = 1)
Number of fourier terms to use in the model
BaseModel : class type (default = LombScargle)
The base model to use for each individual band.
See Also
--------
LombScargle
LombScargleAstroML
LombScargleMultiband | 62598f9e32920d7e50bc5e45 |
class TeacherForm(PersonForm): <NEW_LINE> <INDENT> def __init__(self, container, master): <NEW_LINE> <INDENT> PersonForm.__init__(self, container, master) <NEW_LINE> self.titleText.set("Teacher") <NEW_LINE> <DEDENT> def windowTitle(self): <NEW_LINE> <INDENT> return "Teacher" | This TeacherForm tkinter object is a child class of PersonForm. It is used to collect data for a Teacher type
record in the database. | 62598f9e91f36d47f2230d97 |
class ShipDetails(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView): <NEW_LINE> <INDENT> queryset = Ship.objects.all() <NEW_LINE> serializer_class = ShipSerializer <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.retrieve(request, *args, **kwargs) <NEW_LINE> <DEDENT> def put(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.update(request, *args, **kwargs) <NEW_LINE> <DEDENT> def delete(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.destroy(request, *args, **kwargs) | Class used to retrieve, update, or destroy a Ship object | 62598f9e32920d7e50bc5e44 |
class UrlFileNotFoundError(ValueError): <NEW_LINE> <INDENT> pass | Url file not found error. | 62598f9ef8510a7c17d7e06f |
class FakeSecurityGroup(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def create_one_security_group(attrs=None): <NEW_LINE> <INDENT> attrs = attrs or {} <NEW_LINE> security_group_attrs = { 'id': 'security-group-id-' + uuid.uuid4().hex, 'name': 'security-group-name-' + uuid.uuid4().hex, 'description': 'security-group-description-' + uuid.uuid4().hex, 'project_id': 'project-id-' + uuid.uuid4().hex, 'security_group_rules': [], 'tags': [] } <NEW_LINE> security_group_attrs.update(attrs) <NEW_LINE> security_group = fakes.FakeResource( info=copy.deepcopy(security_group_attrs), loaded=True) <NEW_LINE> security_group.project_id = security_group_attrs['project_id'] <NEW_LINE> return security_group <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_security_groups(attrs=None, count=2): <NEW_LINE> <INDENT> security_groups = [] <NEW_LINE> for i in range(0, count): <NEW_LINE> <INDENT> security_groups.append( FakeSecurityGroup.create_one_security_group(attrs)) <NEW_LINE> <DEDENT> return security_groups <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_security_groups(security_groups=None, count=2): <NEW_LINE> <INDENT> if security_groups is None: <NEW_LINE> <INDENT> security_groups = FakeSecurityGroup.create_security_groups(count) <NEW_LINE> <DEDENT> return mock.Mock(side_effect=security_groups) | Fake one or more security groups. | 62598f9e3d592f4c4edbacbd |
class CancelledBill(models.Model): <NEW_LINE> <INDENT> bill = models.OneToOneField('Bill', verbose_name=_('Original bill')) <NEW_LINE> created = models.DateTimeField(auto_now_add=True, verbose_name=_('Created')) <NEW_LINE> exported = models.BooleanField(default=False) <NEW_LINE> logs = property(_get_logs) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.bill.is_reminder(): <NEW_LINE> <INDENT> raise ValueError("Can not cancel reminder bills") <NEW_LINE> <DEDENT> super(CancelledBill, self).save(*args, **kwargs) | List of bills that have been cancelled | 62598f9e85dfad0860cbf96c |
class AWSStorageService(FileStorageServiceInterface): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.path = FilePaths() <NEW_LINE> self.bucket = aconst.bucket <NEW_LINE> <DEDENT> def set_s3_file_object_path(self, path): <NEW_LINE> <INDENT> self.path.set_s3_file_object_path(path) <NEW_LINE> <DEDENT> def upload_file(self, filename): <NEW_LINE> <INDENT> log.info("Initiating File upload to AWS...") <NEW_LINE> obj = filename <NEW_LINE> s3_client = boto3.client('s3') <NEW_LINE> s3_client.upload_file(filename, self.bucket, obj) <NEW_LINE> <DEDENT> def get_object_url(self, bucket, key_name): <NEW_LINE> <INDENT> bucket_location = boto3.client('s3').get_bucket_location(Bucket=bucket) <NEW_LINE> object_url = "https://s3-{0}.amazonaws.com/{1}/{2}".format( bucket_location['LocationConstraint'], bucket, key_name) <NEW_LINE> self.set_s3_file_object_path(object_url) <NEW_LINE> return object_url | Storage Service responsible for storing the extracted csv/or any file to AWS s3 bucket
Attributes
----------
path: obj
instance of the filePath model
bucket: str
AWS s3 bucket name
Methods
--------
set_s3_file_object_path(path)
saves s3 object url path
upload_file(filename)
Uploads file to a S3 bucket
get_object_url(bucket, keyname)
fetches url of the uploaded s3 object | 62598f9e009cb60464d01314 |
class PluginTest1DialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dialog = PluginTest1Dialog(None) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.dialog = None <NEW_LINE> <DEDENT> def test_dialog_ok(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Ok) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Accepted) <NEW_LINE> <DEDENT> def test_dialog_cancel(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Cancel) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Rejected) | Test dialog works. | 62598f9e9b70327d1c57eb8e |
class ModerationItemSearchListView(ListAPIView): <NEW_LINE> <INDENT> permission_classes = [IsAdminUser] <NEW_LINE> queryset = ModerationItem.objects.all().filter(~Q(status="closed")) <NEW_LINE> filter_backends = (filters.SearchFilter, DjangoFilterBackend) <NEW_LINE> search_fields = ( "target__data__name__fi", "target__data__name__sv", "target__data__name__en", "target__id", ) <NEW_LINE> filter_fields = ("category",) <NEW_LINE> serializer_class = ModerationItemSerializer | Search all closed moderation items | 62598f9e24f1403a926857aa |
class Fixed(Number): <NEW_LINE> <INDENT> def __init__(self, decimals=5, default=0, attribute=None, error=None, *args, **kwargs): <NEW_LINE> <INDENT> super(Fixed, self).__init__(default=default, attribute=attribute, error=error, *args, **kwargs) <NEW_LINE> self.precision = MyDecimal('0.' + '0' * (decimals - 1) + '1') <NEW_LINE> <DEDENT> @validated <NEW_LINE> def format(self, value): <NEW_LINE> <INDENT> dvalue = utils.float_to_decimal(float(value)) <NEW_LINE> if not dvalue.is_normal() and dvalue != ZERO: <NEW_LINE> <INDENT> raise MarshallingError('Invalid Fixed precision number.') <NEW_LINE> <DEDENT> return text_type(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN)) | A fixed-precision number as a string.
| 62598f9e435de62698e9bbe3 |
class Control(models.Model): <NEW_LINE> <INDENT> class Meta(object): <NEW_LINE> <INDENT> verbose_name= u"Control" <NEW_LINE> <DEDENT> parent_id = models.IntegerField( blank = False, default = 0, verbose_name = u"Parent ID") <NEW_LINE> name = models.CharField( max_length = 256, blank = False, verbose_name= u"Name") <NEW_LINE> url=models.CharField( max_length = 256, blank=False, verbose_name = u"URL") <NEW_LINE> type = models.CharField( max_length = 256, verbose_name=u"Type", blank=False, null=True) <NEW_LINE> control_type = models.CharField( max_length = 256, verbose_name=u"Classification", blank=False, null=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % self.name | Control Model | 62598f9e56ac1b37e6301fda |
class TitleGenerator(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.nlp = spacy.load('en') <NEW_LINE> <DEDENT> def initialize(self, nouns_file, adjs_file, determinants=DETERMINANTS, tau=1.0): <NEW_LINE> <INDENT> self.tau = tau <NEW_LINE> self.nouns = util.load_wordlist(nouns_file) <NEW_LINE> self.adjs = util.load_wordlist(adjs_file) <NEW_LINE> self.noun_vectors = np.zeros((len(self.nouns), self.nlp.vocab.vectors_length)) <NEW_LINE> for i, noun in enumerate(self.nouns): <NEW_LINE> <INDENT> self.noun_vectors[i] = self.nlp(noun.decode('utf-8')).vector <NEW_LINE> <DEDENT> self.adj_vectors = np.zeros((len(self.adjs), self.nlp.vocab.vectors_length)) <NEW_LINE> for i, adj in enumerate(self.adjs): <NEW_LINE> <INDENT> self.adj_vectors[i] = self.nlp(adj.decode('utf-8')).vector <NEW_LINE> <DEDENT> <DEDENT> def poem_vector(self, poem): <NEW_LINE> <INDENT> doc = self.nlp(poem.decode('utf-8')) <NEW_LINE> vectors = [w.vector for w in doc if w.tag_.startswith('NN')] <NEW_LINE> vector = sum(vectors) / len(vectors) <NEW_LINE> return vector <NEW_LINE> <DEDENT> def sample_noun(self, vector): <NEW_LINE> <INDENT> p = util.softmax(self.noun_vectors.dot(vector) / self.tau) <NEW_LINE> return npr.choice(self.nouns, p=p) <NEW_LINE> <DEDENT> def sample_adjective(self, vector): <NEW_LINE> <INDENT> p = util.softmax(self.adj_vectors.dot(vector) / self.tau) <NEW_LINE> return npr.choice(self.adjs, p=p) <NEW_LINE> <DEDENT> def sample_det(self, adj): <NEW_LINE> <INDENT> det = npr.choice(DETERMINANTS, p=P_DETERMINANTS) <NEW_LINE> if det == "A " and adj[0] in 'AEIOU': <NEW_LINE> <INDENT> det = "An " <NEW_LINE> <DEDENT> return det <NEW_LINE> <DEDENT> def __call__(self, poem): <NEW_LINE> <INDENT> poem_vector = self.poem_vector(poem) <NEW_LINE> noun = self.sample_noun(poem_vector).capitalize() <NEW_LINE> adj = self.sample_adjective(poem_vector).capitalize() <NEW_LINE> det = self.sample_det(adj).capitalize() <NEW_LINE> return det + adj + " " + noun <NEW_LINE> <DEDENT> def save(self, filename): <NEW_LINE> <INDENT> np.savez(filename, nouns=self.nouns, noun_vectors=self.noun_vectors, adjs=self.adjs, adj_vectors=self.adj_vectors, tau=self.tau) <NEW_LINE> <DEDENT> def load(self, filename): <NEW_LINE> <INDENT> self.__dict__.update(np.load(filename).items()) | Generates the title of a poem | 62598f9ecc0a2c111447adfc |
class Decoder(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, original_dim, intermediate_dim=64, name="decoder", **kwargs): <NEW_LINE> <INDENT> super(Decoder, self).__init__(**kwargs) <NEW_LINE> self.dense_proj = layers.Dense(intermediate_dim, activation=tf.nn.relu) <NEW_LINE> self.dense_output = layers.Dense(original_dim, activation=tf.nn.sigmoid) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> x = self.dense_proj(inputs) <NEW_LINE> return self.dense_output(x) | Converts z, the encoded digit vector, back into a readable digit. | 62598f9ee5267d203ee6b6fd |
class UnaryLogicalOp(Constraint): <NEW_LINE> <INDENT> class Ops(NoValEnum): <NEW_LINE> <INDENT> NOT = 'Not' <NEW_LINE> <DEDENT> def __init__(self, pos: Tuple[int, int], op: 'UnaryLogicalOp.Ops', constraint: Constraint) -> None: <NEW_LINE> <INDENT> super().__init__(pos) <NEW_LINE> self.op: UnaryLogicalOp.Ops = op <NEW_LINE> self.constraint: Constraint = constraint <NEW_LINE> <DEDENT> def __eq__(self, other: object) -> bool: <NEW_LINE> <INDENT> if isinstance(other, UnaryLogicalOp): <NEW_LINE> <INDENT> return self.op == other.op and self.constraint == other.constraint <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self) -> int: <NEW_LINE> <INDENT> return hash(self.op) ^ hash(self.constraint) | Unary logical operation | 62598f9ed99f1b3c44d054a0 |
class MessageEntity(TelegramObject): <NEW_LINE> <INDENT> def __init__(self, type, offset, length, **kwargs): <NEW_LINE> <INDENT> self.type = type <NEW_LINE> self.offset = offset <NEW_LINE> self.length = length <NEW_LINE> self.url = kwargs.get('url') <NEW_LINE> self.user = kwargs.get('user') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def de_json(data): <NEW_LINE> <INDENT> data = super(MessageEntity, MessageEntity).de_json(data) <NEW_LINE> data['user'] = User.de_json(data.get('user')) <NEW_LINE> return MessageEntity(**data) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def de_list(data): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> return list() <NEW_LINE> <DEDENT> entities = list() <NEW_LINE> for entity in data: <NEW_LINE> <INDENT> entities.append(MessageEntity.de_json(entity)) <NEW_LINE> <DEDENT> return entities | This object represents one special entity in a text message. For example,
hashtags, usernames, URLs, etc.
Args:
type (str):
offset (int):
length (int):
url (Optional[str]):
user (Optional[:class:`telegram.User`]): | 62598f9e462c4b4f79dbb7fb |
class NoneOfDistanceMeasureTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def descriptor(self): <NEW_LINE> <INDENT> return NoneOf([WordMatch('hello'), WordMatch('world')]) <NEW_LINE> <DEDENT> def test_no_response1(self): <NEW_LINE> <INDENT> assert self.descriptor().response('hello') == 0 <NEW_LINE> <DEDENT> def test_no_response2(self): <NEW_LINE> <INDENT> assert self.descriptor().response('world') == 0 <NEW_LINE> <DEDENT> def test_no_response3(self): <NEW_LINE> <INDENT> assert self.descriptor().response('hello the world is blue') == 0 <NEW_LINE> <DEDENT> def test_response(self): <NEW_LINE> <INDENT> assert self.descriptor().response('no matched words in here') == 1 <NEW_LINE> <DEDENT> def test_response_if_empty(self): <NEW_LINE> <INDENT> assert self.descriptor().response('') == 1 <NEW_LINE> <DEDENT> def test_normalised_response(self): <NEW_LINE> <INDENT> assert self.descriptor().normalised_response('no matched words') == 1 | Tests NoneOf | 62598f9e6fb2d068a7693d2c |
class _ExecDictProxy(object): <NEW_LINE> <INDENT> def __init__(self, d): <NEW_LINE> <INDENT> self._d = d <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> module_type = type(IMP) <NEW_LINE> d = self._d <NEW_LINE> for k in d.keys(): <NEW_LINE> <INDENT> if type(d[k]) != module_type: <NEW_LINE> <INDENT> del d[k] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for meth in ['__contains__', '__getitem__', '__iter__', '__len__', 'get', 'has_key', 'items', 'keys', 'values']: <NEW_LINE> <INDENT> exec("def %s(self, *args, **keys): " "return self._d.%s(*args, **keys)" % (meth, meth)) | exec returns a Python dictionary, which contains IMP objects, other
Python objects, as well as base Python modules (such as sys and
__builtins__). If we just delete this dictionary, it is entirely
possible that base Python modules are removed from the dictionary
*before* some IMP objects. This will prevent the IMP objects' Python
destructors from running properly, so C++ objects will not be
cleaned up. This class proxies the base dict class, and on deletion
attempts to remove keys from the dictionary in an order that allows
IMP destructors to fire. | 62598f9ea17c0f6771d5c02b |
class QuestionTemplate(object): <NEW_LINE> <INDENT> regex = Star(Any()) <NEW_LINE> weight = 1 <NEW_LINE> def interpret(self, match): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_interpretation(self, words): <NEW_LINE> <INDENT> rulename = self.__class__.__name__ <NEW_LINE> logger.debug("Trying to match with regex: {}".format(rulename)) <NEW_LINE> match = refo.match(self.regex + Literal(_EOL), words + [_EOL]) <NEW_LINE> if not match: <NEW_LINE> <INDENT> logger.debug("No match") <NEW_LINE> return None, None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> match = Match(match, words) <NEW_LINE> result = self.interpret(match) <NEW_LINE> <DEDENT> except BadSemantic as error: <NEW_LINE> <INDENT> logger.debug(str(error)) <NEW_LINE> return None, None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> expression, userdata = result <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> expression, userdata = result, match.words <NEW_LINE> <DEDENT> expression.rule_used = rulename <NEW_LINE> return expression, userdata | Subclass from this to implement a question handler. | 62598f9e851cf427c66b80b8 |
class ConstantDomain(Domain): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) >= 2: <NEW_LINE> <INDENT> super(ConstantDomain, self).__init__(args[0]) <NEW_LINE> self.domain = args[1] <NEW_LINE> <DEDENT> elif len(args) == 1: <NEW_LINE> <INDENT> super(ConstantDomain, self).__init__() <NEW_LINE> self.domain = args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('No domain provided.') <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, obj): <NEW_LINE> <INDENT> domain = cls(obj['name'], obj['domain']) <NEW_LINE> domain.id = obj['id'] <NEW_LINE> domain.current = obj['current'] <NEW_LINE> return domain <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> return self.domain <NEW_LINE> <DEDENT> def map_to_domain(self, idx, bound=True): <NEW_LINE> <INDENT> return self.domain <NEW_LINE> <DEDENT> def to_index(self, value): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> jsonified = super(ConstantDomain, self).to_json() <NEW_LINE> jsonified.update({'domain': self.domain}) <NEW_LINE> return jsonified | A singleton hyperparameter domain.
Parameters
----------
name : str
The name of this hyperparameter domain.
domain
The single value in this domain.
See Also
--------
`pyrameter.domains.base.Domain` | 62598f9e656771135c489473 |
class EventSource(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "Parameters": (EventParameters, False), "Type": (str, True), } | `EventSource <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-eventsource.html>`__ | 62598f9e67a9b606de545dba |
class LoanType(NoSyncModel, models.Model): <NEW_LINE> <INDENT> fund = models.ForeignKey(to='lenders.Fund', related_name='+') <NEW_LINE> name = models.CharField(max_length=50, null=False, blank=False) <NEW_LINE> desc = models.CharField(max_length=100) <NEW_LINE> default_interest_rate = models.DecimalField(max_digits=7, decimal_places=5) <NEW_LINE> grace_months = models.SmallIntegerField() <NEW_LINE> max_terms = models.SmallIntegerField() <NEW_LINE> min_monthly_payment = models.DecimalField(max_digits=7, decimal_places=2) <NEW_LINE> min_quarterly_payment = models.DecimalField(max_digits=7, decimal_places=2) <NEW_LINE> min_yearly_payment = models.DecimalField(max_digits=7, decimal_places=2) <NEW_LINE> allow_deferments = models.BooleanField(default=True) <NEW_LINE> allow_cancellations = models.BooleanField(default=True) <NEW_LINE> origination_fee = models.DecimalField(max_digits=7, decimal_places=2) <NEW_LINE> initial_status = models.ForeignKey(to='structures.Status') <NEW_LINE> accrual_method = models.CharField(max_length=1, choices=ACCRUAL_METHOD) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "loan_type" <NEW_LINE> verbose_name_plural = "Loan Types Book" | Loan-type table. 'loan_type' column is the identifier | 62598f9ee5267d203ee6b6fe |
class Response(CommandResponseBase): <NEW_LINE> <INDENT> def _verify_type(self): <NEW_LINE> <INDENT> assert self.get('type') == 'response' and self.has_key('command_id') | A response to a Command, or a follow up response to a Response | 62598f9e7b25080760ed7297 |
class TADMOvershotError(HamiltonStepError): <NEW_LINE> <INDENT> pass | Overshot of limits during aspirate or dispense.
Note:
On aspirate this error is returned as main error 17.
On dispense this error is returned as main error 4. | 62598f9e7047854f4633f1d3 |
class PriorSchemeViewset(ModelViewSet): <NEW_LINE> <INDENT> queryset = PriorScheme.objects.filter(is_used=1) <NEW_LINE> serializer_class = PriorSchemeSerializer <NEW_LINE> filterset_class = PriorSchemeFilter <NEW_LINE> filter_backends = (OrderingFilter, filters.DjangoFilterBackend) <NEW_LINE> ordering_fields = ('update_time',) <NEW_LINE> def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> print(request.data) <NEW_LINE> partial = kwargs.pop('partial', False) <NEW_LINE> instance = self.get_object() <NEW_LINE> data = dict(request.data) <NEW_LINE> data = {key: value[0] for key, value in data.items()} <NEW_LINE> del data["path"] <NEW_LINE> serializer = self.get_serializer(instance, data=data, partial=partial) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> self.perform_update(serializer) <NEW_LINE> if getattr(instance, '_prefetched_objects_cache', None): <NEW_LINE> <INDENT> instance._prefetched_objects_cache = {} <NEW_LINE> <DEDENT> return Response(serializer.data) <NEW_LINE> <DEDENT> @action(methods=['get'], detail=True) <NEW_LINE> def download(self, request, pk): <NEW_LINE> <INDENT> priorschem = self.get_object() <NEW_LINE> path = priorschem.path <NEW_LINE> base_path = settings.BASE_DIR + '/media' + '/' + str(path) <NEW_LINE> if os.path.exists(base_path): <NEW_LINE> <INDENT> priorschem = self.get_object() <NEW_LINE> priorschem.download_times += 1 <NEW_LINE> priorschem.save() <NEW_LINE> return Response({'download_times': priorschem.download_times}, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response({'error': '下载文件不存在'}, status=status.HTTP_200_OK) | 应急方案管理 | 62598f9e55399d3f05626313 |
class Upscale2DLayer(Layer): <NEW_LINE> <INDENT> def __init__(self, incoming, scale_factor, mode='repeat', **kwargs): <NEW_LINE> <INDENT> super(Upscale2DLayer, self).__init__(incoming, **kwargs) <NEW_LINE> self.scale_factor = as_tuple(scale_factor, 2) <NEW_LINE> if self.scale_factor[0] < 1 or self.scale_factor[1] < 1: <NEW_LINE> <INDENT> raise ValueError('Scale factor must be >= 1, not {0}'.format( self.scale_factor)) <NEW_LINE> <DEDENT> if mode not in {'repeat', 'dilate'}: <NEW_LINE> <INDENT> msg = "Mode must be either 'repeat' or 'dilate', not {0}" <NEW_LINE> raise ValueError(msg.format(mode)) <NEW_LINE> <DEDENT> self.mode = mode <NEW_LINE> <DEDENT> def get_output_shape_for(self, input_shape): <NEW_LINE> <INDENT> output_shape = list(input_shape) <NEW_LINE> if output_shape[2] is not None: <NEW_LINE> <INDENT> output_shape[2] *= self.scale_factor[0] <NEW_LINE> <DEDENT> if output_shape[3] is not None: <NEW_LINE> <INDENT> output_shape[3] *= self.scale_factor[1] <NEW_LINE> <DEDENT> return tuple(output_shape) <NEW_LINE> <DEDENT> def get_output_for(self, input, **kwargs): <NEW_LINE> <INDENT> a, b = self.scale_factor <NEW_LINE> upscaled = input <NEW_LINE> if self.mode == 'repeat': <NEW_LINE> <INDENT> if b > 1: <NEW_LINE> <INDENT> upscaled = T.extra_ops.repeat(upscaled, b, 3) <NEW_LINE> <DEDENT> if a > 1: <NEW_LINE> <INDENT> upscaled = T.extra_ops.repeat(upscaled, a, 2) <NEW_LINE> <DEDENT> <DEDENT> elif self.mode == 'dilate': <NEW_LINE> <INDENT> if b > 1 or a > 1: <NEW_LINE> <INDENT> output_shape = self.get_output_shape_for(input.shape) <NEW_LINE> upscaled = T.zeros(shape=output_shape, dtype=input.dtype) <NEW_LINE> upscaled = T.set_subtensor(upscaled[:, :, ::a, ::b], input) <NEW_LINE> <DEDENT> <DEDENT> return upscaled | 2D upscaling layer
Performs 2D upscaling over the two trailing axes of a 4D input tensor.
Parameters
----------
incoming : a :class:`Layer` instance or tuple
The layer feeding into this layer, or the expected input shape.
scale_factor : integer or iterable
The scale factor in each dimension. If an integer, it is promoted to
a square scale factor region. If an iterable, it should have two
elements.
mode : {'repeat', 'dilate'}
Upscaling mode: repeat element values or upscale leaving zeroes between
upscaled elements. Default is 'repeat'.
**kwargs
Any additional keyword arguments are passed to the :class:`Layer`
superclass.
Notes
-----
Using ``mode='dilate'`` followed by a convolution can be
realized more efficiently with a transposed convolution, see
:class:`lasagne.layers.TransposedConv2DLayer`. | 62598f9e8e71fb1e983bb8a7 |
class IC_74133(Base_16pin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pins = [None, 0, 0, 0, 0, 0, 0, 0, 0, None, 0, 0, 0, 0, 0, 0, 0] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output[9] = NAND( self.pins[1], self.pins[2], self.pins[3], self.pins[4], self.pins[5], self.pins[6], self.pins[7], self.pins[10], self.pins[11], self.pins[12], self.pins[13], self.pins[14], self.pins[15]).output() <NEW_LINE> if self.pins[8] == 0 and self.pins[16] == 1: <NEW_LINE> <INDENT> self.set_IC(output) <NEW_LINE> for i in self.output_connector: <NEW_LINE> <INDENT> self.output_connector[i].state = output[i] <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Ground and VCC pins have not been configured correctly.") | This is a 13-input NAND gate | 62598f9e596a897236127a6b |
class SolaredgeHa(object): <NEW_LINE> <INDENT> def __init__(self, username, password): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.sites = [] <NEW_LINE> self.token = None <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> url = urljoin(LOGINURL, "login") <NEW_LINE> params = { "j_username": self.username, "j_password": self.password } <NEW_LINE> r = requests.post(url, data=params, allow_redirects=False) <NEW_LINE> r.raise_for_status() <NEW_LINE> if (r.status_code != 302): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.token = r.cookies.get(COOKIE_NAME) <NEW_LINE> return self.updateSites() <NEW_LINE> <DEDENT> def updateSites(self): <NEW_LINE> <INDENT> if (self.token == None): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> url = urljoin(LOGINURL, "fields", "list") <NEW_LINE> cookies = { COOKIE_NAME: self.token } <NEW_LINE> r = requests.get(url, cookies=cookies) <NEW_LINE> r.raise_for_status() <NEW_LINE> tree = ElementTree.fromstring(r.content) <NEW_LINE> self.sites = [] <NEW_LINE> for id in tree.iter('id'): <NEW_LINE> <INDENT> self.sites.append(id.text) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def ensureSession(self): <NEW_LINE> <INDENT> if (self.token == None): <NEW_LINE> <INDENT> self.login() <NEW_LINE> <DEDENT> return self.token != None <NEW_LINE> <DEDENT> def get_sites(self): <NEW_LINE> <INDENT> return self.sites <NEW_LINE> <DEDENT> def get_devices(self, site): <NEW_LINE> <INDENT> if (self.ensureSession() == False): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> url = urljoin(BASEURL, "sites", site, "devices") <NEW_LINE> cookies = { COOKIE_NAME: self.token } <NEW_LINE> r = requests.get(url, cookies=cookies) <NEW_LINE> r.raise_for_status() <NEW_LINE> return r.json() <NEW_LINE> <DEDENT> def activate_device(self, reporterId, level, duration=None): <NEW_LINE> <INDENT> if (self.ensureSession() == False): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> url = urljoin(BASEURL, self.sites[0], "devices", reporterId, "activationState") <NEW_LINE> cookies = { COOKIE_NAME: self.token } <NEW_LINE> params = { "mode": "MANUAL", "level": level, "duration": duration } <NEW_LINE> r = requests.put(url, json=params, cookies=cookies) <NEW_LINE> r.raise_for_status() <NEW_LINE> return r.json() | Object containing SolarEdge's Home Automation site API-methods. | 62598f9e4527f215b58e9cd4 |
class ErrorController(object): <NEW_LINE> <INDENT> @expose('biorepo.templates.error') <NEW_LINE> def document(self, *args, **kwargs): <NEW_LINE> <INDENT> resp = request.environ.get('pylons.original_response') <NEW_LINE> default_message = ("<p>We're sorry but we weren't able to process " " this request.</p>") <NEW_LINE> values = dict(prefix=request.environ.get('SCRIPT_NAME', ''), code=request.params.get('code', resp.status_int), message=request.params.get('message', default_message)) <NEW_LINE> return values | Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorController when error
related status codes are returned from the application.
This behaviour can be altered by changing the parameters to the
ErrorDocuments middleware in your config/middleware.py file. | 62598f9ea219f33f346c660b |
class LVMPhysicalVolume(DeviceFormat): <NEW_LINE> <INDENT> _type = "lvmpv" <NEW_LINE> _name = "physical volume (LVM)" <NEW_LINE> _udevTypes = ["LVM2_member"] <NEW_LINE> partedFlag = PARTITION_LVM <NEW_LINE> _formattable = True <NEW_LINE> _supported = True <NEW_LINE> _linuxNative = True <NEW_LINE> _packages = ["lvm2"] <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> log_method_call(self, *args, **kwargs) <NEW_LINE> DeviceFormat.__init__(self, *args, **kwargs) <NEW_LINE> self.vgName = kwargs.get("vgName") <NEW_LINE> self.vgUuid = kwargs.get("vgUuid") <NEW_LINE> self.peStart = kwargs.get("peStart", 0.1875) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = DeviceFormat.__str__(self) <NEW_LINE> s += (" vgName = %(vgName)s vgUUID = %(vgUUID)s" " peStart = %(peStart)s" % {"vgName": self.vgName, "vgUUID": self.vgUuid, "peStart": self.peStart}) <NEW_LINE> return s <NEW_LINE> <DEDENT> @property <NEW_LINE> def dict(self): <NEW_LINE> <INDENT> d = super(LVMPhysicalVolume, self).dict <NEW_LINE> d.update({"vgName": self.vgName, "vgUUID": self.vgUuid, "peStart": self.peStart}) <NEW_LINE> return d <NEW_LINE> <DEDENT> def probe(self): <NEW_LINE> <INDENT> log_method_call(self, device=self.device, type=self.type, status=self.status) <NEW_LINE> if not self.exists: <NEW_LINE> <INDENT> raise PhysicalVolumeError("format has not been created") <NEW_LINE> <DEDENT> <DEDENT> def create(self, *args, **kwargs): <NEW_LINE> <INDENT> log_method_call(self, device=self.device, type=self.type, status=self.status) <NEW_LINE> intf = kwargs.get("intf") <NEW_LINE> w = None <NEW_LINE> if intf: <NEW_LINE> <INDENT> w = intf.progressWindow(_("Formatting"), _("Creating %s on %s") % (self.name, self.device), 100, pulse = True) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> DeviceFormat.create(self, *args, **kwargs) <NEW_LINE> DeviceFormat.destroy(self, *args, **kwargs) <NEW_LINE> lvm.pvcreate(self.device, progress=w) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.exists = True <NEW_LINE> self.notifyKernel() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if w: <NEW_LINE> <INDENT> w.pop() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def destroy(self, *args, **kwargs): <NEW_LINE> <INDENT> log_method_call(self, device=self.device, type=self.type, status=self.status) <NEW_LINE> if not self.exists: <NEW_LINE> <INDENT> raise PhysicalVolumeError("format has not been created") <NEW_LINE> <DEDENT> if self.status: <NEW_LINE> <INDENT> raise PhysicalVolumeError("device is active") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> lvm.pvremove(self.device) <NEW_LINE> <DEDENT> except LVMError: <NEW_LINE> <INDENT> DeviceFormat.destroy(self, *args, **kwargs) <NEW_LINE> <DEDENT> self.exists = False <NEW_LINE> self.notifyKernel() <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return (self.exists and self.vgName and os.path.isdir("/dev/mapper/%s" % self.vgName)) <NEW_LINE> <DEDENT> def writeKS(self, f): <NEW_LINE> <INDENT> f.write("pv.%s" % self.uuid) | An LVM physical volume. | 62598f9ecc0a2c111447adfd |
class CreateHeightLikelihood: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self <NEW_LINE> <DEDENT> def fit(self, *args, **kwargs): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, df, column_name, **transform_params): <NEW_LINE> <INDENT> adult_avg_height = 177+165/2 <NEW_LINE> adult_sd_height = 20 <NEW_LINE> adult_norm = stats.norm(loc=adult_avg_height, scale=adult_sd_height) <NEW_LINE> df[column_name] = df[column_name].fillna(0) <NEW_LINE> df['height_likelihood'] = df[column_name].apply(lambda x: adult_norm.pdf(x)) <NEW_LINE> return df | creates the general likelyhood of the provided height | 62598f9ed7e4931a7ef3be8a |
class PhysicalSitePin(): <NEW_LINE> <INDENT> def __init__(self, site, pin): <NEW_LINE> <INDENT> self.site = site <NEW_LINE> self.pin = pin <NEW_LINE> self.branches = [] <NEW_LINE> <DEDENT> def output_interchange(self, obj, string_id): <NEW_LINE> <INDENT> obj.routeSegment.init('sitePin') <NEW_LINE> obj.routeSegment.sitePin.site = string_id(self.site) <NEW_LINE> obj.routeSegment.sitePin.pin = string_id(self.pin) <NEW_LINE> descend_branch(obj, self, string_id) <NEW_LINE> <DEDENT> def get_device_resource(self, site_types, device_resources): <NEW_LINE> <INDENT> return device_resources.site_pin(self.site, site_types[self.site], self.pin) <NEW_LINE> <DEDENT> def to_tuple(self): <NEW_LINE> <INDENT> return ('site_pin', self.site, self.pin) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'PhysicalSitePin({}, {})'.format( repr(self.site), repr(self.pin), ) | Python class that represents a site pin in a physical net.
site (str) - Site containing site pin
pin (str) - Site pin in physical net. | 62598f9e4f6381625f1993b4 |
class CreateTokenRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(CreateTokenRequest, self).__init__( '/createToken', 'POST', header, version) <NEW_LINE> self.parameters = parameters | 生成token-用户加入房间时携带token校验通过后方能加入 | 62598f9edd821e528d6d8d26 |
class PreciseRetrievalSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> pass | 精准检索 | 62598f9ed268445f26639a7c |
class _CppTypeVector(CppTypeBase): <NEW_LINE> <INDENT> def get_type_name(self): <NEW_LINE> <INDENT> return 'std::vector<std::uint8_t>' <NEW_LINE> <DEDENT> def get_storage_type(self): <NEW_LINE> <INDENT> return self.get_type_name() <NEW_LINE> <DEDENT> def get_getter_setter_type(self): <NEW_LINE> <INDENT> return 'ConstDataRange' <NEW_LINE> <DEDENT> def is_const_type(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def return_by_reference(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def disable_xvalue(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def is_view_type(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_getter_body(self, member_name): <NEW_LINE> <INDENT> return common.template_args( 'return ConstDataRange(reinterpret_cast<const char*>(${member_name}.data()), ${member_name}.size());', member_name=member_name) <NEW_LINE> <DEDENT> def get_setter_body(self, member_name, validator_method_name): <NEW_LINE> <INDENT> return common.template_args( 'auto _tmpValue = ${value}; ${optionally_call_validator} ${member_name} = std::move(_tmpValue);', member_name=member_name, optionally_call_validator=_optionally_make_call( validator_method_name, '_tmpValue'), value=self.get_transform_to_storage_type("value")) <NEW_LINE> <DEDENT> def get_transform_to_getter_type(self, expression): <NEW_LINE> <INDENT> return common.template_args('makeCDR(${expression});', expression=expression) <NEW_LINE> <DEDENT> def get_transform_to_storage_type(self, expression): <NEW_LINE> <INDENT> return common.template_args( 'std::vector<std::uint8_t>(reinterpret_cast<const uint8_t*>(${expression}.data()), ' + 'reinterpret_cast<const uint8_t*>(${expression}.data()) + ${expression}.length())', expression=expression) | Base type for C++ Std::Vector Types information. | 62598f9ed486a94d0ba2bdc7 |
class RStanheaders(RPackage): <NEW_LINE> <INDENT> homepage = "http://mc-stan.org/" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/StanHeaders_2.10.0-2.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/StanHeaders" <NEW_LINE> version('2.21.0-7', sha256='27546e064f0e907e031d9185ad55245d118d82fbe3074ecb1d76fae8b9f2336b') <NEW_LINE> version('2.21.0-6', sha256='a0282a054d0e6ab310ec7edcffa953b77c7e4a858d9ac7028aab1b4fb4ce8cf3') <NEW_LINE> version('2.18.1-10', sha256='8a9f7e22105428e97d14f44f75395c37cf8c809de148d279c620024452b3565a') <NEW_LINE> version('2.18.1', sha256='ce0d609a7cd11725b1203bdeae92acc54da3a48b8266eb9dbdb9d95b14df9209') <NEW_LINE> version('2.17.1', sha256='4300a1910a2eb40d7a6ecabea3c1e26f0aa9421eeb3000689272a0f62cb80d97') <NEW_LINE> version('2.10.0-2', sha256='ce4e335172bc65da874699302f6ba5466cdbcf69458c11954c0f131fc78b59b7') <NEW_LINE> depends_on('r+X', type=('build', 'run')) <NEW_LINE> depends_on('r@3.4.0:', when='@2.18.0:', type=('build', 'run')) <NEW_LINE> depends_on('r-rcppparallel@5.0.1:', when='@2.21.0:', type=('build', 'run')) <NEW_LINE> depends_on('r-rcppeigen', when='@2.21.0:', type=('build', 'run')) <NEW_LINE> depends_on('pandoc', type='build') | C++ Header Files for Stan
The C++ header files of the Stan project are provided by this package,
but it contains no R code, vignettes, or function documentation. There is a
shared object containing part of the CVODES library, but it is not
accessible from R. StanHeaders is only useful for developers who want to
utilize the LinkingTo directive of their package's DESCRIPTION file to
build on the Stan library without incurring unnecessary dependencies. The
Stan project develops a probabilistic programming language that implements
full or approximate Bayesian statistical inference via Markov Chain Monte
Carlo or variational methods and implements (optionally penalized) maximum
likelihood estimation via optimization. The Stan library includes an
advanced automatic differentiation scheme, templated statistical and linear
algebra functions that can handle the automatically differentiable scalar
types (and doubles, ints, etc.), and a parser for the Stan language. The
'rstan' package provides user-facing R functions to parse, compile, test,
estimate, and analyze Stan models. | 62598f9e004d5f362081eef6 |
class ExcelResponse(HttpResponse): <NEW_LINE> <INDENT> def __init__(self, origin_data, output_name='excel_data', headers=None, encoding='utf8', is_template=False, sheet_name=None): <NEW_LINE> <INDENT> valid_data = False <NEW_LINE> if is_template: <NEW_LINE> <INDENT> sheet_data = [headers] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sheet_data = [] <NEW_LINE> for n, obj in enumerate(origin_data): <NEW_LINE> <INDENT> tmp_data = [] <NEW_LINE> if obj: <NEW_LINE> <INDENT> if isinstance(obj, ValuesQuerySet): <NEW_LINE> <INDENT> tmp_data = list(obj) <NEW_LINE> <DEDENT> elif isinstance(obj, QuerySet): <NEW_LINE> <INDENT> tmp_data = list(obj.values()) <NEW_LINE> <DEDENT> if hasattr(obj, '__getitem__'): <NEW_LINE> <INDENT> if isinstance(obj[0], dict): <NEW_LINE> <INDENT> if headers[n] is None: <NEW_LINE> <INDENT> headers = obj[0].keys() <NEW_LINE> <DEDENT> tmp_data = [[row.get(col, '') for col in headers[n]] for row in obj] <NEW_LINE> tmp_data.insert(0, headers[n]) <NEW_LINE> <DEDENT> if hasattr(obj[0], '__getitem__'): <NEW_LINE> <INDENT> valid_data = True <NEW_LINE> <DEDENT> <DEDENT> assert valid_data is True, "ExcelResponse requires a sequence of sequences" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tmp_data.insert(0, headers[n]) <NEW_LINE> <DEDENT> sheet_data.append(tmp_data) <NEW_LINE> <DEDENT> <DEDENT> output = cStringIO.StringIO() <NEW_LINE> for n, data in enumerate(sheet_data): <NEW_LINE> <INDENT> if len(data) < 65536: <NEW_LINE> <INDENT> book = xlwt.Workbook(encoding=encoding) <NEW_LINE> sheet = book.add_sheet(sheet_name[n] if sheet_name else 'Sheet ' + str(n+1)) <NEW_LINE> styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'), 'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'), 'time': xlwt.easyxf(num_format_str='hh:mm:ss'), 'default': xlwt.XFStyle} <NEW_LINE> for rowx, row in enumerate(data): <NEW_LINE> <INDENT> for colx, value in enumerate(row): <NEW_LINE> <INDENT> if isinstance(value, datetime.datetime): <NEW_LINE> <INDENT> cell_style = styles['datetime'] <NEW_LINE> <DEDENT> elif isinstance(value, datetime.date): <NEW_LINE> <INDENT> cell_style = styles['date'] <NEW_LINE> <DEDENT> elif isinstance(value, datetime.time): <NEW_LINE> <INDENT> cell_style = styles['time'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cell_style = styles['default'] <NEW_LINE> <DEDENT> sheet.write(rowx, colx, value, style=cell_style) <NEW_LINE> <DEDENT> <DEDENT> book.save(output) <NEW_LINE> content_type = 'application/vnd.ms-excel' <NEW_LINE> file_ext = 'xls' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for row in data: <NEW_LINE> <INDENT> out_row = [] <NEW_LINE> for value in row: <NEW_LINE> <INDENT> if not isinstance(value, basestring): <NEW_LINE> <INDENT> value = unicode(value) <NEW_LINE> <DEDENT> value = value.encode('gbk', 'ignore') <NEW_LINE> out_row.append(value.replace('"', '""')) <NEW_LINE> <DEDENT> output.write('"%s"\n' % '","'.join(out_row)) <NEW_LINE> <DEDENT> content_type = 'text/csv' <NEW_LINE> file_ext = 'csv' <NEW_LINE> <DEDENT> <DEDENT> output.seek(0) <NEW_LINE> super(ExcelResponse, self).__init__(content=output.getvalue(), content_type=content_type) <NEW_LINE> self['Content-Disposition'] = 'attachment;filename="%s.%s"' % (output_name.replace('"', '\"'), file_ext) | excel文件导出
支持xls和csv格式文件
支持多sheet页导出 | 62598f9e63d6d428bbee25a4 |
class Sniffer(UDisks): <NEW_LINE> <INDENT> def __init__(self, proxy=None): <NEW_LINE> <INDENT> self._proxy = proxy or self.connect_service() <NEW_LINE> self._proxy.property.DaemonVersion <NEW_LINE> <DEDENT> def paths(self): <NEW_LINE> <INDENT> return self._proxy.method.EnumerateDevices() <NEW_LINE> <DEDENT> def get(self, object_path): <NEW_LINE> <INDENT> return OnlineDevice( self, self._proxy.object.bus.get_object(object_path)) <NEW_LINE> <DEDENT> update = get | UDisks DBus service wrapper.
This is a wrapper for the DBus API of the UDisks service at
'org.freedesktop.UDisks'. Access to properties and device states is
completely online, meaning the properties are requested from dbus as
they are accessed in the python object. | 62598f9e21a7993f00c65d75 |
class QueryLayerSourcePropertyPage(CoClass): <NEW_LINE> <INDENT> _reg_clsid_ = GUID('{DA96B9F2-F1A7-4CC8-ABFE-68BF69EB8EED}') <NEW_LINE> _idlflags_ = [] <NEW_LINE> _typelib_path_ = typelib_path <NEW_LINE> _reg_typelib_ = ('{D92377DC-FAB1-4DFB-A4C1-61BD8C40DBEB}', 10, 2) | Property page for managing a query layer's source. | 62598f9e8e7ae83300ee8e92 |
class DataStoreServer(oauth.Server): <NEW_LINE> <INDENT> def __init__(self, signature_methods=None, data_store=None): <NEW_LINE> <INDENT> self.data_store = data_store <NEW_LINE> super(DataStoreServer, self).__init__(signature_methods) <NEW_LINE> <DEDENT> def fetch_request_token(self, oauth_request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = self._get_token(oauth_request, 'request') <NEW_LINE> <DEDENT> except oauth.Error: <NEW_LINE> <INDENT> version = self._get_version(oauth_request) <NEW_LINE> consumer = self._get_consumer(oauth_request) <NEW_LINE> try: <NEW_LINE> <INDENT> callback = self.get_callback(oauth_request) <NEW_LINE> <DEDENT> except oauth.Error: <NEW_LINE> <INDENT> callback = None <NEW_LINE> <DEDENT> self._check_signature(oauth_request, consumer, None) <NEW_LINE> token = self.data_store.fetch_request_token(consumer, callback) <NEW_LINE> <DEDENT> return token <NEW_LINE> <DEDENT> def fetch_access_token(self, oauth_request): <NEW_LINE> <INDENT> version = self._get_version(oauth_request) <NEW_LINE> consumer = self._get_consumer(oauth_request) <NEW_LINE> try: <NEW_LINE> <INDENT> verifier = self._get_verifier(oauth_request) <NEW_LINE> <DEDENT> except oauth.Error: <NEW_LINE> <INDENT> verifier = None <NEW_LINE> <DEDENT> token = self._get_token(oauth_request, 'request') <NEW_LINE> self._check_signature(oauth_request, consumer, token) <NEW_LINE> new_token = self.data_store.fetch_access_token(consumer, token, verifier) <NEW_LINE> return new_token <NEW_LINE> <DEDENT> def authorize_token(self, token, user): <NEW_LINE> <INDENT> return self.data_store.authorize_request_token(token, user) <NEW_LINE> <DEDENT> def get_callback(self, oauth_request): <NEW_LINE> <INDENT> return oauth_request.get_parameter('oauth_callback') <NEW_LINE> <DEDENT> def _get_consumer(self, oauth_request): <NEW_LINE> <INDENT> consumer_key = oauth_request.get_parameter('oauth_consumer_key') <NEW_LINE> consumer = self.data_store.lookup_consumer(consumer_key) <NEW_LINE> if not consumer: <NEW_LINE> <INDENT> raise oauth.Error('Invalid consumer.') <NEW_LINE> <DEDENT> return consumer <NEW_LINE> <DEDENT> def _get_token(self, oauth_request, token_type='access'): <NEW_LINE> <INDENT> token_field = oauth_request.get_parameter('oauth_token') <NEW_LINE> token = self.data_store.lookup_token(token_type, token_field) <NEW_LINE> if not token: <NEW_LINE> <INDENT> raise oauth.Error('Invalid %s token: %s' % (token_type, token_field)) <NEW_LINE> <DEDENT> return token <NEW_LINE> <DEDENT> def verify_access_token(self, oauth_request): <NEW_LINE> <INDENT> version = self._get_version(oauth_request) <NEW_LINE> consumer = self._get_consumer(oauth_request) <NEW_LINE> token = self._get_token(oauth_request, 'access') <NEW_LINE> self._check_signature(oauth_request, consumer, token) | Adds data storage abilities to the base OAuth Server | 62598f9e7cff6e4e811b5815 |
class ClouduseraccountsGroupsListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> orderBy = _messages.StringField(3) <NEW_LINE> pageToken = _messages.StringField(4) <NEW_LINE> project = _messages.StringField(5, required=True) | A ClouduseraccountsGroupsListRequest object.
Fields:
filter: Sets a filter expression for filtering listed resources, in the
form filter={expression}. Your {expression} must be in the format:
field_name comparison_string literal_string. The field_name is the name
of the field you want to compare. Only atomic field types are supported
(string, number, boolean). The comparison_string must be either eq
(equals) or ne (not equals). The literal_string is the string value to
filter to. The literal value must be valid for the type of field you are
filtering by (string, number, boolean). For string fields, the literal
value is interpreted as a regular expression using RE2 syntax. The
literal value must match the entire field. For example, to filter for
instances that do not have a name of example-instance, you would use
filter=name ne example-instance. You can filter on nested fields. For
example, you could filter on instances that have set the
scheduling.automaticRestart field to true. Use filtering on nested
fields to take advantage of labels to organize and search for results
based on label values. To filter on multiple expressions, provide each
separate expression within parentheses. For example,
(scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple
expressions are treated as AND expressions, meaning that resources must
match all expressions to pass the filters.
maxResults: The maximum number of results per page that should be
returned. If the number of available results is larger than maxResults,
Compute Engine returns a nextPageToken that can be used to get the next
page of results in subsequent list requests.
orderBy: Sorts list results by a certain order. By default, results are
returned in alphanumerical order based on the resource name. You can
also sort results in descending order based on the creation timestamp
using orderBy="creationTimestamp desc". This sorts results based on the
creationTimestamp field in reverse chronological order (newest result
first). Use this to sort resources like operations so that the newest
operation is returned first. Currently, only sorting by name or
creationTimestamp desc is supported.
pageToken: Specifies a page token to use. Set pageToken to the
nextPageToken returned by a previous list request to get the next page
of results.
project: Project ID for this request. | 62598f9e0a50d4780f7051cc |
class GKJsonApiException(Exception): <NEW_LINE> <INDENT> title = 'Unknown error' <NEW_LINE> status = '500' <NEW_LINE> source = None <NEW_LINE> def __init__(self, detail, source=None, title=None, status=None, code=None, id_=None, links=None, meta=None): <NEW_LINE> <INDENT> self.detail = detail <NEW_LINE> self.source = source <NEW_LINE> self.code = code <NEW_LINE> self.id = id_ <NEW_LINE> self.links = links or {} <NEW_LINE> self.meta = meta or {} <NEW_LINE> if title is not None: <NEW_LINE> <INDENT> self.title = title <NEW_LINE> <DEDENT> if status is not None: <NEW_LINE> <INDENT> self.status = status <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> error_dict = {} <NEW_LINE> for field in ('status', 'source', 'title', 'detail', 'id', 'code', 'links', 'meta'): <NEW_LINE> <INDENT> if getattr(self, field, None): <NEW_LINE> <INDENT> error_dict.update({field: getattr(self, field)}) <NEW_LINE> <DEDENT> <DEDENT> return error_dict | Base exception class for unknown errors | 62598f9e498bea3a75a57913 |
class Man(object): <NEW_LINE> <INDENT> def __init__(self, name, age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def says(what): <NEW_LINE> <INDENT> print ("hello, %s" % what) | this is a test | 62598f9e1b99ca400228f427 |
class ServicemanagementServicesConfigsListRequest(_messages.Message): <NEW_LINE> <INDENT> pageSize = _messages.IntegerField(1, variant=_messages.Variant.INT32) <NEW_LINE> pageToken = _messages.StringField(2) <NEW_LINE> serviceName = _messages.StringField(3, required=True) | A ServicemanagementServicesConfigsListRequest object.
Fields:
pageSize: The max number of items to include in the response list. Page
size is 50 if not specified. Maximum value is 100.
pageToken: The token of the page to retrieve.
serviceName: The name of the service. See the [overview](/service-
management/overview) for naming requirements. For example:
`example.googleapis.com`. | 62598f9e91f36d47f2230d99 |
class Or_exp(object): <NEW_LINE> <INDENT> def __init__(self, lhs, rhs): <NEW_LINE> <INDENT> self.lhs = lhs <NEW_LINE> self.rhs = rhs <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return (value(lhs) or value(rhs)) | A disjunction: p OR q | 62598f9e32920d7e50bc5e48 |
class GameMap(State): <NEW_LINE> <INDENT> pass | Game running screen
| 62598f9e32920d7e50bc5e49 |
class RandomPyPolicy(py_policy.Base): <NEW_LINE> <INDENT> def __init__(self, time_step_spec, action_spec, seed=None, outer_dims=None): <NEW_LINE> <INDENT> self._seed = seed <NEW_LINE> self._outer_dims = outer_dims <NEW_LINE> self._rng = np.random.RandomState(seed) <NEW_LINE> if time_step_spec is None: <NEW_LINE> <INDENT> time_step_spec = ts.time_step_spec() <NEW_LINE> <DEDENT> super(RandomPyPolicy, self).__init__( time_step_spec=time_step_spec, action_spec=action_spec) <NEW_LINE> <DEDENT> def _action(self, time_step, policy_state): <NEW_LINE> <INDENT> outer_dims = self._outer_dims <NEW_LINE> if outer_dims is None: <NEW_LINE> <INDENT> if self.time_step_spec().observation: <NEW_LINE> <INDENT> outer_dims = nest_utils.get_outer_array_shape( time_step.observation, self.time_step_spec().observation) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> outer_dims = () <NEW_LINE> <DEDENT> <DEDENT> random_action = array_spec.sample_spec_nest( self._action_spec, self._rng, outer_dims=outer_dims) <NEW_LINE> return policy_step.PolicyStep(random_action, policy_state) | Returns random samples of the given action_spec. | 62598f9e379a373c97d98e08 |
class KokuDBAccess: <NEW_LINE> <INDENT> def __init__(self, schema): <NEW_LINE> <INDENT> self.schema = schema <NEW_LINE> self._db = DB_ENGINE <NEW_LINE> self._meta = self._create_metadata() <NEW_LINE> self._session_factory = sessionmaker(bind=self._db) <NEW_LINE> self._session_registry = scoped_session(self._session_factory) <NEW_LINE> self._session = self._create_session() <NEW_LINE> self._base = self._prepare_base() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._session.begin_nested() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exception_type, exception_value, traceback): <NEW_LINE> <INDENT> if exception_type: <NEW_LINE> <INDENT> self._session.rollback() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._session.commit() <NEW_LINE> <DEDENT> self.close_session() <NEW_LINE> <DEDENT> def _create_metadata(self): <NEW_LINE> <INDENT> return sqlalchemy.MetaData(bind=self._db, schema=self.schema) <NEW_LINE> <DEDENT> def _create_session(self): <NEW_LINE> <INDENT> return self._session_registry() <NEW_LINE> <DEDENT> def close_session(self): <NEW_LINE> <INDENT> self._session.close() <NEW_LINE> <DEDENT> def _prepare_base(self): <NEW_LINE> <INDENT> base = automap_base(metadata=self.get_meta()) <NEW_LINE> base.prepare(self.get_engine(), reflect=True) <NEW_LINE> return base <NEW_LINE> <DEDENT> def get_base(self): <NEW_LINE> <INDENT> return self._base <NEW_LINE> <DEDENT> def get_session(self): <NEW_LINE> <INDENT> return self._session <NEW_LINE> <DEDENT> def get_engine(self): <NEW_LINE> <INDENT> return self._db <NEW_LINE> <DEDENT> def get_meta(self): <NEW_LINE> <INDENT> return self._meta <NEW_LINE> <DEDENT> def _get_db_obj_query(self, **filter_args): <NEW_LINE> <INDENT> obj = self._session.query(self._table) <NEW_LINE> if filter_args: <NEW_LINE> <INDENT> return obj.filter_by(**filter_args) <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def does_db_entry_exist(self): <NEW_LINE> <INDENT> return bool(self._get_db_obj_query().first()) <NEW_LINE> <DEDENT> def add(self, use_savepoint=True, **kwargs): <NEW_LINE> <INDENT> new_entry = self._table(**kwargs) <NEW_LINE> if use_savepoint: <NEW_LINE> <INDENT> self.savepoint(self._session.add, new_entry) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._session.add(new_entry) <NEW_LINE> <DEDENT> return new_entry <NEW_LINE> <DEDENT> def delete(self, obj=None, use_savepoint=True): <NEW_LINE> <INDENT> if obj: <NEW_LINE> <INDENT> deleteme = obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> deleteme = self._obj <NEW_LINE> <DEDENT> if use_savepoint: <NEW_LINE> <INDENT> self.savepoint(self._session.delete, deleteme) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._session.delete(deleteme) <NEW_LINE> <DEDENT> <DEDENT> def commit(self): <NEW_LINE> <INDENT> self._session.commit() <NEW_LINE> <DEDENT> def savepoint(self, func, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with self._session.begin_nested(): <NEW_LINE> <INDENT> func(*args, **kwargs) <NEW_LINE> <DEDENT> self._session.commit() <NEW_LINE> <DEDENT> except sqlalchemy.exc.IntegrityError as exc: <NEW_LINE> <INDENT> LOG.warning('query transaction failed: %s', exc) <NEW_LINE> self._session.rollback() | Base Class to connect to the koku database. | 62598f9e3c8af77a43b67e38 |
class StructuralMeasureLand(StructuralMeasure): <NEW_LINE> <INDENT> Land_Water = "Land" <NEW_LINE> def __init__(self, name, layer, loc, cconstant, cvariable, pot_heights, repfactor=1.2, breachfactor=0.2, htunit="m +MSL", costunit='Million', slope=0.25, irribaren=3, core="clay", layermat="sand", layerthick=1, add_strength=1.0, ): <NEW_LINE> <INDENT> StructuralMeasure.__init__(self, name, layer, loc, cconstant, cvariable, pot_heights, repfactor, breachfactor, htunit) <NEW_LINE> self.CostUnits = costunit <NEW_LINE> self.Slope = slope <NEW_LINE> self.CoreMaterial = core <NEW_LINE> self.LayerMaterial = layermat <NEW_LINE> self.LayerThickness = layerthick <NEW_LINE> self.AddStrength = add_strength <NEW_LINE> self.HeightFail = None <NEW_LINE> self.Irribaren = irribaren <NEW_LINE> self.ConstructionCost = 0 <NEW_LINE> self.RepairCost = 0 <NEW_LINE> self.Active = False | example of object class | 62598f9eac7a0e7691f722fe |
class ExtraFallback(object): <NEW_LINE> <INDENT> def __init__(self, name, fallback): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.fallback = fallback <NEW_LINE> <DEDENT> def __get__(self, instance, owner=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> retval = Configurable.__getattr__(instance, self.name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> retval = None <NEW_LINE> <DEDENT> if retval is None: <NEW_LINE> <INDENT> retval = Configurable.__getattr__(instance, self.fallback) <NEW_LINE> <DEDENT> return retval | Adds another layer of fallback to attributes - to look up
a different attribute name | 62598f9ef7d966606f747ddb |
class ListingTestCase(ReSTExtensionTestCase): <NEW_LINE> <INDENT> sample1 = '.. listing:: nikola.py python' <NEW_LINE> sample2 = '.. code-block:: python\n\n import antigravity' <NEW_LINE> sample3 = '.. sourcecode:: python\n\n import antigravity' <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.f = StringIO("import antigravity\n") <NEW_LINE> super(ListingTestCase, self).setUp() <NEW_LINE> pi = self.compiler.site.plugin_manager.getPluginByName('listing', 'RestExtension') <NEW_LINE> def fake_open(*a, **kw): <NEW_LINE> <INDENT> return self.f <NEW_LINE> <DEDENT> sys.modules[pi.plugin_object.__module__].codecs_open = fake_open <NEW_LINE> <DEDENT> def test_listing(self): <NEW_LINE> <INDENT> self.setHtmlFromRst(self.sample1) <NEW_LINE> <DEDENT> def test_codeblock_alias(self): <NEW_LINE> <INDENT> self.setHtmlFromRst(self.sample2) <NEW_LINE> self.setHtmlFromRst(self.sample3) | Listing test case and CodeBlock alias tests | 62598f9e60cbc95b06364140 |
class msdcc(uh.HasUserContext, uh.StaticHandler): <NEW_LINE> <INDENT> name = "msdcc" <NEW_LINE> checksum_chars = uh.HEX_CHARS <NEW_LINE> checksum_size = 32 <NEW_LINE> @classmethod <NEW_LINE> def _norm_hash(cls, hash): <NEW_LINE> <INDENT> return hash.lower() <NEW_LINE> <DEDENT> def _calc_checksum(self, secret): <NEW_LINE> <INDENT> return hexlify(self.raw(secret, self.user)).decode("ascii") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def raw(cls, secret, user): <NEW_LINE> <INDENT> secret = to_unicode(secret, "utf-8", param="secret").encode("utf-16-le") <NEW_LINE> user = to_unicode(user, "utf-8", param="user").lower().encode("utf-16-le") <NEW_LINE> return md4(md4(secret).digest() + user).digest() | This class implements Microsoft's Domain Cached Credentials password hash,
and follows the :ref:`password-hash-api`.
It has a fixed number of rounds, and uses the associated
username as the salt.
The :meth:`~passlib.ifc.PasswordHash.hash`, :meth:`~passlib.ifc.PasswordHash.genhash`, and :meth:`~passlib.ifc.PasswordHash.verify` methods
have the following optional keywords:
:type user: str
:param user:
String containing name of user account this password is associated with.
This is required to properly calculate the hash.
This keyword is case-insensitive, and should contain just the username
(e.g. ``Administrator``, not ``SOMEDOMAIN\Administrator``).
Note that while this class outputs lower-case hexadecimal digests,
it will accept upper-case digests as well. | 62598f9e627d3e7fe0e06c9e |
class Rectangle(): <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return (self.width * self.height) <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.width * 2) + (self.height * 2) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return(" ") <NEW_LINE> <DEDENT> return('\n'.join(("#" * self.width) for i in range(self.height))) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return('Rectangle({:d}, {:d})'.format(self.width, self.height)) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> print('Bye rectangle...') | define rectangle | 62598f9e3eb6a72ae038a435 |
class Direction(enum.Enum): <NEW_LINE> <INDENT> LEFT = LVector3d(-1, 0, 0) <NEW_LINE> RIGHT = LVector3d(1, 0, 0) <NEW_LINE> FORWARD = LVector3d(0, 1, 0) <NEW_LINE> BACKWARD = LVector3d(0, -1, 0) <NEW_LINE> UP = LVector3d(0, 0, 1) <NEW_LINE> DOWN = LVector3d(0, 0, -1) | Represents a direction vector. | 62598f9e435de62698e9bbe7 |
class UserBatteryExercise(models.Model): <NEW_LINE> <INDENT> user_battery = models.ForeignKey(UserBattery, verbose_name=_('user battery')) <NEW_LINE> exercise = models.ForeignKey(Exercise, verbose_name=_('exercise')) <NEW_LINE> position = models.PositiveSmallIntegerField(_('position')) <NEW_LINE> is_correct = models.NullBooleanField(_('is correct?'), blank=True, null=True) <NEW_LINE> attempts_spent = models.IntegerField(_('attempts left'), default=0) <NEW_LINE> time_spent = models.IntegerField(_('time spent'), default=0) <NEW_LINE> objects = UserBatteryExerciseManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('position',) <NEW_LINE> unique_together = ('user_battery', 'position') <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> return self.user_battery.userbatteryexercise_set.next(ref=self) | Intermediate table for the exercises many to many on the user battery. Adds
a position field to let set a custom ordering for each user. | 62598f9e3617ad0b5ee05f44 |
class PathParameterDetail(generics.RetrieveAPIView): <NEW_LINE> <INDENT> serializer_class = PARAMETER_SERIALIZERS['path'] <NEW_LINE> queryset = PathParameter.objects.all() <NEW_LINE> permission_classes = (permissions.IsAuthenticated, IsChrisOrReadOnly,) | A path parameter view. | 62598f9e56ac1b37e6301fde |
class DescribePrivateZoneResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.PrivateZone = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("PrivateZone") is not None: <NEW_LINE> <INDENT> self.PrivateZone = PrivateZone() <NEW_LINE> self.PrivateZone._deserialize(params.get("PrivateZone")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId") | DescribePrivateZone返回参数结构体
| 62598f9e24f1403a926857ac |
class AuthenticationContextDeclaration(AuthnContextDeclarationBaseType_): <NEW_LINE> <INDENT> c_tag = 'AuthenticationContextDeclaration' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = AuthnContextDeclarationBaseType_.c_children.copy() <NEW_LINE> c_attributes = AuthnContextDeclarationBaseType_.c_attributes.copy() <NEW_LINE> c_child_order = AuthnContextDeclarationBaseType_.c_child_order[:] <NEW_LINE> c_cardinality = AuthnContextDeclarationBaseType_.c_cardinality.copy() | The urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword:AuthenticationContextDeclaration element | 62598f9e4e4d562566372217 |
class RecordObjector(serde.CppSerde): <NEW_LINE> <INDENT> pass | A serializer/deserializer for Flume record | 62598f9e796e427e5384e587 |
class FLCActionServer(object): <NEW_LINE> <INDENT> def __init__(self, name, rate): <NEW_LINE> <INDENT> self.rate = rospy.Rate(rate) <NEW_LINE> rospy.on_shutdown(self.hook_on_shutdown) <NEW_LINE> self._as = actionlib.SimpleActionServer( name, flc_teleoperation.msg.FLCAction, execute_cb=self.execute_cb, auto_start=False) <NEW_LINE> self.flc = FLCClass(rate) <NEW_LINE> self._as.start() <NEW_LINE> <DEDENT> def execute_cb(self, goal): <NEW_LINE> <INDENT> rospy.logdebug(rospy.get_name() + " Goal: \n%s", goal) <NEW_LINE> if goal.run: <NEW_LINE> <INDENT> while not rospy.is_shutdown(): <NEW_LINE> <INDENT> if self._as.is_preempt_requested(): <NEW_LINE> <INDENT> rospy.logdebug(rospy.get_name() + " Preempted") <NEW_LINE> self.flc.zero() <NEW_LINE> break <NEW_LINE> <DEDENT> feedback = self.flc.run() <NEW_LINE> self._as.publish_feedback(flc_teleoperation.msg.FLCFeedback(feedback)) <NEW_LINE> self.rate.sleep() <NEW_LINE> <DEDENT> <DEDENT> self._as.set_succeeded(flc_teleoperation.msg.FLCResult(True)) <NEW_LINE> <DEDENT> def hook_on_shutdown(self): <NEW_LINE> <INDENT> self.flc.shutdown() | Wraps FLC in an ActionServer, for easier enable/disable. | 62598f9e92d797404e388a60 |
class TestD20Treasure(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_simple(self): <NEW_LINE> <INDENT> name="nothing useful" <NEW_LINE> description="Realy, nothing useful." <NEW_LINE> treasure = D20Treasure( value=10, sale_value=20, name=name, description=description) <NEW_LINE> self.assertEqual(treasure.value, 10) <NEW_LINE> self.assertEqual(treasure.sale_value, 20) <NEW_LINE> self.assertEqual(treasure.name, name) <NEW_LINE> self.assertEqual(treasure.description, description) | Unit tests for the D20Treasure class | 62598f9e63d6d428bbee25a6 |
class PlayerSocketProtocol(WebSocketServerProtocol): <NEW_LINE> <INDENT> def onConnect(self, request): <NEW_LINE> <INDENT> self.sendMessage("Player socket established") <NEW_LINE> self.username = "anonymous" <NEW_LINE> WebSocketServerProtocol.onConnect(self, request) <NEW_LINE> <DEDENT> def onMessage(self, payload, isBinary): <NEW_LINE> <INDENT> if not isBinary: <NEW_LINE> <INDENT> part = payload.partition(',') <NEW_LINE> if part[0] == 'setname': <NEW_LINE> <INDENT> self.username = part[2] <NEW_LINE> <DEDENT> elif part[0] == 'getroom': <NEW_LINE> <INDENT> response = self.factory.addToRoom(self, self.username, part[2]) <NEW_LINE> self.sendMessage(json.dumps({'type' : 'response', 'status' : response})) <NEW_LINE> <DEDENT> elif part[0] == 'ready': <NEW_LINE> <INDENT> self.player.markReady() <NEW_LINE> <DEDENT> elif part[0] == 'team': <NEW_LINE> <INDENT> self.player.game.tryTeam(part[2].split(','), self.player) <NEW_LINE> <DEDENT> elif part[0] == 'vote': <NEW_LINE> <INDENT> self.player.setVote(part[2]) <NEW_LINE> self.player.game.checkTeamVotes() <NEW_LINE> <DEDENT> elif part[0] == 'mission': <NEW_LINE> <INDENT> self.player.setVote(part[2]) <NEW_LINE> self.player.game.checkMission() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Malformed command:", payload, "from", self.peer) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def connectionLost(self, reason): <NEW_LINE> <INDENT> WebSocketServerProtocol.connectionLost(self, reason) <NEW_LINE> if hasattr(self, 'player'): <NEW_LINE> <INDENT> self.player.destroy() <NEW_LINE> <DEDENT> <DEDENT> def setPlayer(self, player): <NEW_LINE> <INDENT> self.player = player | WebSocket protocol for handling players.
Handles private communication between a player and the server. | 62598f9e63d6d428bbee25a5 |
class dropout: <NEW_LINE> <INDENT> def __init__(self, prob_dropout): <NEW_LINE> <INDENT> assert 0 <= prob_dropout < 1 <NEW_LINE> self.p_dropout = prob_dropout <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> if not self.p_dropout: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> drop_mask = np.random.binomial(1, (1 - self.p_dropout), x.shape) <NEW_LINE> return x * drop_mask / (1 - self.p_dropout) <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameters(self): <NEW_LINE> <INDENT> return tuple() | A dropout layer
This layer will randomly set elements of a tensor to 0, with some specified probability p.
Those elements that pass through unmasked are scaled by a factor of 1 / (1 - p), such that
the magnitude of the tensor, in expectation, is unaffected by the dropout layer.
Examples
--------
>>> import mygrad as mg
>>> x = mg.Tensor([1, 2, 3])
"Dropout" each element of `x` with probability p=0.5. The other elements
are scaled by 1 / (1-p) so that the magnitude of `x`, on average, remains
unchanged.
>>> dropout(x, prob_dropout=0.5)
Tensor([2., 0., 6.])
>>> dropout(x, prob_dropout=0.5)
Tensor([0., 0., 6.])
>>> dropout(x, prob_dropout=0.5)
Tensor([2., 4., 0.]) | 62598f9e38b623060ffa8e86 |
class CustomTermMixin(object): <NEW_LINE> <INDENT> def __new__(cls, inputs=NotSpecified, window_length=NotSpecified, dtype=NotSpecified, missing_value=NotSpecified, **kwargs): <NEW_LINE> <INDENT> unexpected_keys = set(kwargs) - set(cls.params) <NEW_LINE> if unexpected_keys: <NEW_LINE> <INDENT> raise TypeError( "{termname} received unexpected keyword " "arguments {unexpected}".format( termname=cls.__name__, unexpected={k: kwargs[k] for k in unexpected_keys}, ) ) <NEW_LINE> <DEDENT> return super(CustomTermMixin, cls).__new__( cls, inputs=inputs, window_length=window_length, dtype=dtype, missing_value=missing_value, **kwargs ) <NEW_LINE> <DEDENT> def compute(self, today, assets, out, *arrays): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _compute(self, windows, dates, assets, mask): <NEW_LINE> <INDENT> compute = self.compute <NEW_LINE> missing_value = self.missing_value <NEW_LINE> params = self.params <NEW_LINE> out = full_like(mask, missing_value, dtype=self.dtype) <NEW_LINE> with self.ctx: <NEW_LINE> <INDENT> for idx, date in enumerate(dates): <NEW_LINE> <INDENT> compute( date, assets, out[idx], *(next(w) for w in windows), **params ) <NEW_LINE> <DEDENT> <DEDENT> out[~mask] = missing_value <NEW_LINE> return out <NEW_LINE> <DEDENT> def short_repr(self): <NEW_LINE> <INDENT> return type(self).__name__ + '(%d)' % self.window_length | Mixin for user-defined rolling-window Terms.
Implements `_compute` in terms of a user-defined `compute` function, which
is mapped over the input windows.
Used by CustomFactor, CustomFilter, CustomClassifier, etc. | 62598f9ed53ae8145f918282 |
class EntityRegistryDisabledHandler: <NEW_LINE> <INDENT> RELOAD_AFTER_UPDATE_DELAY = 30 <NEW_LINE> def __init__(self, hass: HomeAssistant) -> None: <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.registry: Optional[entity_registry.EntityRegistry] = None <NEW_LINE> self.changed: Set[str] = set() <NEW_LINE> self._remove_call_later: Optional[Callable[[], None]] = None <NEW_LINE> <DEDENT> @callback <NEW_LINE> def async_setup(self) -> None: <NEW_LINE> <INDENT> self.hass.bus.async_listen( entity_registry.EVENT_ENTITY_REGISTRY_UPDATED, self._handle_entry_updated ) <NEW_LINE> <DEDENT> async def _handle_entry_updated(self, event: Event) -> None: <NEW_LINE> <INDENT> if ( event.data["action"] != "update" or "disabled_by" not in event.data["changes"] ): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.registry is None: <NEW_LINE> <INDENT> self.registry = await entity_registry.async_get_registry(self.hass) <NEW_LINE> <DEDENT> entity_entry = self.registry.async_get(event.data["entity_id"]) <NEW_LINE> if ( entity_entry is None or entity_entry.config_entry_id is None or entity_entry.disabled_by ): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> config_entry = self.hass.config_entries.async_get_entry( entity_entry.config_entry_id ) <NEW_LINE> assert config_entry is not None <NEW_LINE> if config_entry.entry_id not in self.changed and await support_entry_unload( self.hass, config_entry.domain ): <NEW_LINE> <INDENT> self.changed.add(config_entry.entry_id) <NEW_LINE> <DEDENT> if not self.changed: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self._remove_call_later: <NEW_LINE> <INDENT> self._remove_call_later() <NEW_LINE> <DEDENT> self._remove_call_later = self.hass.helpers.event.async_call_later( self.RELOAD_AFTER_UPDATE_DELAY, self._handle_reload ) <NEW_LINE> <DEDENT> async def _handle_reload(self, _now: Any) -> None: <NEW_LINE> <INDENT> self._remove_call_later = None <NEW_LINE> to_reload = self.changed <NEW_LINE> self.changed = set() <NEW_LINE> _LOGGER.info( "Reloading configuration entries because disabled_by changed in entity registry: %s", ", ".join(self.changed), ) <NEW_LINE> await asyncio.gather( *[self.hass.config_entries.async_reload(entry_id) for entry_id in to_reload] ) | Handler to handle when entities related to config entries updating disabled_by. | 62598f9e4428ac0f6e65831f |
class ClearChargingProfileStatus(str, Enum): <NEW_LINE> <INDENT> accepted = "Accepted" <NEW_LINE> unknown = "Unknown" | Status returned in response to ClearChargingProfile.req. | 62598f9e498bea3a75a57915 |
class CenterLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_classes=10, feat_dim=2, use_gpu=True): <NEW_LINE> <INDENT> super(CenterLoss, self).__init__() <NEW_LINE> self.num_classes = num_classes <NEW_LINE> self.feat_dim = feat_dim <NEW_LINE> self.use_gpu = use_gpu <NEW_LINE> if self.use_gpu: <NEW_LINE> <INDENT> self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim).cuda()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim)) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x, labels): <NEW_LINE> <INDENT> batch_size = x.size(0) <NEW_LINE> distmat = torch.pow(x, 2).sum(dim=1, keepdim=True).expand(batch_size, self.num_classes) + torch.pow(self.centers, 2).sum(dim=1, keepdim=True).expand(self.num_classes, batch_size).t() <NEW_LINE> distmat.addmm_(x, self.centers.t(), beta=1, alpha=-2) <NEW_LINE> classes = torch.arange(self.num_classes).long() <NEW_LINE> if self.use_gpu: classes = classes.cuda() <NEW_LINE> labels = labels.unsqueeze(1).expand(batch_size, self.num_classes) <NEW_LINE> mask = labels.eq(classes.expand(batch_size, self.num_classes)) <NEW_LINE> dist = distmat * mask.float() <NEW_LINE> loss = dist.clamp(min=1e-12, max=1e+12).sum() / batch_size <NEW_LINE> return loss | Center loss.
Reference:
Wen et al. A Discriminative Feature Learning Approach for Deep Face Recognition. ECCV 2016.
Args:
num_classes (int): number of classes.
feat_dim (int): feature dimension. | 62598f9e8e71fb1e983bb8aa |
class Profile(models.Model): <NEW_LINE> <INDENT> dating_gender = models.CharField(max_length=16, default='女') <NEW_LINE> dating_location = models.CharField(max_length=16, default='上海') <NEW_LINE> max_distance = models.IntegerField(default=5) <NEW_LINE> min_distance = models.IntegerField(default=1) <NEW_LINE> max_dating_age = models.IntegerField(default=30) <NEW_LINE> min_dating_age = models.IntegerField(default=18) <NEW_LINE> vibration = models.BooleanField(default=True) <NEW_LINE> only_matched = models.BooleanField(default=True) <NEW_LINE> auto_play = models.BooleanField(default=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'profile' <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> data = { 'dating_gender': self.dating_gender, 'dating_location': self.dating_location, 'max_distance': self.max_distance, 'min_distance': self.min_distance, 'max_dating_age': self.max_dating_age, 'min_dating_age': self.min_dating_age, 'vibration': self.vibration, 'only_matched': self.only_matched, 'auto_play': self.auto_play, } <NEW_LINE> return data | dating_gender Yes str 匹配的性别
dating_location Yes str ⽬标城市
max_distance Yes float 最⼤查找范围
min_distance Yes float 最⼩查找范围
max_dating_age Yes int 最⼤交友年龄
min_dating_age Yes int 最⼩交友年龄
vibration Yes bool 开启震动
only_matched Yes bool 不让为匹配的⼈看我的相册
auto_play Yes bool ⾃动播放视频 | 62598f9e55399d3f05626316 |
class RestRequest: <NEW_LINE> <INDENT> def __init__(self, method=None, uri=None, parameters=None, headers=None, body=None,): <NEW_LINE> <INDENT> self.method = method <NEW_LINE> self.uri = uri <NEW_LINE> self.parameters = parameters <NEW_LINE> self.headers = headers <NEW_LINE> self.body = body | Attributes:
- method
- uri
- parameters
- headers
- body | 62598f9e57b8e32f52508016 |
class UserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = MyUser <NEW_LINE> fields = ('username', 'email', 'firstname', 'lastname', 'year', 'current_location', 'major', 'current_job', 'is_active', 'is_admin') <NEW_LINE> exclude = ('password',) <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> user = super(UserChangeForm, self).save(commit=False) <NEW_LINE> if commit: <NEW_LINE> <INDENT> user.save() <NEW_LINE> <DEDENT> return user | A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field. | 62598f9e460517430c431f55 |
class PageLink(object): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{0.__class__.__name__}({0.title!r})'.format(self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return unicode(self).encode('utf8') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '{0.__class__.__name__}({0.title})'.format(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def language(self): <NEW_LINE> <INDENT> return object_mapper(self).language | A PageLink | 62598f9e97e22403b383ad00 |
class Resource(Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__(self, location=None, tags=None): <NEW_LINE> <INDENT> self.id = None <NEW_LINE> self.name = None <NEW_LINE> self.type = None <NEW_LINE> self.location = location <NEW_LINE> self.tags = tags | Resource
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id
:vartype id: str
:ivar name: Resource name
:vartype name: str
:ivar type: Resource type
:vartype type: str
:param location: Resource location
:type location: str
:param tags: Resource tags
:type tags: dict | 62598f9e32920d7e50bc5e4a |
class AfterOpenCallback(callback.AbstractCallback, object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def filter(cls, *args): <NEW_LINE> <INDENT> return True, args <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def register(cls, fn): <NEW_LINE> <INDENT> return OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kAfterOpen, fn) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def unregister(cls, token): <NEW_LINE> <INDENT> if token: <NEW_LINE> <INDENT> OpenMaya.MSceneMessage.removeCallback(token) | Callback that is called before opening a DCC scene | 62598f9ec432627299fa2dce |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.