blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 288 | content_id stringlengths 40 40 | detected_licenses listlengths 0 112 | license_type stringclasses 2 values | repo_name stringlengths 5 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 684 values | visit_date timestamp[us]date 2015-08-06 10:31:46 2023-09-06 10:44:38 | revision_date timestamp[us]date 1970-01-01 02:38:32 2037-05-03 13:00:00 | committer_date timestamp[us]date 1970-01-01 02:38:32 2023-09-06 01:08:06 | github_id int64 4.92k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-04 01:52:49 2023-09-14 21:59:50 ⌀ | gha_created_at timestamp[us]date 2008-05-22 07:58:19 2023-08-21 12:35:19 ⌀ | gha_language stringclasses 147 values | src_encoding stringclasses 25 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 128 12.7k | extension stringclasses 142 values | content stringlengths 128 8.19k | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f02ac273758d4f2552d34614c634edef88e64261 | 2a92c55d9231ecdae90c9eb6b3ae7ccc8860b67e | /ding/utils/tests/test_default_helper.py | a98d50090ed901e1f72f112678fd5adfc41196a0 | [
"Apache-2.0"
] | permissive | likeucode/DI-engine | b12bbaaf8c551dbe7869604b270c6b95c1fa6390 | b9d52cbff9d0510473715d90b3a426e0fb1c39f4 | refs/heads/main | 2023-06-20T16:43:34.621930 | 2021-07-12T10:59:24 | 2021-07-12T10:59:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,224 | py | import pytest
import numpy as np
import torch
from collections import namedtuple
from ding.utils.default_helper import lists_to_dicts, dicts_to_lists, squeeze, default_get, override, error_wrapper,\
list_split, LimitedSpaceContainer, set_pkg_seed, deep_merge_dicts, deep_update, flatten_dict
@pytest.mark.unittest
class TestDefaultHelper():
def test_lists_to_dicts(self):
set_pkg_seed(12)
with pytest.raises(ValueError):
lists_to_dicts([])
with pytest.raises(TypeError):
lists_to_dicts([1])
assert lists_to_dicts([{1: 1, 10: 3}, {1: 2, 10: 4}]) == {1: [1, 2], 10: [3, 4]}
T = namedtuple('T', ['location', 'race'])
data = [T({'x': 1, 'y': 2}, 'zerg') for _ in range(3)]
output = lists_to_dicts(data)
assert isinstance(output, T) and output.__class__ == T
assert len(output.location) == 3
data = [{'value': torch.randn(1), 'obs': {'scalar': torch.randn(4)}} for _ in range(3)]
output = lists_to_dicts(data, recursive=True)
assert isinstance(output, dict)
assert len(output['value']) == 3
assert len(output['obs']['scalar']) == 3
def test_dicts_to_lists(self):
assert dicts_to_lists({1: [1, 2], 10: [3, 4]}) == [{1: 1, 10: 3}, {1: 2, 10: 4}]
def test_squeeze(self):
assert squeeze((4, )) == 4
assert squeeze({'a': 4}) == 4
assert squeeze([1, 3]) == (1, 3)
data = np.random.randn(3)
output = squeeze(data)
assert (output == data).all()
def test_default_get(self):
assert default_get({}, 'a', default_value=1, judge_fn=lambda x: x < 2) == 1
assert default_get({}, 'a', default_fn=lambda: 1, judge_fn=lambda x: x < 2) == 1
with pytest.raises(AssertionError):
default_get({}, 'a', default_fn=lambda: 1, judge_fn=lambda x: x < 0)
assert default_get({'val': 1}, 'val', default_value=2) == 1
def test_override(self):
class foo(object):
def fun(self):
raise NotImplementedError
class foo1(foo):
@override(foo)
def fun(self):
return "a"
with pytest.raises(NameError):
class foo2(foo):
@override(foo)
def func(self):
pass
with pytest.raises(NotImplementedError):
foo().fun()
foo1().fun()
def test_error_wrapper(self):
def good_ret(a, b=1):
return a + b
wrap_good_ret = error_wrapper(good_ret, 0)
assert good_ret(1) == wrap_good_ret(1)
def bad_ret(a, b=0):
return a / b
wrap_bad_ret = error_wrapper(bad_ret, 0)
assert wrap_bad_ret(1) == 0
def test_list_split(self):
data = [i for i in range(10)]
output, residual = list_split(data, step=4)
assert len(output) == 2
assert output[1] == [4, 5, 6, 7]
assert residual == [8, 9]
output, residual = list_split(data, step=5)
assert len(output) == 2
assert output[1] == [5, 6, 7, 8, 9]
assert residual is None
@pytest.mark.unittest
class TestLimitedSpaceContainer():
def test_container(self):
container = LimitedSpaceContainer(0, 5)
first = container.acquire_space()
assert first
assert container.cur == 1
left = container.get_residual_space()
assert left == 4
assert container.cur == container.max_val == 5
no_space = container.acquire_space()
assert not no_space
container.increase_space()
six = container.acquire_space()
assert six
for i in range(6):
container.release_space()
assert container.cur == 5 - i
container.decrease_space()
assert container.max_val == 5
class TestDict:
def test_deep_merge_dicts(self):
dict1 = {
'a': 3,
'b': {
'c': 3,
'd': {
'e': 6,
'f': 5,
}
}
}
dict2 = {
'b': {
'c': 5,
'd': 6,
'g': 4,
}
}
new_dict = deep_merge_dicts(dict1, dict2)
assert new_dict['a'] == 3
assert isinstance(new_dict['b'], dict)
assert new_dict['b']['c'] == 5
assert new_dict['b']['c'] == 5
assert new_dict['b']['g'] == 4
def test_deep_update(self):
dict1 = {
'a': 3,
'b': {
'c': 3,
'd': {
'e': 6,
'f': 5,
},
'z': 4,
}
}
dict2 = {
'b': {
'c': 5,
'd': 6,
'g': 4,
}
}
with pytest.raises(RuntimeError):
new1 = deep_update(dict1, dict2, new_keys_allowed=False)
new2 = deep_update(dict1, dict2, new_keys_allowed=False, whitelist=['b'])
assert new2['a'] == 3
assert new2['b']['c'] == 5
assert new2['b']['d'] == 6
assert new2['b']['g'] == 4
assert new2['b']['z'] == 4
dict1 = {
'a': 3,
'b': {
'type': 'old',
'z': 4,
}
}
dict2 = {
'b': {
'type': 'new',
'c': 5,
}
}
new3 = deep_update(dict1, dict2, new_keys_allowed=True, whitelist=[], override_all_if_type_changes=['b'])
assert new3['a'] == 3
assert new3['b']['type'] == 'new'
assert new3['b']['c'] == 5
assert 'z' not in new3['b']
def test_flatten_dict(self):
dict = {
'a': 3,
'b': {
'c': 3,
'd': {
'e': 6,
'f': 5,
},
'z': 4,
}
}
flat = flatten_dict(dict)
assert flat['a'] == 3
assert flat['b/c'] == 3
assert flat['b/d/e'] == 6
assert flat['b/d/f'] == 5
assert flat['b/z'] == 4
| [
"niuyazhe@sensetime.com"
] | niuyazhe@sensetime.com |
ed7ab5a8cb6df66a778b614bb5158c176d873820 | 783ad25f38785023edcc8a6580645e26e68f1fe7 | /app/blog/models.py | 8714344dcd1cc23012e17d01c2836c6c54f2ee93 | [] | no_license | Chrisaor/udemy_blog_practice | be2b255674469833a6f3151ace83acbf21c6cb97 | 80894413b994f7ef23b1046c56550f178d7b4f65 | refs/heads/master | 2020-03-27T06:57:17.441237 | 2018-08-28T08:14:52 | 2018-08-28T08:14:52 | 146,150,371 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,974 | py | from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
from taggit.managers import TaggableManager
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE)
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager()
published = PublishedManager()
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse(
'blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug
]
)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return f'Comment by {self.name} on {self.post}' | [
"pchpch0070@gmail.com"
] | pchpch0070@gmail.com |
aa58c82b4327706f456feef6424d55b16b5e017c | 2ee6c9320c617b77db62cb1199e4096d1066c2a8 | /code/compute_correlation_distance.py | 0883792785e512174c2719013b152214f248cab5 | [
"MIT"
] | permissive | smaharry/make_context_map | 546f34a104156b5976e33a8f492139e1d70afdad | 7576ff4de8d469a78ea4f0a373eb917f41671ec3 | refs/heads/master | 2020-03-23T06:45:46.290382 | 2018-07-15T05:06:53 | 2018-07-15T05:06:53 | 141,227,940 | 0 | 0 | null | 2018-07-17T03:46:28 | 2018-07-17T03:46:28 | null | UTF-8 | Python | false | false | 215 | py | from numpy import absolute, where
from scipy.spatial.distance import correlation
def compute_correlation_distance(x, y):
distance = correlation(x, y)
return where(absolute(distance) < 1e-8, 0, distance)
| [
"kwatme8@gmail.com"
] | kwatme8@gmail.com |
90643e96ad726c79d5568b85a812ad2e56038e83 | a2d36e471988e0fae32e9a9d559204ebb065ab7f | /huaweicloud-sdk-mpc/huaweicloudsdkmpc/v1/model/list_animated_graphics_task_request.py | 8af6dce2114433edef47809660a1e5069cb0002c | [
"Apache-2.0"
] | permissive | zhouxy666/huaweicloud-sdk-python-v3 | 4d878a90b8e003875fc803a61414788e5e4c2c34 | cc6f10a53205be4cb111d3ecfef8135ea804fa15 | refs/heads/master | 2023-09-02T07:41:12.605394 | 2021-11-12T03:20:11 | 2021-11-12T03:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,488 | py | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListAnimatedGraphicsTaskRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'x_language': 'str',
'task_id': 'list[str]',
'status': 'str',
'start_time': 'str',
'end_time': 'str',
'page': 'int',
'size': 'int'
}
attribute_map = {
'x_language': 'x-language',
'task_id': 'task_id',
'status': 'status',
'start_time': 'start_time',
'end_time': 'end_time',
'page': 'page',
'size': 'size'
}
def __init__(self, x_language=None, task_id=None, status=None, start_time=None, end_time=None, page=None, size=None):
"""ListAnimatedGraphicsTaskRequest - a model defined in huaweicloud sdk"""
self._x_language = None
self._task_id = None
self._status = None
self._start_time = None
self._end_time = None
self._page = None
self._size = None
self.discriminator = None
if x_language is not None:
self.x_language = x_language
if task_id is not None:
self.task_id = task_id
if status is not None:
self.status = status
if start_time is not None:
self.start_time = start_time
if end_time is not None:
self.end_time = end_time
if page is not None:
self.page = page
if size is not None:
self.size = size
@property
def x_language(self):
"""Gets the x_language of this ListAnimatedGraphicsTaskRequest.
客户端语言
:return: The x_language of this ListAnimatedGraphicsTaskRequest.
:rtype: str
"""
return self._x_language
@x_language.setter
def x_language(self, x_language):
"""Sets the x_language of this ListAnimatedGraphicsTaskRequest.
客户端语言
:param x_language: The x_language of this ListAnimatedGraphicsTaskRequest.
:type: str
"""
self._x_language = x_language
@property
def task_id(self):
"""Gets the task_id of this ListAnimatedGraphicsTaskRequest.
任务ID。一次最多10个
:return: The task_id of this ListAnimatedGraphicsTaskRequest.
:rtype: list[str]
"""
return self._task_id
@task_id.setter
def task_id(self, task_id):
"""Sets the task_id of this ListAnimatedGraphicsTaskRequest.
任务ID。一次最多10个
:param task_id: The task_id of this ListAnimatedGraphicsTaskRequest.
:type: list[str]
"""
self._task_id = task_id
@property
def status(self):
"""Gets the status of this ListAnimatedGraphicsTaskRequest.
任务执行状态。 取值如下: - INIT:初始状态 - WAITING:待启动 - PREPROCESSING:处理中 - SUCCEED:处理成功 - FAILED:处理失败 - CANCELED:已取消
:return: The status of this ListAnimatedGraphicsTaskRequest.
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this ListAnimatedGraphicsTaskRequest.
任务执行状态。 取值如下: - INIT:初始状态 - WAITING:待启动 - PREPROCESSING:处理中 - SUCCEED:处理成功 - FAILED:处理失败 - CANCELED:已取消
:param status: The status of this ListAnimatedGraphicsTaskRequest.
:type: str
"""
self._status = status
@property
def start_time(self):
"""Gets the start_time of this ListAnimatedGraphicsTaskRequest.
起始时间。格式为yyyymmddhhmmss。必须是与时区无关的UTC时间,指定task_id时该参数无效。
:return: The start_time of this ListAnimatedGraphicsTaskRequest.
:rtype: str
"""
return self._start_time
@start_time.setter
def start_time(self, start_time):
"""Sets the start_time of this ListAnimatedGraphicsTaskRequest.
起始时间。格式为yyyymmddhhmmss。必须是与时区无关的UTC时间,指定task_id时该参数无效。
:param start_time: The start_time of this ListAnimatedGraphicsTaskRequest.
:type: str
"""
self._start_time = start_time
@property
def end_time(self):
"""Gets the end_time of this ListAnimatedGraphicsTaskRequest.
结束时间。格式为yyyymmddhhmmss。必须是与时区无关的UTC时间,指定task_id时该参数无效。
:return: The end_time of this ListAnimatedGraphicsTaskRequest.
:rtype: str
"""
return self._end_time
@end_time.setter
def end_time(self, end_time):
"""Sets the end_time of this ListAnimatedGraphicsTaskRequest.
结束时间。格式为yyyymmddhhmmss。必须是与时区无关的UTC时间,指定task_id时该参数无效。
:param end_time: The end_time of this ListAnimatedGraphicsTaskRequest.
:type: str
"""
self._end_time = end_time
@property
def page(self):
"""Gets the page of this ListAnimatedGraphicsTaskRequest.
分页编号。查询指定“task_id”时,该参数无效。 默认值:0。
:return: The page of this ListAnimatedGraphicsTaskRequest.
:rtype: int
"""
return self._page
@page.setter
def page(self, page):
"""Sets the page of this ListAnimatedGraphicsTaskRequest.
分页编号。查询指定“task_id”时,该参数无效。 默认值:0。
:param page: The page of this ListAnimatedGraphicsTaskRequest.
:type: int
"""
self._page = page
@property
def size(self):
"""Gets the size of this ListAnimatedGraphicsTaskRequest.
每页记录数。查询指定“task_id”时,该参数无效。 取值范围:[1,100]。 默认值:10。
:return: The size of this ListAnimatedGraphicsTaskRequest.
:rtype: int
"""
return self._size
@size.setter
def size(self, size):
"""Sets the size of this ListAnimatedGraphicsTaskRequest.
每页记录数。查询指定“task_id”时,该参数无效。 取值范围:[1,100]。 默认值:10。
:param size: The size of this ListAnimatedGraphicsTaskRequest.
:type: int
"""
self._size = size
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListAnimatedGraphicsTaskRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
fc47032d814f6da3b38ecb3c4c5bb906406252d5 | b0f41ef2af5309fc172b05232dbde501a01d1234 | /fyt/transport/migrations/0014_internalbus_dirty.py | a3ee52824f918bac16f74cb05ce4a9b350f850ce | [] | no_license | rlmv/doc-trips | c4dfec9b80cf531b69b17ac2caaef509fa048cd3 | 59c1ffc0bff1adb4f86f1dcfaa66d8970ff55b72 | refs/heads/master | 2023-05-27T01:48:49.251830 | 2021-08-07T04:02:26 | 2021-08-07T04:02:26 | 21,745,373 | 10 | 3 | null | 2023-05-23T00:51:26 | 2014-07-11T17:36:35 | Python | UTF-8 | Python | false | false | 533 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-09 14:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('transport', '0013_auto_20170808_1114'),
]
operations = [
migrations.AddField(
model_name='internalbus',
name='dirty',
field=models.BooleanField(default=True, editable=False, verbose_name='Do directions and times need to be updated?'),
),
]
| [
"bo.marchman@gmail.com"
] | bo.marchman@gmail.com |
795233071e9dd7e7b8a2fcdde2e93c79fff0d7ef | b1ea2d35e6ef999c6c15a6af7892573de40cbf54 | /thrift/compiler/codemod/cppref_to_structured_test.py | db313297dce1b33e99f48e1cda6ca5c927d1e053 | [
"Apache-2.0"
] | permissive | billybob3659/fbthrift | 76db526d4d1f7457697184dada0de1b3d38572aa | 3a47e3b8259867a1ca68dd155b473387aa9aa3d7 | refs/heads/master | 2023-07-27T07:53:08.917232 | 2021-09-11T02:22:31 | 2021-09-11T02:24:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,934 | py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import shutil
import tempfile
import textwrap
import unittest
from thrift.compiler.codemod.test_utils import write_file, run_binary, read_file
# TODO(urielrivas): We can use clangr's unit-test formatting in the future.
class CppRefToUnstructured(unittest.TestCase):
def setUp(self):
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
self.tmp = tmp
self.addCleanup(os.chdir, os.getcwd())
os.chdir(self.tmp)
self.maxDiff = None
def test_basic_replace(self):
write_file(
"foo.thrift",
textwrap.dedent(
"""\
struct Faa {
1: i32 faa1;
2: optional Faa faa2 (cpp.ref);
3: i32 faa3;
}
"""
),
)
run_binary("cppref_to_structured", "foo.thrift")
# NOTE: For current tests, user should rely on automated formatting.
self.assertEqual(
read_file("foo.thrift"),
textwrap.dedent(
"""\
include "thrift/lib/thrift/annotation/cpp.thrift"
struct Faa {
1: i32 faa1;
@cpp.Ref{type = cpp.RefType.Unique}
2: optional Faa faa2 ;
3: i32 faa3;
}
"""
),
)
def test_existing_includes(self):
write_file("a.thrift", "")
write_file("b.thrift", "")
write_file("c.thrift", "")
write_file(
"foo.thrift",
textwrap.dedent(
"""\
include "a.thrift"
include "b.thrift"
include "c.thrift"
struct Faa {
1: i32 faa1;
2: optional Faa faa2 (cpp.ref);
3: i32 faa3;
}
"""
),
)
run_binary("cppref_to_structured", "foo.thrift")
self.assertEqual(
read_file("foo.thrift"),
textwrap.dedent(
"""\
include "a.thrift"
include "b.thrift"
include "c.thrift"
include "thrift/lib/thrift/annotation/cpp.thrift"
struct Faa {
1: i32 faa1;
@cpp.Ref{type = cpp.RefType.Unique}
2: optional Faa faa2 ;
3: i32 faa3;
}
"""
),
)
def test_namespaces(self):
write_file(
"foo.thrift",
textwrap.dedent(
"""\
namespace cpp2 apache.thrift
namespace py3 thrift.lib.thrift
struct Faa {
1: i32 faa1;
2: optional Faa faa2 (cpp.ref);
3: i32 faa3;
}
"""
),
)
run_binary("cppref_to_structured", "foo.thrift")
self.assertEqual(
read_file("foo.thrift"),
textwrap.dedent(
"""\
namespace cpp2 apache.thrift
namespace py3 thrift.lib.thrift
struct Faa {
1: i32 faa1;
2: optional Faa faa2 (cpp.ref);
3: i32 faa3;
}
"""
),
)
def test_cpp_and_cpp2(self):
write_file(
"foo.thrift",
textwrap.dedent(
"""\
struct Faa {
1: i32 faa1;
2: optional Faa faa2 (cpp.ref = "true", cpp2.ref = "true");
3: i32 faa3;
}
"""
),
)
run_binary("cppref_to_structured", "foo.thrift")
self.assertEqual(
read_file("foo.thrift"),
textwrap.dedent(
"""\
include "thrift/lib/thrift/annotation/cpp.thrift"
struct Faa {
1: i32 faa1;
@cpp.Ref{type = cpp.RefType.Unique}
2: optional Faa faa2 ;
3: i32 faa3;
}
"""
),
)
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
20fb562e6d3d641947e0b2e932a176398c67ac1c | cf32120ab89eadcb3427d035a7d826f88ece6a8b | /most_common_word.py | a6bc2c0ab8c7362c5e0165724945f51ec15048ff | [] | no_license | jaehyunan11/leetcode_Practice | 2037bcce72c84ba3002f20230f59722d69433b8a | e80f56f2334b260935e4ebc4b8dbba404601099c | refs/heads/main | 2023-04-23T16:53:31.502597 | 2021-05-14T16:47:08 | 2021-05-14T16:47:08 | 335,520,444 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,579 | py | import re
class Solution:
def mostCommonWord(self, paragraph, banned):
# 1) Create tracking empty dict
tracking_dict = {}
print(f"Initial Paragraph: {paragraph}")
# 2) Replace punctuation by Whitespace (re.sub(pattern, what to replace, string to be applied))
no_punc_paragraph = re.sub('[^A-Za-z0-9]+', ' ', paragraph)
print(f"Removed punctuation: {no_punc_paragraph}")
# 3) Repalce to all lower case
all_lower = no_punc_paragraph.lower()
print(f"all_lower case: {all_lower}")
# 4) Word to split in the list
words = all_lower.split(' ')
print(f"words: {words}")
# 5) Loop through the words and count them.
for val in words:
# word in not in banned and not in empty case
if val not in banned and val != '':
if val not in tracking_dict:
tracking_dict[val] = 1
else:
tracking_dict[val] += 1
print(f"Tracking dictionary:{tracking_dict}")
# 6) sorted tracking_dict by descending order
sorted_dict = sorted(tracking_dict.items(),
key=lambda x: (-x[1], x[0]))
print(f"Sorted Dictionary: {sorted_dict}")
# 7) return first key in the first index from sorted dictionary
return sorted_dict[0][0]
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
s = Solution()
print(s.mostCommonWord(paragraph, banned))
# Time Complexity: O(N)
# Space Complexity: O(N)
| [
"jaehyuna11@gmail.com"
] | jaehyuna11@gmail.com |
41e318ff00f74700378e23339ff1f5d861ad3f22 | 4f3786c072c3fb7992924c7a714b626c04849d4a | /auto_tag/cli.py | b6f510830722e05731888e3eca32730c7dd68896 | [
"MIT"
] | permissive | mateimicu/auto-tag | b8deebc61020f3e4cb75646bb3cc7cadb2801242 | 3ecbb005e5e585983a65fa15f7d6bf011b25752e | refs/heads/master | 2023-04-14T08:49:01.778689 | 2023-04-01T19:50:06 | 2023-04-01T19:50:06 | 205,390,141 | 13 | 1 | NOASSERTION | 2023-04-10T03:32:24 | 2019-08-30T13:41:35 | Python | UTF-8 | Python | false | false | 2,255 | py | #!/usr/bin/env python3
"""
CLI parser for auto-tag.
"""
import logging
import argparse
from auto_tag import constants
from auto_tag import tag_search_strategy
def get_parser() -> argparse.ArgumentParser:
"""Return the argument parser setup."""
parser = argparse.ArgumentParser(
description='Tag branch based on commit messages')
parser.add_argument('-b', '--branch', type=str, default='master',
help='On what branch to work on. Default `master`')
parser.add_argument('-r', '--repo', type=str, default='.',
help='Path to repository. Default `.`')
parser.add_argument('-u', '--upstream_remote', type=str, nargs='*',
help=('To what remote to push to.'
'Can be specified multiple time.'))
# pylint:disable=no-member, protected-access
parser.add_argument('-l', '--logging', type=str, default='INFO',
help='Logging level.',
choices=list(logging._nameToLevel.keys()))
parser.add_argument('--name', type=str, default=None,
help=('User name used for creating git objects.'
'If not specified the system one will be used.'))
parser.add_argument('--email', type=str, default=None,
help=('Email name used for creating git objects.'
'If not specified the system one will be used.'))
parser.add_argument('-c', '--config', type=str, default=None,
help='Path to detectors configuration.')
parser.add_argument('--skip-tag-if-one-already-present',
action='store_true',
help=('If a tag is already present on the latest '
'commit don\'t apply a new tag'))
parser.add_argument('--append-v-to-tag', action='store_true',
help='Append a v to the tag (ex v1.0.5)')
parser.add_argument('--tag-search-strategy',
choices=constants.SEARCH_STRATEGYS,
default=tag_search_strategy.DEFAULT_STRAGETY_NAME,
help='Strategy for searching the tag.')
return parser
| [
"micumatei@gmail.com"
] | micumatei@gmail.com |
e2d777d064e7ed3dda93b0e8f1bacdc17ea9f653 | cfb4e8721137a096a23d151f2ff27240b218c34c | /mypower/matpower_ported/most/lib/t/t_most_3b_3_1_2.py | 949872d688a7f318f2ec770df9b004ed818ae28f | [
"Apache-2.0"
] | permissive | suryo12/mypower | eaebe1d13f94c0b947a3c022a98bab936a23f5d3 | ee79dfffc057118d25f30ef85a45370dfdbab7d5 | refs/heads/master | 2022-11-25T16:30:02.643830 | 2020-08-02T13:16:20 | 2020-08-02T13:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 166 | py | def t_most_3b_3_1_2(*args,nout=1,oc=None):
if oc == None:
from .....oc_matpower import oc_matpower
oc = oc_matpower()
return oc.t_most_3b_3_1_2(*args,nout=nout)
| [
"muhammadyasirroni@gmail.com"
] | muhammadyasirroni@gmail.com |
1c7055da917139875b36abf1e6028e0da6f69166 | 00fe1823bbadc9300e4fec42ca1d12dfbd4bcde9 | /Dictionary/18.py | 3d15dfffa705ec0eb596e9b41867ef33e79124c5 | [] | no_license | monteua/Python | 6b36eb01959f34ccaa2bb9044e2e660383ed7695 | 64b6154d9f59e1e2dbe033e5b9f246734b7d4064 | refs/heads/master | 2020-07-05T07:29:51.250343 | 2018-02-09T11:09:51 | 2018-02-09T11:09:51 | 74,122,698 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 472 | py | '''Write a Python program to check a dictionary is empty or not.'''
not_empty = {'name':
{'name': 'Vadym',
},
'one': 1,
'two': 2,
'three': 3,
'one': 1,
'zero': 0
}
empty = {}
if len(not_empty) >= 1:
print ("Dictionary #1 is not empty!")
else:
print("Dictionary #1 is empty!")
if len(empty) >= 1:
print ("Dictionary #2 is not empty!")
else:
print("Dictionary #2 is empty!") | [
"arximed.monte@gmail.com"
] | arximed.monte@gmail.com |
7fcda7ef21b1de16b37b74278c6f01f279ca2bdd | a08e50e295c75fb6b2dd58100ec6e220e05fa27f | /Elimination/chal2.py | dc7836c2799f060ce68dcda960dccf42029a88b3 | [] | no_license | CianLR/Bayan-Programming-Contest-2014 | 5908c4f543426c1acf21c444fe838b71476b22be | 4151eea2dc6914e33241773c5cd64dc930dc35df | refs/heads/master | 2021-01-16T17:47:05.915489 | 2015-03-07T19:56:22 | 2015-03-07T19:56:22 | 31,823,382 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 496 | py | T = input()
blank = raw_input()
for x in range(T):
line = raw_input().split()
W = int(line[0])
R = int(line[1])
M = int(line[2])
S = int(line[3])
print 'Case #' + str(x + 1) + ':'
if (R < 40 or W < 35) and M < 10:
print 'EMERGENCY'
elif M < 10 and R > 60 and M < 10:
print 'NIGHTMARE'
elif S > 28800 and M < 10:
print 'WAKE-UP'
else:
print 'NOTHING'
try:
blank = raw_input()
except:
pass
| [
"cian.ruane1@gmail.com"
] | cian.ruane1@gmail.com |
c468dc836279d3187e3345b11302f68f18653030 | 2801896c7fcd06e3cf4ae644fb9630857aac1626 | /app/auth/forms.py | 3da2406bb40f941696429974726d147bd1e62ff2 | [
"MIT"
] | permissive | Koech-code/bookings | 9a9f9bd2c19705b5f66a5d2889b31b0d549f3ba0 | e164ba118de32e82dac9d9c69961df1eeb4d384c | refs/heads/master | 2023-07-15T04:20:07.359983 | 2021-08-28T15:31:30 | 2021-08-28T15:31:30 | 400,294,330 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,556 | py | from flask_wtf import FlaskForm
from sqlalchemy.orm import query
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required, Email, EqualTo
from wtforms.validators import ValidationError
from ..models import User
class RegistrationForm(FlaskForm):
username = StringField(
'Input your preferred username', validators=[Required()])
email = StringField('Your email address', validators=[Required(), Email()])
password = PasswordField('Create your password', validators=[
Required(), EqualTo('password_confirm', message='passwords must match')])
password_confirm = PasswordField(
'confirm the password you\'ve created', validators=[Required()])
submit = SubmitField('Create Account')
def validate_email(self, data_field):
if User.query.filter_by(email=data_field.data).first():
raise ValidationError(
'There is already an account with that email. Please use another email.')
def validate_username(self, data_field):
if User.query.filter_by(username=data_field.data).first():
raise ValidationError(
'The username you have used has already been taken. use another one.')
class LoginForm(FlaskForm):
email = StringField('You email address', validators=[Required(), Email()])
password = PasswordField('Input your password', validators=[Required()])
remember = BooleanField('Do want your password remembered?')
submit = SubmitField('sign In')
| [
"nixon.koech@moringaschool.com"
] | nixon.koech@moringaschool.com |
6063a00c0ea1724653c2af13cbf127b17e013930 | 8e74bebc2fc811ad2d09950a20f3ba926d239489 | /telegrambot/src/corona_assistent_bot/web/api.py | 379d1ac0363734661c9e74ec972f171aea591495 | [
"MIT"
] | permissive | LittleKita/CoronaAssistent | 299b924128a51e4dfa90140db84e095ed01dda7d | 1e0862d94bdc509aa468921ee7b056ec59e6f472 | refs/heads/master | 2023-01-19T12:02:25.379681 | 2021-05-11T15:36:17 | 2021-05-11T15:36:17 | 248,859,044 | 1 | 0 | MIT | 2023-01-07T16:11:29 | 2020-03-20T21:53:22 | TypeScript | UTF-8 | Python | false | false | 342 | py | from http import HTTPStatus
from flask import Blueprint, request
from ..model import ReceivedMessage
from . import db
bp = Blueprint('api', __name__)
@bp.route('/message', methods=['POST'])
def receive_message():
db.session.add(ReceivedMessage(text=request.json['text']))
db.session.commit()
return '', HTTPStatus.NO_CONTENT
| [
"frazer@frazermclean.co.uk"
] | frazer@frazermclean.co.uk |
71d97373fa6b0a0b7b9eb4ec74c6d19f7c80e472 | 2af4823ae83fbcc780ef538bd02fa5bf3a51208c | /ABC123/C.py | 25c0cf46d5401eff742784e4ae0834c17f291ec0 | [] | no_license | jre233kei/procon-atcoder | 102420cc246a5123ac9774f8b28440f1d8b70b0f | c463c9c92d45f19fba32d0c8a25f97d73db67bc5 | refs/heads/master | 2022-12-04T09:30:39.271433 | 2020-08-14T11:38:46 | 2020-08-14T11:38:46 | 276,779,835 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 164 | py | import math
n = int(input())
ma = 10**16
ind = 0
for i in range(5):
ai = int(input())
if ma >= ai:
ind = i
ma = ai
print(math.ceil(n/ma)+4)
| [
"jre233kei+github@gmail.com"
] | jre233kei+github@gmail.com |
4fd3da9df984194f30fd3bacc9885343b4862eb1 | b1e7481f8b5bf40c2547c95b1863e25b11b8ef78 | /Kai/crab/NANOv7_NoveCampaign/2018/crab_cfg_2018_ttHH.py | c21eda93ff3fe91e9f5f6fb14e8456869e682231 | [
"Apache-2.0"
] | permissive | NJManganelli/FourTopNAOD | 3df39fd62c0546cdbb1886b23e35ebdc1d3598ad | c86181ae02b1933be59d563c94e76d39b83e0c52 | refs/heads/master | 2022-12-22T22:33:58.697162 | 2022-12-17T01:19:36 | 2022-12-17T01:19:36 | 143,607,743 | 1 | 1 | Apache-2.0 | 2022-06-04T23:11:42 | 2018-08-05T11:40:42 | Python | UTF-8 | Python | false | false | 1,602 | py | import os
from WMCore.Configuration import Configuration
from CRABClient.UserUtilities import config, getUsernameFromCRIC
config = Configuration()
config.section_("General")
config.General.requestName = '2018_ttHH'
config.General.transferOutputs = True
config.General.transferLogs = True
config.section_("JobType")
config.JobType.allowUndistributedCMSSW = True
config.JobType.pluginName = 'Analysis'
config.JobType.psetName = 'crab_PSet_2018_ttHH.py'
config.JobType.maxMemoryMB = 3000
config.JobType.maxJobRuntimeMin = 1315
config.JobType.numCores = 1
config.JobType.scriptExe = 'crab_script_2018_ttHH.sh'
config.JobType.inputFiles = ['crab_script_2018_ttHH.py',
os.path.join(os.environ['CMSSW_BASE'],'src/PhysicsTools/NanoAODTools/scripts/haddnano.py'),
]
config.JobType.outputFiles = [] #['hist.root']
config.JobType.sendPythonFolder = True
config.section_("Data")
config.Data.inputDataset = '/TTHH_TuneCP5_13TeV-madgraph-pythia8/RunIIAutumn18NanoAODv7-Nano02Apr2020_102X_upgrade2018_realistic_v21_ext1-v1/NANOAODSIM'
config.Data.inputDBS = 'global'
config.Data.splitting = 'FileBased'
if config.Data.splitting == 'FileBased':
config.Data.unitsPerJob = 1
# config.Data.totalUnits = $TOTAL_UNITS
# config.Data.userInputFiles = []
# config.Data.outLFNDirBase = '/store/user/{user}/NoveCampaign'.format(user=getUsernameFromCRIC())
config.Data.outLFNDirBase = '/store/group/fourtop/NoveCampaign'
config.Data.publication = True
config.Data.outputDatasetTag = 'NoveCampaign'
config.section_("Site")
config.Site.storageSite = 'T2_BE_IIHE'
| [
"nicholas.james.manganelli@cern.ch"
] | nicholas.james.manganelli@cern.ch |
8932b763a784ad16c5ec41d9b77716274582af7a | 6364bb727b623f06f6998941299c49e7fcb1d437 | /msgraph-cli-extensions/src/groupsplanner/azext_groupsplanner/generated/_client_factory.py | a0e315166b33c89b8b8da37ea13dcd6e16f00ae4 | [
"MIT"
] | permissive | kanakanaidu/msgraph-cli | 1d6cd640f4e10f4bdf476d44d12a7c48987b1a97 | b3b87f40148fb691a4c331f523ca91f8a5cc9224 | refs/heads/main | 2022-12-25T08:08:26.716914 | 2020-09-23T14:29:13 | 2020-09-23T14:29:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,469 | py | # --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
def cf_groupsplanner_cl(cli_ctx, *_):
from msgraph.cli.core.commands.client_factory import get_mgmt_service_client
from ..vendored_sdks.groupsplanner import GroupsPlanner
return get_mgmt_service_client(cli_ctx,
GroupsPlanner,
subscription_bound=False,
base_url_bound=False)
def cf_group(cli_ctx, *_):
return cf_groupsplanner_cl(cli_ctx).group
def cf_group_planner(cli_ctx, *_):
return cf_groupsplanner_cl(cli_ctx).group_planner
def cf_group_planner_plan(cli_ctx, *_):
return cf_groupsplanner_cl(cli_ctx).group_planner_plan
def cf_group_planner_plan_bucket(cli_ctx, *_):
return cf_groupsplanner_cl(cli_ctx).group_planner_plan_bucket
def cf_group_planner_plan_bucket_task(cli_ctx, *_):
return cf_groupsplanner_cl(cli_ctx).group_planner_plan_bucket_task
def cf_group_planner_plan_task(cli_ctx, *_):
return cf_groupsplanner_cl(cli_ctx).group_planner_plan_task
| [
"japhethobalak@gmail.com"
] | japhethobalak@gmail.com |
e0911fbb139de2701c750a7f76b2ecce9b055994 | cacb92c6dba32dfb7f2a4a2a02269f40ab0413dd | /configs/regnet/faster_rcnn_regnetx-3GF_fpn_1x_coco.py | 943b4ea9beecbf64e7195fef0b1cd085a3f411b2 | [
"Apache-2.0"
] | permissive | dereyly/mmdet_sota | 697eab302faf28d5bce4092ecf6c4fd9ffd48b91 | fc14933ca0ec2eebb8e7b3ec0ed67cae0da3f236 | refs/heads/master | 2022-11-26T14:52:13.665272 | 2020-08-04T00:26:46 | 2020-08-04T00:26:46 | 272,046,903 | 15 | 5 | Apache-2.0 | 2020-07-16T06:22:39 | 2020-06-13T16:37:26 | Python | UTF-8 | Python | false | false | 1,885 | py | _base_ = [
'../_base_/models/faster_rcnn_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
pretrained='open-mmlab://regnetx_3.2gf',
backbone=dict(
_delete_=True,
type='RegNet',
arch='regnetx_3.2gf',
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'),
neck=dict(
type='FPN',
in_channels=[96, 192, 432, 1008],
out_channels=256,
num_outs=5))
img_norm_cfg = dict(
# The mean and std is used in PyCls when training RegNets
mean=[103.53, 116.28, 123.675],
std=[57.375, 57.12, 58.395],
to_rgb=False)
train_pipeline = [
dict(type='LoadImageFromFile', to_float32=True),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
train=dict(pipeline=train_pipeline),
val=dict(pipeline=test_pipeline),
test=dict(pipeline=test_pipeline))
optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.00005)
| [
"nikolay@xix.ai"
] | nikolay@xix.ai |
b53be84e945c19531b02835a636f38c0be5f8bdb | b3c47795e8b6d95ae5521dcbbb920ab71851a92f | /Project Euler/0045.py | f2681db8b5f0c3ca9dd2d0ed566328fec06e91f0 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Wizmann/ACM-ICPC | 6afecd0fd09918c53a2a84c4d22c244de0065710 | 7c30454c49485a794dcc4d1c09daf2f755f9ecc1 | refs/heads/master | 2023-07-15T02:46:21.372860 | 2023-07-09T15:30:27 | 2023-07-09T15:30:27 | 3,009,276 | 51 | 23 | null | null | null | null | UTF-8 | Python | false | false | 1,118 | py | #coding=utf-8
def judge(func, x):
now = 0
step = x
while step:
half = step / 2
mid = now + half
if func(mid) >= x:
step = half
else:
now = mid + 1
step = step - half - 1
return func(now) == x
tri = lambda x: x * (x + 1) / 2
pen = lambda x: x * (3 * x - 1) / 2
hxa = lambda x: x * (2 * x - 1)
def test_judge():
for i in xrange(1, 16):
if i in [1, 3, 6, 10, 15]:
assert(judge(tri, i) == True)
else:
assert(judge(tri, i) == False)
for i in xrange(1, 36):
if i in [1, 5, 12, 22, 35]:
assert(judge(pen, i) == True)
else:
assert(judge(pen, i) == False)
for i in xrange(1, 46):
if i in [1, 6, 15, 28, 45]:
assert(judge(hxa, i) == True)
else:
assert(judge(hxa, i) == False)
if __name__ == '__main__':
test_judge()
i = 165
while True:
i += 1
v = pen(i)
if judge(tri, v) and \
judge(pen, v) and \
judge(hxa, v):
break
print pen(i)
| [
"mail.kuuy@gmail.com"
] | mail.kuuy@gmail.com |
86e8c953a972751c4a8555d90850370a1d07b9b7 | 35dbd536a17d7127a1dd1c70a2903ea0a94a84c2 | /tests/sentry/api/endpoints/test_sentry_app_installation_external_issues.py | be7be0126e70806b69e2f738c1d12a1bd4294da0 | [
"Apache-2.0",
"BUSL-1.1"
] | permissive | nagyist/sentry | efb3ef642bd0431990ca08c8296217dabf86a3bf | d9dd4f382f96b5c4576b64cbf015db651556c18b | refs/heads/master | 2023-09-04T02:55:37.223029 | 2023-01-09T15:09:44 | 2023-01-09T15:09:44 | 48,165,782 | 0 | 0 | BSD-3-Clause | 2022-12-16T19:13:54 | 2015-12-17T09:42:42 | Python | UTF-8 | Python | false | false | 3,627 | py | from django.urls import reverse
from sentry.models import PlatformExternalIssue
from sentry.testutils import APITestCase
class SentryAppInstallationExternalIssuesEndpointTest(APITestCase):
def setUp(self):
self.superuser = self.create_user(email="a@example.com", is_superuser=True)
self.user = self.create_user(email="boop@example.com")
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.org)
self.group = self.create_group(project=self.project)
def _set_up_sentry_app(self, name, scopes):
self.sentry_app = self.create_sentry_app(
name=name,
organization=self.org,
webhook_url="https://example.com",
scopes=scopes,
)
self.install = self.create_sentry_app_installation(
organization=self.org, slug=self.sentry_app.slug, user=self.user
)
self.api_token = self.create_internal_integration_token(
install=self.install, user=self.user
)
self.url = reverse(
"sentry-api-0-sentry-app-installation-external-issues", args=[self.install.uuid]
)
def _post_data(self):
return {
"issueId": self.group.id,
"webUrl": "https://somerandom.io/project/issue-id",
"project": "ExternalProj",
"identifier": "issue-1",
}
def test_creates_external_issue(self):
self._set_up_sentry_app("Testin", ["event:write"])
data = self._post_data()
response = self.client.post(
self.url, data=data, HTTP_AUTHORIZATION=f"Bearer {self.api_token.token}"
)
external_issue = PlatformExternalIssue.objects.first()
assert response.status_code == 200
assert response.data == {
"id": str(external_issue.id),
"issueId": str(self.group.id),
"serviceType": self.sentry_app.slug,
"displayName": "ExternalProj#issue-1",
"webUrl": "https://somerandom.io/project/issue-id",
}
def test_invalid_group_id(self):
self._set_up_sentry_app("Testin", ["event:write"])
data = self._post_data()
data["issueId"] = self.create_group(project=self.create_project()).id
response = self.client.post(
self.url, data=data, HTTP_AUTHORIZATION=f"Bearer {self.api_token.token}"
)
assert response.status_code == 404
def test_invalid_scopes(self):
self._set_up_sentry_app("Testin", ["project:read"])
data = self._post_data()
response = self.client.post(
self.url, data=data, HTTP_AUTHORIZATION=f"Bearer {self.api_token.token}"
)
assert response.status_code == 403
def test_invalid_token(self):
"""
You can only create external issues for the integration
whose token you are using to hit this endpoint.
"""
self._set_up_sentry_app("Testin", ["event:write"])
new_install = self.create_sentry_app_installation(
organization=self.org,
slug=self.create_sentry_app(
name="NewApp", organization=self.org, scopes=["event:write"]
).slug,
user=self.user,
)
new_api_token = self.create_internal_integration_token(install=new_install, user=self.user)
data = self._post_data()
response = self.client.post(
self.url,
data=data,
HTTP_AUTHORIZATION=f"Bearer {new_api_token.token}",
)
assert response.status_code == 403
| [
"noreply@github.com"
] | nagyist.noreply@github.com |
314b4c400de8e62e8549da1b64fdbd5dac346279 | 6923f79f1eaaba0ab28b25337ba6cb56be97d32d | /Introduction_to_numerical_programming_using_Python_and_CPP_Beu/Ch12/Python/P12-PendulumRKT.py | d8b46110571d6040edd787cf36e7601500a26af3 | [] | no_license | burakbayramli/books | 9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0 | 5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95 | refs/heads/master | 2023-08-17T05:31:08.885134 | 2023-08-14T10:05:37 | 2023-08-14T10:05:37 | 72,460,321 | 223 | 174 | null | 2022-10-24T12:15:06 | 2016-10-31T17:24:00 | Jupyter Notebook | UTF-8 | Python | false | false | 4,651 | py | # Angular motion of a nonlinear pendulum by the Runge-Kutta method
# u" = -g/l * sin(u) - k * u', u(0) = u0, u'(0) = u0'
from math import *
from ode import *
from integral import *
from graphlib import *
g = 9.81e0 # gravitational acceleration
def Func(t, u, f): # RHS of 1st order ODEs
f[1] = u[2] # u[1] = u, u[2] = u'
f[2] = -g/l * sin(u[1]) - k * u[2]
#============================================================================
def Kel(m):
#----------------------------------------------------------------------------
# Returns the complete elliptic integral of the 1st kind
# Calls: qImprop2 (integral.py)
#----------------------------------------------------------------------------
eps = 1e-7 # relative precision
def fKel(z): return 1e0 / sqrt((1e0-z*z)*(1e0-m*z*z)) # integrand
return qImprop2(fKel,0e0,1e0,eps)
# main
nn = [0]*3 # ending indexes of plots
col = [""]*3 # colors of plots
sty = [0]*3 # styles of plots
l = 1e0 # pendulum length
k = 0e0 # velocity coefficient
du0 = 0e0 # initial derivative
tmax = 20e0 # time span
ht = 0.001e0 # time step size
u0min = 0.1e0 # minimum u0
u0max = 3.1e0 # maximum u0
hu = 0.1e0 # increment for u0
n = 2 # number of 1st order ODEs
nt = int(tmax/ht + 0.5) + 1 # number of time steps
nu = int((u0max-u0min)/hu + 0.5) + 1 # number of u0s
u = [0]*(n+1) # solution components
tt = [0]*(2*nt+1); ut = [0]*(2*nt+1) # arrays for t-dep. plots
tu = [0]*(2*nu+1); uu = [0]*(2*nu+1) # arrays for u0-dep. plots
for iu in range(1,nu+1):
u0 = u0min + (iu-1)*hu # initial displacement
t = 0e0; it = 1
u[1] = u0; u[2] = du0 # initial values
if (iu == 1 ): tt[1 ] = t; ut[1 ] = u[1] # for smallest u0
if (iu == nu): tt[1+nt] = t; ut[1+nt] = u[1] # for largest u0
nT = 0 # number of half-periods
t1 = t2 = 0e0 # bounding solution zeros
us = u[1] # save solution
while (t+ht <= tmax): # propagation loop
RungeKutta(t,ht,u,n,Func)
t += ht; it += 1
if (u[1]*us < 0e0): # count solution passages through zero
if (t1 == 0): t1 = t # initial zero
else: t2 = t; nT += 1 # final zero
us = u[1] # save solution
# store for plotting
if (iu == 1 ): tt[it ] = t; ut[it ] = u[1] # for smallest u0
if (iu == nu): tt[it+nt] = t; ut[it+nt] = u[1] # for largest u0
T = 2e0*(t2-t1) / nT # calculated period
T0 = 2e0*pi*sqrt(l/g) # harmonic period
Tex = 2/pi * T0 * Kel(pow(sin(0.5e0*u0),2)) # exact period
uu[iu ] = u0; tu[iu ] = T/T0
uu[iu+nu] = u0; tu[iu+nu] = Tex/T0
GraphInit(1200,600)
nn[1] = it ; col[1] = "blue"; sty[1] = 1 # for smallest u0
nn[2] = it+nt; col[2] = "red" ; sty[2] = 1 # for largest u0
MultiPlot(tt,ut,ut,nn,col,sty,2,10,0e0,0e0,0,0e0,0e0,0,0.10,0.45,0.15,0.85, \
"t (s)","u (rad)","Displacement of nonlinear pendulum")
nn[1] = nu; col[1] = "red" ; sty[1] = 0 # calculated periods
nn[2] = 2*nu; col[2] = "blue"; sty[2] = 1 # exact periods
MultiPlot(uu,tu,tu,nn,col,sty,2,10,0e0,0e0,0,0e0,0e0,0,0.60,0.95,0.15,0.85, \
"u0 (rad)","T/T0","Period of nonlinear pendulum")
MainLoop()
| [
"me@yomama.com"
] | me@yomama.com |
44aad0beb071f8148927b511129c5a438e28793a | 2bc18a13c4a65b4005741b979f2cb0193c1e1a01 | /test/suite/E22.py | 2ff470b12e1ef1e68f1d4cb262ca4ca989a50d63 | [
"MIT"
] | permissive | hhatto/autopep8 | b0b9daf78050d981c4355f096418b9283fc20a0f | 4e869ad63a11575267450bfefdf022bb6128ab93 | refs/heads/main | 2023-09-01T05:14:18.553939 | 2023-08-27T14:12:45 | 2023-08-27T14:12:45 | 1,206,729 | 3,966 | 329 | MIT | 2023-08-27T14:12:46 | 2010-12-29T20:08:51 | Python | UTF-8 | Python | false | false | 1,904 | py | #: E221
a = 12 + 3
b = 4 + 5
#: E221 E221
x = 1
y = 2
long_variable = 3
#: E221 E221
x[0] = 1
x[1] = 2
long_variable = 3
#: E221 E221
x = f(x) + 1
y = long_variable + 2
z = x[0] + 3
#: E221:3:14
text = """
bar
foo %s""" % rofl
#: Okay
x = 1
y = 2
long_variable = 3
#:
#: E222
a = a + 1
b = b + 10
#: E222 E222
x = -1
y = -2
long_variable = 3
#: E222 E222
x[0] = 1
x[1] = 2
long_variable = 3
#:
#: E223
foobart = 4
a = 3 # aligned with tab
#:
#: E224
a += 1
b += 1000
#:
#: E225
submitted +=1
#: E225
submitted+= 1
#: E225
c =-1
#: E225
x = x /2 - 1
#: E225
c = alpha -4
#: E225
c = alpha- 4
#: E225
z = x **y
#: E225
z = (x + 1) **y
#: E225
z = (x + 1)** y
#: E225
_1kB = _1MB >>10
#: E225
_1kB = _1MB>> 10
#: E225 E225
i=i+ 1
#: E225 E225
i=i +1
#: E225 E226
i=i+1
#: E225 E226
i =i+1
#: E225 E226
i= i+1
#: E225 E226
c = (a +b)*(a - b)
#: E225 E226
c = (a+ b)*(a - b)
#:
#: E226
z = 2**30
#: E226 E226
c = (a+b) * (a-b)
#: E226
norman = True+False
#: E226
x = x*2 - 1
#: E226
x = x/2 - 1
#: E226 E226
hypot2 = x*x + y*y
#: E226
c = (a + b)*(a - b)
#: E226
def squares(n):
return (i**2 for i in range(n))
#: E227
_1kB = _1MB>>10
#: E227
_1MB = _1kB<<10
#: E227
a = b|c
#: E227
b = c&a
#: E227
c = b^a
#: E228
a = b%c
#: E228
msg = fmt%(errno, errmsg)
#: E228
msg = "Error %d occured"%errno
#:
#: Okay
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
_1MB = 2 ** 20
foo(bar, key='word', *args, **kwargs)
baz(**kwargs)
negative = -1
spam(-1)
-negative
lambda *args, **kw: (args, kw)
lambda a, b=h[:], c=0: (a, b, c)
if not -5 < x < +5:
print >>sys.stderr, "x is out of range."
print >> sys.stdout, "x is an integer."
z = 2 ** 30
x = x / 2 - 1
if alpha[:-i]:
*a, b = (1, 2, 3)
def squares(n):
return (i ** 2 for i in range(n))
#:
| [
"git@stevenmyint.com"
] | git@stevenmyint.com |
5a8108aa85b60f456469472cc895b31a4dd578d6 | 989bb5d2d3e89db21fcbeac91a1e64967ea6377b | /reinforcement_learning/rl_stock_trading_coach_customEnv/src/preset-stock-trading-ddqn.py | b3b9e819d441d08edcb2904a0a7596abfdc77dfa | [
"Apache-2.0"
] | permissive | araitats/amazon-sagemaker-examples | 7cec9ea5822f0469d5dfabbcf3cab62ce9c0f0d1 | 512cb3b6310ae812c6124a451751237d98a109b1 | refs/heads/master | 2023-04-19T05:54:47.334359 | 2021-04-27T21:04:33 | 2021-04-27T21:04:33 | 338,094,683 | 2 | 1 | Apache-2.0 | 2021-04-27T15:35:14 | 2021-02-11T17:07:39 | Jupyter Notebook | UTF-8 | Python | false | false | 2,550 | py | # Preset file in Amazon SageMaker RL
from rl_coach.agents.ddqn_agent import DDQNAgentParameters
from rl_coach.architectures.head_parameters import DuelingQHeadParameters
from rl_coach.architectures.layers import Dense
from rl_coach.base_parameters import VisualizationParameters, PresetValidationParameters
from rl_coach.core_types import TrainingSteps, EnvironmentEpisodes, EnvironmentSteps
from rl_coach.environments.gym_environment import GymVectorEnvironment
from rl_coach.graph_managers.basic_rl_graph_manager import BasicRLGraphManager
from rl_coach.graph_managers.graph_manager import ScheduleParameters
from rl_coach.schedules import LinearSchedule
from rl_coach.memories.memory import MemoryGranularity
#################
# Graph Scheduling
#################
schedule_params = ScheduleParameters()
schedule_params.improve_steps = TrainingSteps(50000)
schedule_params.steps_between_evaluation_periods = EnvironmentSteps(5000)
schedule_params.evaluation_steps = EnvironmentEpisodes(5)
schedule_params.heatup_steps = EnvironmentSteps(1000)
############
# DQN Agent
############
agent_params = DDQNAgentParameters()
# DQN params
agent_params.algorithm.discount = 0.99
agent_params.algorithm.num_consecutive_playing_steps = EnvironmentSteps(1)
agent_params.algorithm.num_steps_between_copying_online_weights_to_target = EnvironmentSteps(1000)
# NN configuration
agent_params.network_wrappers['main'].batch_size = 32
agent_params.network_wrappers['main'].learning_rate = 0.0001
agent_params.network_wrappers['main'].input_embedders_parameters['observation'].scheme = [Dense(512)]
agent_params.network_wrappers['main'].replace_mse_with_huber_loss = False
agent_params.network_wrappers['main'].heads_parameters = [DuelingQHeadParameters()]
agent_params.network_wrappers['main'].middleware_parameters.scheme = [Dense(512)]
# ER size
agent_params.memory.max_size = (MemoryGranularity.Transitions, 10000)
# E-Greedy schedule
agent_params.exploration.epsilon_schedule = LinearSchedule(1.0, 0.01, 40000)
#############
# Environment
#############
env_params = GymVectorEnvironment(level='trading_env:TradingEnv')
##################
# Manage resources
##################
preset_validation_params = PresetValidationParameters()
preset_validation_params.test = True
graph_manager = BasicRLGraphManager(agent_params=agent_params, env_params=env_params, schedule_params=schedule_params,
vis_params=VisualizationParameters(),
preset_validation_params=preset_validation_params)
| [
"noreply@github.com"
] | araitats.noreply@github.com |
5e39d154bb237d501d3319296ce682ccc8ad804b | 7858ef9fab9cccf7874d34d2db8a781dc83e9afc | /musicLrc.py | bcbef8c15ce4fa1656c062f45eb901b87f935220 | [
"MIT"
] | permissive | xiangxing98/Rhythm-Enlightment | b3a3beabf065f9974b740770a22a6711f0a4e5b9 | d6302321e858d07480b18e94c59de87f91c39202 | refs/heads/main | 2023-08-31T07:51:47.772193 | 2021-10-10T11:16:42 | 2021-10-10T11:16:42 | 311,373,916 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,180 | py | import time
musicLrc = """
[00:03.50]传奇
[00:19.10]作词:刘兵 作曲:李健
[00:20.60]演唱:王菲
[00:26.60]
[04:40.75][02:39.90][00:36.25]只是因为在人群中多看了你一眼
[04:49.00]
[02:47.44][00:43.69]再也没能忘掉你容颜
[02:54.83][00:51.24]梦想着偶然能有一天再相见
[03:02.32][00:58.75]从此我开始孤单思念
[03:08.15][01:04.30]
[03:09.35][01:05.50]想你时你在天边
[03:16.90][01:13.13]想你时你在眼前
[03:24.42][01:20.92]想你时你在脑海
[03:31.85][01:28.44]想你时你在心田
[03:38.67][01:35.05]
[04:09.96][03:39.87][01:36.25]宁愿相信我们前世有约
[04:16.37][03:46.38][01:42.47]今生的爱情故事 不会再改变
[04:24.82][03:54.83][01:51.18]宁愿用这一生等你发现
[04:31.38][04:01.40][01:57.43]我一直在你身旁 从未走远
[04:39.55][04:09.00][02:07.85]
"""
lrcDict = {}
musicLrcList = musicLrc.splitlines()
#print(musicLrcList)
for lrcLine in musicLrcList:
#[04:40.75][02:39.90][00:36.25]只是因为在人群中多看了你一眼
#[04:40.75 [02:39.90 [00:36.25 只是因为在人群中多看了你一眼
#[00:20.60]演唱:王菲
lrcLineList = lrcLine.split("]")
for index in range(len(lrcLineList) - 1):
timeStr = lrcLineList[index][1:]
#print(timeStr)
#00:03.50
timeList = timeStr.split(":")
timelrc = float(timeList[0]) * 60 + float(timeList[1])
#print(time)
lrcDict[timelrc] = lrcLineList[-1]
print(lrcDict)
allTimeList = []
for t in lrcDict:
allTimeList.append(t)
allTimeList.sort()
#print(allTimeList)
'''
while 1:
getTime = float(input("请输入一个时间"))
for n in range(len(allTimeList)):
tempTime = allTimeList[n]
if getTime < tempTime:
break
if n == 0:
print("时间太小")
else:
print(lrcDict[allTimeList[n - 1]])
'''
getTime = 0
while 1:
for n in range(len(allTimeList)):
tempTime = allTimeList[n]
if getTime < tempTime:
break
lrc = lrcDict.get(allTimeList[n - 1])
if lrc == None:
pass
else:
print(lrc)
time.sleep(1)
getTime += 1 | [
"xiangxing985529@163.com"
] | xiangxing985529@163.com |
14e42df22590759448d1d68052ea24b138f033fa | 0cd2fe66676b8c5fc005ce6010a5040acc725961 | /IIS/WordEngineering/Python/PythonBasics.org/ArgumentStatistics.py | 349f1317f79fdd26511223a1bf95352dab8bd746 | [] | no_license | KenAdeniji/WordEngineering | c360095dcbc0cbf2908e16c8b05774b40abd6a08 | d924cb4579c54c4e65547050c9a6defecf927407 | refs/heads/main | 2023-08-18T04:14:38.439110 | 2023-08-17T01:15:48 | 2023-08-17T01:15:48 | 9,719,085 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 957 | py | """
2022-08-08T21:09:00 Created. https://pythonbasics.org/list/
2022-08-08T21:35:00 https://www.w3schools.com/python/python_lists_add.asp
"""
if __name__ == '__main__':
import sys
elements = []
for argumentIndex in range(1, len(sys.argv)):
elements.append ( float( sys.argv[argumentIndex] ) )
print( "All elements: ", elements )
print( "First element: ", elements[0] )
print( "Last element: ", elements[-1] )
print( "Average elements: ", sum( elements ) / len( elements) )
print( "Count elements: ", len( elements ) )
print( "Minimum element: ", min( elements ) )
print( "Maximum element: ", max( elements ) )
print( "Sum elements: ", sum( elements ) )
elements.sort() #Sorted - Ascending order
print( "Sorted - Ascending order: ", elements )
sortedDescendingOrder = list(reversed(elements))
print( "Sorted - Descending order: ", sortedDescendingOrder )
elements = elements[::-1]
print( "Sorted - Descending order: ", elements ) | [
"kenadeniji@hotmail.com"
] | kenadeniji@hotmail.com |
fdcf336736d2f0b1c3a6b2993fd50d57443c4b8a | 1415fa90c4d86e76d76ead544206d73dd2617f8b | /venv/Lib/site-packages/direct/extensions_native/extension_native_helpers.py | e9648e7440e0e3babaca997d3dfe9df1d56af16e | [
"MIT"
] | permissive | Darpra27/Juego-senales | 84ea55aea7c61308ec1821dac9f5a29d2e0d75de | e94bc819e05eff1e0126c094d21ae1ec2a1ef46d | refs/heads/main | 2023-04-04T07:27:53.878785 | 2021-04-09T00:00:44 | 2021-04-09T00:00:44 | 353,472,016 | 0 | 1 | MIT | 2021-04-09T00:04:31 | 2021-03-31T19:46:14 | Python | UTF-8 | Python | false | false | 661 | py | __all__ = ["Dtool_ObjectToDict", "Dtool_funcToMethod"]
import sys
def Dtool_ObjectToDict(cls, name, obj):
cls.DtoolClassDict[name] = obj
def Dtool_funcToMethod(func, cls, method_name=None):
"""Adds func to class so it is an accessible method; use method_name to specify the name to be used for calling the method.
The new method is accessible to any instance immediately."""
if sys.version_info < (3, 0):
func.im_class = cls
func.im_func = func
func.im_self = None
func.__func__ = func
func.__self__ = None
if not method_name:
method_name = func.__name__
cls.DtoolClassDict[method_name] = func
| [
"daviricado08@gmail.com"
] | daviricado08@gmail.com |
9232f1097d96bfc636547100f25e94ec34ba4be7 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/otherforms/_allowed.py | 80da70e90e4edd675339760df3e58fdc167a8dfc | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 220 | py |
#calss header
class _ALLOWED():
def __init__(self,):
self.name = "ALLOWED"
self.definitions = allow
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['allow']
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
d5f6e3d56b94f7eb62b8cfe5f9d5731e71cb7227 | 167c6226bc77c5daaedab007dfdad4377f588ef4 | /python/ql/test/library-tests/frameworks/django-orm/testproj/wsgi.py | 2d192b707be6157f205928bdaafc8f2650cdf272 | [
"MIT",
"LicenseRef-scancode-python-cwi",
"LicenseRef-scancode-other-copyleft",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Python-2.0"
] | permissive | github/codeql | 1eebb449a34f774db9e881b52cb8f7a1b1a53612 | d109637e2d7ab3b819812eb960c05cb31d9d2168 | refs/heads/main | 2023-08-20T11:32:39.162059 | 2023-08-18T14:33:32 | 2023-08-18T14:33:32 | 143,040,428 | 5,987 | 1,363 | MIT | 2023-09-14T19:36:50 | 2018-07-31T16:35:51 | CodeQL | UTF-8 | Python | false | false | 393 | py | """
WSGI config for testproj project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testproj.settings')
application = get_wsgi_application()
| [
"rasmuswl@github.com"
] | rasmuswl@github.com |
7516a788d75c67837c538c0c4b008d1c8fd483bd | c751562ea538476464a13a281f321cbfebf89b76 | /python_stack/django_assignments/dj_multi_app/assignments/apps/random_word/urls.py | 7f9d10a9a41c3fae3fc681cc5e1f4103f7612076 | [] | no_license | brizjose/JBCodingDojo | 7e598419c0e090be4a92f7c3e80323daa9b4bb26 | fc161de86995d285bb5b2c39e28e9adbe04faebc | refs/heads/master | 2020-03-21T09:31:02.402139 | 2019-02-18T03:45:22 | 2019-02-18T03:45:22 | 138,403,753 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 196 | py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^generate$', views.index),
url(r'^reset$', views.reset)
] | [
"brizjosem@gmail.com"
] | brizjosem@gmail.com |
865aa17c6f002cf1561940b008ce39786fc4b0bd | c31c8095ce4d4e9686e3e7ad6b004342e49671fa | /forum/migrations/0107_auto_20190222_1529.py | b05f63a3572f698529b9f48e75e977ba3fb76d1c | [] | no_license | Lionalisk/arrakambre | 7bcc96dea2ca2a471572bfb1646256f1382ce25b | 2caece9be5eebf21ddfa87a6c821c32b5d5019a2 | refs/heads/master | 2020-12-07T19:31:24.471090 | 2020-01-09T10:14:29 | 2020-01-09T10:14:29 | 232,782,172 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 890 | py | # Generated by Django 2.1.3 on 2019-02-22 14:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('forum', '0106_auto_20190214_1523'),
]
operations = [
migrations.AddField(
model_name='action',
name='post_OK',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='resultat',
name='fini',
field=models.BooleanField(default=False, null=True),
),
migrations.AlterField(
model_name='resultat',
name='public',
field=models.BooleanField(default=False, null=True),
),
migrations.AlterField(
model_name='resultat',
name='unique',
field=models.BooleanField(default=False, null=True),
),
]
| [
"lionel.varaire@free.fr"
] | lionel.varaire@free.fr |
f35589622bfdf0aad52c6ca55268e12de8f1e7af | aec3cb058bc5b50a09b39808fff10a3858104777 | /broadcasts/admin.py | 7abe984e30f6989bea4814bbfb3d73d819bfb622 | [] | no_license | igoo-Y/Busker | 37076cb3d97d253525374238c45ed0bc34d95b1e | 33433392b77d392d562c833ab0263e0b6dc87d8f | refs/heads/main | 2023-06-05T10:21:33.594770 | 2021-06-29T16:31:30 | 2021-06-29T16:31:30 | 380,946,007 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 766 | py | from django.contrib import admin
from django.utils.safestring import mark_safe
from . import models
@admin.register(models.Broadcast)
class BroadcastAdmin(admin.ModelAdmin):
"""Broadcast Admin Definition"""
list_display = [
"name",
"broadcast_host",
"resolution",
"on_air",
"get_thumbnail",
]
list_filter = ("on_air", "genre", "resolution")
filter_horizontal = ("genre",)
raw_id_fields = ("broadcast_host",)
def get_thumbnail(self, obj):
return mark_safe(f'<img width="50px" src="{obj.image.url}" />')
get_thumbnail.short_description = "Thumbnail"
@admin.register(models.Genre, models.Resolution)
class ItemAdmin(admin.ModelAdmin):
"""Item Admin Definition"""
pass
| [
"79055280+igoo-Y@users.noreply.github.com"
] | 79055280+igoo-Y@users.noreply.github.com |
a6cc76c7d4b8796021153072dd7b245838ade37e | 8450c3a56cae4df1ca26a1a251be9fb073ccf261 | /contents/serializers.py | 047960027451a250bc0b644bb920857cafbae403 | [] | no_license | veggieavocado/Gobble-VA | a7548eb5699f5acda85b0437ed6532451ecd601c | 3e507c5eb99c313e43fac3f2fdb6e4e2cba612c4 | refs/heads/master | 2022-12-10T03:03:16.737651 | 2018-08-20T12:41:41 | 2018-08-20T12:41:41 | 144,936,741 | 0 | 0 | null | 2022-12-08T02:46:26 | 2018-08-16T04:30:25 | Python | UTF-8 | Python | false | false | 809 | py | from rest_framework import serializers
from contents.models import (
WantedContent,
WantedUrl,
WantedData,
NaverData,
NaverContent,
)
class WantedContentSerializer(serializers.ModelSerializer):
class Meta:
model = WantedContent
fields = "__all__"
class WantedUrlSerializer(serializers.ModelSerializer):
class Meta:
model = WantedUrl
fields = "__all__"
class WantedDataSerializer(serializers.ModelSerializer):
class Meta:
model = WantedData
fields = "__all__"
class NaverContentSerializer(serializers.ModelSerializer):
class Meta:
model = NaverContent
fields = "__all__"
class NaverDataSerializer(serializers.ModelSerializer):
class Meta:
model = NaverData
fields = "__all__"
| [
"ppark9553@gmail.com"
] | ppark9553@gmail.com |
8436577aa5df2a79e57a02aa80d729fd3c5c56f4 | e57d7785276053332c633b57f6925c90ad660580 | /sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2021_05_01/aio/operations/_private_link_resources_operations.py | b8283cdfee176cb6df2a08abc3ac1532219f7d0e | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | adriananeci/azure-sdk-for-python | 0d560308497616a563b6afecbb494a88535da4c5 | b2bdfe659210998d6d479e73b133b6c51eb2c009 | refs/heads/main | 2023-08-18T11:12:21.271042 | 2021-09-10T18:48:44 | 2021-09-10T18:48:44 | 405,684,423 | 1 | 0 | MIT | 2021-09-12T15:51:51 | 2021-09-12T15:51:50 | null | UTF-8 | Python | false | false | 4,967 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class PrivateLinkResourcesOperations:
"""PrivateLinkResourcesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.containerservice.v2021_05_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def list(
self,
resource_group_name: str,
resource_name: str,
**kwargs: Any
) -> "_models.PrivateLinkResourcesListResult":
"""Gets a list of private link resources in the specified managed cluster.
To learn more about private clusters, see:
https://docs.microsoft.com/azure/aks/private-clusters.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param resource_name: The name of the managed cluster resource.
:type resource_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PrivateLinkResourcesListResult, or the result of cls(response)
:rtype: ~azure.mgmt.containerservice.v2021_05_01.models.PrivateLinkResourcesListResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PrivateLinkResourcesListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-05-01"
accept = "application/json"
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', min_length=1),
'resourceName': self._serialize.url("resource_name", resource_name, 'str', max_length=63, min_length=1, pattern=r'^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PrivateLinkResourcesListResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/privateLinkResources'} # type: ignore
| [
"noreply@github.com"
] | adriananeci.noreply@github.com |
f68b49227da78a4b3e1b284b8590d1b5d74fcd27 | 00d1856dbceb6cef7f92d5ad7d3b2363a62446ca | /djexample/account/models.py | c1a4c0545167c8551ea5a84b00bc5c1ea6428f30 | [] | no_license | lafabo/django_by_example | 0b05d2b62117f70681c5fc5108b4072c097bc119 | 3cf569f3e6ead9c6b0199d150adf528bd0b2a7c5 | refs/heads/master | 2020-12-29T17:54:12.894125 | 2016-06-04T10:35:22 | 2016-06-04T10:35:22 | 58,313,176 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,067 | py | from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
def __str__(self):
return 'Profile for user %s' % self.user.username
class Contact(models.Model):
user_from = models.ForeignKey(User, related_name='rel_from_set')
user_to = models.ForeignKey(User, related_name='rel_to_set')
created = models.DateTimeField(auto_now_add=True, db_index=True)
class Meta:
ordering = ['-created', ]
def __str__(self):
return '{} follows {}'.format(self.user_from, self.user_to)
# add the following field to User dynamicaly
# old try:
# following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)
# new try:
User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False))
| [
"lazyfatboy@ya.ru"
] | lazyfatboy@ya.ru |
669ad5258dc8974e3d669a1026cd95e4586a0300 | 0668f9b72fc027269e8203ad0da1fb54ef1b168f | /web/regression/feature_utils/locators.py | 297b84086db2e783335d560cd40edbcc0e7b43ae | [
"PostgreSQL"
] | permissive | musicfox/pgadmin4 | 6d6beed5df04e081afd51fdc8d8f2d4a1df2f41d | be55ff33b28da8a15a365413c94e67b24453f7d8 | refs/heads/master | 2021-07-10T04:49:28.167599 | 2021-03-10T18:53:06 | 2021-03-10T18:53:06 | 235,440,538 | 0 | 0 | NOASSERTION | 2021-03-10T18:52:47 | 2020-01-21T21:00:22 | Python | UTF-8 | Python | false | false | 7,613 | py | #
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2021, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
class BrowserToolBarLocators():
"""This will contains element locators for browser tool bar"""
open_query_tool_button_css = \
".wcFrameButton[title='Query Tool']:not(.disabled)"
query_tool_panel_css = \
".wcPanelTab .wcTabIcon.pg-font-icon.icon-query-tool"
view_table_data_button_css = \
".wcFrameButton[title='View Data']:not(.disabled)"
view_data_panel_css = ".wcPanelTab .wcTabIcon.fa.fa-table"
filter_data_button_css = \
".wcFrameButton[title='Filtered Rows']:not(.disabled)"
filter_alertify_box_css = ".alertify .ajs-header[data-title~='Filter']"
class NavMenuLocators:
"This will contains element locators of navigation menu bar"
file_menu_css = "#mnu_file"
preference_menu_item_css = "#mnu_preferences"
tools_menu_link_text = "Tools"
view_data_link_text = "View/Edit Data"
object_menu_link_text = "Object"
properties_obj_css = "#show_obj_properties.dropdown-item:not(.disabled)"
backup_obj_css = "#backup_object.dropdown-item:not(.disabled)"
restore_obj_css = "#restore_object.dropdown-item:not(.disabled)"
maintenance_obj_css = "#maintenance.dropdown-item:not(.disabled)"
show_system_objects_pref_label_xpath = \
"//label[contains(text(), 'Show system objects?')]"
maximize_pref_dialogue_css = ".ajs-dialog.pg-el-container .ajs-maximize"
specified_pref_node_exp_status = \
"//div[div[span[span[(@class='aciTreeText')and " \
"(text()='{0} ' or text()='{0}')]]]]"
specified_preference_tree_node = \
"//div//span[(@class='aciTreeText')and " \
"(text()='{0} ' or text()='{0}')]"
specified_sub_node_of_pref_tree_node = \
"//span[text()='{0}']//following::span[text()='{1}']"
insert_bracket_pair_switch_btn = \
"//div[span[normalize-space(text())='Insert bracket pairs?']]" \
"//div[contains(@class,'toggle btn')]"
backup_filename_txt_box_name = "file"
restore_file_name_txt_box_name = "file"
backup_btn_xpath = \
"//button[contains(@class,'fa-save')and contains(.,'Backup')]"
bcg_process_status_alertifier_css = \
".ajs-message.ajs-bg-bgprocess.ajs-visible"
status_alertifier_more_btn_css = ".pg-bg-more-details"
process_watcher_alertfier = \
"//div[contains(@class,'wcFrameTitleBar')]" \
"//div[contains(text(),'Process Watcher')]"
process_watcher_detailed_command_canvas_css = \
".bg-process-details .bg-detailed-desc"
process_watcher_close_button_xpath = \
"//div[contains(@class,'wcFloating')]//" \
"div[@aria-label='Close panel']//div"
restore_file_name_xpath = "//div[contains(text(),'Restore')]" \
"//following::input[@name='file']"
restore_button_xpath = \
"//button[contains(@class,'fa-upload') and contains(.,'Restore')]"
maintenance_operation = "//label[text()='Maintenance operation']"
select_tab_xpath = \
"//*[contains(@class,'wcTabTop')]//*[contains(@class,'wcPanelTab') " \
"and contains(.,'{}')]"
process_watcher_error_close_xpath = \
".btn.btn-sm-sq.btn-primary.pg-bg-close > i"
class QueryToolLocators:
btn_save_file = "#btn-save-file"
btn_save_data = "#btn-save-data"
btn_query_dropdown = "#btn-query-dropdown"
btn_auto_rollback = "#btn-auto-rollback"
btn_auto_rollback_check_status = "#btn-auto-rollback > i"
btn_auto_commit = "#btn-auto-commit"
btn_auto_commit_check_status = "#btn-auto-commit > i"
btn_cancel_query = "#btn-cancel-query"
btn_explain = "#btn-explain"
btn_explain_analyze = "#btn-explain-analyze"
btn_explain_options_dropdown = "#btn-explain-options-dropdown"
btn_explain_verbose = "#btn-explain-verbose"
btn_explain_costs = "#btn-explain-costs"
btn_explain_buffers = "#btn-explain-buffers"
btn_explain_timing = "#btn-explain-timing"
btn_clear_dropdown = "#btn-clear-dropdown"
btn_clear_history = "#btn-clear-history"
btn_clear = "#btn-clear"
query_editor_panel = "#output-panel"
query_history_selected = "#query_list .selected"
query_history_entries = "#query_list>.query-group>ul>li"
query_history_specific_entry = \
"#query_list>.query-group>ul>li:nth-child({})"
query_history_detail = "#query_detail"
invalid_query_history_entry_css = "#query_list .entry.error .query"
editor_panel = "#output-panel"
query_messages_panel = ".sql-editor-message"
output_row_xpath = "//div[contains(@class, 'slick-row')][{}]/*[1]"
output_column_header_css = "[data-column-id='{}']"
output_column_data_xpath = "//div[contains(@class, 'slick-cell')]" \
"[contains(., '{}')]"
output_cell_xpath = "//div[contains(@class, 'slick-cell') and " \
"contains(@class, 'l{0} r{1}')]"
select_all_column = \
"//div[contains(@id,'row-header-column')]"
new_row_xpath = "//div[contains(@class, 'new-row')]"
scratch_pad_css = ".sql-scratch > textarea"
copy_button_css = "#btn-copy-row"
paste_button_css = "#btn-paste-row"
row_editor_text_area_css = ".pg-text-editor > textarea"
text_editor_ok_btn_css = ".btn.btn-primary.long_text_editor"
btn_load_file_css = "#btn-load-file"
btn_execute_query_css = "#btn-flash"
input_file_path_css = "input#file-input-path"
select_file_content_css = "table#contents"
query_output_canvas_css = "#datagrid .slick-viewport .grid-canvas"
query_output_cells = ".slick-cell"
sql_editor_message = "//div[contains(@class, 'sql-editor-message') and " \
"contains(string(), '{}')]"
code_mirror_hint_box_xpath = "//ul[@class='CodeMirror-hints default']"
code_mirror_hint_item_xpath = \
"//ul[contains(@class, 'CodeMirror-hints') and contains(., '{}')]"
code_mirror_data_xpath = "//pre[@class=' CodeMirror-line ']/span"
save_data_icon = "icon-save-data-changes"
commit_icon = "icon-commit"
execute_icon = "fa-play"
explain_icon = "fa-hand-pointer"
explain_analyze_icon = "fa-list-alt"
query_history_selected_icon = '#query_list .selected #query_source_icon'
btn_commit = "#btn-commit"
show_query_internally_btn = \
"//div[label[contains(normalize-space(text())," \
"'Show queries generated internally by')]]//" \
"div[contains(@class,'toggle btn')]"
editable_column_icon_xpath = "//div[contains(@class," \
" 'editable-column-header-icon')]" \
"/i[contains(@class, 'fa-pencil-alt')]"
read_only_column_icon_xpath = "//div[contains(@class," \
" 'editable-column-header-icon')]" \
"/i[contains(@class, 'fa-lock')]"
class ConnectToServerDiv:
# This will contain xpaths for element relating to Connect to server div
password_field = "//input[@id='password']"
ok_button = \
"//div [@class='alertify ajs-modeless ajs-movable ajs-zoom']" \
"//button[text()='OK']"
error_message = \
"//form[@id='frmPassword']/div/div//div[@class='alert-text']"
cancel_button = \
"//div [@class='alertify ajs-modeless ajs-movable ajs-zoom']" \
"//button[text()='Cancel']"
| [
"akshay.joshi@enterprisedb.com"
] | akshay.joshi@enterprisedb.com |
5945e1f0ec97a5d3527a309df210b2eb12f22504 | bb33e6be8316f35decbb2b81badf2b6dcf7df515 | /source/res/battle_royale/scripts/client/battle_royale/gui/Scaleform/daapi/view/lobby/level_up_view.py | b909a5e9680b6ccb633deb9d2543aee31a5a1855 | [] | no_license | StranikS-Scan/WorldOfTanks-Decompiled | 999c9567de38c32c760ab72c21c00ea7bc20990c | d2fe9c195825ececc728e87a02983908b7ea9199 | refs/heads/1.18 | 2023-08-25T17:39:27.718097 | 2022-09-22T06:49:44 | 2022-09-22T06:49:44 | 148,696,315 | 103 | 39 | null | 2022-09-14T17:50:03 | 2018-09-13T20:49:11 | Python | UTF-8 | Python | false | false | 4,521 | py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: battle_royale/scripts/client/battle_royale/gui/Scaleform/daapi/view/lobby/level_up_view.py
import SoundGroups
from gui.Scaleform.daapi.view.lobby.missions.awards_formatters import EpicCurtailingAwardsComposer
from gui.Scaleform.daapi.view.meta.BattleRoyaleLevelUpViewMeta import BattleRoyaleLevelUpViewMeta
from gui.Scaleform.daapi.view.lobby.epicBattle import after_battle_reward_view_helpers
from gui.impl import backport
from gui.impl.gen import R
from gui.server_events.awards_formatters import AWARDS_SIZES, getEpicViewAwardPacker
from gui.server_events.bonuses import mergeBonuses, splitBonuses
from gui.sounds.epic_sound_constants import EPIC_METAGAME_WWISE_SOUND_EVENTS
from helpers import dependency
from skeletons.gui.game_control import IBattleRoyaleController
from skeletons.gui.lobby_context import ILobbyContext
from skeletons.gui.server_events import IEventsCache
def _getTitleString(prevTitle, achievedTitle):
titleDiff = achievedTitle - prevTitle
if titleDiff == 1:
lvlReachedText = backport.text(R.strings.battle_royale.levelUp.title(), level=achievedTitle)
elif titleDiff > 2:
lvlReachedText = backport.text(R.strings.battle_royale.levelUp.severalTitles(), firstLevel=prevTitle + 1, lastLevel=achievedTitle)
else:
lvlReachedText = backport.text(R.strings.battle_royale.levelUp.twoTitles(), firstLevel=prevTitle + 1, secondLevel=achievedTitle)
return lvlReachedText
class BattleRoyaleLevelUpView(BattleRoyaleLevelUpViewMeta):
_MAX_VISIBLE_AWARDS = 8
_awardsFormatter = EpicCurtailingAwardsComposer(_MAX_VISIBLE_AWARDS, getEpicViewAwardPacker())
__eventsCache = dependency.descriptor(IEventsCache)
__battleRoyaleController = dependency.descriptor(IBattleRoyaleController)
__lobbyCtx = dependency.descriptor(ILobbyContext)
def __init__(self, ctx=None):
super(BattleRoyaleLevelUpView, self).__init__()
self.__ctx = ctx
self.__maxLvlReached = False
self.__isProgressBarAnimating = False
def onIntroStartsPlaying(self):
SoundGroups.g_instance.playSound2D(EPIC_METAGAME_WWISE_SOUND_EVENTS.EB_ACHIEVED_RANK)
def onRibbonStartsPlaying(self):
if not self.__maxLvlReached:
SoundGroups.g_instance.playSound2D(EPIC_METAGAME_WWISE_SOUND_EVENTS.EB_LEVEL_REACHED)
else:
SoundGroups.g_instance.playSound2D(EPIC_METAGAME_WWISE_SOUND_EVENTS.EB_LEVEL_REACHED_MAX)
def onEscapePress(self):
self.__close()
def onCloseBtnClick(self):
self.__close()
def onWindowClose(self):
self.__close()
def _populate(self):
super(BattleRoyaleLevelUpView, self)._populate()
battleRoyaleInfo = self.__ctx['reusableInfo'].personal.getBattleRoyaleInfo()
title, _ = battleRoyaleInfo.get('accBRTitle', (None, None))
prevTitle, _ = battleRoyaleInfo.get('prevBRTitle', (None, None))
maxTitle = self.__battleRoyaleController.getMaxPlayerLevel()
season = self.__battleRoyaleController.getCurrentSeason() or None
cycleNumber = 0
if season is not None:
cycleNumber = self.__battleRoyaleController.getCurrentOrNextActiveCycleNumber(season)
awardsVO = self._awardsFormatter.getFormattedBonuses(self.__getBonuses(title), size=AWARDS_SIZES.BIG)
awardsSmallVO = self._awardsFormatter.getFormattedBonuses(self.__getBonuses(title))
if prevTitle >= maxTitle or title >= maxTitle:
self.__maxLvlReached = True
lvlReachedText = _getTitleString(prevTitle, title)
data = {'awards': awardsVO,
'awardsSmall': awardsSmallVO,
'epicMetaLevelIconData': after_battle_reward_view_helpers.getProgressionIconVODict(cycleNumber, title),
'levelUpText': lvlReachedText,
'backgroundImageSrc': backport.image(R.images.gui.maps.icons.battleRoyale.backgrounds.back_congrats()),
'maxLvlReached': self.__maxLvlReached}
self.as_setDataS(data)
return
def __getBonuses(self, level):
questsProgressData = self.__ctx['reusableInfo'].progress.getQuestsProgress()
bonuses = after_battle_reward_view_helpers.getQuestBonuses(questsProgressData, (self.__battleRoyaleController.TOKEN_QUEST_ID,), self.__battleRoyaleController.TOKEN_QUEST_ID + str(level))
bonuses = mergeBonuses(bonuses)
bonuses = splitBonuses(bonuses)
return bonuses
def __close(self):
self.destroy()
| [
"StranikS_Scan@mail.ru"
] | StranikS_Scan@mail.ru |
95863d8299a65c4c28cab33f3d17e32cb40a5250 | 388c156092f690f6f7fdff0e1cb0c8997dc5fca3 | /provider/sftp.py | eae1aaacfe758f00f76f6b5c1ddb7ce415511dc2 | [
"MIT"
] | permissive | jhroot/elife-bot | 24cfa3a683d15083d7f029e14f0c5bf17c44238f | c98e72ce20a62caaec473b63c124eec157985616 | refs/heads/master | 2021-01-09T06:46:10.864054 | 2017-07-14T23:15:11 | 2017-07-14T23:15:11 | 34,174,287 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,705 | py | import paramiko
import os
"""
"""
class SFTP(object):
def __init__(self, logger=None):
paramiko.util.log_to_file('paramiko.log')
self.logger = logger
def sftp_connect(self, uri, username, password, port=22):
"""
Connect to SFTP server without a host key
"""
#print "trying to SFTP now"
transport = paramiko.Transport((uri, port))
try:
transport.connect(hostkey=None,
username=username,
password=password)
except:
if self.logger:
self.logger.info("was unable to connect to SFTP server")
return None
sftp = paramiko.SFTPClient.from_transport(transport)
return sftp
def sftp_to_endpoint(self, sftp_client, uploadfiles, sftp_cwd='', sub_dir=None):
"""
Given a paramiko SFTP client, upload files to it
"""
if sub_dir:
# Making the sub directory if it does or does not exist
absolute_sub_dir = sftp_cwd + '/' + sub_dir
try:
sftp_client.mkdir(absolute_sub_dir)
except IOError:
pass
for uploadfile in uploadfiles:
remote_file = uploadfile.split(os.sep)[-1]
if sub_dir:
remote_file = sub_dir + '/' + remote_file
if sftp_cwd != '':
remote_file = sftp_cwd + '/' + remote_file
if self.logger:
self.logger.info("putting file by sftp " + uploadfile +
" to remote_file " + remote_file)
result = sftp_client.put(uploadfile, remote_file)
| [
"gnott@starglobal.ca"
] | gnott@starglobal.ca |
3cc08fa7fce8d91cf29f51960128eb726465542e | 5835910bb7d7df92f6efe55b63c38137aeda76ef | /scripts/setoresRede_teorico.py | 4154234ae64cfb87503fb4f03360d0a3dcde2b31 | [
"Unlicense"
] | permissive | ttm/articleStabilityInteractionNetworks | b54a859a9abf6c82d88f2233242910e4cd1b1482 | 051dbbdee4d4b3ec033af18621be3c6fb5a8ca83 | refs/heads/master | 2020-05-21T22:15:24.656653 | 2019-07-16T10:47:33 | 2019-07-16T10:47:33 | 28,440,596 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,651 | py | #-*- coding: utf8 -*-
from __future__ import division
import numpy as n, pylab as p, networkx as x, random as r, collections as c, string
from scipy import special # special.binom(x,y) ~ binom(x,y)
__doc__="""Script to plot both scale-free network and random network distributions."""
N=1200
# for the free scale network
# P(k) = \beta * k^(-\alpha), with \alpha typically in (2, 3)
kk=n.arange(N)
Pk=.10*kk**(-10.5)
# for the random network
# P(k) = (N-1 k)p^k(1-p)^(N-k)
p_=.1
Pk_=special.binom(N-1, kk)*(p_**kk)*((1-p_)**(N-kk))
#p.plot(n.log(kk),n.log(Pk));p.plot(n.log(kk),n.log(Pk),"ro",label="free-scale model")
#p.plot(n.log(kk),n.log(Pk_));p.plot(n.log(kk),n.log(Pk_),"bo",label="Edos-Renyi model")
#F=p.gcf()
#F.set_size_inches((10.,3.))
#F.set_figwidth(10.)
p.figure(figsize=(10.,3.))
p.subplots_adjust(left=0.06,bottom=0.32,right=0.99,top=0.86)
p.plot(n.log(kk),n.log(Pk),label="scale-free model", linewidth=3)
p.plot(n.log(kk),n.log(Pk_),label=u"Erdös-Rényi model", linewidth=3)
p.text(0.9,-70,"periphery" ,size=15)
p.text(4,-100,"intermediary",size=15)
p.text(6.1,-110,"hubs" ,size=15)
p.title(u"Three sections of a scale-free network",size=25)
p.legend()
p.xlabel(r"$\log(k)\;\rightarrow$",size=25)
p.ylabel(r"$\log(P(k))\;\rightarrow$",size=25)
p.yticks(())
p.xticks(())
p.xlim((-0.1,n.log(N)+1))
p.ylim((-150,1))
# pontos de intersecção:
x1=3.7; y=-41.16-5
p.plot((x1,x1),(-1000,y),"r--")
x2=5.4951; y=-60.-5
p.plot((x2,x2),(-1000,y),"r--")
p.xticks((x1,x2),(r"$(k_L)$",r"$(k_R)$"),size=25)
p.savefig("../figs/fser_.png")
#p.show()
#p.plot(kk,Pk) ;p.plot(kk,Pk,"ro")
#p.plot(kk,Pk_);p.plot(kk,Pk_,"bo")
#p.show()
| [
"renato.fabbri@gmail.com"
] | renato.fabbri@gmail.com |
8517a06c467886fe2a0c025fc1028fed0437aa42 | 2f3be02ae7aabbec751392df769f88f17220f7d5 | /cheeseboys/character/playingcharacter.py | 5a296109452cccb01c7bdbeb4ed63799c2c9fe20 | [] | no_license | keul/Cheese-Boys | 730a3dc45f23390e31e802f7524eb1fbde73967f | 6a017bb3124415b67b55979c36edd24c865bda4d | refs/heads/master | 2021-06-01T16:47:37.728144 | 2016-10-22T15:45:38 | 2016-10-22T15:45:38 | 16,045,166 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,328 | py | # -*- coding: utf-8 -
import pygame
from pygame.locals import *
from cheeseboys import utils
from cheeseboys import cblocals
from cheeseboys.pygame_extensions.sprite import GameSprite
from cheeseboys.vector2 import Vector2
from character import Character
class PlayingCharacter(Character):
"""Human player character class"""
def afterInit(self):
self.side = "Veneto"
self.experienceLevel = 2
self._trackedEnemy = None
self.attackDamage = "1d6+2"
self.hitPoints = self.hitPointsLeft = 30
self.rest_time_needed = .25
self._speech.textcolor = (0,0,150,0)
# stealth
self.stealthLevel = 1
self.stealthRestTimeNeeded = 3000
# list of visible other character
self.can_see_list = {}
def update(self, time_passed):
"""Update method of pygame Sprite class.
Overrided the one in Character main class because we need to handle user controls here.
"""
GameSprite.update(self, time_passed)
if cblocals.global_lastMouseLeftClickPosition or cblocals.global_lastMouseRightClickPosition:
self.stopThinking()
if self._brain.active_state and self._brain.active_state.name!="controlled":
return Character.update(self, time_passed)
pressed_keys = pygame.key.get_pressed()
# update stealth level
if pressed_keys[K_LSHIFT] and self.canStealthAgain() and not self.stealth:
self.stealth = True
elif not pressed_keys[K_LSHIFT] and self.stealth:
self.stealth = False
# Check for mouse actions setted
if cblocals.global_lastMouseLeftClickPosition:
self.navPoint.set(self.currentLevel.transformToLevelCoordinate(cblocals.global_lastMouseLeftClickPosition))
cblocals.global_lastMouseLeftClickPosition = ()
if cblocals.global_lastMouseRightClickPosition and not self.isAttacking():
attackHeading = Vector2.from_points(self.position, self.currentLevel.transformToLevelCoordinate(cblocals.global_lastMouseRightClickPosition))
attackHeading.normalize()
cblocals.global_lastMouseRightClickPosition = ()
# Right click on a distant enemy will move the hero towards him...
if self.seeking:
# enable the hero brain
enemy = self.seeking
print "Seeking %s" % enemy.name
self.enemyTarget = enemy
self._brain.setState("hunting")
# ...or attack (even if moving)...
else:
self.setAttackState(attackHeading)
if pygame.key.get_pressed()[K_z] and not self.stealth:
self._brain.setState("retreat")
if self.navPoint:
self.moveBasedOnNavPoint(time_passed)
if self._attackDirection:
self.updateAttackState(time_passed)
def _setSeeking(self, enemy):
self._trackedEnemy = enemy
seeking = property(lambda self: self._trackedEnemy, _setSeeking, doc="""The enemy that the hero is hunting""")
def stopThinking(self):
"""Block all state machine brain actions of the hero, keeping back the control of him"""
self._brain.setState("controlled")
def moveBasedOnRetreatAction(self, time_passed):
"""See moveBasedOnRetreatAction of Character class.
The playing character movement is based on the mouse position on the screen, but you can't retreat moving
in front.
"""
cpos = self.toScreenCoordinate()
mpos = pygame.mouse.get_pos()
toMouse = Vector2.from_points(cpos,mpos)
toMouse.normalize()
rheading = -toMouse
heading = self.heading
angle_between = heading.angle_between(rheading)
if angle_between>=-30 and angle_between<=30:
return
distance = time_passed * self.speed
movement = rheading * distance
x = movement.get_x()
y = movement.get_y()
if not self.checkCollision(x, y) and self.checkValidCoord(x, y):
self.move(x, y)
def kill(self):
"""When playing character die all mouse pointer must be disabled"""
Character.kill(self)
cblocals.global_controlsEnabled = False
| [
"luca@keul.it"
] | luca@keul.it |
ed9fb9a181fa71652862f4934287abda287d0965 | d36de316f920342823dd60dc10fa8ee5ce146c5e | /search/views.py | 4017903bae50c4964b8bf2834c3bd450c6be275e | [] | no_license | DemocracyClub/EURegulation | a621afa3ffae555ebd5fbdc205eceb7746a468d1 | 7cf0bf31b200ab1cb59922f0b3ca120be3757637 | refs/heads/master | 2022-07-22T04:48:59.555642 | 2018-06-26T14:42:19 | 2018-06-26T14:42:19 | 80,203,236 | 2 | 0 | null | 2022-07-08T16:02:53 | 2017-01-27T11:47:20 | Python | UTF-8 | Python | false | false | 828 | py | from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from .forms import SearchByDocumentForm
from .more_like_text_helper import more_like_text
@method_decorator(csrf_exempt, name='dispatch')
class SearchView(TemplateView):
template_name = "search/search.html"
def get_context_data(self, **kwargs):
context = super(SearchView, self).get_context_data(**kwargs)
context['form'] = SearchByDocumentForm(self.request.POST)
if context['form'].is_valid():
text = context['form'].cleaned_data['document_text']
context['results'] = more_like_text(text)
return context
def post(self, request, *args, **kwargs):
return self.get(self, request, *args, **kwargs)
| [
"sym.roe@talusdesign.co.uk"
] | sym.roe@talusdesign.co.uk |
568505794d3eae12b06c664e95e8820c538eab20 | 1b962b1796a8fecf0b0c1bb6f3ddf012334f61de | /examples/stop_all_application.py | 06625a23ea2380970bea783550cf3e1ee3969da8 | [
"Apache-2.0"
] | permissive | chaostoolkit-incubator/chaostoolkit-cloud-foundry | a6ec41c71a5308a54e7c4e773a6230b088633696 | d0b10d14d0ca817913765d3d0ffa7490274789ac | refs/heads/master | 2023-03-05T02:16:17.715126 | 2023-02-27T08:03:18 | 2023-02-27T08:03:18 | 116,668,969 | 6 | 9 | Apache-2.0 | 2022-12-15T09:00:01 | 2018-01-08T11:34:45 | Python | UTF-8 | Python | false | false | 555 | py | # -*- coding: utf-8 -*-
import argparse
from connection import create_connection_config
from chaoscf.actions import stop_all_apps
def cli():
parser = argparse.ArgumentParser()
parser.add_argument('--org', dest='org_name', help='org name')
return parser.parse_args()
def run(org_name: str):
"""
Stop all given applications in an CF Org.
"""
config, secrets = create_connection_config()
stop_all_apps(org_name, configuration=config, secrets=secrets)
if __name__ == '__main__':
args = cli()
run(args.org_name)
| [
"sh@defuze.org"
] | sh@defuze.org |
06b5d7cf3046c29a53322bdc212dfcf7d5f35261 | ad14bfaa88467d8d1278e87651b2c393ba5c8780 | /skytrip/ticket_reservation/reservation_handler.py | 577ca09b7acdc117a589aebf379edde8762b461d | [] | no_license | NumanIbnMazid/reservation | e2ecb9ff3eb7dc9241ed8b71e4d00c2a39cc38ad | bbe7c7e74313ed63d7765a16cf11fdf7f3ad706a | refs/heads/master | 2023-03-30T17:30:50.889955 | 2021-04-06T14:52:07 | 2021-04-06T14:52:07 | 355,220,371 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,702 | py | # import necessary modules and libraries
from skytrip.ticket_reservation.sabre_reservation_prefs import SabreReservationPrefs
from skytrip.gds_handler import SabreHandler
from skytrip.ticket_reservation.reservation_validator import validate_reservation_request
from skytrip.utils.helper import generate_json, get_root_exception_message, finalize_response
import inspect
from skytrip.ticket_reservation.db_handler import DBhandler
# remove JSON
import json # remove JSON Dependency after removing fake finalized response
# Reservation handler Class
class ReservationHandler:
# create sabre handler instance
__sabre_handler = SabreHandler()
def __init__(self, EventBodyData=None):
self.event_body_data = EventBodyData
# handler function
def sabre_reservation_handler(self, generateJSON=False):
"""
sabre_reservation_handler for PNR (Passenger Name Record) Module
params => generateJSON (boolean)
return => object
"""
# define actual result placeholder
result = None
try:
# ------------------- *** validate request body *** -------------------
validated_request_body = validate_reservation_request(
EventBodyData=self.event_body_data
)
# ------------------- *** get main response from Sabre *** -------------------
# sabre reservation prefs
__sabre_reservation_prefs = SabreReservationPrefs()
# get result and assign to result variable
result = self.__sabre_handler.get_sabre_response(
EventBodyData=validated_request_body, request_pref_func=__sabre_reservation_prefs.get_reservation_preference, endpoint_identifier='v2.passenger.records', generateJSON=generateJSON
)
# ------------------- *** validate structure and finalize response *** -------------------
finalized_response = finalize_response(response=result)
# ------------------- *** insert PNR data into Database *** -------------------
# FAKE RESPONSE
# reservation_structured_JSON = "UTILS/REQ-RES-SAMPLE-STORE/responses/sabre/reservation_structured_response_sabre.json"
# with open(reservation_structured_JSON) as f:
# finalized_response = json.load(f)
if finalized_response.get("statusCode", None) == 200 and finalized_response["body"]["responseData"]["CreatePassengerNameRecordRS"]["ApplicationResults"].get("status", None) == "Complete":
db_handler = DBhandler()
db_pnr_id = db_handler.insert_data(
request=validated_request_body,
response=finalized_response
)
# insert DBpnrID in finalized response
finalized_response["body"]["responseData"]["DBpnrID"] = db_pnr_id
# ------------------- *** generate JSON file of Skytrip structured response *** -------------------
if generateJSON == True:
generate_json(
gds="sabre", isReq=False, filename="reservation_structured_response_sabre.json", data=finalized_response
)
# return finalized response
return finalized_response
# ------------------- *** handle exceptions *** -------------------
except Exception as E:
# assign exceptions to result
return get_root_exception_message(
Ex=E, gdsResponse=result, appResponse=None, file=__file__,
parent=inspect.stack()[0][3], line=inspect.stack()[0][2],
msg="Failed to reserve itinerary!"
)
| [
"numanibnmazid@gmail.com"
] | numanibnmazid@gmail.com |
cf94d592fbd9cdd45ddc2aad878445f6d5b84b29 | b47f2e3f3298388b1bcab3213bef42682985135e | /experiments/jacobi-2d/tmp_files/1308.py | 21eab06cb1fb7e619be56156caf58358cdbc4abd | [
"BSD-2-Clause"
] | permissive | LoopTilingBenchmark/benchmark | 29cc9f845d323431e3d40e878cbfc6d1aad1f260 | 52a3d2e70216552a498fd91de02a2fa9cb62122c | refs/heads/master | 2020-09-25T09:45:31.299046 | 2019-12-04T23:25:06 | 2019-12-04T23:25:06 | 225,975,074 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 346 | py | from chill import *
source('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/jacobi-2d/kernel.c')
destination('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/experiments/jacobi-2d/tmp_files/1308.c')
procedure('kernel_jacobi_2d')
loop(0)
tile(0,2,8,2)
tile(0,4,8,4)
tile(1,2,8,2)
tile(1,4,8,4)
| [
"nashenruoyang@163.com"
] | nashenruoyang@163.com |
3f7c2a36050fed808a933b5dca1883dcfeff22ca | 2ab2afc76f6e5d0ac7bfbbbc8c4b0aa51c48ca05 | /test/functional/wallet_txn_doublespend.py | d75ff002f1fe476aacc3337a12e3458357947ea9 | [
"MIT"
] | permissive | stance-project/stance-core | 3587f016edb2a6d785ea36a26183f7ce1c98414b | 7a3930614506c3d949b6a425e23421c9d191f4fc | refs/heads/master | 2020-05-01T16:54:59.247874 | 2019-03-28T22:01:13 | 2019-03-28T22:01:13 | 177,481,588 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,665 | py | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Stancecoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet accounts properly when there is a double-spend conflict."""
from decimal import Decimal
from test_framework.test_framework import StancecoinTestFramework
from test_framework.util import (
assert_equal,
connect_nodes,
disconnect_nodes,
find_output,
sync_blocks,
)
class TxnMallTest(StancecoinTestFramework):
def set_test_params(self):
self.num_nodes = 4
def add_options(self, parser):
parser.add_argument("--mineblock", dest="mine_block", default=False, action="store_true",
help="Test double-spend of 1-confirmed transaction")
def setup_network(self):
# Start with split network:
super().setup_network()
disconnect_nodes(self.nodes[1], 2)
disconnect_nodes(self.nodes[2], 1)
def run_test(self):
# All nodes should start with 1,250 BTC:
starting_balance = 1250
for i in range(4):
assert_equal(self.nodes[i].getbalance(), starting_balance)
self.nodes[i].getnewaddress("") # bug workaround, coins generated assigned to first getnewaddress!
# Assign coins to foo and bar addresses:
node0_address_foo = self.nodes[0].getnewaddress()
fund_foo_txid = self.nodes[0].sendtoaddress(node0_address_foo, 1219)
fund_foo_tx = self.nodes[0].gettransaction(fund_foo_txid)
node0_address_bar = self.nodes[0].getnewaddress()
fund_bar_txid = self.nodes[0].sendtoaddress(node0_address_bar, 29)
fund_bar_tx = self.nodes[0].gettransaction(fund_bar_txid)
assert_equal(self.nodes[0].getbalance(),
starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"])
# Coins are sent to node1_address
node1_address = self.nodes[1].getnewaddress()
# First: use raw transaction API to send 1240 BTC to node1_address,
# but don't broadcast:
doublespend_fee = Decimal('-.02')
rawtx_input_0 = {}
rawtx_input_0["txid"] = fund_foo_txid
rawtx_input_0["vout"] = find_output(self.nodes[0], fund_foo_txid, 1219)
rawtx_input_1 = {}
rawtx_input_1["txid"] = fund_bar_txid
rawtx_input_1["vout"] = find_output(self.nodes[0], fund_bar_txid, 29)
inputs = [rawtx_input_0, rawtx_input_1]
change_address = self.nodes[0].getnewaddress()
outputs = {}
outputs[node1_address] = 1240
outputs[change_address] = 1248 - 1240 + doublespend_fee
rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
doublespend = self.nodes[0].signrawtransactionwithwallet(rawtx)
assert_equal(doublespend["complete"], True)
# Create two spends using 1 50 BTC coin each
txid1 = self.nodes[0].sendtoaddress(node1_address, 40)
txid2 = self.nodes[0].sendtoaddress(node1_address, 20)
# Have node0 mine a block:
if (self.options.mine_block):
self.nodes[0].generate(1)
sync_blocks(self.nodes[0:2])
tx1 = self.nodes[0].gettransaction(txid1)
tx2 = self.nodes[0].gettransaction(txid2)
# Node0's balance should be starting balance, plus 50BTC for another
# matured block, minus 40, minus 20, and minus transaction fees:
expected = starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"]
if self.options.mine_block:
expected += 50
expected += tx1["amount"] + tx1["fee"]
expected += tx2["amount"] + tx2["fee"]
assert_equal(self.nodes[0].getbalance(), expected)
if self.options.mine_block:
assert_equal(tx1["confirmations"], 1)
assert_equal(tx2["confirmations"], 1)
# Node1's balance should be both transaction amounts:
assert_equal(self.nodes[1].getbalance(), starting_balance - tx1["amount"] - tx2["amount"])
else:
assert_equal(tx1["confirmations"], 0)
assert_equal(tx2["confirmations"], 0)
# Now give doublespend and its parents to miner:
self.nodes[2].sendrawtransaction(fund_foo_tx["hex"])
self.nodes[2].sendrawtransaction(fund_bar_tx["hex"])
doublespend_txid = self.nodes[2].sendrawtransaction(doublespend["hex"])
# ... mine a block...
self.nodes[2].generate(1)
# Reconnect the split network, and sync chain:
connect_nodes(self.nodes[1], 2)
self.nodes[2].generate(1) # Mine another block to make sure we sync
sync_blocks(self.nodes)
assert_equal(self.nodes[0].gettransaction(doublespend_txid)["confirmations"], 2)
# Re-fetch transaction info:
tx1 = self.nodes[0].gettransaction(txid1)
tx2 = self.nodes[0].gettransaction(txid2)
# Both transactions should be conflicted
assert_equal(tx1["confirmations"], -2)
assert_equal(tx2["confirmations"], -2)
# Node0's total balance should be starting balance, plus 100BTC for
# two more matured blocks, minus 1240 for the double-spend, plus fees (which are
# negative):
expected = starting_balance + 100 - 1240 + fund_foo_tx["fee"] + fund_bar_tx["fee"] + doublespend_fee
assert_equal(self.nodes[0].getbalance(), expected)
# Node1's balance should be its initial balance (1250 for 25 block rewards) plus the doublespend:
assert_equal(self.nodes[1].getbalance(), 1250 + 1240)
if __name__ == '__main__':
TxnMallTest().main()
| [
"moabproject@protonmail.com"
] | moabproject@protonmail.com |
ecce1997786191156dd7898a762cddfcf114a257 | c3cd2d040ceb3eabd387281835cacd0967fdbb6a | /web2py/gluon/packages/dal/pydal/dialects/mysql.py | a386100236fc3c259e2fc8605df4844776df1ff7 | [
"MIT",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-2.0-only",
"Apache-2.0",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | operepo/smc | cc55338b8b9fbeac78e67397079759965d859b68 | d10e7b7567266e31de73e5b29663577cab119a90 | refs/heads/master | 2022-09-22T07:17:59.970650 | 2022-07-11T00:20:45 | 2022-07-11T00:20:45 | 116,905,452 | 1 | 3 | MIT | 2021-03-09T03:01:37 | 2018-01-10T03:53:08 | Python | UTF-8 | Python | false | false | 3,393 | py | from ..adapters.mysql import MySQL
from ..helpers.methods import varquote_aux
from .base import SQLDialect
from . import dialects, sqltype_for
@dialects.register_for(MySQL)
class MySQLDialect(SQLDialect):
quote_template = "`%s`"
@sqltype_for("datetime")
def type_datetime(self):
return "DATETIME"
@sqltype_for("text")
def type_text(self):
return "LONGTEXT"
@sqltype_for("blob")
def type_blob(self):
return "LONGBLOB"
@sqltype_for("bigint")
def type_bigint(self):
return "BIGINT"
@sqltype_for("id")
def type_id(self):
return "INT AUTO_INCREMENT NOT NULL"
@sqltype_for("big-id")
def type_big_id(self):
return "BIGINT AUTO_INCREMENT NOT NULL"
@sqltype_for("reference")
def type_reference(self):
return (
"INT %(null)s %(unique)s, INDEX %(index_name)s "
+ "(%(field_name)s), FOREIGN KEY (%(field_name)s) REFERENCES "
+ "%(foreign_key)s ON DELETE %(on_delete_action)s"
)
@sqltype_for("big-reference")
def type_big_reference(self):
return (
"BIGINT %(null)s %(unique)s, INDEX %(index_name)s "
+ "(%(field_name)s), FOREIGN KEY (%(field_name)s) REFERENCES "
+ "%(foreign_key)s ON DELETE %(on_delete_action)s"
)
@sqltype_for("reference FK")
def type_reference_fk(self):
return (
", CONSTRAINT `FK_%(constraint_name)s` FOREIGN KEY "
+ "(%(field_name)s) REFERENCES %(foreign_key)s ON DELETE "
+ "%(on_delete_action)s"
)
def varquote(self, val):
return varquote_aux(val, "`%s`")
def insert_empty(self, table):
return "INSERT INTO %s VALUES (DEFAULT);" % table
def delete(self, table, where=None):
tablename = self.writing_alias(table)
whr = ""
if where:
whr = " %s" % self.where(where)
return "DELETE %s FROM %s%s;" % (table.sql_shortref, tablename, whr)
@property
def random(self):
return "RAND()"
def substring(self, field, parameters, query_env={}):
return "SUBSTRING(%s,%s,%s)" % (
self.expand(field, query_env=query_env),
parameters[0],
parameters[1],
)
def epoch(self, first, query_env={}):
return "UNIX_TIMESTAMP(%s)" % self.expand(first, query_env=query_env)
def concat(self, *items, **kwargs):
query_env = kwargs.get("query_env", {})
tmp = (self.expand(x, "string", query_env=query_env) for x in items)
return "CONCAT(%s)" % ",".join(tmp)
def regexp(self, first, second, query_env={}):
return "(%s REGEXP %s)" % (
self.expand(first, query_env=query_env),
self.expand(second, "string", query_env=query_env),
)
def cast(self, first, second, query_env={}):
if second == "LONGTEXT":
second = "CHAR"
return "CAST(%s AS %s)" % (first, second)
def drop_table(self, table, mode):
# breaks db integrity but without this mysql does not drop table
return [
"SET FOREIGN_KEY_CHECKS=0;",
"DROP TABLE %s;" % table._rname,
"SET FOREIGN_KEY_CHECKS=1;",
]
def drop_index(self, name, table, if_exists = False):
return "DROP INDEX %s ON %s;" % (self.quote(name), table._rname)
| [
"ray@cmagic.biz"
] | ray@cmagic.biz |
78c7e89df03336f03441e3ea87e8fa5579caa157 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02838/s446074232.py | 8eb0f4b4ed1ea2eebf2880c48347086873f21dcd | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 405 | py | def cin():
in_ = list(map(int,input().split()))
if len(in_) == 1: return in_[0]
else: return in_
N = cin()
A = cin()
INF = 10 ** 9 + 7
res = [0 for _ in range(65)]
for i in range(65):
c0, c1 = 0, 0
for j in range(N):
if bool(A[j] & (1 << i)): c1 += 1
else: c0 += 1
res[i] = c0 * c1
ans = 0
for i in range(65): ans = (ans + (1 << i) * res[i]) % INF
print(ans) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
403b8b16bedf5b7845ef8cfff8d119976c5b01fe | 62420ebada64ae351d18b1979e4151d012229b23 | /Labs/lab1_integral_7.py | 875be34ecf585b3fd48ecd5ba3871edf78af473e | [
"CC-BY-3.0",
"CC-BY-4.0",
"MIT"
] | permissive | snowdj/NumericalMethods | d9b0e3b56ebfa27249b7e8b4a3eaae17a81f7f71 | aaf52142aca4e972a6918979ad7d40ade17ca4c9 | refs/heads/master | 2021-01-17T22:32:06.564271 | 2018-05-30T23:36:06 | 2018-05-30T23:36:06 | 23,029,480 | 0 | 0 | MIT | 2018-05-30T23:36:07 | 2014-08-16T23:49:40 | null | UTF-8 | Python | false | false | 583 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 30 14:37:24 2016
@author: ih3
"""
import numpy
def integral(f, Nstrips):
"""
The general integral: integrate f between 0 and 1.
"""
locations = numpy.linspace(0.0, 1.0, Nstrips, endpoint=False)
integral = numpy.sum(f(locations)/Nstrips)
return integral
if __name__ == "__main__":
def f_1(x):
return x**2
def f_2(x):
return numpy.sqrt(1.0-x**2)
print("I_1, one hundred strips:", integral(f_1, 100))
print("I_2, one hundred strips:", integral(f_2, 100))
| [
"I.Hawke@soton.ac.uk"
] | I.Hawke@soton.ac.uk |
ca746e0b98fb85f941e76472d77409bcaf92f7c5 | 26faed0c9c8e6eaa6109f886f7c0029f8c117c81 | /MKLpy/metrics/__init__.py | a27e48df699fca2a070c966d22741f1c9197991b | [] | no_license | minghao2016/MKLpy | 9b16efc476360cd216a56382d9a505ba9d31df2f | efd11dc1e46b7a0593eaa8dfc4b2e5e678316954 | refs/heads/master | 2020-06-10T21:52:46.293245 | 2016-07-22T09:44:30 | 2016-07-22T09:44:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 419 | py | from evaluate import radius, margin, ratio, trace, frobenius, spectral_ratio
from alignment import alignment, alignment_ID, alignment_yy#, centered_alignment
__all__ = ['radius',
'margin',
'ratio',
'alignment',
'alignment_ID',
'alignment_yy',
'centered_alignment',
'trace',
'frobenius',
'spectral_ratio'
]
| [
"noreply@github.com"
] | minghao2016.noreply@github.com |
7109e39a3d033df97fbc792d96eec7df76ae48f7 | 498deea585b1b4a1086cd8cfa9e68163d4b85055 | /lecture_3/direct_pins_noreject.py | 93c75cb1f1d6b3cb5dc74806209ed1466804544b | [] | no_license | bmalgithub/smac | e1f92bdff4e2ca6775602208ade38f14d5bb6a63 | 06692ba9790784728285e495dff6bdccd3ec0400 | refs/heads/master | 2022-09-18T14:29:45.887784 | 2020-06-04T21:15:18 | 2020-06-04T21:15:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 222 | py | import random
N = 10
L = 20.0
sigma = 0.75
n_runs = 800
for run in range(n_runs):
y = [random.uniform(0.0, L - 2 * N * sigma) for k in range(N)]
y.sort()
print ([y[i] + (2 * i + 1) * sigma for i in range(N)])
| [
"simon@greenweaves.nz"
] | simon@greenweaves.nz |
8bde5e700d8be5b7bce5aca0f0150320927bff87 | ef54d37f8a3303013ca7469871a320d303957ed7 | /robo4.2/i3s/tests/i3s/api/golden_image/data_variables_loop.py | 77d37c731f27949e88e761d3ad272470acb9f4b2 | [] | no_license | richa92/Jenkin_Regression_Testing | d18badfcf16bda682dfe7bcbbd66f54a9a27a58d | 24a74926170cbdfafa47e972644e2fe5b627d8ff | refs/heads/master | 2020-07-12T10:01:59.099137 | 2019-08-27T12:14:53 | 2019-08-27T12:14:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 178 | py | ''' Input variables for the test '''
goldenimage_add = {'name': 'goldenimage_',
'description': 'valid_goldenimage',
'file': "valid_file"} | [
"akul@SAC0MKUVCQ.asiapacific.hpqcorp.net"
] | akul@SAC0MKUVCQ.asiapacific.hpqcorp.net |
372aeb18b47a34d1436fcf9647054a06ac3e7b8e | 53b529e8edf046971db0ef4a740520e0b3e60699 | /.history/recipebox/views_20200203112701.py | 71882561ea397723be77463be098a8711330a435 | [] | no_license | EnriqueGalindo/recipebox | 6b6662e517ac045a23cd43aaf296c83cf61608b2 | ace7b2699db8be20568ced7062dc85ae92aa2eee | refs/heads/master | 2020-12-28T00:46:09.079202 | 2020-02-04T04:44:35 | 2020-02-04T04:44:35 | 238,124,659 | 0 | 1 | null | 2020-04-04T21:40:24 | 2020-02-04T04:42:05 | Python | UTF-8 | Python | false | false | 141 | py | from django.shortcuts import render
from .models import Recipe
def index_view(request):
recipes = Recipe.objects.all()
return render | [
"egalindo@protonmail.com"
] | egalindo@protonmail.com |
57ed25eff211b530be1059971e9ed3c35dbd4a45 | 5e343fd4e782ce346e0e2d7b0b3cbdf2e845e1b3 | /tests_latinos.py | 9c959a8fdc4b3c241c4e615e1971aed8e9c1135f | [] | no_license | pigmonchu/bz6__romanos | e32edffe4c886d8aab6fbf51cb5e977f37551346 | c2d478fcd3342ac96d18ff7a1ca8b1f8e567a031 | refs/heads/master | 2023-01-14T10:19:48.416256 | 2020-11-19T22:51:08 | 2020-11-19T22:51:08 | 312,406,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 664 | py | import unittest
from romanos import *
import unittest
class RomanosTest(unittest.TestCase):
def test_descomponer(self):
self.assertEqual(descomponer(1987), [1,9,8,7])
def test_descomponer_solo_enteros(self):
self.assertRaises(SyntaxError, entero_a_romano, 1987.0)
def test_convertir_987(self):
self.assertEqual(convertir([9,8,7]), 'CMLXXXVII')
def test_entero_a_romano(self):
self.assertEqual(entero_a_romano(1987), 'MCMLXXXVII')
self.assertRaises(OverflowError, entero_a_romano, 4000)
self.assertRaises(OverflowError, entero_a_romano, 0)
if __name__ == '__main__':
unittest.main()
| [
"monterdi@gmail.com"
] | monterdi@gmail.com |
c168b456575a1def19a40a305ed706955514f324 | a821e5a6e45665f7e219e3e3ed07c150219e4add | /exercicio94.py | 5dc14b6228136877a4c4b8b46e3c56ef616c1aba | [] | no_license | andreplacet/exercicios_python | 18a28af942eb2bb211438f0aca10d651b7324fe5 | 0affe524e99f7739b08fdf58e2b54c5b577c8624 | refs/heads/master | 2020-08-29T02:05:52.850805 | 2020-06-01T19:09:50 | 2020-06-01T19:09:50 | 217,887,722 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,719 | py | pessoas = dict()
grupo = list()
maiore_media = list()
total_mulheres = list()
soma = 0
print(f'\033[7;31m{"PROGRAMA CADASTRO: DICIONARIO E LISTAS": ^30}\033[m')
print('\033[33m-=\033[m' * 19)
while True:
pessoas['nome'] = str(input('Nome: ').capitalize().strip())
pessoas['idade'] = int(input('Idade:'))
pessoas['sexo'] = str(input('Sexo: ')).upper().strip()[0]
while pessoas['sexo'] not in 'MF':
print('VALOR INVALIDO, DIGITE "M" para masculino e "F" para feminino')
pessoas['sexo'] = str(input('Sexo: ')).upper().strip()[0]
soma += pessoas['idade']
continuar = str(input('Deseja continuar: [s/n] ')).lower()[0]
grupo.append(pessoas.copy())
while continuar not in 'sn':
print('VALOR INVALIDO, DIGITE SIM OU NÃO PARA SAIR!')
continuar = str(input('Deseja continuar: [s/n] ')).lower()[0]
if continuar == 'n':
break
media = soma / ((len(grupo)))
print('\033[33m-=\033[m' * 19)
for d in range(0, len(grupo)):
if grupo[d]['idade'] > media:
maiore_media.append(grupo[d]['nome'])
maiore_media.append(grupo[d]['idade'])
else:
pass
if grupo[d]['sexo'] == 'F':
total_mulheres.append(grupo[d]['nome'])
else:
pass
print(f' - O grupo tem {len(grupo)} pessoas')
print(f' - A média de idade é de {media:.2f} anos')
print(f' - A mulheres cadastrasdas foram: ', end='')
for c in range(0, len(total_mulheres)):
print(f'{total_mulheres[c]}', end=' ')
print()
print(f'A lista de pessoas com idade acima da média: ')
for j in range(0, len(maiore_media), 2):
print(f' Nome: \033[33m{maiore_media[j]}\033[m; idade: \033[33m{maiore_media[j + 1]}\033[m')
print('Programa encerrado com sucesso!')
| [
"andreplacet@gmail.com"
] | andreplacet@gmail.com |
93169c15cf84deb549b75eda7a668b2bda3a32bf | 640b0b60010c2cc777a7942aebea3278648e1380 | /rsopt/pkcli/optimize.py | c198ac20fb0f9fbc4acb4fe0789ad60133adf190 | [
"Apache-2.0"
] | permissive | ahebnl/rsopt | c70aa117bc8daeaf82ada1f5bc4e737b1ab60155 | 61e17e43f89966d6f9c1d410efee578d91815d88 | refs/heads/master | 2023-06-08T09:31:34.725585 | 2021-06-03T19:11:25 | 2021-06-03T19:11:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,160 | py | import rsopt.parse as parse
import numpy as np
import os
from rsopt import run
from libensemble.tools import save_libE_output
def configuration(config):
_config = run.startup_sequence(config)
software = _config.options.NAME
try:
nworkers = _config.options.nworkers
except AttributeError:
# Any method that doesn't allow user specification must use 2 workers
nworkers = 2
runner = run.run_modes[software](_config)
H, persis_info, _ = runner.run()
if _config.is_manager:
filename = os.path.splitext(config)[0]
history_file_name = "H_" + filename + ".npy"
save_libE_output(H, persis_info, history_file_name, nworkers, mess='Run completed')
if software in _final_result:
_final_result[software](H)
def _final_local_result(H):
best, index = np.nanmin(H['f']), np.argmin(H['f'])
print("Minimum result:", H['x'][index], best)
def _final_global_result(H):
print("Local Minima Found: ('x', 'f')")
for lm in H[H['local_min']]:
print(lm['x'], lm['f'])
_final_result = {
'nlopt': _final_local_result,
'aposmm': _final_global_result
} | [
"chall@radiasoft.net"
] | chall@radiasoft.net |
d1aeed351a2e8688855fde5ccb2e5ccb4e76a3d0 | ab5a59822d646e13be5f988e9c7e12fe1b8be507 | /Curso de Python USP Part1/Exercicios/Distancia_entre_dois_pontos.py | 238f2ede9cf48e322fde00f7a39457de1faaaba8 | [
"MIT"
] | permissive | JorgeTranin/Cursos_Coursera | db05e0644cccfee7714958693280dfa998c88633 | 37d26b5f92d9324225f6701d0eb0fd466cff9d86 | refs/heads/master | 2021-06-13T23:30:04.562052 | 2020-04-21T18:32:39 | 2020-04-21T18:32:39 | 254,464,475 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 860 | py | '''
Receba 4 números na entrada, um de cada vez. Os dois primeiros devem corresponder,
respectivamente, às coordenadas x e y de um ponto em um plano cartesiano. Os dois
últimos devem corresponder, respectivamente, às coordenadas x e y de um outro ponto no mesmo plano.
Calcule a distância entre os dois pontos. Se a distância for maior ou igual a 10, imprima
'longe'
na saída. Caso o contrário, quando a distância for menor que 10, imprima
'perto'
Dica: lembre-se que a fórmula da distância para dois pontos num plano cartesiano é a seguinte:
'''
from math import sqrt
x1 = int(input('Digite um numero: '))
y1 = int(input('Digite um numero: '))
x2 = int(input('Digite um numero: '))
y2 = int(input('Digite um numero: '))
Distancia_x_y = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
if Distancia_x_y >= 10:
print('longe')
else:
print('perto')
| [
"antoniotraninjorge@gmail.com"
] | antoniotraninjorge@gmail.com |
3ae53afb63325218dbdeb6903cfae061519c465f | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_carnations.py | 3ec93932e26acdf49024a8a7a0c1e24d788aaa81 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 259 | py |
from xai.brain.wordbase.nouns._carnation import _CARNATION
#calss header
class _CARNATIONS(_CARNATION, ):
def __init__(self,):
_CARNATION.__init__(self)
self.name = "CARNATIONS"
self.specie = 'nouns'
self.basic = "carnation"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
595f4f85bc4a24da6055fba6085fa3611391eb33 | df9c6d5d8c25a02d62081215792394ebfc9d1c5f | /LangExplore/python/crawler/my-python-Crawler/main.py | bb769289954ca545ec83341e322bc3e97a72549f | [] | no_license | jk983294/Store | 1af2f33b80dc559cf61e284695a0485441e4956f | 01cf006b4f6751d1f80083339ae26598d851b1a5 | refs/heads/master | 2021-05-16T03:07:56.025060 | 2017-03-05T09:59:06 | 2017-03-05T09:59:06 | 21,042,350 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,149 | py | #!/usr/bin/python -tt
import sys
import urllib, urllib2
from urllib2 import urlopen
from storehouse import Store
from engin import Engine
from validator import Valid
from change_dir import Change_Dir
def main(first_url,max):
''' Engine is the class that fetches a url from global Store of URLs and calls downloader to find URLs in the page of that url'''
engine = Engine(first_url,max)
''' This function sets the first URL in the global store afterchecking it '''
engine.set_first()
''' The next 4 lines starts the retrival process of URLs if the first URL was ok '''
if len(engine.store.URLs)>0:
engine.start()
else:
print "The first URL you entered was not correct"
change_Dir = Change_Dir('URLs')
file_w = open('URL_Names.txt','w')
for url in engine.store.URLs:
print url
file_w.write(url)
file_w.write('\n')
file_w.close()
change_Dir.__del__()
if __name__ == '__main__':
''' collecting basic two inputs '''
first_url = raw_input('Enter a url -> ')
max = raw_input('Enter the no of links you want to obtain -> ')
max = (20 if max == '' else int(max))
''' calling main() with the two values '''
main(first_url,max) | [
"jk983294@gmail.com"
] | jk983294@gmail.com |
e7cd3e800dcdd33643f0e3f90abe212b6c2f32d5 | 23a1faa037ddaf34a7b5db8ae10ff8fa1bb79b94 | /HackerRank/Two_Characters.py | ba4416ca7c7126b8d01a2b3ea4255fa0509a8e65 | [] | no_license | Pyk017/Competetive-Programming | e57d2fe1e26eeeca49777d79ad0cbac3ab22fe63 | aaa689f9e208bc80e05a24b31aa652048858de22 | refs/heads/master | 2023-04-27T09:37:16.432258 | 2023-04-22T08:01:18 | 2023-04-22T08:01:18 | 231,229,696 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 498 | py | def check(s):
for i in range(1, len(s)):
if s[i - 1] == s[i]:
return False
return True
def alternate(s):
maxi = -1
unique = list(set(s))
for i in range(len(unique)):
for j in range(i + 1, len(unique)):
temp = [k for k in s if k == unique[i] or k == unique[j]]
if check(temp):
maxi = max(maxi, len(temp))
return maxi
n = int(input())
string = input()
print(alternate(string)) | [
"prakharkumar506978@gmail.com"
] | prakharkumar506978@gmail.com |
7a663f51988f8596fe0311bd9b7421fbc7eea0e4 | c902edb48603caa58ef40fcd50f78944a98b5ca4 | /addresses/templatetags/btc_formats.py | 469248730cbc9ef793061823eeea87e9827f6226 | [
"Apache-2.0"
] | permissive | enrichened/explorer | 1fa57750d62d4e96492fb39bdd96a64754f0008b | 3b6a99223a174a4b01408e2e2babdfef0948ae2c | refs/heads/master | 2020-12-28T19:56:46.205248 | 2015-10-26T06:45:30 | 2015-10-26T06:45:30 | 44,997,335 | 1 | 0 | null | 2015-10-26T21:07:39 | 2015-10-26T21:07:39 | null | UTF-8 | Python | false | false | 2,086 | py | from django import template
from blockcypher.utils import format_crypto_units, estimate_satoshis_transacted
from blockcypher.api import _get_websocket_url
from blockcypher.constants import COIN_SYMBOL_MAPPINGS
register = template.Library()
@register.simple_tag(name='satoshis_to_user_units_trimmed')
def satoshis_to_user_units_trimmed(input_satoshis, user_unit='btc', coin_symbol='btc', print_cs=True, round_digits=0):
return format_crypto_units(
input_quantity=input_satoshis,
input_type='satoshi',
output_type=user_unit,
coin_symbol=coin_symbol,
print_cs=print_cs,
safe_trimming=True,
round_digits=round_digits,
)
@register.assignment_tag
def estimate_satoshis_from_tx(txn_inputs, txn_outputs):
return estimate_satoshis_transacted(inputs=txn_inputs, outputs=txn_outputs)
@register.filter(name='coin_symbol_to_display_name')
def coin_symbol_to_display_name(coin_symbol):
return COIN_SYMBOL_MAPPINGS[coin_symbol]['display_name']
@register.filter(name='coin_symbol_to_display_shortname')
def coin_symbol_to_display_shortname(coin_symbol):
return COIN_SYMBOL_MAPPINGS[coin_symbol]['display_shortname']
@register.filter(name='coin_symbol_to_currency_name')
def coin_symbol_to_currency_name(coin_symbol):
return COIN_SYMBOL_MAPPINGS[coin_symbol]['currency_abbrev']
@register.filter(name='coin_symbol_to_wss')
def coin_symbol_to_wss(coin_symbol):
return _get_websocket_url(coin_symbol)
@register.filter(name='txn_outputs_to_data_dict')
def txn_outputs_to_data_dict(txn_outputs):
'''
NOTE: Assumes each transaction can only have one null data output, which is not a strict requirement
https://github.com/blockcypher/explorer/issues/150#issuecomment-143899714
'''
for txn_output in txn_outputs:
if txn_output.get('data_hex') or txn_output.get('data_string'):
return {
'data_hex': txn_output.get('data_hex'),
'data_string': txn_output.get('data_string'),
}
| [
"mflaxman@gmail.com"
] | mflaxman@gmail.com |
fd1af9b7efdb92633fdbc72eeaa900fd693799db | dab68b742da7945b75ac957deed6e9a72283934f | /Stock-Insight/stock/migrations/0001_initial.py | 95a3accf7f6ea722abe9ff880d81c2e10cc1b4cd | [] | no_license | hyunmin0317/Stock-Insight | 90dd03665c8c5edbc041284ccefa78e877f9c3c3 | 558f4da73e62aa064994e680d923ba68d5b8ca4f | refs/heads/master | 2023-06-29T23:56:42.979878 | 2021-08-02T02:15:08 | 2021-08-02T02:15:08 | 389,097,513 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 633 | py | # Generated by Django 3.2.5 on 2021-07-24 11:29
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Stock',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.TextField()),
('code', models.CharField(max_length=6)),
('sales', models.IntegerField()),
('profit', models.IntegerField()),
],
),
]
| [
"choihm9903@naver.com"
] | choihm9903@naver.com |
23185ba5e53e4d11464abd775cd3fc0650aa0fbd | b18793c1f2f08b72461f1c5c47258e072109cdce | /test/functional/wallet_dump.py | 18be2fae052262d7aacfe05fd651710705cf11be | [
"MIT"
] | permissive | Penny-Admixture/BarrelCrudeCoin | 58af9873197df4eb39f235adeab90ca4252e509f | 6cba56f636f72c0aeba79a0ea1cb9ac71da83691 | refs/heads/main | 2023-03-17T14:27:03.947863 | 2021-03-13T04:31:08 | 2021-03-13T04:31:08 | 348,196,653 | 3 | 1 | MIT | 2021-03-16T03:05:47 | 2021-03-16T03:05:47 | null | UTF-8 | Python | false | false | 7,562 | py | #!/usr/bin/env python3
# Copyright (c) 2016-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the dumpwallet RPC."""
import os
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
)
def read_dump(file_name, addrs, script_addrs, hd_master_addr_old):
"""
Read the given dump, count the addrs that match, count change and reserve.
Also check that the old hd_master is inactive
"""
with open(file_name, encoding='utf8') as inputfile:
found_legacy_addr = 0
found_p2sh_segwit_addr = 0
found_bech32_addr = 0
found_script_addr = 0
found_addr_chg = 0
found_addr_rsv = 0
hd_master_addr_ret = None
for line in inputfile:
# only read non comment lines
if line[0] != "#" and len(line) > 10:
# split out some data
key_date_label, comment = line.split("#")
key_date_label = key_date_label.split(" ")
# key = key_date_label[0]
date = key_date_label[1]
keytype = key_date_label[2]
imported_key = date == '1970-01-01T00:00:01Z'
if imported_key:
# Imported keys have multiple addresses, no label (keypath) and timestamp
# Skip them
continue
addr_keypath = comment.split(" addr=")[1]
addr = addr_keypath.split(" ")[0]
keypath = None
if keytype == "inactivehdseed=1":
# ensure the old master is still available
assert (hd_master_addr_old == addr)
elif keytype == "hdseed=1":
# ensure we have generated a new hd master key
assert (hd_master_addr_old != addr)
hd_master_addr_ret = addr
elif keytype == "script=1":
# scripts don't have keypaths
keypath = None
else:
keypath = addr_keypath.rstrip().split("hdkeypath=")[1]
# count key types
for addrObj in addrs:
if addrObj['address'] == addr.split(",")[0] and addrObj['hdkeypath'] == keypath and keytype == "label=":
if addr.startswith('m') or addr.startswith('n'):
# P2PKH address
found_legacy_addr += 1
elif addr.startswith('Q'):
# P2SH-segwit address
found_p2sh_segwit_addr += 1
elif addr.startswith('rbcc1'):
found_bech32_addr += 1
break
elif keytype == "change=1":
found_addr_chg += 1
break
elif keytype == "reserve=1":
found_addr_rsv += 1
break
# count scripts
for script_addr in script_addrs:
if script_addr == addr.rstrip() and keytype == "script=1":
found_script_addr += 1
break
return found_legacy_addr, found_p2sh_segwit_addr, found_bech32_addr, found_script_addr, found_addr_chg, found_addr_rsv, hd_master_addr_ret
class WalletDumpTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [["-keypool=90", "-addresstype=legacy"]]
self.rpc_timeout = 120
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def setup_network(self):
self.add_nodes(self.num_nodes, extra_args=self.extra_args)
self.start_nodes()
def run_test(self):
wallet_unenc_dump = os.path.join(self.nodes[0].datadir, "wallet.unencrypted.dump")
wallet_enc_dump = os.path.join(self.nodes[0].datadir, "wallet.encrypted.dump")
# generate 30 addresses to compare against the dump
# - 10 legacy P2PKH
# - 10 P2SH-segwit
# - 10 bech32
test_addr_count = 10
addrs = []
for address_type in ['legacy', 'p2sh-segwit', 'bech32']:
for i in range(0, test_addr_count):
addr = self.nodes[0].getnewaddress(address_type=address_type)
vaddr = self.nodes[0].getaddressinfo(addr) # required to get hd keypath
addrs.append(vaddr)
# Test scripts dump by adding a 1-of-1 multisig address
multisig_addr = self.nodes[0].addmultisigaddress(1, [addrs[1]["address"]])["address"]
# Refill the keypool. getnewaddress() refills the keypool *before* taking a key from
# the keypool, so the final call to getnewaddress leaves the keypool with one key below
# its capacity
self.nodes[0].keypoolrefill()
# dump unencrypted wallet
result = self.nodes[0].dumpwallet(wallet_unenc_dump)
assert_equal(result['filename'], wallet_unenc_dump)
found_legacy_addr, found_p2sh_segwit_addr, found_bech32_addr, found_script_addr, found_addr_chg, found_addr_rsv, hd_master_addr_unenc = \
read_dump(wallet_unenc_dump, addrs, [multisig_addr], None)
assert_equal(found_legacy_addr, test_addr_count) # all keys must be in the dump
assert_equal(found_p2sh_segwit_addr, test_addr_count) # all keys must be in the dump
assert_equal(found_bech32_addr, test_addr_count) # all keys must be in the dump
assert_equal(found_script_addr, 1) # all scripts must be in the dump
assert_equal(found_addr_chg, 0) # 0 blocks where mined
assert_equal(found_addr_rsv, 90 * 2) # 90 keys plus 100% internal keys
# encrypt wallet, restart, unlock and dump
self.nodes[0].encryptwallet('test')
self.nodes[0].walletpassphrase('test', 10)
# Should be a no-op:
self.nodes[0].keypoolrefill()
self.nodes[0].dumpwallet(wallet_enc_dump)
found_legacy_addr, found_p2sh_segwit_addr, found_bech32_addr, found_script_addr, found_addr_chg, found_addr_rsv, _ = \
read_dump(wallet_enc_dump, addrs, [multisig_addr], hd_master_addr_unenc)
assert_equal(found_legacy_addr, test_addr_count) # all keys must be in the dump
assert_equal(found_p2sh_segwit_addr, test_addr_count) # all keys must be in the dump
assert_equal(found_bech32_addr, test_addr_count) # all keys must be in the dump
assert_equal(found_script_addr, 1)
assert_equal(found_addr_chg, 90 * 2) # old reserve keys are marked as change now
assert_equal(found_addr_rsv, 90 * 2)
# Overwriting should fail
assert_raises_rpc_error(-8, "already exists", lambda: self.nodes[0].dumpwallet(wallet_enc_dump))
# Restart node with new wallet, and test importwallet
self.stop_node(0)
self.start_node(0, ['-wallet=w2'])
# Make sure the address is not IsMine before import
result = self.nodes[0].getaddressinfo(multisig_addr)
assert not result['ismine']
self.nodes[0].importwallet(wallet_unenc_dump)
# Now check IsMine is true
result = self.nodes[0].getaddressinfo(multisig_addr)
assert result['ismine']
if __name__ == '__main__':
WalletDumpTest().main()
| [
"quentin.neveu@hotmail.ca"
] | quentin.neveu@hotmail.ca |
aedf0fada42716e74807b5c2a7be59f7a447cc96 | 5c2e0fe391f7c720d0a6c117a64f4c8e89fece93 | /research/slim/preprocessing/lenet_preprocessing.py | 594b190db55ca67c66ae579e6808319141cae484 | [
"Apache-2.0"
] | permissive | lyltencent/tf_models_v15 | e3bed9dfee42685118b0f3d21bb9de37d58cf500 | 0081dbe36831342051c09a2f94ef9ffa95da0e79 | refs/heads/master | 2022-10-20T20:00:26.594259 | 2020-09-19T05:37:22 | 2020-09-19T05:37:22 | 161,750,047 | 0 | 1 | Apache-2.0 | 2021-03-31T21:04:01 | 2018-12-14T07:47:33 | Python | UTF-8 | Python | false | false | 1,576 | py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Provides utilities for preprocessing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
slim = tf.contrib.slim
def preprocess_image(image, output_height, output_width, is_training):
"""Preprocesses the given image.
Args:
image: A `Tensor` representing an image of arbitrary size.
output_height: The height of the image after preprocessing.
output_width: The width of the image after preprocessing.
is_training: `True` if we're preprocessing the image for training and
`False` otherwise.
Returns:
A preprocessed image.
"""
image = tf.to_float(image)
image = tf.image.resize_image_with_crop_or_pad(
image, output_width, output_height)
image = tf.subtract(image, 128.0)
image = tf.div(image, 128.0)
return image
| [
"yxl7245@eng-4150-nix03.main.ad.rit.edu"
] | yxl7245@eng-4150-nix03.main.ad.rit.edu |
70415dd9deef6ab1e8966d5e55f421078161addb | 55c250525bd7198ac905b1f2f86d16a44f73e03a | /Python/Games/RPG/2D-Rpg/dist/RPg/install.spec | 33596684219ed2ff5f789ac1a3aae2dfb34a9d1b | [] | no_license | NateWeiler/Resources | 213d18ba86f7cc9d845741b8571b9e2c2c6be916 | bd4a8a82a3e83a381c97d19e5df42cbababfc66c | refs/heads/master | 2023-09-03T17:50:31.937137 | 2023-08-28T23:50:57 | 2023-08-28T23:50:57 | 267,368,545 | 2 | 1 | null | 2022-09-08T15:20:18 | 2020-05-27T16:18:17 | null | UTF-8 | Python | false | false | 1,008 | spec | # -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['install', 'RPG.py'],
pathex=['C:\\Users\\Administrator\\PycharmProjects\\RPg'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='install',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='install')
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
49355e3f506ad306b872c1b246e349797f64e282 | f87f51ec4d9353bc3836e22ac4a944951f9c45c0 | /.history/HW02_20210630160907.py | 52129c81b3ccfcab609e7ac8d0a9332aa5e66235 | [] | no_license | sanjayMamidipaka/cs1301 | deaffee3847519eb85030d1bd82ae11e734bc1b7 | 9ddb66596497382d807673eba96853a17884d67b | refs/heads/main | 2023-06-25T04:52:28.153535 | 2021-07-26T16:42:44 | 2021-07-26T16:42:44 | 389,703,530 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,805 | py | """
Georgia Institute of Technology - CS1301
HW02 - Conditionals and Loops
Collaboration Statement:
"""
#########################################
"""
Function Name: snackBar()
Parameters: snack (str), ingredient (str), yourMoney (float)
Returns: whether you can get the snack (bool)
"""
#########################################
########## WRITE FUNCTION HERE ##########
#########################################
def snackBar(snack, ingredient, yourMoney):
if snack == 'Hotdog':
if not ingredient == 'Gluten' and not ingredient == 'Meat' and yourMoney >= 5.99:
return True
else:
return False
if snack == 'Veggie Burger':
if not ingredient == 'Gluten' and yourMoney >= 5.99:
return True
else:
return False
if snack == 'Chili Bowl':
if not ingredient == 'Meat' and yourMoney >= 3.99:
return True
else:
return False
if snack == 'Chili Cheese Fries':
if not ingredient == 'Meat' and not ingredient == 'Diary' and yourMoney >= 4.99:
return True
else:
return False
"""
Function Name: waterGames()
Parameters: gameName (str), numPlayers (int), totalFriends (int)
Returns: None (NoneType)
"""
#########################################
########## WRITE FUNCTION HERE ##########
#########################################
def waterGames(gameName, numPlayers, totalFriends):
percentPlaying = numPlayers / totalFriends
if percentPlaying < 0.3:
print('Let’s choose something else.')
elif percentPlaying >= 0.3 and percentPlaying < 0.75:
print('We will {} for a little bit!'.format(gameName))
elif percentPlaying >= 0.75:
print("Let's " + gameName + '!!!')
"""
Function Name: summerShopping()
Parameters: clothingItem (str), size (str)
Returns: None (NoneType)
"""
#########################################
########## WRITE FUNCTION HERE ##########
#########################################
def summerShopping(clothingItem, size):
if clothingItem == 'shorts':
if size == 'S':
print("2 colors are available in this item and size.")
elif size == 'M':
print("1 colors are available in this item and size.")
elif size == 'L':
print("No colors are available in this item and size.")
if clothingItem == 'tank':
if size == 'S':
print("1 colors are available in this item and size.")
elif size == 'M':
print("1 colors are available in this item and size.")
elif size == 'L':
print("2 colors are available in this item and size.")
if clothingItem == 'flipflops':
if size == 'S':
print("1 colors are available in this item and size.")
elif size == 'M':
print("1 colors are available in this item and size.")
elif size == 'L':
print("2 colors are available in this item and size.")
"""
Function Name: stopGame()
Parameters: initialPrice (float), finalPrice (float), percentGrowth (float)
Returns: numberOfDays (int)
"""
#########################################
########## WRITE FUNCTION HERE ##########
#########################################
def stopGame(initialPrice, finalPrice, percentGrowth):
if finalPrice <= initialPrice:
return 0
newPrice = ini
"""
Function Name: adventure()
Parameters: startDay (int), stopDay (int), hikeLimit(int)
Returns: None (NoneType)
"""
#########################################
########## WRITE FUNCTION HERE ##########
#########################################
summerShopping("shorts", "S") | [
"sanjay.mamidipaka@gmail.com"
] | sanjay.mamidipaka@gmail.com |
77ad50410d1bdc0313e1f865a0a2aeeabb70fce6 | 8afb5afd38548c631f6f9536846039ef6cb297b9 | /GIT-USERS/TOM-Lambda/adv1/adventure/room.py | e89828681c2054266f81eb60f66d339a57a64bfa | [
"MIT"
] | permissive | bgoonz/UsefulResourceRepo2.0 | d87588ffd668bb498f7787b896cc7b20d83ce0ad | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | refs/heads/master | 2023-03-17T01:22:05.254751 | 2022-08-11T03:18:22 | 2022-08-11T03:18:22 | 382,628,698 | 10 | 12 | MIT | 2022-10-10T14:13:54 | 2021-07-03T13:58:52 | null | UTF-8 | Python | false | false | 2,558 | py | # Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, name, description, id=0, x=None, y=None):
self.id = id
self.name = name
self.description = description
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
self.x = x
self.y = y
<<<<<<< HEAD
def __str__(self):
return f"\n-------------------\n\n{self.name}\n\n {self.description}\n\n{self.get_exits_string()}\n"
def print_room_description(self, player):
print(str(self))
=======
def __str__(self):
return f"\n-------------------\n\n{self.name}\n\n {self.description}\n\n{self.get_exits_string()}\n"
def print_room_description(self, player):
print(str(self))
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
def get_exits(self):
exits = []
if self.n_to is not None:
exits.append("n")
if self.s_to is not None:
exits.append("s")
if self.w_to is not None:
exits.append("w")
if self.e_to is not None:
exits.append("e")
return exits
<<<<<<< HEAD
def get_exits_string(self):
return f"Exits: [{', '.join(self.get_exits())}]"
=======
def get_exits_string(self):
return f"Exits: [{', '.join(self.get_exits())}]"
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
def connect_rooms(self, direction, connecting_room):
if direction == "n":
self.n_to = connecting_room
connecting_room.s_to = self
elif direction == "s":
self.s_to = connecting_room
connecting_room.n_to = self
elif direction == "e":
self.e_to = connecting_room
connecting_room.w_to = self
elif direction == "w":
self.w_to = connecting_room
connecting_room.e_to = self
else:
print("INVALID ROOM CONNECTION")
return None
<<<<<<< HEAD
=======
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
def get_room_in_direction(self, direction):
if direction == "n":
return self.n_to
elif direction == "s":
return self.s_to
elif direction == "e":
return self.e_to
elif direction == "w":
return self.w_to
else:
return None
<<<<<<< HEAD
=======
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
def get_coords(self):
return [self.x, self.y]
| [
"bryan.guner@gmail.com"
] | bryan.guner@gmail.com |
9cbe96ea46986a7818d9aeb7cc6d24c6d34b4ba3 | a205f76141a6f21f7c200f2159bedcfab582dc00 | /train_Verifier/experiments/_init_paths.py | 5e975df3740ee482577d721cacde23d0f8977363 | [] | no_license | iiau-tracker/SPLT | c054a356e5a9181238b116df6da9e6fedb5d4808 | a196e603798e9be969d9d985c087c11cad1cda43 | refs/heads/py36 | 2022-12-04T21:11:59.610453 | 2020-04-27T13:52:34 | 2020-04-27T13:52:34 | 198,601,914 | 138 | 31 | null | 2022-11-22T03:56:30 | 2019-07-24T09:23:34 | Python | UTF-8 | Python | false | false | 238 | py | import os.path as osp
import sys
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
this_dir = osp.dirname(__file__)
# Add lib to PYTHONPATH
lib_path = osp.join(this_dir, '..', 'lib')
add_path(lib_path)
| [
"yan_bin@mail.dlut.edu.cn"
] | yan_bin@mail.dlut.edu.cn |
f38686067b777f18a9d5e47fbfc924eb2b6ee11a | 531c47c15b97cbcb263ec86821d7f258c81c0aaf | /sdk/botservice/azure-mgmt-botservice/azure/mgmt/botservice/models/facebook_channel_properties.py | 934885b5b4f9dc8dd0ebe4f80c2373209c4876ad | [
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later",
"MIT"
] | permissive | YijunXieMS/azure-sdk-for-python | be364d3b88204fd3c7d223df23756386ff7a3361 | f779de8e53dbec033f98f976284e6d9491fd60b3 | refs/heads/master | 2021-07-15T18:06:28.748507 | 2020-09-04T15:48:52 | 2020-09-04T15:48:52 | 205,457,088 | 1 | 2 | MIT | 2020-06-16T16:38:15 | 2019-08-30T21:08:55 | Python | UTF-8 | Python | false | false | 2,484 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class FacebookChannelProperties(Model):
"""The parameters to provide for the Facebook channel.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar verify_token: Verify token. Value only returned through POST to the
action Channel List API, otherwise empty.
:vartype verify_token: str
:param pages: The list of Facebook pages
:type pages: list[~azure.mgmt.botservice.models.FacebookPage]
:param app_id: Required. Facebook application id
:type app_id: str
:param app_secret: Required. Facebook application secret. Value only
returned through POST to the action Channel List API, otherwise empty.
:type app_secret: str
:ivar callback_url: Callback Url
:vartype callback_url: str
:param is_enabled: Required. Whether this channel is enabled for the bot
:type is_enabled: bool
"""
_validation = {
'verify_token': {'readonly': True},
'app_id': {'required': True},
'app_secret': {'required': True},
'callback_url': {'readonly': True},
'is_enabled': {'required': True},
}
_attribute_map = {
'verify_token': {'key': 'verifyToken', 'type': 'str'},
'pages': {'key': 'pages', 'type': '[FacebookPage]'},
'app_id': {'key': 'appId', 'type': 'str'},
'app_secret': {'key': 'appSecret', 'type': 'str'},
'callback_url': {'key': 'callbackUrl', 'type': 'str'},
'is_enabled': {'key': 'isEnabled', 'type': 'bool'},
}
def __init__(self, **kwargs):
super(FacebookChannelProperties, self).__init__(**kwargs)
self.verify_token = None
self.pages = kwargs.get('pages', None)
self.app_id = kwargs.get('app_id', None)
self.app_secret = kwargs.get('app_secret', None)
self.callback_url = None
self.is_enabled = kwargs.get('is_enabled', None)
| [
"lmazuel@microsoft.com"
] | lmazuel@microsoft.com |
b49017febf9455f92910b62b9beb9f13cae67489 | 442662a56b91729921cfc00aa786ec9b7a806ade | /DZ/accounts/migrations/0003_auto_20210113_2029.py | b63d5e5018744e6eec71133a34b61ccaa9899531 | [] | no_license | Evn1/Python-Development | 25f814ec2c8be41acb797484f770f16ca23976fd | 34850ce56b60cee787da51afdb277b25ed42ad21 | refs/heads/master | 2023-02-15T16:04:30.324116 | 2021-01-14T15:50:59 | 2021-01-14T15:50:59 | 296,029,415 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 716 | py | # Generated by Django 3.1.4 on 2021-01-13 17:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_courses_registration'),
]
operations = [
migrations.AddField(
model_name='registration',
name='course',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.courses'),
),
migrations.AddField(
model_name='registration',
name='student',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.student'),
),
]
| [
"you@example.com"
] | you@example.com |
12a0db49cb8ee47e5ccc6a3c3abcf5124932ba31 | dab3caaab87e0069ade1eccfd0884c2a734206e6 | /array/add_digits.py | 6b55e4b00df02bf15f77eb0bde49f252b0027a21 | [] | no_license | sinoyuco/leetcode_solutions | 026b7be370d7fe43413e8a5d9aa8d6431759477f | b73decacb340841f49e2a37cf0ca5c0ca427cab0 | refs/heads/master | 2023-02-20T21:15:26.524946 | 2021-01-26T19:07:43 | 2021-01-26T19:07:43 | 290,261,639 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 206 | py | class Solution:
def addDigits(self, num: int) -> int:
l = sum([int(i) for i in str(num)])
while l >= 10:
t = sum([int(i) for i in str(l)])
l = t
return l
| [
"sinan.yucesan@gmail.com"
] | sinan.yucesan@gmail.com |
3e4adff4b8b009642ea983d752598a9538e93384 | 1ba1144b09e97cbf1a79e9ba16b148d7284beddd | /lib/node_modules/@stdlib/math/base/special/exp10/benchmark/python/scipy/benchmark.py | 4f93477f2c8219cda84d6f35e7ce442c218639cd | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"SunPro",
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | doc22940/stdlib | faecf4fbd61c3c5b5d782c3e1ffe78ecd6d5ab27 | 3bfc8bcf42ee5ee3db4db534aa2b2cbdbf131db7 | refs/heads/develop | 2021-03-02T15:52:14.912013 | 2020-02-15T19:20:34 | 2020-02-15T19:20:34 | 245,879,921 | 1 | 0 | Apache-2.0 | 2021-01-28T02:43:52 | 2020-03-08T20:06:08 | null | UTF-8 | Python | false | false | 2,202 | py | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Benchmark scipy.special.exp10."""
from __future__ import print_function
import timeit
NAME = "exp10"
REPEATS = 3
ITERATIONS = 1000000
def print_version():
"""Print the TAP version."""
print("TAP version 13")
def print_summary(total, passing):
"""Print the benchmark summary.
# Arguments
* `total`: total number of tests
* `passing`: number of passing tests
"""
print("#")
print("1.." + str(total)) # TAP plan
print("# total " + str(total))
print("# pass " + str(passing))
print("#")
print("# ok")
def print_results(elapsed):
"""Print benchmark results.
# Arguments
* `elapsed`: elapsed time (in seconds)
# Examples
``` python
python> print_results(0.131009101868)
```
"""
rate = ITERATIONS / elapsed
print(" ---")
print(" iterations: " + str(ITERATIONS))
print(" elapsed: " + str(elapsed))
print(" rate: " + str(rate))
print(" ...")
def benchmark():
"""Run the benchmark and print benchmark results."""
setup = "from scipy.special import exp10; from random import random;"
stmt = "y = exp10(100.0*random() - 50.0)"
t = timeit.Timer(stmt, setup=setup)
print_version()
for i in xrange(REPEATS):
print("# python::scipy::" + NAME)
elapsed = t.timeit(number=ITERATIONS)
print_results(elapsed)
print("ok " + str(i+1) + " benchmark finished")
print_summary(REPEATS, REPEATS)
def main():
"""Run the benchmark."""
benchmark()
if __name__ == "__main__":
main()
| [
"kgryte@gmail.com"
] | kgryte@gmail.com |
4a6a68b2df0ba1800fadb7492235bd467b3f384b | 3d95cc7df2530c22595b91a7f4b381bf1360bc8f | /src/aioquic/about.py | 6dc02495c74b6ba265bb249de5f255a44caec09e | [
"BSD-3-Clause"
] | permissive | the-rene/aioquic | 0fd26c6d39cd3d00eb83778279778ccbcabb398d | a9805eabf9d18825d61531256f9b9e4a791a5369 | refs/heads/master | 2020-11-27T07:29:29.349154 | 2020-02-08T19:29:35 | 2020-02-08T19:29:35 | 229,354,974 | 0 | 0 | BSD-3-Clause | 2019-12-21T00:18:14 | 2019-12-21T00:18:13 | null | UTF-8 | Python | false | false | 227 | py | __author__ = "Jeremy Lainé"
__email__ = "jeremy.laine@m4x.org"
__license__ = "BSD"
__summary__ = "An implementation of QUIC and HTTP/3"
__title__ = "aioquic"
__uri__ = "https://github.com/aiortc/aioquic"
__version__ = "0.8.4"
| [
"jeremy.laine@m4x.org"
] | jeremy.laine@m4x.org |
e19842a025778ff5151e96fbfb360144586a7d98 | 62b90c18b882df48dc47210d6023b448910d2e07 | /example/show_time.py | 6d196deb328a181a3f587d5ab853be8bca0ecff1 | [
"BSD-3-Clause"
] | permissive | Kirill888/websockets | 62edc19ca1e3845f5e37610b0160816994bb83c1 | af9abc4dd7524d63df7045e8f91b2c12d2a31aa9 | refs/heads/master | 2020-04-14T07:15:28.319873 | 2019-01-02T00:34:10 | 2019-01-02T00:34:10 | 163,707,650 | 0 | 1 | BSD-3-Clause | 2019-01-01T01:54:51 | 2019-01-01T01:54:51 | null | UTF-8 | Python | false | false | 487 | py | #!/usr/bin/env python
# WS server that sends messages at random intervals
import asyncio
import datetime
import random
import websockets
async def time(websocket, path):
while True:
now = datetime.datetime.utcnow().isoformat() + 'Z'
await websocket.send(now)
await asyncio.sleep(random.random() * 3)
start_server = websockets.serve(time, '127.0.0.1', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
| [
"aymeric.augustin@m4x.org"
] | aymeric.augustin@m4x.org |
bdbf08ae1a0b0813a254ef5c270acf0029ab625d | b47f2e3f3298388b1bcab3213bef42682985135e | /experiments/heat-3d/tmp_files/4280.py | f1554b291258f0a17f513c276ae9cf789188fd0f | [
"BSD-2-Clause"
] | permissive | LoopTilingBenchmark/benchmark | 29cc9f845d323431e3d40e878cbfc6d1aad1f260 | 52a3d2e70216552a498fd91de02a2fa9cb62122c | refs/heads/master | 2020-09-25T09:45:31.299046 | 2019-12-04T23:25:06 | 2019-12-04T23:25:06 | 225,975,074 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 355 | py | from chill import *
source('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/heat-3d/kernel.c')
destination('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/experiments/heat-3d/tmp_files/4280.c')
procedure('kernel_heat_3d')
loop(0)
known('n>3')
tile(0,2,8,2)
tile(0,4,64,3)
tile(1,2,8,2)
tile(1,4,64,3)
| [
"nashenruoyang@163.com"
] | nashenruoyang@163.com |
9419a1998c3a470874025ae739ab733a553cabe1 | 683d81b0d0ac10e3782b42f1ea6007124d72a663 | /1. Problems/b. Strings & Hash/0. Template/c. Best Substring - Find Longest Subarray with Distinct Entries.py | 5d6c4016e51b59fc2df63c9a2376ef08cb1f02b7 | [] | no_license | valleyceo/code_journal | 4b5e6fcbd792fedc639f773ca2bbf6725a9b9146 | 0191a6623e7a467c2c0070c4545358301a5e42ba | refs/heads/master | 2022-09-16T17:47:55.343712 | 2022-09-03T23:46:38 | 2022-09-03T23:46:38 | 129,997,935 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,026 | py | # Find The Longest Subarray With Distinct Entries
'''
- Given an array
- Return the length of longest subarray where all its elements are distinct
- Ex: < f,s,f,e,t,w,e,n,w,e > -> < s,f,e,t,w, >
'''
# O(n) time
def longest_subarray_with_distinct_entries(A: List[int]) -> int:
# Records the most recent occurrences of each entry.
most_recent_occurrence: Dict[int, int] = {}
longest_dup_free_subarray_start_idx = result = 0
for i, a in enumerate(A):
# Defer updating dup_idx until we see a duplicate.
if a in most_recent_occurrence:
dup_idx = most_recent_occurrence[a]
# A[i] appeared before. Did it appear in the longest current
# subarray?
if dup_idx >= longest_dup_free_subarray_start_idx:
result = max(result, i - longest_dup_free_subarray_start_idx)
longest_dup_free_subarray_start_idx = dup_idx + 1
most_recent_occurrence[a] = i
return max(result, len(A) - longest_dup_free_subarray_start_idx)
| [
"ericjkim9@gmail.com"
] | ericjkim9@gmail.com |
08054036f4c3a2e75d377b6e19f38b9de3adf161 | d2189145e7be2c836017bea0d09a473bf1bc5a63 | /Reposiciones/Carina Chavez Granados/12 septiembre 2018/Aprobado.py | 9611771d8ded8d6eef3de83eb7c77bd1a87db5b4 | [] | no_license | emilianoNM/Tecnicas3 | 12d10ce8d78803c8d2cd6a721786a68f7ee2809d | 6ad7f0427ab9e23643a28ac16889bca8791421d0 | refs/heads/master | 2020-03-25T18:06:34.126165 | 2018-11-24T04:42:14 | 2018-11-24T04:42:14 | 144,013,045 | 3 | 5 | null | 2018-09-14T10:47:26 | 2018-08-08T12:49:57 | Python | UTF-8 | Python | false | false | 693 | py | #Programa que determina si el alumno a aprobado o no
#Chavez Granados Carina
nota1 = float(input("Ingrese la calificacion obtenida en el primer parcial "))
nota2 = float(input("Ingrese la calificacion obtenida en el segundo parcial "))
nota3 = float(input("Ingrese la calificacion obtenida en el tercer parcial "))
puntosExtra = float(input("Ingrese puntos extra sobre calificacion final. De no tener ingrese 0 "))
calificacion = ((nota1+nota2+nota3)/3)+ puntosExtra
if(calificacion ==0 or calificacion > 10):
print ("Nota invalida")
elif (calificacion <= 5.9):
print ("Estudiante Reprobado")
elif(calificacion >= 6):
print ("Estudiante Aprobado")
else:
print ("Nota registrada")
| [
"noreply@github.com"
] | emilianoNM.noreply@github.com |
6fcbae292226ca0df91a1262396edff293e55426 | 72ea8dbdbd68813156b76c077edb5a3806bf42ab | /synapse/models/syn.py | 52034d79f42a87c3c24fcd12ef773c1a0a06b8c8 | [
"Apache-2.0"
] | permissive | williballenthin/synapse | 5c6f197f5a3cb3566c48dc444770592e89d4152a | 799854da814b79d6631e5cc2796c347bf4a80ce7 | refs/heads/master | 2020-12-24T14:19:12.530026 | 2017-03-16T20:30:38 | 2017-03-16T20:30:38 | 41,521,212 | 2 | 0 | null | 2015-08-28T02:01:50 | 2015-08-28T02:01:50 | null | UTF-8 | Python | false | false | 164 | py | import synapse.compat as s_compat
import synapse.common as s_common
def getDataModel():
return {
'prefix':'syn',
'version':201611251045,
}
| [
"invisigoth.kenshoto@gmail.com"
] | invisigoth.kenshoto@gmail.com |
aa32923fbd572cd498fb62627530c7d9b900fc71 | 372185cd159c37d436a2f2518d47b641c5ea6fa4 | /413. 等差数列划分.py | 39b4f0dfbb8db4e984bb2abfd914bb7c5ae6873d | [] | no_license | lidongze6/leetcode- | 12022d1a5ecdb669d57274f1db152882f3053839 | 6135067193dbafc89e46c8588702d367489733bf | refs/heads/master | 2021-07-16T09:07:14.256430 | 2021-04-09T11:54:52 | 2021-04-09T11:54:52 | 245,404,304 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 546 | py | class Solution:
def numberOfArithmeticSlices(self, A):
l = len(A)
if l <= 2: return 0
diff = [0]
for i in range(1, l):
diff.append(A[i] - A[i - 1])
f = [0] * l # f[i]表示以i结尾的数字组成的等差数列的个数
# 若连续三个数的差相等,则f[i]=f[i-1]+1
for i in range(2, l):
if diff[i] == diff[i - 1]:
f[i] += f[i - 1] + 1
return sum(f)
A = [1, 2, 3, 4]
print(Solution().numberOfArithmeticSlices(A))
| [
"lidongze6@163.com"
] | lidongze6@163.com |
ae26fe64e6810360680b6da6c841166e9db818da | a7da58ad91b007b3650003708eb91928f1e3684a | /bt5/erp5_pdm/SkinTemplateItem/portal_skins/erp5_pdm/SupplyLine_asCellRange.py | eda0a0f89d2ee885ca282f1b886772300ff84937 | [] | no_license | jgpjuniorj/j | 042d1bd7710fa2830355d4312a6b76103e29639d | dc02bfa887ffab9841abebc3f5c16d874388cef5 | refs/heads/master | 2021-01-01T09:26:36.121339 | 2020-01-31T10:34:17 | 2020-02-07T04:39:18 | 239,214,398 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,345 | py | portal = context.getPortalObject()
Base_translateString = portal.Base_translateString
cell_range = []
add_predicate = 1
# Get base category list
if option_variation:
# Get option base category list
add_predicate = 0
no_option_base_category_list = context.getVariationRangeBaseCategoryList(
omit_option_base_category=1)
base_category_list = context.getVariationRangeBaseCategoryList()
option_base_category_list = [x for x in base_category_list \
if x not in no_option_base_category_list]
if not option_base_category_list:
base_category_list_list = []
else:
base_category_list_list = [option_base_category_list]
else:
# Compatibility with ERP5 Shop
if base_id == 'reference':
add_predicate = 0
# Get base categories selected by the user
if base_id in ('path', 'reference'):
# XXX Compatibility
selected_base_category_list = context.getPVariationBaseCategoryList()
if not selected_base_category_list:
# XXX Compatibility...
if context.getParentValue().getPortalType() in \
context.getPortalResourceTypeList():
selected_base_category_list = context.getParentValue().\
getPVariationBaseCategoryList()
else:
property_id = '%s_variation_base_category_list' % base_id[len('path_'):]
selected_base_category_list = context.getProperty(property_id)
base_category_list_list = [[x] for x in selected_base_category_list]
# Generate cell range
for base_category_list in base_category_list_list:
if matrixbox:
# XXX matrixbox is right_display (not as listfield)
# => invert display and value in item
cell_range.append(map(lambda x: (x[1], x[0]),
context.getVariationRangeCategoryItemList(
base_category_list=base_category_list,
display_base_category=display_base_category,
sort_id='id')))
else:
cell_range.append(
context.getVariationRangeCategoryList(
base_category_list=base_category_list,
sort_id='id'))
# If no option, don't display quantity range
if option_variation:
if cell_range != []:
add_predicate = 1
# Do we need to add predicate ?
if add_predicate:
# Get quantity step
# XXX Dirty, use the same quantity range for option/no option matrix
if base_id == 'path':
# XXX Compatibility
price_parameter = 'base_price'
else:
price_parameter = base_id[len('path_'):]
option_base_id_begin_with = 'optional_'
if price_parameter.startswith(option_base_id_begin_with):
price_parameter = price_parameter[len(option_base_id_begin_with):]
predicate_list = context.getQuantityPredicateValueList(price_parameter)
if matrixbox:
# pred_ids = [(x.getRelativeUrl(), x.getTitle()) for x in predicate_list]
# Translate the matrixbox ranges
pred_ids = []
for predicate in predicate_list:
predicate_criterion_list = predicate.getCriterionList()
predicate_title = ''
for criterion in predicate_criterion_list:
if criterion.property == 'quantity':
min_qty = criterion.min
max_qty = criterion.max
if min_qty is None:
predicate_title = Base_translateString("Quantity < ${max_quantity}",
mapping={'max_quantity': max_qty})
elif max_qty is None:
predicate_title = Base_translateString("${min_quantity} <= Quantity",
mapping={'min_quantity': min_qty})
else:
predicate_title = Base_translateString("${min_quantity} <= Quantity < ${max_quantity}",
mapping={'min_quantity': min_qty,
'max_quantity': max_qty})
break
pred_ids.append((predicate.getRelativeUrl(), predicate_title))
else:
pred_ids = [x.getRelativeUrl() for x in predicate_list]
# Insert predicat list for display in columns
cell_range.insert(1, pred_ids)
# Remove empty range
cell_range = [x for x in cell_range if x!=[]]
return cell_range
| [
"georgios.dagkakis@nexedi.com"
] | georgios.dagkakis@nexedi.com |
64f6891461be0b9fd842280474e65369c45f9559 | 853640f0000951c54075d7fc06eb8dd142baf488 | /Staff/mclavan/old/mecScripts/myDev/mecModImport.py | 4f579360dc9a953b73c5dad3d457d321d3465878 | [] | no_license | creuter23/fs-tech-artist | fe666a61d7356bea45a23a27f9345733f696a2bc | ce3da679e3726baec7840156d6c6f6867b427383 | refs/heads/master | 2021-01-10T13:15:50.382194 | 2012-06-24T01:33:52 | 2012-06-24T01:33:52 | 45,221,516 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,203 | py |
# Load the information from a director into a gui as
import glob
import os, os.path
import maya.cmds as cmds
winWidth = 300
# path, list files or directories, type
# type = 0 (tabs), 1 (frames), 2(iconTextButton)
win = "mecModIWin"
def gui():
global mainCol
if( cmds.window(win, q=True, ex=True)):
cmds.deleteUI(win)
cmds.window(win, w=winWidth, h=400, t="Model Import")
mainCol = cmds.columnLayout()
cmds.showWindow(win)
def dynFrmGUI(filePath, items, parent, dirType=0 )
'''
filePath(string) is the filePath that each file will be at.
items(string list) will be files or directories
parent(string) which gui component will the the newly created gui components will be connected to.
dirType(int) 0 means tabs are going to be created, where 1 will create frames
'''
# items will be formatted correctly so only what is needed is included.
# keeping track of all the gui components created.
guiCom = []
# Mainlayout for the gui.
cmds.setParent(parent)
allPaths = os.walk(filePath)
"""
for item in items:
if(dirType):
'''
Create frames
'''
layoutTemp = cmds.frameLayout(label=item)
newPath = os.path.join( filePath,item )
files = glob.glob( os.path.join(newPath,"*.mb") )
guiImages = dynGUI( newPath, files, layoutTemp )
return [layoutTemp, guiImages]
else:
'''
Create tabs.
'''
print("Create tabs")
layoutTemp = cmds.tabLayout()
newPath = os.path.join( filePath,item )
# List all the files and isolate the directories.
dynFrmGUI(newPath, items, parent, dirType=0 )
"""
def dynGUI( filePath, items, parent ):
'''
filePath(string) is the filePath that each file will be at.
items(string list) will be files or directories
parent(string) which gui component will the the newly created gui components will be connected to.
'''
# items will be formatted correctly so only what is needed is included.
# keeping track of all the gui components created.
guiCom = []
# Mainlayout for the gui.
cmds.setParent(parent)
mainRow = cmds.rowColumnLayout( nc=2, cw=[[1,winWidth/2],[2, winWidth/2]] )
for item in items:
# Need to check to see if there is an image version like it.
# Extra the file name
fileParts = os.path.splitext(item)
# Check to see if the image exists?
'''
iconBtn = cmds.button( w=winWidth/2, h=30, label=fileParts[0], parent=mainRow,
c="print('Load file: %s')" %(item))
'''
iconBtn = cmds.iconTextButton( label=fileParts[0], style="iconAndTextHorizontal",
marginWidth=10, marginHeight=5, labelOffset=5,
w=winWidth/2, h=50 , parent=mainRow,
c="print('Load file: %s')" %(item))
if( os.path.exists(os.path.join(filePath,fileParts[0]+".xpm")) ):
cmds.iconTextButton(iconBtn, edit=True, image=os.path.join(filePath,fileParts[0]+".xpm") )
elif( os.path.exists(os.path.join(filePath,fileParts[0]+".bmp")) ):
cmds.iconTextButton(iconBtn, edit=True, image=os.path.join(filePath,fileParts[0]+".bmp") )
else:
print("Didn't find a match. %s != %s" %(os.path.join(filePath,fileParts[0]+".xmp"), item))
''''''
print("Icon Button:%s %s" %(item, iconBtn))
guiCom.append(iconBtn)
return guiCom
| [
"mclavan@gmail.com"
] | mclavan@gmail.com |
1d5182070ff7eb0f5888e23c461b86b3f1c8c66a | c0bfb092d73644dbb237e6f0aae5f3ba244f0984 | /donations/migrations/0001_initial.py | 3a505dd07dd5cbbef2a0657872ec98261a9f6849 | [] | no_license | callump5/share_respite | a58a2fc6c2585347a3ff5dec8e69d4191d87a77d | 5de8c46acc276b41ce0a7f7fd7e15bcbfb027135 | refs/heads/master | 2022-12-17T00:45:23.507128 | 2019-12-19T02:27:08 | 2019-12-19T02:27:08 | 217,771,733 | 0 | 0 | null | 2022-12-10T11:45:15 | 2019-10-26T21:32:49 | JavaScript | UTF-8 | Python | false | false | 663 | py | # Generated by Django 2.2.6 on 2019-11-08 14:46
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Donation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('donation', models.DecimalField(decimal_places=2, default=10.0, max_digits=8)),
],
options={
'verbose_name': 'Donations',
'verbose_name_plural': '1 - Donations',
},
),
]
| [
"clpullinger@gmail.com"
] | clpullinger@gmail.com |
baa6d62af9a153fb56d1d6f9a552b6ad48a67820 | efdd433fb2e358bb9ec4cb293db2211f5516a9e4 | /.local/share/virtualenvs/4-minidjango-P3G7Ftdt/bin/django-admin | 0ba0613f5f214415a6c8a4390c1e04e6c6c922f6 | [] | no_license | errinmarie/FeedBack | 3e5c2e581ee207f486567bd838ac864f2c959f18 | c7cf1aefea226b10b4387ded4a0693d786558d14 | refs/heads/master | 2021-10-01T20:08:53.846515 | 2018-11-28T02:49:41 | 2018-11-28T02:49:41 | 159,429,473 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 329 | #!/home/errinmixon/.local/share/virtualenvs/4-minidjango-P3G7Ftdt/bin/python3.6m
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
| [
"errinmixon@gmail.com"
] | errinmixon@gmail.com | |
0ac7805820be5bf5791783a39c2326bf86bcda7b | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_apprentice.py | 813d28f17ddfac6dcb2f6607bab63449394256c0 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 439 | py |
#calss header
class _APPRENTICE():
def __init__(self,):
self.name = "APPRENTICE"
self.definitions = [u"someone who has agreed to work for a skilled person for a particular period of time and often for low payment, in order to learn that person's skills: "]
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
f40dee84cc0a709e9af8c971d1d9af6a2fbb6de2 | 54e187ce123daff920027560a83f5bb4f6bea602 | /20190511/tp_shop/page_test.py | 621918c52b5172c6fe5c5296a8423def43cf4d8f | [] | no_license | GuoQin8284/PythonCode | 272b01d16ff508685b68c51b523a25e9753162ea | c4016a693c9ab4c798567aabf00135be10beae0c | refs/heads/master | 2023-05-06T03:45:55.667271 | 2021-05-27T15:29:28 | 2021-05-27T15:29:28 | 267,345,633 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,916 | py | import time
from selenium.webdriver.common.by import By
from tp_shop.base_test import Base_page, Base_handle
from tp_shop.unit_test import UnitDriver
class Page_driver(Base_page):
def __init__(self):
super().__init__()
self.username=(By.ID,"username")
self.password=(By.ID,"password")
self.verify_code=(By.ID,"verify_code")
self.login_btn=(By.NAME,"sbtbutton")
def find_username(self):
return self.base_page(self.username)
def find_password(self):
return self.base_page(self.password)
def find_verify_code(self):
return self.base_page(self.verify_code)
def find_login(self):
return self.base_page(self.login_btn)
class Handle_driver(Base_handle):
def __init__(self):
self.dri=Page_driver()
def input_username(self,num):
self.base_handle(self.dri.find_username(),num)
def input_password(self,pwd):
self.base_handle(self.dri.find_password(), pwd)
def input_verify(self,verify):
self.base_handle(self.dri.find_verify_code(), verify)
def click_login(self):
self.dri.find_login().click()
class Proxy_driver():
def __init__(self):
self.driver=Handle_driver()
self.udriver=UnitDriver.setup()
def proxy_login(self,num,pwd,verify):
self.driver.input_username(num)
self.driver.input_password(pwd)
self.driver.input_verify(verify)
self.driver.click_login()
def proxu_result(self,bool):
if bool is True:
time.sleep(3)
msg = self.udriver.title
print("true_msg:",msg)
self.udriver.find_element_by_xpath('//a[@title="退出"]').click()
return msg
else:
time.sleep(3)
msg = self.udriver.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]').text
print("msg:",msg)
return msg
| [
"1143908462@qq.com"
] | 1143908462@qq.com |
a799042308b5cbe9c4b002b596897942a11b2c3b | 35dbd536a17d7127a1dd1c70a2903ea0a94a84c2 | /src/sentry_plugins/gitlab/plugin.py | 3a046335398326b2e590b0835ad4fba58cc227b9 | [
"Apache-2.0",
"BUSL-1.1"
] | permissive | nagyist/sentry | efb3ef642bd0431990ca08c8296217dabf86a3bf | d9dd4f382f96b5c4576b64cbf015db651556c18b | refs/heads/master | 2023-09-04T02:55:37.223029 | 2023-01-09T15:09:44 | 2023-01-09T15:09:44 | 48,165,782 | 0 | 0 | BSD-3-Clause | 2022-12-16T19:13:54 | 2015-12-17T09:42:42 | Python | UTF-8 | Python | false | false | 7,711 | py | from rest_framework.request import Request
from sentry.integrations import FeatureDescription, IntegrationFeatures
from sentry.plugins.bases.issue2 import IssuePlugin2
from sentry.shared_integrations.exceptions import ApiError
from sentry.utils.http import absolute_uri
from sentry_plugins.base import CorePluginMixin
from sentry_plugins.utils import get_secret_field_config
from .client import GitLabClient
class GitLabPlugin(CorePluginMixin, IssuePlugin2):
description = "Integrate GitLab issues by linking a repository to a project"
slug = "gitlab"
title = "GitLab"
conf_title = title
conf_key = "gitlab"
required_field = "gitlab_url"
feature_descriptions = [
FeatureDescription(
"""
Track commits and releases (learn more
[here](https://docs.sentry.io/learn/releases/))
""",
IntegrationFeatures.COMMITS,
),
FeatureDescription(
"""
Resolve Sentry issues via GitLab commits and merge requests by
including `Fixes PROJ-ID` in the message
""",
IntegrationFeatures.COMMITS,
),
FeatureDescription(
"""
Create GitLab issues from Sentry
""",
IntegrationFeatures.ISSUE_BASIC,
),
FeatureDescription(
"""
Link Sentry issues to existing GitLab issues
""",
IntegrationFeatures.ISSUE_BASIC,
),
]
def is_configured(self, request: Request, project, **kwargs):
return bool(
self.get_option("gitlab_repo", project)
and self.get_option("gitlab_token", project)
and self.get_option("gitlab_url", project)
)
def get_new_issue_fields(self, request: Request, group, event, **kwargs):
fields = super().get_new_issue_fields(request, group, event, **kwargs)
return [
{
"name": "repo",
"label": "Repository",
"default": self.get_option("gitlab_repo", group.project),
"type": "text",
"readonly": True,
},
*fields,
{
"name": "assignee",
"label": "Assignee",
"default": "",
"type": "select",
"required": False,
"choices": self.get_allowed_assignees(request, group),
},
{
"name": "labels",
"label": "Labels",
"default": self.get_option("gitlab_labels", group.project),
"type": "text",
"placeholder": "e.g. high, bug",
"required": False,
},
]
def get_link_existing_issue_fields(self, request: Request, group, event, **kwargs):
return [
{
"name": "issue_id",
"label": "Issue #",
"default": "",
"placeholder": "e.g. 1543",
"type": "text",
},
{
"name": "comment",
"label": "Comment",
"default": absolute_uri(
group.get_absolute_url(params={"referrer": "gitlab_plugin"})
),
"type": "textarea",
"help": ("Leave blank if you don't want to " "add a comment to the GitLab issue."),
"required": False,
},
]
def get_allowed_assignees(self, request: Request, group):
repo = self.get_option("gitlab_repo", group.project)
client = self.get_client(group.project)
try:
response = client.list_project_members(repo)
except ApiError as e:
raise self.raise_error(e)
users = tuple((u["id"], u["username"]) for u in response)
return (("", "(Unassigned)"),) + users
def get_new_issue_title(self, **kwargs):
return "Create GitLab Issue"
def get_client(self, project):
url = self.get_option("gitlab_url", project).rstrip("/")
token = self.get_option("gitlab_token", project)
return GitLabClient(url, token)
def create_issue(self, request: Request, group, form_data, **kwargs):
repo = self.get_option("gitlab_repo", group.project)
client = self.get_client(group.project)
try:
response = client.create_issue(
repo,
{
"title": form_data["title"],
"description": form_data["description"],
"labels": form_data.get("labels"),
"assignee_id": form_data.get("assignee"),
},
)
except Exception as e:
raise self.raise_error(e)
return response["iid"]
def link_issue(self, request: Request, group, form_data, **kwargs):
client = self.get_client(group.project)
repo = self.get_option("gitlab_repo", group.project)
try:
issue = client.get_issue(repo=repo, issue_id=form_data["issue_id"])
except Exception as e:
raise self.raise_error(e)
comment = form_data.get("comment")
if comment:
try:
client.create_note(repo=repo, issue_iid=issue["iid"], data={"body": comment})
except Exception as e:
raise self.raise_error(e)
return {"title": issue["title"]}
def get_issue_label(self, group, issue_id, **kwargs):
return f"GL-{issue_id}"
def get_issue_url(self, group, issue_iid, **kwargs):
url = self.get_option("gitlab_url", group.project).rstrip("/")
repo = self.get_option("gitlab_repo", group.project)
return f"{url}/{repo}/issues/{issue_iid}"
def get_configure_plugin_fields(self, request: Request, project, **kwargs):
gitlab_token = self.get_option("gitlab_token", project)
secret_field = get_secret_field_config(
gitlab_token, "Enter your GitLab API token.", include_prefix=True
)
secret_field.update(
{
"name": "gitlab_token",
"label": "Access Token",
"placeholder": "e.g. g5DWFtLzaztgYFrqhVfE",
}
)
return [
{
"name": "gitlab_url",
"label": "GitLab URL",
"type": "url",
"default": "https://gitlab.com",
"placeholder": "e.g. https://gitlab.example.com",
"required": True,
"help": "Enter the URL for your GitLab server.",
},
secret_field,
{
"name": "gitlab_repo",
"label": "Repository Name",
"type": "text",
"placeholder": "e.g. getsentry/sentry",
"required": True,
"help": "Enter your repository name, including the owner.",
},
{
"name": "gitlab_labels",
"label": "Issue Labels",
"type": "text",
"placeholder": "e.g. high, bug",
"required": False,
"help": "Enter the labels you want to auto assign to new issues.",
},
]
def validate_config(self, project, config, actor=None):
url = config["gitlab_url"].rstrip("/")
token = config["gitlab_token"]
repo = config["gitlab_repo"]
client = GitLabClient(url, token)
try:
client.get_project(repo)
except Exception as e:
raise self.raise_error(e)
return config
| [
"noreply@github.com"
] | nagyist.noreply@github.com |
d3997a778c6a237ebc84a8713138315f575446ba | 5e120b710f4fb13ca6b445dfd26a1e56c82ba464 | /backend/driver/migrations/0001_initial.py | 6eaacdb0dabe3947bc212180e78da34361cbcb1c | [] | no_license | crowdbotics-apps/rasoda-house-20728 | 3e0757cb3590f19d0c706fa9d6b0ee44d77b6023 | 8af09ec250085074eba14b94635ab4f5f3e5b1a7 | refs/heads/master | 2022-12-20T05:17:41.979347 | 2020-09-26T14:31:39 | 2020-09-26T14:31:39 | 298,829,963 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,540 | py | # Generated by Django 2.2.16 on 2020-09-26 14:24
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("delivery_order", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="DriverProfile",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("photo", models.URLField()),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
("last_updated", models.DateTimeField(auto_now=True)),
("details", models.TextField(blank=True, null=True)),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="driverprofile_user",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="DriverOrder",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"driver",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="driverorder_driver",
to="driver.DriverProfile",
),
),
(
"order",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="driverorder_order",
to="delivery_order.Order",
),
),
],
),
]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
b8ef9255d660c674f5716a408b3c9d926bcac2e3 | f9d564f1aa83eca45872dab7fbaa26dd48210d08 | /huaweicloud-sdk-bss/huaweicloudsdkbss/v2/model/service_types.py | 18aacc71f4fc4c80fd0cae02267b7092b25a7363 | [
"Apache-2.0"
] | permissive | huaweicloud/huaweicloud-sdk-python-v3 | cde6d849ce5b1de05ac5ebfd6153f27803837d84 | f69344c1dadb79067746ddf9bfde4bddc18d5ecf | refs/heads/master | 2023-09-01T19:29:43.013318 | 2023-08-31T08:28:59 | 2023-08-31T08:28:59 | 262,207,814 | 103 | 44 | NOASSERTION | 2023-06-22T14:50:48 | 2020-05-08T02:28:43 | Python | UTF-8 | Python | false | false | 5,128 | py | # coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ServiceTypes:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'service_type_name': 'str',
'service_type_code': 'str',
'abbreviation': 'str'
}
attribute_map = {
'service_type_name': 'service_type_name',
'service_type_code': 'service_type_code',
'abbreviation': 'abbreviation'
}
def __init__(self, service_type_name=None, service_type_code=None, abbreviation=None):
"""ServiceTypes
The model defined in huaweicloud sdk
:param service_type_name: 云服务类型的名称。
:type service_type_name: str
:param service_type_code: 云服务类型的编码。
:type service_type_code: str
:param abbreviation: 云服务类型的缩写。
:type abbreviation: str
"""
self._service_type_name = None
self._service_type_code = None
self._abbreviation = None
self.discriminator = None
if service_type_name is not None:
self.service_type_name = service_type_name
if service_type_code is not None:
self.service_type_code = service_type_code
if abbreviation is not None:
self.abbreviation = abbreviation
@property
def service_type_name(self):
"""Gets the service_type_name of this ServiceTypes.
云服务类型的名称。
:return: The service_type_name of this ServiceTypes.
:rtype: str
"""
return self._service_type_name
@service_type_name.setter
def service_type_name(self, service_type_name):
"""Sets the service_type_name of this ServiceTypes.
云服务类型的名称。
:param service_type_name: The service_type_name of this ServiceTypes.
:type service_type_name: str
"""
self._service_type_name = service_type_name
@property
def service_type_code(self):
"""Gets the service_type_code of this ServiceTypes.
云服务类型的编码。
:return: The service_type_code of this ServiceTypes.
:rtype: str
"""
return self._service_type_code
@service_type_code.setter
def service_type_code(self, service_type_code):
"""Sets the service_type_code of this ServiceTypes.
云服务类型的编码。
:param service_type_code: The service_type_code of this ServiceTypes.
:type service_type_code: str
"""
self._service_type_code = service_type_code
@property
def abbreviation(self):
"""Gets the abbreviation of this ServiceTypes.
云服务类型的缩写。
:return: The abbreviation of this ServiceTypes.
:rtype: str
"""
return self._abbreviation
@abbreviation.setter
def abbreviation(self, abbreviation):
"""Sets the abbreviation of this ServiceTypes.
云服务类型的缩写。
:param abbreviation: The abbreviation of this ServiceTypes.
:type abbreviation: str
"""
self._abbreviation = abbreviation
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ServiceTypes):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
de422c04e42be82d6206d20f6ecfd3b98933ee87 | fc6eefb980b53baae393980c46ac40d256687014 | /Udacity-Intro-to-Algorithms/Lesson 4/Lesson 4 - Quizzes/Make a Combination Lock.py | b15858bc1673074fdfe97e539c7c189236002c6d | [] | no_license | Brian-Mascitello/UCB-Third-Party-Classes | 7bc151d348f753f93850f5e286c263639f782b05 | e2d26e3d207d364462024759ad2342a8e172f657 | refs/heads/master | 2021-01-02T09:10:01.146169 | 2018-10-08T00:19:58 | 2018-10-08T00:19:58 | 99,150,324 | 0 | 0 | null | 2018-02-01T06:33:25 | 2017-08-02T18:47:29 | Python | UTF-8 | Python | false | false | 2,361 | py | # Generate a combination lock graph given a list of nodes
def make_link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = 1
if node2 not in G:
G[node2] = {}
(G[node2])[node1] = 1
return G
def create_combo_lock(nodes):
G = {}
make_link(G, nodes[0], nodes[1])
for x in range(2, len(nodes)):
make_link(G, nodes[0], nodes[x])
make_link(G, nodes[x - 1], nodes[x])
return G
##############
# Code for testing
def is_chain(graph, nodes):
# find the first node with degree one
start = (n for n, e in graph.iteritems()
if len(e) == 1).next()
count = 1
# keep track of what we've seen to make
# sure there are no cycles
seen = set([start])
# follow the edges
prev = None
current = start
while True:
nexts = graph[current].keys()
# get rid of the edge back to prev
nexts = [n for n in nexts if not n == prev]
if len(nexts) > 1:
# bad. too many edges to be a chain
return False
elif len(nexts) == 0:
# We're done following the chain
# Did we get enough edges:
return count == len(nodes)
prev = current
current = nexts[0]
if current in seen:
# bad. this isn't a chain
# it has a loop
return False
seen.add(current)
count += 1
def is_combo_lock(graph, nodes):
# first see if we have a star
center = None
degree = None
for node, edges in graph.iteritems():
if len(edges) > degree:
center = node
degree = len(edges)
if not degree == len(nodes) - 1:
return False
# make a graph out of all the edges
# not connected to the center
chain = {}
for node, edges in graph.iteritems():
if node == center:
continue
for e in edges:
if e == center:
continue
make_link(chain, node, e)
return is_chain(chain, [n for n in nodes if n != center])
def test():
for n in [5, 10, 20]:
combo = create_combo_lock(range(n))
if not is_combo_lock(combo, range(n)):
return False
return True
print(test()) # Worked in the Udacity classroom as True, probably a Python 2 conversion error.
| [
"bmascitello@gmail.com"
] | bmascitello@gmail.com |
132553e8da80d41a19ba7787d7c58c832b5dbbd3 | a923d62758af3d9700dcca5e9258783e1355e1e2 | /reviews/utils.py | cf614c4b2cdbdeb425b8d2479ad87d0088525967 | [
"MIT"
] | permissive | moshthepitt/answers | c248b539ef16018ad42f6d6ea4af7864b5d4115c | 9febf465a18c41e7a48130e987a8fd64ceae3358 | refs/heads/master | 2022-11-29T12:00:00.964280 | 2020-07-14T07:31:35 | 2020-07-14T07:31:35 | 35,694,085 | 6 | 3 | MIT | 2022-11-22T00:52:43 | 2015-05-15T20:05:03 | Python | UTF-8 | Python | false | false | 1,764 | py | from .models import Review
def check_equal(lst):
return lst[1:] == lst[:-1]
def review_groups(name, sitting, quiz, group=None):
"""
Bulk create reviews
Usage:
from questions.models import Quiz, Sitting
from users.models import UserGroup
from reviews.utils import review_groups
quiz = Quiz.objects.get(pk=7)
sitting = Sitting.objects.get(pk=5)
group = UserGroup.objects.get(pk=10)
name = "Accounts"
review_groups(name=name, sitting=sitting, quiz=quiz, group=group)
"""
proceed = False
if sitting.customer == quiz.customer:
if group:
if isinstance(group, list):
cus_list = [x.customer for x in group]
if cus_list and check_equal(cus_list):
if cus_list[0] == quiz.customer:
proceed = True
elif isinstance(group, object):
if group.customer == quiz.customer:
proceed = True
else:
proceed = True
if proceed:
r = Review()
r.title = name
r.customer = sitting.customer
r.sitting = sitting
r.quiz = quiz
r.save()
if not group:
r.public = True
r.save()
else:
if isinstance(group, list):
done = []
for g in group:
if g not in done:
g_userprofiles = g.userprofile_set.all()
r.reviewers.add(*list(g_userprofiles))
done.append(g)
elif isinstance(group, object):
userprofiles = group.userprofile_set.all()
r.reviewers.add(*list(userprofiles))
| [
"kelvin@jayanoris.com"
] | kelvin@jayanoris.com |
4df2cd9a563bc20db64a95f177049d66636412fd | d0be6253944017ce3375b9e761127cb32f95b5fe | /wxpythonInAction/part1_wxPython入门/_2_给你的wxPython程序一个稳固的基础/redirectionStd.py | 05ce57d24f48ac8fffe61c13d8210589f5ca2c85 | [] | no_license | xuguangmin/Programming-for-study | b99a42a64e54d02ffdd9fc49aa0d90a46b9a15e1 | 5298f48b9b358c6f3968432bfdebbdf6bd478acc | refs/heads/master | 2020-03-29T16:06:33.238082 | 2015-07-29T07:54:07 | 2015-07-29T07:54:07 | 39,826,114 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,044 | py | #!/usr/bin/env python
#coding:utf-8
"""演示程序的生命周期和重定向标准输出"""
import wx
import sys, time
class Frame(wx.Frame):
def __init__(self, parent, id, title):
print "Frame __init__"#框架被打开之前输出
wx.Frame.__init__(self, parent, id, title, style=wx.DEFAULT_FRAME_STYLE|wx.FRAME_TOOL_WINDOW)
class App(wx.App):
def __init__(self, redirect=True, filename=None):
print "App __init__"
wx.App.__init__(self, redirect, filename)
def OnInit(self):
print ">>>>>>>>>>>>>>>>>"
print "OnInit" #输出到stdout
self.frame = Frame(parent=None, id=-1, title='Startup')#创建框架
self.frame.Show()
self.SetTopWindow(self.frame)
#self.SetExitOnFrameDelete(False)#程序不关闭
print >> sys.stderr, "a pretend error message"#输出到stderr
return True
def OnExit(self):
print "OnExit"
if __name__ == "__main__":
app = App(redirect=True, filename="output")#文本重定向从这里开始
print "before Mainloop"
app.MainLoop()
print "after MainLoop"#框架被关闭之后输出
| [
"1312909726@qq.com"
] | 1312909726@qq.com |
0e5669008f6172abbb1c70c5a606a9b19ea6d415 | 90cebb6ec2862ece52ac14fd28c590d5d48d7afa | /fip_project/staff_profile_app/views.py | 9208f9a7b4a960e83b8c9596c91163554592b04f | [] | no_license | muddy700/FIP-Backend | a770a60f0431c8c72c8986035f9310d2a9fdd847 | f07da0622ebd275036dee10b58c24b8449944c59 | refs/heads/main | 2023-07-09T10:11:19.159630 | 2021-08-15T20:44:44 | 2021-08-15T20:44:44 | 360,058,550 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 353 | py | from rest_framework import generics, permissions, viewsets
from .models import StaffProfile
from .serializers import StaffProfileSerializer
class StaffProfileViewSet(viewsets.ModelViewSet):
queryset = StaffProfile.objects.all()
permission_classes = [
permissions.IsAuthenticated,
]
serializer_class = StaffProfileSerializer
| [
"mohamedmfaume700@gmail.com"
] | mohamedmfaume700@gmail.com |
e460154eca770c71dd67b7333102ebb4d6b73476 | 450c27ee64ab60f9cf842eaddda52279012d7885 | /0x0F-python-object_relational_mapping/4-cities_by_state.py | 121941f8080fc1298e13b4dcdcace5fa6b54a48f | [] | no_license | dacorredor11/holbertonschool-higher_level_programming | 5a2805d62736021d26c0731085ad251bf58d45f6 | 85e54b116fbf359909cad39698ca09945cb639e1 | refs/heads/master | 2022-12-16T19:43:21.508586 | 2020-09-25T03:48:23 | 2020-09-25T03:48:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 601 | py | #!/usr/bin/python3
"""This module defines a simple query """
import MySQLdb
from sys import argv
if __name__ == "__main__":
user = argv[1]
passw = argv[2]
database = argv[3]
db = MySQLdb.connect(host="localhost", port=3306, user=user,
passwd=passw, db=database)
cur = db.cursor()
cur.execute("SELECT cities.id, cities.name, states.name\
FROM cities INNER JOIN states\
ON cities.state_id=states.id ORDER BY id ASC")
rows = cur.fetchall()
for row in rows:
print(row)
cur.close()
db.close()
| [
"vidmore8@gmail.com"
] | vidmore8@gmail.com |
f110b89b2b7324c338fc38f8bb9b062a85ac558d | c6cdf43bb35b55b02cffe30c9e267d9ccdcbf050 | /fluent_comments/__init__.py | f7f4d32dafa323b79ca3fd3d8519333d318a8c67 | [
"Apache-2.0"
] | permissive | matmoxam/django-fluent-comments | b608a888c44a5f99ffd4449dfff93426f11ecedb | 441e90047f1fa6143788996b42567d76d1f06806 | refs/heads/master | 2021-01-12T06:34:36.285149 | 2016-12-26T13:54:29 | 2016-12-26T13:54:29 | 77,386,864 | 0 | 0 | null | 2016-12-26T13:49:25 | 2016-12-26T13:49:25 | null | UTF-8 | Python | false | false | 678 | py | """
API for :ref:`custom-comment-app-api`
"""
from fluent_comments import appsettings
# following PEP 440
__version__ = "1.2.2"
def get_model():
"""
Return the model to use for commenting.
"""
if appsettings.USE_THREADEDCOMMENTS:
from threadedcomments.models import ThreadedComment
return ThreadedComment
else:
# Our proxy model that performs select_related('user') for the comments
from fluent_comments.models import FluentComment
return FluentComment
def get_form():
"""
Return the form to use for commenting.
"""
from fluent_comments.forms import FluentCommentForm
return FluentCommentForm
| [
"vdboor@edoburu.nl"
] | vdboor@edoburu.nl |
8c637e726931c4e8cf3f2a28dc8f742e97b3b0ae | ce4cb5a1b577a680f951c7aaa22f71299ed01138 | /redis_metrics/management/commands/delete_metric.py | 309412a18365d1a3460c956df6c6e9dfe00672f7 | [
"MIT"
] | permissive | remohammadi/django-redis-metrics | 614cc854e432ce02efa88db878031b0b284d06b7 | bd6a4fa8ecf40416652071d480f159d9044640cf | refs/heads/master | 2021-01-18T11:10:57.232095 | 2014-06-22T14:45:12 | 2014-06-22T14:45:12 | 21,093,396 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 417 | py | from django.core.management.base import BaseCommand, CommandError
from redis_metrics.models import R
class Command(BaseCommand):
args = '<metric-key>'
help = "Removes a metric and its data"
def handle(self, *args, **options):
if len(args) == 0:
raise CommandError("You must provide a metric name")
metric_slug = args[0]
r = R()
r.delete_metric(metric_slug)
| [
"brad@bradmontgomery.net"
] | brad@bradmontgomery.net |
50898aa48f292d40ff6fa60f4b28d99842d8ee37 | 141b42d9d72636c869ff2ce7a2a9f7b9b24f508b | /myvenv/Lib/site-packages/graphene_django/tests/urls_pretty.py | dfe4e5b92729441499a0313579db217ef25049ac | [
"BSD-3-Clause"
] | permissive | Fa67/saleor-shop | 105e1147e60396ddab6f006337436dcbf18e8fe1 | 76110349162c54c8bfcae61983bb59ba8fb0f778 | refs/heads/master | 2021-06-08T23:51:12.251457 | 2018-07-24T08:14:33 | 2018-07-24T08:14:33 | 168,561,915 | 1 | 0 | BSD-3-Clause | 2021-04-18T07:59:12 | 2019-01-31T17:00:39 | Python | UTF-8 | Python | false | false | 188 | py | from django.conf.urls import url
from ..views import GraphQLView
from .schema_view import schema
urlpatterns = [
url(r'^graphql', GraphQLView.as_view(schema=schema, pretty=True)),
]
| [
"gruzdevasch@gmail.com"
] | gruzdevasch@gmail.com |
50c4ef422705200baaed6ae9acc6e9abab88e2b9 | 95255a27a22d16cdb4a365b2794f8c95377e7e71 | /mobike-api-test/lib/util/md5_util.py | 12d75ec02f3a0da8b8c4855afcc86ee137edb8aa | [] | no_license | lijule168/python_test_web | 9cc23c42e9f1a0392466131234598c8805c0cf62 | 3e51e9e80e9778540c8cc1c799fed402f2469ae8 | refs/heads/master | 2023-06-04T14:49:45.533518 | 2021-06-12T08:05:51 | 2021-06-12T08:05:51 | 376,212,939 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,988 | py | #!/usr/bin/python
import hashlib
import base64,datetime
class MD5Util(object):
str_digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
def __init__(self):
pass
@staticmethod
def abc(str):
md5_str = hashlib.md5(str).digest()
#print md5_str
binpwd = [bin(int(i.encode('hex'), 16))[2:] for i in md5_str]
intpwd = [MD5Util.bin2int(i) for i in binpwd]
return intpwd
@staticmethod
def bin2int(bin):
x = int(bin, 2)
if len(bin) == 8:
x -= 2 ** 8
return x
@staticmethod
def get_md5_code(str):
md5_str = MD5Util.abc(str)
ret = ""
for char in md5_str:
#print char
i_ret = char
if i_ret< 0:
i_ret = i_ret + 256
id1 = i_ret / 16
id2 = i_ret % 16
ret = ret + MD5Util.str_digits[id1] + MD5Util.str_digits[id2]
return ret
# @staticmethod
# def get_md5(str):
# md2 = hashlib.md5()
# md2.update(str)
# return md2.hexdigest()
@classmethod
def get_eption(cls, time_stamp, nu, if_epdata=1):
if not isinstance(time_stamp, str):
time_stamp = str(time_stamp)
if not isinstance(nu, str):
nu = str(nu)
m = hashlib.md5()
m.update((nu + '#' + time_stamp).encode(encoding="utf-8"))
psw = m.hexdigest()
if if_epdata:
return psw[2:10]
else:
return psw[2:7]
@classmethod
def get_md5(cls, str_list):
m = hashlib.md5()
m.update(str_list.encode(encoding='utf-8'))
md = m.hexdigest()
return md
@classmethod
def get_sha1_encrypt(self,origin_str):
"""
使用sha1加密算法,返回str加密后的字符串
"""
sha = hashlib.sha1(origin_str.encode("utf-8"))
encrypts = sha.hexdigest()
return encrypts | [
"lijule168@163.com"
] | lijule168@163.com |
d738c1d2381b3860731993767393372dd29cd809 | 7cb626363bbce2f66c09e509e562ff3d371c10c6 | /multimodel_inference/py3_v1/sc11nm.py | 6bdfea328462088d3b6fb97dfdb0e94e601771e3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | z0on/AFS-analysis-with-moments | 76bfd6b0361ab7e9173144dbd21b6fa2c7bf1795 | eea4735b3b6fbe31c4e396da3d798387884a1500 | refs/heads/master | 2023-07-31T20:49:20.865161 | 2023-07-19T06:57:32 | 2023-07-19T06:57:32 | 96,915,117 | 4 | 5 | null | 2020-09-02T17:39:08 | 2017-07-11T16:38:03 | Python | UTF-8 | Python | false | false | 3,030 | py | #!/usr/bin/env python3
# size change before split, one epoch after split, NO migration
# n(para): 6
import matplotlib
matplotlib.use('PDF')
import moments
import pylab
import random
import matplotlib.pyplot as plt
import numpy as np
from numpy import array
from moments import Misc,Spectrum,Numerics,Manips,Integration,Demographics1D,Demographics2D
import sys
infile=sys.argv[1]
pop_ids=[sys.argv[2],sys.argv[3]]
projections=[int(sys.argv[4]),int(sys.argv[5])]
if len(sys.argv)==9:
params = np.loadtxt(sys.argv[8], delimiter=" ", unpack=False)
else:
params=[1,1,1,1,1,0.01]
# mutation rate per sequenced portion of genome per generation: for A.millepora, 0.02
mu=float(sys.argv[6])
# generation time, in thousand years: 0.005 (5 years)
gtime=float(sys.argv[7])
# set Polarized=False below for folded AFS analysis
fs = moments.Spectrum.from_file(infile)
data=fs.project(projections)
ns=data.sample_sizes
np.set_printoptions(precision=3)
#-------------------
# split into unequal pop sizes with asymmetrical migration
def sc11nm(params , ns):
# p_misid: proportion of misidentified ancestral states
nu0, nu1_2,nu2_2,T1, T2, p_misid = params
sts = moments.LinearSystem_1D.steady_state_1D(ns[0] + ns[1])
fs = moments.Spectrum(sts)
fs.integrate([nu0], T1)
fs = moments.Manips.split_1D_to_2D(fs, ns[0], ns[1])
fs.integrate([nu1_2, nu2_2], T2, m = np.array([[0, 0], [0, 0]]))
return (1-p_misid)*fs + p_misid*moments.Numerics.reverse_array(fs)
func=sc11nm
upper_bound = [100, 100, 100, 100,100,0.25]
lower_bound = [1e-3,1e-3,1e-3,1e-3,1e-3,1e-5]
params = moments.Misc.perturb_params(params, fold=2, upper_bound=upper_bound,
lower_bound=lower_bound)
poptg = moments.Inference.optimize_log(params, data, func,
lower_bound=lower_bound,
upper_bound=upper_bound,
verbose=False, maxiter=30)
# extracting model predictions, likelihood and theta
model = func(poptg, ns)
ll_model = moments.Inference.ll_multinom(model, data)
theta = moments.Inference.optimal_sfs_scaling(model, data)
# random index for this replicate
ind=str(random.randint(0,999999))
# plotting demographic model
plot_mod = moments.ModelPlot.generate_model(func, poptg, ns)
moments.ModelPlot.plot_model(plot_mod, save_file="sc11nm_"+ind+".png", pop_labels=pop_ids, nref=theta/(4*mu), draw_scale=False, gen_time=gtime, gen_time_units="KY", reverse_timeline=True)
# bootstrapping for SDs of params and theta
# printing parameters and their SDs
print( "RESULT","sc11nm",ind,len(params),ll_model,sys.argv[1],sys.argv[2],sys.argv[3],poptg,theta)
# plotting quad-panel figure witt AFS, model, residuals:
moments.Plotting.plot_2d_comp_multinom(model, data, vmin=0.1, resid_range=3,
pop_ids =pop_ids)
plt.savefig("sc11nm_"+ind+"_"+sys.argv[1]+"_"+sys.argv[2]+"_"+sys.argv[3]+"_"+sys.argv[4]+"_"+sys.argv[5]+'.pdf')
| [
"matz@utexas.edu"
] | matz@utexas.edu |
425772324787c708fdd781c392f229fce2044053 | 1f5f8f95530003c6c66419519d78cb52d21f65c0 | /projects/golem_gui/tests/test_builder_code/access_test_code_does_not_exist.py | 40a8bac40ff5d2b61f1fa4c0afee9bdd16ccaba1 | [] | no_license | golemhq/golem-tests | c5d3ab04b1ea3755d8b812229feb60f513d039ac | dff8fd3a606c3d1ef8667aece6fddef8ac441230 | refs/heads/master | 2023-08-17T23:05:26.286718 | 2021-10-04T20:34:17 | 2021-10-04T20:34:17 | 105,579,436 | 4 | 1 | null | 2018-11-19T00:14:24 | 2017-10-02T20:05:55 | Python | UTF-8 | Python | false | false | 505 | py | from golem import actions
from projects.golem_gui.pages import common
from projects.golem_gui.pages import api
description = 'Verify a correct message is displayed when the test does not exist'
def setup(data):
common.access_golem(data.env.url, data.env.admin)
api.project.using_project('test_builder_code')
def test(data):
actions.navigate(data.env.url + 'project/'+data.project+'/test/not_existent/code/')
actions.assert_page_contains_text('The test not_existent does not exist')
| [
"luciano@lucianorenzi.com"
] | luciano@lucianorenzi.com |
86b58e9108130f2dff5013525c7f7f0fa3906107 | b5dd8d1b798c94731a84c02d98aafb9147200a85 | /sentence_matching/BSCESIMSYNTree/model/BiLSTMModel.py | 869c7942ce50796786795acd58145e48e04100c7 | [] | no_license | zhangmeishan/DepSAWR | 1ae348dd04ec5e46bc5a75c8972b4bc4008528fe | 104f44fd962a42fdee9b1a9332997d35e8461ff4 | refs/heads/master | 2021-07-09T20:56:56.897774 | 2020-10-27T05:41:08 | 2020-10-27T05:41:08 | 206,974,879 | 15 | 3 | null | null | null | null | UTF-8 | Python | false | false | 7,800 | py | from module.ESIM import *
from module.Utils import *
from module.CPUEmbedding import *
from module.Common import *
from module.TreeGRU import *
class BiLSTMModel(nn.Module):
def __init__(self, vocab, config, init_embedding):
super(BiLSTMModel, self).__init__()
self.config = config
initvocab_size, initword_dims = init_embedding.shape
self.word_dims = initword_dims
if config.word_dims != initword_dims or vocab.vocab_size != initvocab_size:
print("prev embedding shape size does not match, check config file")
self.word_embed = nn.Embedding(vocab.vocab_size, self.word_dims, padding_idx=vocab.PAD)
self.word_embed.weight.data.copy_(torch.from_numpy(init_embedding))
self.rel_embed = nn.Embedding(vocab.rel_size, self.word_dims, padding_idx=vocab.PAD)
embedding_matrix = np.zeros((vocab.rel_size, self.word_dims))
for i in range(vocab.rel_size):
if i == vocab.PAD: continue
embedding_matrix[i] = np.random.normal(size=(self.word_dims))
embedding_matrix[i] = embedding_matrix[i] / np.std(embedding_matrix[i])
self.rel_embed.weight.data.copy_(torch.from_numpy(embedding_matrix))
self.rnn_dropout = RNNDropout(p=config.dropout_mlp)
self.dt_tree = DTTreeGRU(3*self.word_dims, config.lstm_hiddens)
self.td_tree = TDTreeGRU(3*self.word_dims, config.lstm_hiddens)
self.hidden_size = config.lstm_hiddens
self.lstm_enc = Seq2SeqEncoder(nn.LSTM,
2*self.hidden_size,
self.hidden_size,
bidirectional=True)
self.atten = SoftmaxAttention()
self.hidden_dim = 4*2*config.lstm_hiddens
self.mlp = nn.Sequential(nn.Linear(4*2*self.hidden_size,
self.hidden_size),
nn.ReLU())
self.lstm_dec = Seq2SeqEncoder(nn.LSTM,
self.hidden_size,
self.hidden_size,
bidirectional=True)
self.feature_dim = 2*4*config.lstm_hiddens
self.proj = nn.Sequential(nn.Dropout(p=config.dropout_mlp),
nn.Linear(2*4*self.hidden_size, self.hidden_size),
nn.Tanh(),
nn.Dropout(p=config.dropout_mlp),
nn.Linear(self.hidden_size, vocab.tag_size))
self.apply(_init_esim_weights)
def forward(self, tinputs):
##unpack inputs
src_words, src_extwords_embed, src_rels, src_heads, src_lens, src_masks, \
tgt_words, tgt_extwords_embed, tgt_rels, tgt_heads, tgt_lens, tgt_masks = tinputs
src_dyn_embed = self.word_embed(src_words)
tgt_dyn_embed = self.word_embed(tgt_words)
src_rel_embed = self.rel_embed(src_rels)
tgt_rel_embed = self.rel_embed(tgt_rels)
src_embed = torch.cat([src_dyn_embed, src_extwords_embed, src_rel_embed], dim=-1)
tgt_embed = torch.cat([tgt_dyn_embed, tgt_extwords_embed, tgt_rel_embed], dim=-1)
src_embed = self.rnn_dropout(src_embed)
tgt_embed = self.rnn_dropout(tgt_embed)
batch_size, src_length, input_dim = src_embed.size()
src_trees = []
src_indexes = np.zeros((src_length, batch_size), dtype=np.int32)
for b, head in enumerate(src_heads):
root, tree = creatTree(head)
root.traverse()
for step, index in enumerate(root.order):
src_indexes[step, b] = index
src_trees.append(tree)
src_embed = src_embed.transpose(1, 0)
src_dt_outputs, src_dt_hidden_ts = self.dt_tree(src_embed, src_indexes, src_trees, src_lens)
src_td_outputs, src_td_hidden_ts = self.td_tree(src_embed, src_indexes, src_trees, src_lens)
src_shiddens = torch.cat([src_dt_outputs, src_td_outputs], dim=2)
batch_size, tgt_length, input_dim = tgt_embed.size()
tgt_trees = []
tgt_indexes = np.zeros((tgt_length, batch_size), dtype=np.int32)
for b, head in enumerate(tgt_heads):
root, tree = creatTree(head)
root.traverse()
for step, index in enumerate(root.order):
tgt_indexes[step, b] = index
tgt_trees.append(tree)
tgt_embed = tgt_embed.transpose(1, 0)
tgt_dt_outputs, tgt_dt_hidden_ts = self.dt_tree(tgt_embed, tgt_indexes, tgt_trees, tgt_lens)
tgt_td_outputs, tgt_td_hidden_ts = self.td_tree(tgt_embed, tgt_indexes, tgt_trees, tgt_lens)
tgt_shiddens = torch.cat([tgt_dt_outputs, tgt_td_outputs], dim=2)
src_hiddens = self.lstm_enc(src_shiddens, src_lens)
tgt_hiddens = self.lstm_enc(tgt_shiddens, tgt_lens)
src_hiddens_att, tgt_hiddens_att = self.atten(src_hiddens, src_masks, \
tgt_hiddens, tgt_masks)
src_diff_hiddens = src_hiddens - src_hiddens_att
src_prod_hiddens = src_hiddens * src_hiddens_att
src_summary_hiddens = torch.cat([src_hiddens, src_hiddens_att, src_diff_hiddens, \
src_prod_hiddens], dim=-1)
tgt_diff_hiddens = tgt_hiddens - tgt_hiddens_att
tgt_prod_hiddens = tgt_hiddens * tgt_hiddens_att
tgt_summary_hiddens = torch.cat([tgt_hiddens, tgt_hiddens_att, tgt_diff_hiddens, \
tgt_prod_hiddens], dim=-1)
src_hiddens_proj = self.mlp(src_summary_hiddens)
tgt_hiddens_proj = self.mlp(tgt_summary_hiddens)
src_hiddens_proj = self.rnn_dropout(src_hiddens_proj)
tgt_hiddens_proj = self.rnn_dropout(tgt_hiddens_proj)
src_final_hiddens = self.lstm_dec(src_hiddens_proj, src_lens)
tgt_final_hiddens = self.lstm_dec(tgt_hiddens_proj, tgt_lens)
src_hidden_avg = torch.sum(src_final_hiddens * src_masks.unsqueeze(1)
.transpose(2, 1), dim=1)\
/ (torch.sum(src_masks, dim=1, keepdim=True) + 1e-7)
tgt_hidden_avg = torch.sum(tgt_final_hiddens * tgt_masks.unsqueeze(1)
.transpose(2, 1), dim=1)\
/ (torch.sum(tgt_masks, dim=1, keepdim=True) + 1e-7)
src_hidden_max, _ = replace_masked(src_final_hiddens, src_masks, -1e7).max(dim=1)
tgt_hidden_max, _ = replace_masked(tgt_final_hiddens, tgt_masks, -1e7).max(dim=1)
hiddens = torch.cat([src_hidden_avg, src_hidden_max, tgt_hidden_avg, tgt_hidden_max], dim=1)
outputs = self.proj(hiddens)
return outputs
def _init_esim_weights(module):
"""
Initialise the weights of the ESIM model.
"""
if isinstance(module, nn.Linear):
nn.init.xavier_uniform_(module.weight.data)
if module.bias is not None:
nn.init.constant_(module.bias.data, 0.0)
elif isinstance(module, nn.LSTM):
nn.init.xavier_uniform_(module.weight_ih_l0.data)
nn.init.orthogonal_(module.weight_hh_l0.data)
nn.init.constant_(module.bias_ih_l0.data, 0.0)
nn.init.constant_(module.bias_hh_l0.data, 0.0)
hidden_size = module.bias_hh_l0.data.shape[0] // 4
module.bias_hh_l0.data[hidden_size:(2*hidden_size)] = 1.0
if (module.bidirectional):
nn.init.xavier_uniform_(module.weight_ih_l0_reverse.data)
nn.init.orthogonal_(module.weight_hh_l0_reverse.data)
nn.init.constant_(module.bias_ih_l0_reverse.data, 0.0)
nn.init.constant_(module.bias_hh_l0_reverse.data, 0.0)
module.bias_hh_l0_reverse.data[hidden_size:(2*hidden_size)] = 1.0 | [
"mason.zms@gmail.com"
] | mason.zms@gmail.com |
5803d2bdac854626e3b88d695df22e6ff659d9ca | d094ba0c8a9b1217fbf014aa79a283a49aabe88c | /env/lib/python3.6/site-packages/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py | 61141f65dbfe30615256a06ed5e4e1e5f6fc591c | [
"Apache-2.0"
] | permissive | Raniac/NEURO-LEARN | d9274e0baadd97bb02da54bdfcf6ca091fc1c703 | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | refs/heads/master | 2022-12-25T23:46:54.922237 | 2020-09-06T03:15:14 | 2020-09-06T03:15:14 | 182,013,100 | 9 | 2 | Apache-2.0 | 2022-12-09T21:01:00 | 2019-04-18T03:57:00 | CSS | UTF-8 | Python | false | false | 1,497 | py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..petstandarduptakevaluecomputation import PETStandardUptakeValueComputation
def test_PETStandardUptakeValueComputation_inputs():
input_map = dict(
OutputLabel=dict(argstr='--OutputLabel %s', ),
OutputLabelValue=dict(argstr='--OutputLabelValue %s', ),
SUVMax=dict(argstr='--SUVMax %s', ),
SUVMean=dict(argstr='--SUVMean %s', ),
SUVMin=dict(argstr='--SUVMin %s', ),
args=dict(argstr='%s', ),
color=dict(argstr='--color %s', ),
csvFile=dict(
argstr='--csvFile %s',
hash_files=False,
),
environ=dict(
nohash=True,
usedefault=True,
),
labelMap=dict(argstr='--labelMap %s', ),
petDICOMPath=dict(argstr='--petDICOMPath %s', ),
petVolume=dict(argstr='--petVolume %s', ),
)
inputs = PETStandardUptakeValueComputation.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_PETStandardUptakeValueComputation_outputs():
output_map = dict(csvFile=dict(), )
outputs = PETStandardUptakeValueComputation.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| [
"leibingye@outlook.com"
] | leibingye@outlook.com |
e1a4eb8a1f6dadb3cb47834fa30664dbcd713464 | 1dacbf90eeb384455ab84a8cf63d16e2c9680a90 | /pkgs/bokeh-0.11.1-py27_0/Examples/bokeh/plotting/file/scatter10k.py | 9364f0981280640d2cfe1b1051dcafb5b83feed8 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | permissive | wangyum/Anaconda | ac7229b21815dd92b0bd1c8b7ec4e85c013b8994 | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | refs/heads/master | 2022-10-21T15:14:23.464126 | 2022-10-05T12:10:31 | 2022-10-05T12:10:31 | 76,526,728 | 11 | 10 | Apache-2.0 | 2022-10-05T12:10:32 | 2016-12-15T05:26:12 | Python | UTF-8 | Python | false | false | 380 | py |
import numpy as np
from bokeh.plotting import figure, show, output_file
N = 10000
x = np.random.normal(0, np.pi, N)
y = np.sin(x) + np.random.normal(0, 0.2, N)
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p = figure(tools=TOOLS, webgl=True)
p.circle(x, y, alpha=0.1, nonselection_alpha=0.001)
output_file("scatter10k.html", title="scatter 10k points")
show(p)
| [
"wgyumg@mgail.com"
] | wgyumg@mgail.com |
983e9c1f09c014bc65c9dada48f2289de7ebf4c5 | a62dba78104e3ed76cd680ae9764419e7adb3690 | /Clash/problem3/project/migrations/0025_auto_20190901_2148.py | 686ba97f5ef0f44bfc8e06d07559a59e09f6058c | [] | no_license | DK770/Clash-RC_Credenz2019 | 3c75d020bb182ab832953d801c2eb8493e75bebe | 5be974ac752a72370fc75528f2a6987324c06bf1 | refs/heads/master | 2020-08-01T03:36:32.208556 | 2019-09-24T16:42:25 | 2019-09-24T16:42:25 | 210,848,042 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 401 | py | # Generated by Django 2.2.3 on 2019-09-01 16:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0024_profile_list_cntr'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='visited',
field=models.CharField(default='0', max_length=100),
),
]
| [
"tanmaypardeshi@gmail.com"
] | tanmaypardeshi@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.