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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fa0969ec326cfb3e1f13c24ab9b1f289f1196e41
|
ccb73097804b2bf6070dba519658ab77bd9a044e
|
/leetcode/4_二叉树专题/08_二叉树中的最大路径和.py
|
38691afc21fef7b84f5b8f4dbaadddf093fe627c
|
[] |
no_license
|
ryanatgz/data_structure_and_algorithm
|
4c43d426534381739891819c4c1e25b500f017ae
|
967b0fbb40ae491b552bc3365a481e66324cb6f2
|
refs/heads/master
| 2022-03-13T01:17:58.015457
| 2019-09-23T06:49:20
| 2019-09-23T06:49:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,681
|
py
|
# encoding: utf-8
"""
@project:data_structure_and_algorithm
@author: Jiang Hui
@language:Python 3.7.2 [GCC 7.3.0] :: Anaconda, Inc. on linux
@time: 2019/8/21 16:01
@desc: 第124题
"""
"""
本题思路和上一题有相通之处,每一个节点有一个权重,以该节点为根结点的路径最大值有三种情况:
(1) 从根结点往左子树走,不一定到达左子树的根结点,此时 max_path = root.val + L
(2) 从根结点往右子树走,不一定到达右子树的根结点,此时 max_path = root.val + R
(3) 不走,路径只有该节点一个节点,当L和R都小于0时取这种情况
重点:##
最终取得的最大值,如果小于0,则应当返回0,表示我们在计算最大路径时,不考虑该分支的路径长度。
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
ans = 0
def maxPathSum(self, root: TreeNode) -> int:
self.ans = float('-inf')
self.dfs(root)
return self.ans
def dfs(self, root):
if not root:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
self.ans = max(self.ans, left + right + root.val)
# 原始为:max(0,max(root.val,root.val+left,root.val+right))
# 可以把root.val提出来,得到 max(0,root.val+max(0,left,right))
# 因为left和right是大于等于0的,所以内层的0也可以去掉,max(0,root.val+max(left,right))
return max(0, root.val + max(left, right)) # 如果最大值小于0的话,则返回0,对应我们说明的三种情况
|
[
"942642428@qq.com"
] |
942642428@qq.com
|
8f6f439a66a4f9dd1e2b7499a465f033c7001ddb
|
db8a9a6d2dd4abb762727b2f4570e553ed349c70
|
/opengever/task/response_syncer/comment.py
|
a75a331a2b66d20d65e2b28abc203ae559e24916
|
[] |
no_license
|
braegelno5/opengever.core
|
75e8e31a6f15385c9f7551b9c671fdc75ba358be
|
88d9bec614544de8ca51bf9fcc8cfc0c05449bb5
|
refs/heads/master
| 2020-05-30T11:53:44.003641
| 2017-06-28T15:32:11
| 2017-06-28T15:32:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 832
|
py
|
from opengever.task.response_syncer import BaseResponseSyncerReceiver
from opengever.task.response_syncer import BaseResponseSyncerSender
from opengever.task.response_syncer import ResponseSyncerSenderException
class CommentResponseSyncerSender(BaseResponseSyncerSender):
TARGET_SYNC_VIEW_NAME = '@@sync-task-comment-response'
def raise_sync_exception(self, task, transition, text, **kwargs):
raise ResponseSyncerSenderException(
'Could not add comment on task on remote admin unit {} ({})'.format(
task.admin_unit_id,
task.physical_path))
class CommentResponseSyncerReceiver(BaseResponseSyncerReceiver):
"""This view receives a sync-task-comment-response request from another
client after new comments have been added to a successor or predecessor.
"""
|
[
"e.schmutz@4teamwork.ch"
] |
e.schmutz@4teamwork.ch
|
356abdb44404654a8daade1fdfc7d21c7b2833a7
|
9835b6949fe4c8018de57aee531dedf1509337cc
|
/October_2020/oct_09_Serialize_and_Deserialize_BST.py
|
a0bd3b0f3ad419ec369340ef77c919f66fd8aec5
|
[] |
no_license
|
jcai0o0/My_Leetcode_Solutions
|
f6edea0693d252a99e6507a1724a89763113f8a0
|
3fc909c01c6a345f625c9ab9e0f1584ea5fa8ab4
|
refs/heads/master
| 2023-01-01T04:08:33.929184
| 2020-10-17T02:01:56
| 2020-10-17T02:01:56
| 289,094,613
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 795
|
py
|
class Codec:
def serialize(self, root):
"""
Encodes a tree to a single string.
"""
def postorder(root):
return postorder(root.left) + postorder(root.right) + [root.val] if root else []
return ' '.join(map(str, postorder(root)))
def deserialize(self, data):
"""
Decodes your encoded data to tree.
"""
def helper(lower=float('-inf'), upper=float('inf')):
if not data or data[-1] < lower or data[-1] > upper:
return None
val = data.pop()
root = TreeNode(val)
root.right = helper(val, upper)
root.left = helper(lower, val)
return root
data = [int(x) for x in data.split(' ') if x]
return helper()
|
[
"44845593+jcai0o0@users.noreply.github.com"
] |
44845593+jcai0o0@users.noreply.github.com
|
db09ee14b15a7db7c6252da33646d85dda887742
|
f0af28c525a6eac5dbdaf8ffba23dad1138e5b7e
|
/src/yaml/yaml_prefab.py
|
f8a39bc82164004356c0e20af7862cdf14451b93
|
[
"MIT"
] |
permissive
|
adrianogil/SemanticCode
|
740886756d83e569dcfe1aa30d9f4e5db3f394cb
|
b826b99965f80fc42e654e33ebbebc3aad10f0cd
|
refs/heads/main
| 2021-01-22T18:02:25.065879
| 2020-10-22T20:51:19
| 2020-10-22T20:51:19
| 85,055,494
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,416
|
py
|
import os, sys
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
# print(__path__)
if __path__ not in sys.path:
sys.path.insert(0, __path__)
from yaml_element import YamlElement
class YamlPrefab(YamlElement):
guid = ''
target_id = ''
game_object = None
transform = None
# def __init__(self, gameobject_name, definition_line):
# super(YamlPrefab, self).__init__(gameobject_name, definition_line)
# def print_outline(self):
# object_outline = '<a href="' + str(self.definition_line) + '">Prefab ' + \
# self.gameobject_name + '</a>'
# return object_outline
# Variables used to compoung YamlGameObject
current_go_id = ''
current_go_line = 0
go_instance = None
#Prefab detection
if last_line.find('--- !u!') != -1 and line.find("Prefab") != -1:
current_prefab_id = last_line[14:-1]
current_prefab_line = i
found_prefab = True
if found_prefab and line.find("target: {") != -1:
start_prefab_guid = 0
end_prefab_guid = 0
for l in range(20, line_size):
if line[l-6:l].find("guid: ") != -1:
start_prefab_guid = l
if start_prefab_guid > 0 and line[l] == ",":
end_prefab_guid = l
break
current_prefab_guid = line[start_prefab_guid:end_prefab_guid]
# print("found prefab with guid: " + current_prefab_guid)
if current_prefab_guid in parse_data['yaml']['filenames_by_guid']:
prefab_filename = parse_data['yaml']['filenames_by_guid'][current_prefab_guid]
# outline_data.append(YamlPrefab(prefab_filename, current_prefab_line))
found_prefab = False
current_prefab_line = 0
current_prefab_id = ''
current_prefab_guid = ''
def is_start_of_yaml_section(line):
return line.find("GameObject") != -1
def on_yaml_section_start(line, line_number):
current_go_id = line[10:-1]
current_go_line = line_number
go_instance = None
def parse_line(line, file_data):
if line.find("m_Name") != -1:
gameobject_name = line[9:-1]
file_data['gameobject_name_by_id'][current_go_id] = gameobject_name
file_data['row_by_id'][current_go_id] = current_go_line
go_instance = YamlGameObject(gameobject_name, current_go_line)
go_instance.yaml_id = current_go_id
return file_data
def on_yaml_section_finish():
return go_instance
|
[
"adrianogil.san@gmail.com"
] |
adrianogil.san@gmail.com
|
a66e50dea2e018898bfbd892032ea056afcd0c30
|
f0b741f24ccf8bfe9bd1950425d83b6291d21b10
|
/backend/api/v1beta1/python_http_client/kfp_server_api/models/api_run_storage_state.py
|
1175a3a1e85da38aa0bcbec22b383fc7873b53ff
|
[
"Apache-2.0"
] |
permissive
|
kubeflow/pipelines
|
e678342b8a325559dec0a6e1e484c525fdcc8ce8
|
3fb199658f68e7debf4906d9ce32a9a307e39243
|
refs/heads/master
| 2023-09-04T11:54:56.449867
| 2023-09-01T19:07:33
| 2023-09-01T19:12:27
| 133,100,880
| 3,434
| 1,675
|
Apache-2.0
| 2023-09-14T20:19:06
| 2018-05-12T00:31:47
|
Python
|
UTF-8
|
Python
| false
| false
| 2,894
|
py
|
# coding: utf-8
"""
Kubeflow Pipelines API
This file contains REST API specification for Kubeflow Pipelines. The file is autogenerated from the swagger definition.
Contact: kubeflow-pipelines@google.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kfp_server_api.configuration import Configuration
class ApiRunStorageState(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
allowed enum values
"""
AVAILABLE = "STORAGESTATE_AVAILABLE"
ARCHIVED = "STORAGESTATE_ARCHIVED"
allowable_values = [AVAILABLE, ARCHIVED] # noqa: E501
"""
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.
"""
openapi_types = {
}
attribute_map = {
}
def __init__(self, local_vars_configuration=None): # noqa: E501
"""ApiRunStorageState - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self.discriminator = None
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:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ApiRunStorageState):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ApiRunStorageState):
return True
return self.to_dict() != other.to_dict()
|
[
"noreply@github.com"
] |
kubeflow.noreply@github.com
|
0b6ce0e2925acd8b5d04ee7bf7b8649418802315
|
ca23b411c8a046e98f64b81f6cba9e47783d2584
|
/es_maml/task.py
|
d84fcbc1384da4dc3099407c9c88cf633642152d
|
[
"CC-BY-4.0",
"Apache-2.0"
] |
permissive
|
pdybczak/google-research
|
1fb370a6aa4820a42a5d417a1915687a00613f9c
|
0714e9a5a3934d922c0b9dd017943a8e511eb5bc
|
refs/heads/master
| 2023-03-05T23:16:11.246574
| 2021-01-04T11:30:28
| 2021-01-04T11:30:28
| 326,629,357
| 1
| 0
|
Apache-2.0
| 2021-02-01T12:39:09
| 2021-01-04T09:17:36
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 7,023
|
py
|
# coding=utf-8
# Copyright 2020 The Google Research 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.
# pylint: disable=g-doc-return-or-yield,unused-argument,missing-docstring,g-doc-args,line-too-long,invalid-name,pointless-string-statement
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import numpy as np
class Task(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def state_dimensionality(self):
raise NotImplementedError("Abstract method")
@abc.abstractmethod
def action_dimensionality(self):
raise NotImplementedError("Abstract method")
class ClassificationTask(Task):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def generate_samples(self):
raise NotImplementedError("Abstract method")
class RLTask(Task):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def deterministic_start(self):
raise NotImplementedError("Abstract method")
@abc.abstractmethod
def step(self, action):
raise NotImplementedError("Abstract method")
class SinusodialTask(ClassificationTask):
def __init__(self, task_id, sample_num=100, **kwargs):
self.task_id = task_id
np.random.seed(task_id)
self.amp = np.random.uniform(0.1, 5.0)
self.phase = np.random.uniform(0.0, np.pi)
self.sample_num = sample_num
def generate_samples(self):
xs = np.random.uniform(-5.0, 5.0, self.sample_num)
ys = np.array([self.amp * np.sin(x - self.phase) for x in xs])
return xs, ys
def state_dimensionality(self):
return 1
def action_dimensionality(self):
return 1
class NavigationTask2d(RLTask):
def __init__(self, task_id, **kwargs):
self.task_id = task_id
np.random.seed(task_id)
self.goal_pos = np.random.uniform(low=-1.0, high=1.0, size=2)
self.t = 0
def random_start(self):
self.agent_pos = np.array([0.0, 0.0])
return self.agent_pos
def deterministic_start(self):
self.agent_pos = np.array([0.0, 0.0])
return self.agent_pos
def step(self, action):
clipped_action = np.clip(action, a_min=-0.1, a_max=0.1)
self.agent_pos += clipped_action
self.agent_pos = np.clip(self.agent_pos, a_min=-1.0, a_max=1.0)
reward = -1.0 * np.square(np.linalg.norm(self.agent_pos - self.goal_pos))
done = False
if reward >= -0.01:
done = True
return self.agent_pos, reward, done, None
def reset(self):
self.t = 0
return self.deterministic_start()
def restart(self):
return self.reset()
def state_dimensionality(self):
return 2
def action_dimensionality(self):
return 2
class NavigationTask4corner(RLTask):
def __init__(self, task_id, **kwargs):
self.task_id = task_id
corner_int = task_id % 4
corner_id_to_pos = {
0: np.array([2., 2.]),
1: np.array([-2., 2.]),
2: np.array([-2., -2.]),
3: np.array([2., -2.])
}
self.goal_pos = corner_id_to_pos[corner_int]
self.t = 0
def random_start(self):
self.agent_pos = np.array([0.0, 0.0])
return self.agent_pos
def deterministic_start(self):
self.agent_pos = np.array([0.0, 0.0])
return self.agent_pos
def step(self, action):
clipped_action = np.clip(action, a_min=-0.1, a_max=0.1)
self.agent_pos += clipped_action
self.agent_pos = np.clip(self.agent_pos, a_min=-5.0, a_max=5.0)
sq_dist = np.square(np.linalg.norm(self.agent_pos - self.goal_pos))
alive_penalty = -4.0
# reward is only shown if near the corner
reward = alive_penalty + max(0.0, 4.0 - sq_dist)
return self.agent_pos, reward, False, None
def reset(self):
self.t = 0
return self.deterministic_start()
def restart(self):
return self.reset()
def state_dimensionality(self):
return 2
def action_dimensionality(self):
return 2
class NavigationTaskCombo(RLTask):
def __init__(self, task_id, num_subset_goals=2, num_goals=6, **kwargs):
self.task_id = task_id
self.id_to_goal = {}
for i in range(num_goals):
temp_goal = np.sqrt(8.0) * np.array([
np.cos(2 * np.pi * i / float(num_goals)),
np.sin(2 * np.pi * i / float(num_goals))
])
self.id_to_goal[i] = np.copy(temp_goal)
np.random.seed(task_id)
self.goal_ids = np.random.choice(num_goals, num_subset_goals, replace=False)
self.t = 0.0
self.num_subset_goals = num_subset_goals
self.num_goals = num_goals
self.boundary = 4.0
self.visited_goals = []
def random_start(self):
self.t = 0.0
self.visited_goals = []
self.agent_pos = np.array([0.0, 0.0])
self.final_obs = np.concatenate((self.agent_pos, np.array([self.t])))
# return self.final_obs
return self.agent_pos
def deterministic_start(self):
self.t = 0.0
self.visited_goals = []
self.agent_pos = np.array([0.0, 0.0])
self.final_obs = np.concatenate((self.agent_pos, np.array([self.t])))
# return self.final_obs
return self.agent_pos
def step(self, action):
self.t += 1.0
clipped_action = np.clip(action, a_min=-0.1, a_max=0.1)
self.agent_pos += clipped_action
self.agent_pos = np.clip(self.agent_pos, a_min=-5.0, a_max=5.0)
total_reward = 0.0
for g in range(self.num_goals):
if g not in self.goal_ids:
temp_dist = np.square(
np.linalg.norm(self.agent_pos - self.id_to_goal[g]))
# higher penalties
wrong_goal_penalty = 10000.0 * min(0.0, temp_dist - self.boundary)
total_reward += wrong_goal_penalty
else: # g is a correct goal
if g not in self.visited_goals: # if it hasn't been turned off yet
sq_dist = np.square(
np.linalg.norm(self.agent_pos - self.id_to_goal[g]))
alive_penalty = -1.0 * self.boundary
# reward is only shown if near the corner
total_reward += (alive_penalty + max(0.0, self.boundary - sq_dist))
if sq_dist < 0.01:
self.visited_goals.append(g)
# g is a correct goal and was visited, and this goal is turned off
else:
total_reward += 0.0
self.final_obs = np.concatenate((self.agent_pos, np.array([self.t])))
# return self.final_obs, total_reward, False, None
return self.agent_pos, total_reward, False, None
def reset(self):
self.t = 0.0
self.visited_goals = []
return self.deterministic_start()
def restart(self):
return self.reset()
def state_dimensionality(self):
return 2
def action_dimensionality(self):
return 2
|
[
"copybara-worker@google.com"
] |
copybara-worker@google.com
|
7ad079b58c3e966fe6c64ed4a5fb161abf1e06f0
|
07ec5a0b3ba5e70a9e0fb65172ea6b13ef4115b8
|
/lib/python3.6/site-packages/matplotlib/tests/test_backend_qt5.py
|
5c472c488c0e5f50c53b7fb31b265f732c5bc4ca
|
[] |
no_license
|
cronos91/ML-exercise
|
39c5cd7f94bb90c57450f9a85d40c2f014900ea4
|
3b7afeeb6a7c87384049a9b87cac1fe4c294e415
|
refs/heads/master
| 2021-05-09T22:02:55.131977
| 2017-12-14T13:50:44
| 2017-12-14T13:50:44
| 118,736,043
| 0
| 0
| null | 2018-01-24T08:30:23
| 2018-01-24T08:30:22
| null |
UTF-8
|
Python
| false
| false
| 129
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:3a3557f8e3099b0a26d5723cd3f215b246a4b65b74b89afe5e5b2c08ef15cb85
size 5103
|
[
"seokinj@jangseog-in-ui-MacBook-Pro.local"
] |
seokinj@jangseog-in-ui-MacBook-Pro.local
|
8fff01e105f0aa6711b1988eac61df3ec5a04400
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_142/418.py
|
e273a5f2ab13e3c6917814dd6401043855e717f1
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,693
|
py
|
import math
#YOLOSWAG
def getRepeats(string):
last = ""
repeats = []
cur = -1
for c in string:
if c == last:
repeats[cur][1] += 1
else:
repeats.append([c,1])
cur += 1
last = c
return repeats
def getMoves(checkLengths, repeats):
moves = 0
for x in range(0,checkLengths):
bestMove = -1
for a in repeats:
checkMoves = 0
charCompare = a[x][0]
for b in repeats:
if b[x][0] == charCompare:
checkMoves += abs(a[x][1] - b[x][1])
else:
return -1
if bestMove == -1 or bestMove > checkMoves:
bestMove = checkMoves
moves += bestMove
return moves
inputs = open("in.txt").readlines()
output = open('out.txt', 'w')
t = int(inputs[0])
r = 1
for i in range(1, t + 1):
#r = (i - 1) * 3 + 1
n = int(inputs[r])
r += 1
repeats = []
for j in range(0, n):
repeats.append(getRepeats(inputs[r].rstrip()))
r+=1
moves = 0
checkLengths = -1
for re in repeats:
if checkLengths == -1:
checkLengths = len(re)
if len(re) != checkLengths:
checkLengths = -1
break
if checkLengths == -1:
answer = "Case #%d: Fegla Won\n"%(i)
else:
moves = getMoves(checkLengths, repeats)
if(moves == -1):
answer = "Case #%d: Fegla Won\n"%(i)
else:
answer = "Case #%d: %d\n"%(i,moves)
print(answer)
output.write(answer)
output.close()
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
d8564359bfe77459d7cad265911cb5ead91e4c39
|
c61c9bedba1968bfaf571ac3996b696fc35890a6
|
/Chapter3/3-4.py
|
11467a4eb3c9f06b6bdd059979b31d2f5dca20e8
|
[] |
no_license
|
ArunRamachandran/ThinkPython-Solutions
|
497b3dbdeba1c64924fe1d9aa24204a9ca552c5b
|
1a0872efd169e5d39b25134960168e3f09ffdc99
|
refs/heads/master
| 2020-04-01T10:23:20.255132
| 2014-11-07T17:04:52
| 2014-11-07T17:04:52
| 25,806,318
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,360
|
py
|
# A fn. object is a value you can assign to a variable or pass as an argument
# 'do_twice' is a fn that take a fn objct as an argument and calls it twice
#
def print_spam():
print "spam"
def do_twice(f):
f()
f()
do_twice(print_spam)
# 2.Modify do_twice so that it takes two arguments, a fn objct and a value,
# and calls the fn twice, passing the value as an argument.
word = raw_input("Enter a word..\n")
def print_spam(word):
print word
def do_twice(f,word):
f(word)
f(word)
do_twice(print_spam,word)
#3. Write a grn. version of print_spam, called print_twice, that takes a
# a string as a paramtere and print it twice.
word = raw_input("Enter a string\n");
def print_twice(word):
print word
print word
print_twice(word)
#4. Use the modified version of do_twice to call print_twice, passing 'spam'
# as an argument.
print "\n"
def do_twice(word):
print_twice(word)
print_twice(word)
def print_twice(word):
print word
s = "hello"
do_twice(s)
# 5.Define a new fn. called do_four(), that takes a fn object and a value
# and calls the fn four times, passing the values as a parameter . There
# should be only two statements in the body of this fn, not four
obj = raw_input("Give a string .\n")
def f(obj):
print obj
def do_twice(f,obj):
f(obj)
f(obj)
def do_four(f,obj):
do_twice(f,obj)
do_twice(f,obj)
do_four(f,obj)
|
[
"arunkramachandran92@gmail.com"
] |
arunkramachandran92@gmail.com
|
1405f80452859a40af6dcef9d1d18726e19f09e1
|
300eb733976a31d73a68ddf20d986ba6aceb6ef5
|
/ewoexit2708/routes.py
|
1f90724f91805ba14797141cffb48edcf96512fa
|
[
"MIT"
] |
permissive
|
ajthummar/jesse_strategies
|
f168ae455970bd91845807dd7b0346e77471db09
|
5d23b44f97006e6cecf8519a3951accbfde09fc7
|
refs/heads/master
| 2023-08-12T21:35:22.458840
| 2021-10-18T13:26:12
| 2021-10-18T13:26:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,595
|
py
|
# Some pairs have been disabled due to a lack of candle data.
# You can restore them to test within recent months.
routes = [
('FTX Futures', 'ETC-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
# ('FTX Futures', 'LUNA-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'FIL-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
# ('FTX Futures', 'FTM-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'ETH-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'DOT-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'XTZ-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'BNB-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'NEO-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'SOL-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'LINK-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'XLM-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'MATIC-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'TRX-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'BTC-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'AAVE-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'ALGO-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'ADA-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'ATOM-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'XRP-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'LTC-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
# ('FTX Futures', '1INCH-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
('FTX Futures', 'BCH-USD', '15m', 'ewoexit2708', '86lZ6^AX3'),
]
extra_candles = [
('FTX Futures', 'ETC-USD', '1h'),
# ('FTX Futures', 'LUNA-USD', '1h'),
('FTX Futures', 'FIL-USD', '1h'),
# ('FTX Futures', 'FTM-USD', '1h'),
('FTX Futures', 'ETH-USD', '1h'),
('FTX Futures', 'DOT-USD', '1h'),
('FTX Futures', 'XTZ-USD', '1h'),
('FTX Futures', 'BNB-USD', '1h'),
('FTX Futures', 'NEO-USD', '1h'),
('FTX Futures', 'SOL-USD', '1h'),
('FTX Futures', 'LINK-USD', '1h'),
('FTX Futures', 'XLM-USD', '1h'),
('FTX Futures', 'MATIC-USD', '1h'),
('FTX Futures', 'TRX-USD', '1h'),
('FTX Futures', 'BTC-USD', '1h'),
('FTX Futures', 'AAVE-USD', '1h'),
('FTX Futures', 'ALGO-USD', '1h'),
('FTX Futures', 'ADA-USD', '1h'),
('FTX Futures', 'ATOM-USD', '1h'),
('FTX Futures', 'XRP-USD', '1h'),
('FTX Futures', 'LTC-USD', '1h'),
# ('FTX Futures', '1INCH-USD', '1h'),
('FTX Futures', 'BCH-USD', '1h'),
]
|
[
"yunusseyhandede@gmail.com"
] |
yunusseyhandede@gmail.com
|
4805be7815446bf43c70387ee55ae67dd9eb421b
|
cffe83637b3965ad27f5a679e187bfaf46afa690
|
/.stversions/cookbook/magic_browser/cookbook/cookbook/.stversions/blender/menus/utilities/DeleteDefaults~20201019-122406~20210212-114808.py
|
0e6df3d29eb9c86b1351c57ea11ff99386143025
|
[] |
no_license
|
gmolinart/LC_MASTER
|
da768a592821fe4dc55bdf693291df3409c3f035
|
2f17eaf5c4c7f70be0c0b5976b479002da4e7d52
|
refs/heads/master
| 2023-04-29T07:38:24.653457
| 2021-05-17T18:42:34
| 2021-05-17T18:42:34
| 368,287,070
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 749
|
py
|
import bpy
# from cgl.plugins.blender import lumbermill as lm
class DeleteDefaults(bpy.types.Operator):
"""
This class is required to register a button in blender.
"""
bl_idname = 'object.delete_defaults'
bl_label = 'Delete Defaults'
def execute(self, context):
run()
return {'FINISHED'}
def run():
"""
This run statement is what's executed when your button is pressed in blender.
:return:
"""
for object in bpy.data.objects:
if 'DEFAULT' in object.name:
bpy.data.objects.remove(object)
for collection in bpy.data.collections:
if 'DEFAULT' in collection.name:
bpy.data.collections.remove(collection)
print('Defaults deleted')
|
[
"gmolinart@gmail.com"
] |
gmolinart@gmail.com
|
8a41096df1f6fffbe6e574d02dcbbe0cb1336a33
|
71acb7214efd91c0d327f6d8958e1798eadb4401
|
/locations/spiders/fast_stop_us.py
|
52aba2f44fcbdd93fc49d2c9ccbf9017896e264b
|
[
"CC0-1.0",
"MIT"
] |
permissive
|
alltheplaces/alltheplaces
|
21b9f8b4ace1352e52ae7b8f8825a930d2cb033e
|
1bcbb55cfcf06f2c714465570711f6e83f205c22
|
refs/heads/master
| 2023-08-30T19:45:35.098658
| 2023-08-30T17:51:54
| 2023-08-30T17:51:54
| 61,166,935
| 453
| 176
|
NOASSERTION
| 2023-09-14T17:16:40
| 2016-06-15T01:09:18
|
Python
|
UTF-8
|
Python
| false
| false
| 1,286
|
py
|
import re
from urllib.parse import urljoin
import chompjs
from scrapy import Spider
from locations.linked_data_parser import LinkedDataParser
from locations.microdata_parser import convert_item, get_object
class FastStopUSSpider(Spider):
name = "fast_stop_us"
item_attributes = {"brand": "FAST STOP", "brand_wikidata": "Q116734101"}
start_urls = ["https://www.efaststop.com/store-locator"]
def parse(self, response, **kwargs):
coords_map = {}
if m := re.search(r"init_map\(.+, (\[.+\]), (\[.+\])\);", response.text):
coords, popup = m.groups()
lat_lon = re.compile(r"LatLng\((-?\d+\.\d+), (-?\d+\.\d+)\)")
for location in chompjs.parse_js_object(coords):
if ll := re.search(lat_lon, location["position"]):
coords_map[location["title"]] = ll.groups()
for location in response.xpath('//section[@itemtype="http://schema.org/GasStation"]'):
ld = convert_item(get_object(location.root))
item = LinkedDataParser.parse_ld(ld)
item["ref"] = item["website"] = urljoin(response.url, location.xpath(".//a/@href").get())
if ll := coords_map.get(item["name"]):
item["lat"], item["lon"] = ll
yield item
|
[
"noreply@github.com"
] |
alltheplaces.noreply@github.com
|
2ba1d13a4758708ce06af4763c6bd9aad52b1632
|
39bcdb8ab7262e9a09556540d677cac162757f74
|
/items/models.py
|
e027feb7741490262fde716b9d8de4661da2957b
|
[] |
no_license
|
NiiColeman/mywarehouse
|
c08c1aee3a4d8a5dd17642358a14e2b122d9cb14
|
d9b2fae9ab5d164a13b208042d8e3366e3b81b79
|
refs/heads/master
| 2023-04-06T22:29:52.771226
| 2021-04-16T23:19:10
| 2021-04-16T23:19:10
| 224,866,298
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,424
|
py
|
from django.db import models
# from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin)
# Create your models here.
from departments.models import Department
from django.shortcuts import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
class UserManager(BaseUserManager):
def create_user(
self, username, email, first_name, last_name, password=None,
commit=True):
"""
Creates and saves a User with the given email, first name, last name
and password.
"""
if not username:
raise ValueError(_('Users must have username'))
if not email:
raise ValueError(_('Users must have an email address'))
if not first_name:
raise ValueError(_('Users must have a first name'))
if not last_name:
raise ValueError(_('Users must have a last name'))
user = self.model(
username=username,
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
)
user.set_password(password)
if commit:
user.save(using=self._db)
return user
def create_superuser(self, username, email, first_name, last_name, password):
"""
Creates and saves a superuser with the given email, first name,
last name and password.
"""
user = self.create_user(
username=username,
email=email,
password=password,
first_name=first_name,
last_name=last_name,
commit=False,
)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=50, unique=True, null=True)
email = models.EmailField(
verbose_name=_('email address'), max_length=255, unique=True
)
# password field supplied by AbstractBaseUser
# last_login field supplied by AbstractBaseUser
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=150, blank=True)
phone_number = models.CharField(max_length=50, null=True, blank=True)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_(
'Designates whether the user can log into this admin site.'
),
)
# is_superuser field provided by PermissionsMixin
# groups field provided by PermissionsMixin
# user_permissions field provided by PermissionsMixin
date_joined = models.DateTimeField(
_('date joined'), default=timezone.now
)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'username']
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def __str__(self):
return '{} <{}>'.format(self.get_full_name(), self.email)
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
def get_absolute_url(self):
return reverse("user_detail", kwargs={"pk": self.pk})
class Category(models.Model):
name = models.CharField(max_length=250)
# TODO: Define fields here
class Meta:
"""Meta definition for Category."""
verbose_name = 'Category'
verbose_name_plural = 'Categories'
def __str__(self):
"""Unicode representation of Category."""
return self.name
def get_absolute_url(self):
return reverse("items:category_detail", kwargs={"pk": self.pk})
def get_update_url(self):
return reverse("items:update_category", kwargs={"pk": self.pk})
def get_delete_url(self):
return reverse("items:category_delete", kwargs={"pk": self.pk})
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=250, unique=True)
image = models.ImageField(upload_to='images/', null=True, blank=True)
category = models.ForeignKey(
Category, related_name='categories', on_delete=models.CASCADE)
stock_on_hand = models.IntegerField(default=0)
expiry_date = models.DateTimeField(auto_now=False)
shelf_number = models.CharField(max_length=50)
description = models.CharField(max_length=450)
perishable = models.BooleanField(default=False)
expired = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now=True)
shelved = models.BooleanField(default=False)
# TODO: Define fields here
class Meta:
"""Meta definition for Item."""
verbose_name = 'Item'
verbose_name_plural = 'Items'
def __str__(self):
"""Unicode representation of Item."""
return self.name
def get_absolute_url(self):
return reverse("items:item_detail", kwargs={"pk": self.pk})
def get_update_url(self):
return reverse("items:item_update", kwargs={"pk": self.pk})
def get_delete_url(self):
return reverse("items:item_delete", kwargs={"pk": self.pk})
class ItemSetting(models.Model):
CHOICES = (
(30, ("1 Months")),
(60, ("2 Months")),
(90, ("3 Months")),
(120, ("4 Months"))
)
name = models.CharField(default="Item Settings", max_length=50)
low_stock_limit = models.IntegerField(default=10)
item_expiration_limit = models.IntegerField(choices=CHOICES, default=30)
class Meta:
verbose_name = ("Item Setting")
verbose_name_plural = ("Item Settings")
def __str__(self):
return self.name
class ShelfItem(models.Model):
"""Model definition for ShelfItem."""
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=0)
date_add = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
shelf = models.CharField(max_length=50)
# TODO: Define fields here
class Meta:
"""Meta definition for ShelfItem."""
verbose_name = 'Shelf Item'
verbose_name_plural = 'Shelf Items'
def __str__(self):
"""Unicode representation of ShelfItem."""
return self.item.name
def get_absolute_url(self):
return reverse("items:shelf_detail", kwargs={"pk": self.pk})
def get_update_url(self):
return reverse("items:shelf_update", kwargs={"pk": self.pk})
def get_delete_url(self):
return reverse("items:shelf_delete", kwargs={"pk": self.pk})
# TODO: Define custom methods here
|
[
"nii.cole@outlook.com"
] |
nii.cole@outlook.com
|
2a193ad76eebcee16956107da08f264bb2ddbdf3
|
78d17c3a7332be85078b513eee02f7ae4f18b3db
|
/lintcode/unique_binary_search_treesII.py
|
5d39703efaeeda53c679c19120045959b595db4a
|
[] |
no_license
|
yuhanlyu/coding-challenge
|
c28f6e26acedf41cef85519aea93e554b43c7e8e
|
9ff860c38751f5f80dfb177aa0d1f250692c0500
|
refs/heads/master
| 2021-01-22T21:59:27.278815
| 2017-11-26T07:34:04
| 2017-11-26T07:34:04
| 85,498,747
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 807
|
py
|
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
# @paramn n: An integer
# @return: A list of root
def generateTrees(self, n):
if n == 0: return [None]
DP = [[[None] for _ in xrange(n + 2) ] for _ in xrange(n + 2)]
for k in xrange(n):
for i in xrange(1, n - k + 1):
DP[i][i + k] = []
for root in xrange(i, i + k + 1):
for left in DP[i][root - 1]:
for right in DP[root + 1][i + k]:
node = TreeNode(root)
node.left, node.right = left, right
DP[i][i + k].append(node)
return DP[1][n]
|
[
"yuhanlyu@gmail.com"
] |
yuhanlyu@gmail.com
|
1139ed09672ed55f980751bb9577805830e7ef9e
|
a9ef3be91fe746b44b8a4e2fcbd92b79ddc50305
|
/04day/4-文件备份.py
|
b9e012de78ed01c6cdd0a87069d210d7ad85e780
|
[] |
no_license
|
ittoyou/2-1807
|
a7718791bbc4095b6ef07003e6a2ef0b07fcd6de
|
82bf09f57ccb86b88abfd4a60bca51c5cf757065
|
refs/heads/master
| 2020-03-25T10:29:53.324428
| 2018-09-06T01:14:43
| 2018-09-06T01:14:43
| 143,694,904
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 373
|
py
|
class Tool():
def beifen(self):
name = input('请输入要备份的文件名字(加上后缀名)')
f = open(name,'r')
position = name.rfind('.')
newname = name[:position]+'备份'+name[position:]
f1 = open(newname,'w')
while True:
content = f.read(1024)
if len(content) == 0:
break
f1.write(content)
f.close()
f1.close()
t = Tool()
t.beifen()
|
[
"429013601@qq.com"
] |
429013601@qq.com
|
ae7367178e0e60131384ac607edca90ef9c8223b
|
3a01d6f6e9f7db7428ae5dc286d6bc267c4ca13e
|
/unittests/pytests/meshio/TestDataWriterVTK.py
|
c334c27a8c2de840f1b352498638889d757e5a00
|
[
"MIT"
] |
permissive
|
youngsolar/pylith
|
1ee9f03c2b01560706b44b4ccae99c3fb6b9fdf4
|
62c07b91fa7581641c7b2a0f658bde288fa003de
|
refs/heads/master
| 2020-12-26T04:04:21.884785
| 2014-10-06T21:42:42
| 2014-10-06T21:42:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,454
|
py
|
#!/usr/bin/env python
#
# ======================================================================
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2014 University of California, Davis
#
# See COPYING for license information.
#
# ======================================================================
#
## @file unittests/pytests/meshio/TestDataWriterVTK.py
## @brief Unit testing of Python DataWriterVTK object.
import unittest
from pylith.meshio.DataWriterVTK import DataWriterVTK
# ----------------------------------------------------------------------
class TestDataWriterVTK(unittest.TestCase):
"""
Unit testing of Python DataWriterVTK object.
"""
def test_constructor(self):
"""
Test constructor.
"""
filter = DataWriterVTK()
filter._configure()
return
def test_initialize(self):
"""
Test constructor.
"""
filter = DataWriterVTK()
filter._configure()
from spatialdata.units.Nondimensional import Nondimensional
normalizer = Nondimensional()
filter.initialize(normalizer)
return
def test_factory(self):
"""
Test factory method.
"""
from pylith.meshio.DataWriterVTK import data_writer
filter = data_writer()
return
# End of file
|
[
"baagaard@usgs.gov"
] |
baagaard@usgs.gov
|
f66d8b1db0ed02a43f7fd494ec762de4b5aa8153
|
4f4f2b808729b4820a4cf11d0dff23951e2c9b71
|
/plugins/m/__init__.py
|
035a9c98dd10a81960ac8d14852bcfa8ef3efcd3
|
[
"MIT"
] |
permissive
|
MikePopoloski/m.css
|
b3c32b1c4bf40881462933966b987d4147c63b49
|
a93186270f4707e61b77e54361111e126aa54187
|
refs/heads/master
| 2023-06-29T10:56:29.764245
| 2023-06-11T14:51:55
| 2023-06-11T14:51:55
| 235,468,011
| 0
| 0
|
MIT
| 2020-01-22T00:23:06
| 2020-01-22T00:23:06
| null |
UTF-8
|
Python
| false
| false
| 1,313
|
py
|
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019, 2020, 2021, 2022
# Vladimír Vondruš <mosra@centrum.cz>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# This file is here only to make python unittest work, it's not needed
# otherwise
|
[
"mosra@centrum.cz"
] |
mosra@centrum.cz
|
b360d090334b535299fa0d74c81c35df3d4ae0ed
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2583/60643/284273.py
|
485f61abe4ae07954935acfa01760795366b68b6
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011
| 2020-07-28T16:21:24
| 2020-07-28T16:21:24
| 259,576,640
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,791
|
py
|
#最大公因数
def GCD(a,b):
while b>0:
temp=a%b
a=b
b=temp
return a#是a啊不是b
#最小公倍数
def MCM(a,b):
return a*b/GCD(a,b)
#二分搜索
def binSearch(low,high,n,a,b,c):
if low>=high:
return low
else:
middle=(low+high)>>1#相当于模200.
#独立的丑数个数为,当前数分别除以a、b、c,相加求和,减去当前数除以a、b、c两两间最小公倍数的和,再加上当前数除以 a、b、c三者的最小公倍数 就等于[low,当前数]之间的丑数因子!的数量
temp=int(middle//a+middle//b+middle//c-middle//MCM(a,b)-middle//MCM(b,c)-middle//MCM(a,c)+middle//MCM(MCM(a,b),c))#temp是low边界到当前位置之间丑数因子的个数
if temp==n:
return middle
elif temp<n:
return binSearch(middle+1,high,n,a,b,c)#middle+1!!
else:
return binSearch(low,middle-1,n,a,b,c)#middle-1!!!
def nthUglyNum(n:int,a:int,b:int,c:int):
low=min(a,b,c)
high=low*n
roughRange=binSearch(low,high,n,a,b,c)
res=roughRange-min(roughRange%a,roughRange%b,roughRange%c)
return res
#比如第n个丑数是X,那么[X,X + min(a,b,c))这个半开区间内的所有数都同时包含n个丑数因子,
# 我们通过二分法得到的答案也随机分布于这个区间中。而实际上我们只需要得到该区间的左端即可。
# 处理方法很简单:假设我们得到的临时答案是K(K∈[X,X + min(a,b,c))),那么K - min(K%a,K%b,K%c) = X.
# 也就是只需要把临时答案减去其与a、b、c三者中取余的最小值即可!
if __name__=="__main__":
n=int(input())
a=int(input())
b=int(input())
c=int(input())
ans=nthUglyNum(n,a,b,c)
print(ans)
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
d93b9fba81f15e2d48d1303a7d79ec25511d27a7
|
1e76baee819a897eb45a50d907575723c2329fda
|
/math/0x00-linear_algebra/10-ill_use_my_scale.py
|
43774c9ccc049db8379fb0921fa8d846b6703d57
|
[] |
no_license
|
paisap/holbertonschool-machine_learning
|
ce1942d3c5e8753104a40cfc4b9fc0953628a3dc
|
bdb84f37f44e52a073887a8fee306092165c3329
|
refs/heads/main
| 2023-08-31T17:32:46.337737
| 2021-10-04T03:30:53
| 2021-10-04T03:30:53
| 317,323,784
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 178
|
py
|
#!/usr/bin/env python3
""" hat calculates the shape of a numpy.ndarray """
def np_shape(matrix):
""" hat calculates the shape of a numpy.ndarray"""
return matrix.shape
|
[
"santiagoaldana58@gmail.com"
] |
santiagoaldana58@gmail.com
|
3f1ae58368ea03f06b92ab49cd208c15071bf614
|
db415f2470905729ff6301ed9dfd4a21b916f616
|
/setup.py
|
3b91f8ba50005fb166b43c935a1a7ecea9b1c8e0
|
[] |
no_license
|
biobakery/anpan-legacy
|
9786aae0cf114909882508c21193fe28bd0fbf37
|
e9171321bd34dc43820ebce729399098368418f3
|
refs/heads/master
| 2022-08-11T08:35:29.323448
| 2015-03-03T15:49:26
| 2015-03-03T15:49:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 926
|
py
|
from setuptools import setup, find_packages
setup(
name='anpan',
version='0.0.1',
description='AnADAMA Put on A Network',
packages=find_packages(exclude=['ez_setup', 'tests', 'tests.*']),
zip_safe=False,
install_requires=[
'nose>=1.3.0',
'python-dateutil>=2.2',
'bottle>=0.10',
# doit, six, networkx, etc should come with anadama
'anadama',
'anadama_workflows',
],
dependency_links=[
'git+https://bitbucket.org/biobakery/anadama.git@master#egg=anadama-0.0.1',
'git+https://bitbucket.org/biobakery/anadama_workflows.git@master#egg=anadama_workflows-0.0.1',
],
classifiers=[
"Development Status :: 2 - Pre-Alpha"
],
entry_points= {
'console_scripts': [
'anpan-email-validate = anpan.email.cli:main',
'anpan = anpan.automated.cli:main',
],
}
)
|
[
"vagrant@localhost.localdomain"
] |
vagrant@localhost.localdomain
|
e7a1d1ac8906987075dbea0b976e57dd7b9d6898
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2714/60705/295697.py
|
72590979ac543842bbbb9cc5637ef64f4f8e8d60
|
[] |
no_license
|
AdamZhouSE/pythonHomework
|
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
|
ffc5606817a666aa6241cfab27364326f5c066ff
|
refs/heads/master
| 2022-11-24T08:05:22.122011
| 2020-07-28T16:21:24
| 2020-07-28T16:21:24
| 259,576,640
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,083
|
py
|
def judge(word1, word2):
if len(word2) != len(word1) + 1:
return False
dic1 = {}
dic2 = {}
for char in word1:
dic1.setdefault(char, 0)
dic1[char] += 1
for char in word2:
dic2.setdefault(char, 0)
dic2[char] += 1
key1 = list(dic1.keys())
key2 = list(dic2.keys())
for k in key1:
if k not in key2:
return False
if dic1[k] > dic2[k]:
return False
return True
if __name__ == '__main__':
words = []
while True:
try:
words.append(input())
except EOFError:
break
words.sort(key=lambda k: len(k))
print(words)
ans = []
for i in range(0, len(words)):
temp_ans = [words[i]]
j = i+1
while j < len(words):
if judge(temp_ans[-1], words[j]):
temp_ans.append(words[j])
if len(temp_ans) > len(ans):
ans = temp_ans
temp_ans.remove(words[j])
j += 1
print(len(ans))
for a in ans:
print(a)
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
f5cc3606a67a533e7c20254c5a9b9fe5cc417556
|
408099135939ccdb7fc52f110792ce651fb6b00a
|
/test/unit/tools/test_yacc.py
|
2f91ecacf66b15203e3b2c0950bf6f4db372f818
|
[
"BSD-3-Clause"
] |
permissive
|
thomasrockhu/bfg9000
|
757271db484ddcd06e8b391c3b8818882857f66e
|
1cd1226eab9bed2fc2ec6acccf7864fdcf2ed31a
|
refs/heads/master
| 2022-11-29T00:07:15.914649
| 2020-07-24T21:12:38
| 2020-07-24T21:12:38
| 282,257,111
| 0
| 0
|
BSD-3-Clause
| 2020-07-24T15:37:41
| 2020-07-24T15:37:40
| null |
UTF-8
|
Python
| false
| false
| 3,616
|
py
|
from .. import *
from bfg9000 import options as opts
from bfg9000.file_types import *
from bfg9000.languages import Languages
from bfg9000.path import Path, Root
from bfg9000.tools.yacc import YaccBuilder
known_langs = Languages()
with known_langs.make('yacc') as x:
x.vars(compiler='YACC', flags='YFLAGS')
class TestYaccBuilder(CrossPlatformTestCase):
def __init__(self, *args, **kwargs):
super().__init__(clear_variables=True, *args, **kwargs)
def setUp(self):
self.yacc = YaccBuilder(self.env, known_langs['yacc'], ['yacc'],
'version')
self.compiler = self.yacc.transpiler
def test_properties(self):
self.assertEqual(self.compiler.num_outputs, 1)
self.assertEqual(self.compiler.deps_flavor, None)
def test_call(self):
self.assertEqual(self.compiler('in', 'out'),
[self.compiler, 'in', '-o', 'out'])
self.assertEqual(self.compiler('in', 'out', ['flags']),
[self.compiler, 'flags', 'in', '-o', 'out'])
def test_default_name(self):
src = SourceFile(Path('file.l', Root.srcdir), 'yacc')
self.assertEqual(self.compiler.default_name(src, None),
['file.tab.c', 'file.tab.h'])
self.assertEqual(self.compiler.default_name(src, AttrDict(
user_options=opts.option_list(opts.lang('c++'))
)), ['file.tab.cpp', 'file.tab.hpp'])
with self.assertRaises(ValueError):
self.compiler.default_name(src, AttrDict(
user_options=opts.option_list(opts.lang('java'))
))
def test_output_file(self):
src = SourceFile(Path('file.tab.c'), 'c')
hdr = HeaderFile(Path('file.tab.h'), 'c')
self.assertEqual(self.compiler.output_file('file.tab.c', None), src)
self.assertEqual(self.compiler.output_file(
['file.tab.c', 'file.tab.h'], None
), [src, hdr])
src = SourceFile(Path('file.tab.cpp'), 'c++')
hdr = HeaderFile(Path('file.tab.hpp'), 'c++')
context = AttrDict(user_options=opts.option_list(opts.lang('c++')))
self.assertEqual(self.compiler.output_file('file.tab.cpp', context),
src)
self.assertEqual(self.compiler.output_file(
['file.tab.cpp', 'file.tab.hpp'], context
), [src, hdr])
with self.assertRaises(ValueError):
self.compiler.output_file(['file.tab.c', 'file.tab.h', 'extra'],
None)
def test_flags_empty(self):
self.assertEqual(self.compiler.flags(opts.option_list()), [])
def test_flags_define(self):
self.assertEqual(self.compiler.flags(opts.option_list(
opts.define('NAME')
)), ['-DNAME'])
self.assertEqual(self.compiler.flags(opts.option_list(
opts.define('NAME', 'value')
)), ['-DNAME=value'])
def test_flags_warning(self):
self.assertEqual(self.compiler.flags(opts.option_list(
opts.warning('disable')
)), ['-w'])
with self.assertRaises(ValueError):
self.compiler.flags(opts.option_list(opts.warning('all')))
def test_flags_lang(self):
self.assertEqual(self.compiler.flags(opts.option_list(
opts.lang('c++')
)), ['--language=c++'])
def test_flags_string(self):
self.assertEqual(self.compiler.flags(opts.option_list('-i')), ['-i'])
def test_flags_invalid(self):
with self.assertRaises(TypeError):
self.compiler.flags(opts.option_list(123))
|
[
"itsjimporter@gmail.com"
] |
itsjimporter@gmail.com
|
3ae926ab8843eec0a48e5311cb84ca5ea56307a6
|
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
|
/cases/pa2/sample/class_def_methods-90.py
|
3dcbb59597615ba1a047cbb30d4e3c1e003f222d
|
[] |
no_license
|
Virtlink/ccbench-chocopy
|
c3f7f6af6349aff6503196f727ef89f210a1eac8
|
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
|
refs/heads/main
| 2023-04-07T15:07:12.464038
| 2022-02-03T15:42:39
| 2022-02-03T15:42:39
| 451,969,776
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 343
|
py
|
class A(object):
x:int = 1
def get_A(self: "A") -> int:
return self.x
class B(A):
def __init__(self: "B"):
pass
class C(B):
z:bool = True
def set_A(self: "C", val: int) -> object:
$Statement
a:A = None
b:B = None
c:C = None
a = A()
b = B()
c = C()
b.x = a.get_A()
a.x = b.get_A()
c.set_A(0)
|
[
"647530+Virtlink@users.noreply.github.com"
] |
647530+Virtlink@users.noreply.github.com
|
fbdbec2ed50db76f9752144a6a1158b6cdf6b24d
|
9184e230f8b212e8f686a466c84ecc89abe375d1
|
/histogrammode/tests/reduction/histCompat/generateTestInstrument.py
|
653265a59f8187ce84e4fb2669cbee2008cb6252
|
[] |
no_license
|
danse-inelastic/DrChops
|
75b793d806e6351dde847f1d92ab6eebb1ef24d2
|
7ba4ce07a5a4645942192b4b81f7afcae505db90
|
refs/heads/master
| 2022-04-26T17:37:41.666851
| 2015-05-02T23:21:13
| 2015-05-02T23:21:13
| 34,094,584
| 0
| 1
| null | 2020-09-10T01:50:10
| 2015-04-17T03:30:52
|
Python
|
UTF-8
|
Python
| false
| false
| 2,597
|
py
|
#!/usr/bin/env python
# Timothy M. Kelley Copyright (c) 2005 All rights reserved
# Jiao Lin Copyright (c) 2007 All rights reserved
def generate():
"""generate an instrument graph appropriate for testing"""
from instrument.elements import instrument, detectorArray, detectorPack, \
detector, moderator, monitor
from instrument.geometers import ARCSGeometer
test = Instrument.Instrument("Test")
geometer = ARCSGeometer.Geometer()
geometer.register( test, [0,0,0], [0,0,0])
detArrayID = test.getUniqueID()
detArray = DetectorArray.DetectorArray( detArrayID, test.guid())
test.addDetectorArray( detArray)
# make a detector pack
dpackGuid = test.getUniqueID()
dpack = DetectorPack.DetectorPack( dpackGuid, test.guid())
detArray.addElement( dpack)
geometer.register( dpack, [1.,1.,1.], [1.,1.,1.])
dpack.setAttribute('name', 'detPack1')
# put an LPSD in the pack
lpsd1id = test.getUniqueID()
detectorID = detArray.getLongDetectorID()
lpsd1 = LPSD.LPSD( lpsd1id, dpackGuid, detectorID)
dpack.addElement( lpsd1)
geometer.register( lpsd1, [2.,90.0,2.0], [2.,2.,2.])
lpsd1.setAttribute('name', 'LPSD1')
# add some pixels to the lpsd
for i in range(5):
pixid = test.getUniqueID()
pixel = LPSDPixel.Pixel( pixid, detectorID, i, 0.01, 200.0, 12.7)
lpsd1.addElement( pixel)
geometer.register( pixel, [i+3.0,i+3.0,i+3.0], [i+3.0,i+3.0,i+3.0])
pixel.setAttribute( 'name', 'pixel%s' % i)
# add a monitor
monid = test.getUniqueID()
monitor = Monitor.Monitor( monid, test.guid(), 'nifty', 20.0, 100.0, 100.0,
'testMonitor')
geometer.register( monitor, [8.,8.,8.], [8.,8.,8.])
test.addElement( monitor)
# add a moderator
modid = test.getUniqueID()
moderator = Moderator.Moderator( modid, test.guid(), 100.0, 100.0, 100.0,
'testModerator')
# position in spherical coords (x=-14.0, y=0.0, z = 0.0)
modPosition = [14000.0, 90.0, 180.0]
modOrientation = [0.0, 0.0, 0.0]
geometer.register( moderator, modPosition, modOrientation)
test.addModerator( moderator)
return test, geometer
if __name__ == '__main__':
import journal
journal.debug("instrument.elements").activate()
instrument, geometer = generate()
from InstrumentPrinter import Printer
printer = Printer()
printer.render( instrument, geometer)
# version
__id__ = "$Id: generateTestInstrument.py 1431 2007-11-03 20:36:41Z linjiao $"
# End of file
|
[
"linjiao@caltech.edu"
] |
linjiao@caltech.edu
|
48ff8544d059e0a034a3c07fe27cb062dff8c1a8
|
c10ef416832b3e99e58fb93c85f414d94bbdbc2e
|
/py3canvas/tests/result.py
|
3aeaf5a7cd1dfa532943ac1a6d246a344ffa8b73
|
[
"MIT"
] |
permissive
|
tylerclair/py3canvas
|
83bab26d1624a11acffaeb0392c6a9a38f995f16
|
7485d458606b65200f0ffa5bbe597a9d0bee189f
|
refs/heads/master
| 2021-10-26T03:27:48.418437
| 2021-10-23T15:07:26
| 2021-10-23T15:07:26
| 92,841,638
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 991
|
py
|
"""Result API Tests for Version 1.0.
This is a testing template for the generated ResultAPI Class.
"""
import unittest
import requests
import secrets
from py3canvas.apis.result import ResultAPI
from py3canvas.apis.result import Result
class TestResultAPI(unittest.TestCase):
"""Tests for the ResultAPI."""
def setUp(self):
self.client = ResultAPI(secrets.instance_address, secrets.access_token)
def test_show_collection_of_results(self):
"""Integration test for the ResultAPI.show_collection_of_results method."""
course_id = None # Change me!!
line_item_id = None # Change me!!
r = self.client.show_collection_of_results(course_id, line_item_id)
def test_show_result(self):
"""Integration test for the ResultAPI.show_result method."""
course_id = None # Change me!!
line_item_id = None # Change me!!
id = None # Change me!!
r = self.client.show_result(course_id, id, line_item_id)
|
[
"tyler.clair@gmail.com"
] |
tyler.clair@gmail.com
|
8ad089f44de9540d84c38dda8d42ea64d4a44194
|
55c250525bd7198ac905b1f2f86d16a44f73e03a
|
/Python/Flask/Book_evaluator/venv/Lib/site-packages/cryptography/hazmat/primitives/keywrap.py
|
a3220495a10c5372ad9237bae667cf23b76a957c
|
[] |
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
| 129
|
py
|
version https://git-lfs.github.com/spec/v1
oid sha256:2f23dbacdbaddb11439413b821d3b9344d7857d70b3ee31b511de764f4cdc224
size 5453
|
[
"nateweiler84@gmail.com"
] |
nateweiler84@gmail.com
|
ade99175de46f946bb72da1575a7f965f4589768
|
c6d0bc814c3c7b621f2a07e293d3c4e36521b1f0
|
/validators.py
|
262fe543b2902a2506348f07794667f5dc811474
|
[] |
no_license
|
captain204/Quiz-app
|
9ead59d74df6ad35fa25eb209762f57e3b64e780
|
72136fc27dc18254c5de8149ff631deb6f6eaccc
|
refs/heads/master
| 2020-08-25T04:43:39.415027
| 2019-10-28T01:18:10
| 2019-10-28T01:18:10
| 216,962,636
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,651
|
py
|
from config import *
class Post(Form):
title = StringField(u'Title',validators=[validators.input_required(),
validators.Length(min=10,max=250)])
body = TextAreaField(u'Body',validators=[validators.input_required(),
validators.Length(min=10,max=2500)])
class User(Form):
username = StringField(u'Username',validators=[validators.input_required(),
validators.Length(min=3, max=250)])
email = StringField(u'email',validators=[validators.input_required(),
validators.Length(min=3,max=50)])
password = PasswordField('Password',[validators.DataRequired(),
validators.EqualTo('confirm',message='Passwords do not match')])
confirm = PasswordField('Confirm Password')
stack = SelectField('Select Stack', choices=[('python', 'python'),('php', 'php'),('javascript', 'javascript'),])
class Add(Form):
number = StringField(u'Question Number',validators=[validators.input_required(),
validators.Length(max=250)])
question = TextAreaField(u'Question',validators=[validators.input_required(),
validators.Length(min=10,max=2500)])
option_a = StringField(u'Option A',validators=[validators.input_required(),
validators.Length(max=250)])
option_b = StringField(u'Option B',validators=[validators.input_required(),
validators.Length(max=250)])
option_c = StringField(u'Option C',validators=[validators.input_required(),
validators.Length(max=250)])
option_d = StringField(u'Option D',validators=[validators.input_required(),
validators.Length(max=250)])
correct = StringField(u'Correct Answer',validators=[validators.input_required(),
validators.Length(max=250)])
|
[
"nurudeenakindele8@gmail.com"
] |
nurudeenakindele8@gmail.com
|
4655d48747e83026599fd27c8933c9c4f593b3b4
|
2a24dba82767419cf7d2269875bf0a297f41580c
|
/vispy/scene/widgets/widget.py
|
bfe4e89710bddb6814a7c0ec13ffb1df9c71637c
|
[
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] |
permissive
|
shjoshi/vispy
|
58b300d23486b7478b786977b3548dd7225de847
|
2f3d169aa60c738467e766c59096f51570483d6f
|
refs/heads/master
| 2020-12-25T12:40:36.545768
| 2014-08-06T22:59:35
| 2014-08-06T22:59:35
| 22,704,584
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,178
|
py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
import numpy as np
from ..visuals.visual import Visual
from ..visuals.line import Line
from ..transforms import STTransform
from ...util.event import Event
from ...util.geometry import Rect
from ...color import Color
class Widget(Visual):
""" A widget takes up a rectangular space, intended for use in
a 2D pixel coordinate frame.
The widget is positioned using the transform attribute (as any
entity), and its extend (size) is kept as a separate property.
"""
def __init__(self, *args, **kwargs):
self._border = kwargs.pop('border', (0.2, 0.2, 0.2, 0.5))
# for drawing border
self._visual = Line(color=self._border)
# whether this widget should clip its children
self._clip = kwargs.pop('clip', False)
# reserved space inside border
self._padding = kwargs.pop('padding', 0)
# reserved space outside border
self._margin = kwargs.pop('margin', 0)
pos = kwargs.pop('pos', (0, 0))
size = kwargs.pop('size', (10, 10))
Visual.__init__(self, *args, **kwargs)
self.events.add(resize=Event)
self._size = 16, 16
self.transform = STTransform()
# todo: TTransform (translate only for widgets)
self._widgets = []
self.pos = pos
self.size = size
@property
def pos(self):
return tuple(self.transform.translate[:2])
@pos.setter
def pos(self, p):
assert isinstance(p, tuple)
assert len(p) == 2
self.transform.translate = p[0], p[1], 0, 0
self._update_line()
self.events.resize()
@property
def size(self):
# Note that we cannot let the size be reflected in the transform.
# Consider a widget of 40x40 in a pixel grid, a child widget therin
# with size 20x20 would get a scale of 800x800!
return self._size
@size.setter
def size(self, s):
assert isinstance(s, tuple)
assert len(s) == 2
self._size = s
self._update_line()
self.events.resize()
self._update_child_widgets()
@property
def rect(self):
return Rect((0, 0), self.size)
@rect.setter
def rect(self, r):
with self.events.resize.blocker():
self.pos = r.pos
self.size = r.size
self.update()
self.events.resize()
@property
def border(self):
return self._border
@border.setter
def border(self, b):
self._border = b
self._visual.set_data(color=b)
self.update()
@property
def background(self):
""" The background color of the Widget.
"""
return self._background
@background.setter
def background(self, value):
self._background = Color(value)
self.update()
@property
def margin(self):
return self._margin
@margin.setter
def margin(self, m):
self._margin = m
self._update_line()
@property
def padding(self):
return self._padding
@padding.setter
def padding(self, p):
self._padding = p
self._update_child_boxes()
def _update_line(self):
""" Update border line to match new shape """
m = self.margin
r = self.size[0] - m
t = self.size[1] - m
pos = np.array([
[m, m],
[r, m],
[r, t],
[m, t],
[m, m]]).astype(np.float32)
self._visual.set_data(pos=pos)
def draw(self, event):
self._visual.draw(event)
def on_resize(self, ev):
self._update_child_widgets()
def _update_child_widgets(self):
# Set the position and size of child boxes (only those added
# using add_widget)
for ch in self._widgets:
ch.rect = self.rect.padded(self.padding + self.margin)
def add_widget(self, widget):
"""
Add a Widget as a managed child of this Widget. The child will be
automatically positioned and sized to fill the entire space inside
this Widget (unless _update_child_widgets is redefined).
"""
self._widgets.append(widget)
widget.parent = self
self._update_child_widgets()
return widget
def add_grid(self, *args, **kwds):
"""
Create a new Grid and add it as a child widget.
All arguments are given to add_widget().
"""
from .grid import Grid
grid = Grid()
return self.add_widget(grid, *args, **kwds)
def add_view(self, *args, **kwds):
"""
Create a new ViewBox and add it as a child widget.
All arguments are given to add_widget().
"""
from .viewbox import ViewBox
view = ViewBox()
return self.add_widget(view, *args, **kwds)
def remove_widget(self, widget):
self._widgets.remove(widget)
widget.remove_parent(self)
self._update_child_widgets()
|
[
"luke.campagnola@gmail.com"
] |
luke.campagnola@gmail.com
|
2d8099c9724448fa929eb0d7a1a81d01928c712e
|
969f28be98f607767d5564a6bbbc08fdfb778633
|
/pypenrose/net_tests.py
|
cb25db1cb6d83cf7c21b683d3aa35454be138c07
|
[] |
no_license
|
meawoppl/penrose-play
|
66dde0e2ec1c6997bc06f53852af2c4240dff79c
|
c44d40893a70176efb1ee29b395db973e27f730f
|
refs/heads/master
| 2020-01-23T21:56:22.765852
| 2017-01-16T06:36:23
| 2017-01-16T06:36:23
| 74,727,801
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,736
|
py
|
import math
from mock import MagicMock
import nose.tools
from pypenrose.line import Line
import pypenrose.net
import pypenrose.net_testlib
from pypenrose.net_testlib import assert_graph_props
import pypenrose.space
def test_net_graphgen_degenerate():
# No lines to intersect
g = pypenrose.net.gridlines_to_gridgraph([])
assert_graph_props(g, nodes=0, edges=0)
# Too few lines to intersect
g = pypenrose.net.gridlines_to_gridgraph([Line(0, 1, 1)])
assert_graph_props(g, nodes=0, edges=0)
# All parallel lines
g = pypenrose.net.gridlines_to_gridgraph([
Line(0, 1, 1),
Line(0, 1, 2),
Line(0, 1, 3),
])
assert_graph_props(g, nodes=0, edges=0)
def test_net_graphgen_1():
# One intersection, no connected
g = pypenrose.net.gridlines_to_gridgraph([
Line(0, 1, 1),
Line(1, 0, 1),
])
assert_graph_props(g, nodes=1, edges=0)
def test_net_graphgen_2():
# Two intersection, one connection
g = pypenrose.net.gridlines_to_gridgraph([
Line(0, 1, 1),
Line(1, 0, 1),
Line(1, 0, 2),
])
assert_graph_props(g, nodes=2, edges=1)
def test_net_graphgen_3():
# Triangle, 3 intersects, 3 edges
g = pypenrose.net.gridlines_to_gridgraph([
Line(1, 1, 0),
Line(1, 0, 0),
Line(0, 1, 1),
])
assert_graph_props(g, nodes=3, edges=3)
def test_net_graphgen_5d():
for line_count in range(1, 7):
lol_of_lines = pypenrose.space.get_nd_grid_p1(line_count)
all_lines = sum(lol_of_lines, [])
g = pypenrose.net.gridlines_to_gridgraph(all_lines)
expected_nodecount = 10 * line_count**2
assert_graph_props(g, nodes=expected_nodecount)
def test_determine_winding():
net = pypenrose.net_testlib.get_simple_net()
center, edge_node = pypenrose.net_testlib.get_center_edge(net.g)
winding = net.determine_winding(center, edge_node)
nose.tools.assert_equal(len(winding), 4)
nose.tools.assert_equal(
winding[0],
edge_node
)
for node in winding:
nose.tools.assert_in(node, net.g)
def test_compute_angles():
net = pypenrose.net_testlib.get_simple_net()
center, edge_node = pypenrose.net_testlib.get_center_edge(net.g)
# For the square mesh, all angles should be 90
for angle in net.compute_angles(center, edge_node):
nose.tools.assert_equal(angle, math.pi / 2)
def test_get_primary_spoke():
net = pypenrose.net_testlib.get_simple_net()
center, edge_node = pypenrose.net_testlib.get_center_edge(net.g)
# Graph directions should point up in x and y
# Y is CCW from X, so X sorts first
spoke_node = net.get_primary_spoke(center)
nose.tools.assert_equal(
net.g.node[spoke_node]["intersection"],
(1.0, 0.0)
)
def test_get_node_on_line():
# Pull out a node to draw from and the center
net = pypenrose.net_testlib.get_simple_net()
for line in net.lines:
net.get_node_on_line(line)
def test_get_line_root():
# Pull out a node to draw from and the center
net = pypenrose.net_testlib.get_simple_net()
root_nodes = set()
for line in net.lines:
root_node = net.get_line_root(line)
root_nodes.add(root_node)
nose.tools.assert_equal(len(root_nodes), 5)
def _assert_displacement(mock_call, displacement):
x_sum, y_sum = 0, 0
for (dx, dy), _ in mock_call.call_args_list:
x_sum += dx
y_sum += dy
try:
nose.tools.assert_almost_equal(x_sum, displacement[0])
nose.tools.assert_almost_equal(y_sum, displacement[1])
except AssertionError:
print("\n_assert_displacement failure.")
print("Call dump follows:")
for (dx, dy), _ in mock_call.call_args_list:
print("call(", dx, ",", dy, ")")
raise
def test_draw_tile():
# Pull out a node to draw from and the center
net = pypenrose.net_testlib.get_simple_net()
center, edge_node = pypenrose.net_testlib.get_center_edge(net.g)
ctx_mock = MagicMock()
line_to_mock = ctx_mock.rel_line_to
net.draw_tile(ctx_mock, edge_node, center)
# Should make 4 relative line calls
nose.tools.assert_equal(line_to_mock.call_count, 4)
# Line calls should close the graphing loop
_assert_displacement(line_to_mock, (0, 0))
def test_draw_ribbon():
net = pypenrose.net_testlib.get_simple_net(shape=(3, 5))
line = net.lines[1]
ctx_mock = MagicMock()
move_to_mock = ctx_mock.move_to
line_to_mock = ctx_mock.rel_line_to
net.draw_ribbon(ctx_mock, line)
# These should all be closed loops
nose.tools.assert_equal(line_to_mock.call_count, 12)
_assert_displacement(line_to_mock, (0, 0))
|
[
"meawoppl@gmail.com"
] |
meawoppl@gmail.com
|
395ca378d374ed81267bce67ad399409aefe0bd2
|
c1350fbcb269cdab0f36a12a27f694697e08ce7f
|
/libs/db/db_handler.py
|
53add1030fb2b880c28b40c507df2732190f2892
|
[] |
no_license
|
deepmicrosystems/object-detection-server
|
86dd4178c9dbfe8e1e802062a1a44c4f758ed758
|
97893dfcef89219a11a87bb34a663912b273fce3
|
refs/heads/master
| 2022-12-18T00:44:58.906967
| 2019-07-29T18:50:25
| 2019-07-29T18:50:25
| 147,842,577
| 0
| 0
| null | 2022-11-22T01:57:57
| 2018-09-07T15:33:49
|
Python
|
UTF-8
|
Python
| false
| false
| 2,323
|
py
|
import sqlite3
import time
import datetime
class DataBaseManager:
def __init__(self, db_name = None):
self.conn = None
self.cursor = None
if db_name:
self.open(db_name)
def open(self, db_name):
try:
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
self.create_table()
except Exception as e:
print(f'Cannot connect to db or {e}')
def create_table(self, case):
if (case == "detections"):
self.cursor.execute("CREATE TABLE IF NOT EXISTS \
detections( item_id REAL, w REAL, h REAL, x REAL, y REAL, prob REAL,\
datestamp TEXT, class TEXT, imgPath TEXT)")
elif (case == "plates"):
self.cursor.execute("CREATE TABLE IF NOT EXISTS \
plates( item_id REAL, w REAL, h REAL, x REAL, y REAL, prob REAL,\
datestamp TEXT, imgPath TEXT)")
def close(self):
self.cursor.close()
self.conn.close()
def __enter__(self):
return self
# def __exit__(self,exc_type,exc_value,traceback):
# self.close()
def dynamic_data_entry(self, item_id, image_path, detection, prob, obj_class, date):
x = detection["xmin"]
y = detection["ymin"]
h = detection["xmax"]
w = detection["ymax"]
self.cursor.execute("INSERT INTO detections \
(item_id, w, h, x, y, prob, datestamp, class, imgPath) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
(item_id, w, h, x, y, prob, date, obj_class, image_path))
self.conn.commit()
#self.close()
def dynamic_data_entry_plates(self,image_path_crop, detection, plate, prob , date, item_id):
x = detection["xmin"]
y = detection["ymin"]
h = detection["xmax"]
w = detection["ymax"]
self.cursor.execute("INSERT INTO plates \
(item_id, w, h, x, y, prob, datestamp, imgPath) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(item_id, w, h, x, y, prob, date, image_path_crop))
self.conn.commit()
#self.close()
|
[
"stanlee321@gmail.com"
] |
stanlee321@gmail.com
|
9e2292ed6aad43b70783af1b63396c473b5483e2
|
2e08552e1eb86ffa4870d9208d83b903f0f847d0
|
/paperswithcode/models/method.py
|
68db3851e56de877c738be0007eb111575f3a402
|
[
"Apache-2.0",
"CC-BY-SA-4.0"
] |
permissive
|
paperswithcode/paperswithcode-client
|
c1fffc0a17066f0eb7128ea726bf4f0485f47c5d
|
70bd7ee5157fcaeff39145d2e03cc9ed5bb7421b
|
refs/heads/develop
| 2022-12-12T21:20:17.493109
| 2021-12-01T17:44:04
| 2021-12-01T17:44:04
| 283,026,422
| 113
| 17
|
Apache-2.0
| 2022-12-01T22:24:42
| 2020-07-27T21:58:46
|
Python
|
UTF-8
|
Python
| false
| false
| 909
|
py
|
from typing import List, Optional
from tea_client.models import TeaClientModel
from paperswithcode.models.page import Page
class Method(TeaClientModel):
"""Method object.
Attributes:
id (str): Method ID.
name (str): Method short name.
full_name (str): Method full name.
description (str): Method description.
paper (str, optional): ID of the paper that describes the method.
"""
id: str
name: str
full_name: str
description: str
paper: Optional[str]
class Methods(Page):
"""Object representing a paginated page of methods.
Attributes:
count (int): Number of elements matching the query.
next_page (int, optional): Number of the next page.
previous_page (int, optional): Number of the previous page.
results (List[Method]): List of methods on this page.
"""
results: List[Method]
|
[
"alefnula@gmail.com"
] |
alefnula@gmail.com
|
59139ee9c6c59c9e6407b92820cac368678556b0
|
79df1e2fde419883fba5f3a79eddfd6c3b7875cc
|
/udacity/cs253/Lesson02a_Templates/Page.py
|
4ce93600c8582ba5e8b020de17473b34e04ae73b
|
[] |
no_license
|
jJayyyyyyy/network
|
284a2845c4431e802a48ea331135a3e2035663cd
|
86794dd9d828fe66b7ada28233fbbd5c66ecc50d
|
refs/heads/master
| 2022-03-01T23:51:10.619772
| 2019-08-11T12:27:35
| 2019-08-11T12:27:35
| 116,240,231
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,050
|
py
|
from html import escape
from flask import render_template # flask will help us auto escape html
import os
import ROT13, FizzBuzz
def fill_template(name='index', **kw):
filename = '%s.html' % name
return render_template(filename, **kw)
def get_default_signup_args():
return {'username': '',
'username_error': '',
'password_error': '',
'verify_error': '',
'email': '',
'email_error': ''}
def render_fizzbuzz(n):
fizzbuzz = FizzBuzz.get(n)
page = fill_template('fizzbuzz', FizzBuzz=fizzbuzz)
return page
def render_index():
page = fill_template('index')
return page
def render_rot13(text=''):
text = ROT13.encode(text)
args = {'text': text}
return fill_template('rot13', **args)
def render_signup(form={}):
if form:
args = form
else:
args = get_default_signup_args()
print(args)
return fill_template('signup', **args)
def render_welcome(username=''):
if username:
args = {'username': username, 'a': 'a'}
return fill_template('welcome', **args)
else:
return 'Invalid username<br><br><a href="/">Back</a>'
|
[
"ljjdbd123@hotmail.com"
] |
ljjdbd123@hotmail.com
|
4571754551752803df00023b5b17c08759238d50
|
e0980f704a573894350e285f66f4cf390837238e
|
/.history/streams/blocks_20201022115527.py
|
3674f140da693d1c6dea4759795d6a2e1dd4f2fe
|
[] |
no_license
|
rucpata/WagtailWebsite
|
28008474ec779d12ef43bceb61827168274a8b61
|
5aa44f51592f49c9a708fc5515ad877c6a29dfd9
|
refs/heads/main
| 2023-02-09T15:30:02.133415
| 2021-01-05T14:55:45
| 2021-01-05T14:55:45
| 303,961,094
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,747
|
py
|
from wagtail.core import blocks
from wagtail.images.blocks import ImageChooserBlock
class TitleBlock(blocks.StructBlock):
text = blocks.CharBlock(
required = True,
elp_text='Tekst do wyświetlenia',
)
class Meta:
template = 'streams/title_block.html'
icon = 'edycja'
label = 'Tytuł'
help_text = 'Wyśrodkowany tekst do wyświetlenia na stronie.'
class LinkValue(blocks.StructValue):
"""Dodatkowao logika dla lików"""
def url(self):
internal_page = self.get('internal_page')
external_link = self.get('external_link')
if internal_page:
return internal_page.url
elif external_link:
return external_link
class Link(blocks.StructBlock):
link_text = blocks.CharBlock(
max_length=50,
default='Więcej szczegółów'
)
interal_page = blocks.PageChooserBlock(
required=False
)
external_link = blocks.URLBlock(
required=False
)
class Meta:
value_class = LinkValue
class Card(blocks.StructBlock):
title = blocks.CharBlock(
max_length=100,
help_text = 'Pogrubiony tytuł tej karty. Maksymalnie 100 znaków.'
)
text = blocks.TextBlock(
max_length=255,
help_text='Opcjonalny tekst tej karty. Maksymalnie 255 znaków.'
)
image = ImageChooserBlock(
help_text = 'Obraz zostanie automatycznie przycięty o 570 na 370 pikseli'
)
link = Link(help_text = 'Wwybierz link')
class CardsBlock(blocks.StructBlock):
cards = blocks.ListBlock(
Card()
)
class Meta:
template = 'streams/card_block.html'
icon = 'image'
label = 'Karty standardowe'
|
[
"rucinska.patrycja@gmail.com"
] |
rucinska.patrycja@gmail.com
|
ca7a71cd0e1dece862f0b5ed7066061699c5661c
|
c7ec556bfdc2ec5eaf234c679ffb1fbcc58d651a
|
/cftda/wsgi.py
|
061f4071370b887c2c842852ef9259770162346a
|
[] |
no_license
|
dmitryduev/cftda
|
ba2a7c4b7295b42c36e3ad4cd89d2b2bbfa9a76c
|
4cc1456f2794f52529ba354d94bfff2bb8405434
|
refs/heads/master
| 2020-03-10T03:40:25.090449
| 2018-04-17T08:36:02
| 2018-04-17T08:36:02
| 129,171,296
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 472
|
py
|
"""
WSGI config for cftda 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/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cftda.settings.dev")
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cftda.settings.production")
application = get_wsgi_application()
|
[
"dmitry.duev@gmail.com"
] |
dmitry.duev@gmail.com
|
e9537acd041786dc77ea7aa000b3f43627ecdea4
|
d97e90a0ff598249a3b28fe7a4bb8e4c5b39d210
|
/tests/test_service_tax_category.py
|
2d165f52cfa2f155fabc08e56b9591eeeb7f6b46
|
[
"MIT"
] |
permissive
|
jeroenubbink/commercetools-python-sdk
|
024ef08d04d8d8e8609bd265d1eaac5a067a47b0
|
ee27768d6fdde3e12618059891d1d4f75dd61390
|
refs/heads/master
| 2022-12-01T11:24:26.953904
| 2020-08-05T09:12:50
| 2020-08-05T15:22:06
| 287,386,564
| 0
| 0
|
MIT
| 2020-08-13T21:50:57
| 2020-08-13T21:50:57
| null |
UTF-8
|
Python
| false
| false
| 1,025
|
py
|
from commercetools import types
def test_tax_category_create(client):
tax_category = client.tax_categories.create(types.TaxCategoryDraft(name="Hoog"))
assert tax_category.id
assert tax_category.name == "Hoog"
def test_tax_category_get_by_id(client):
tax_category = client.tax_categories.create(types.TaxCategoryDraft(name="Hoog"))
assert tax_category.id
assert tax_category.name == "Hoog"
tax_category = client.tax_categories.get_by_id(tax_category.id)
assert tax_category.id
assert tax_category.name == "Hoog"
def test_tax_category_update_by_id(client):
tax_category = client.tax_categories.create(types.TaxCategoryDraft(name="Hoog"))
assert tax_category.id
assert tax_category.name == "Hoog"
tax_category = client.tax_categories.update_by_id(
tax_category.id,
version=tax_category.version,
actions=[types.TaxCategorySetDescriptionAction(description="Some text")],
)
assert tax_category.id
assert tax_category.name == "Hoog"
|
[
"michael@mvantellingen.nl"
] |
michael@mvantellingen.nl
|
2b6e279d904c9d7ac089522c567cdbe2a1cc707d
|
2eb7cac33991ecf95e6ed0af0b7a440c319d0913
|
/viz/migrations/0003_auto_20170924_0138.py
|
fb66dfa6c948e109b23860f4e9adcf7e612b13a1
|
[] |
no_license
|
felipinbombin/osirisWebPlatform
|
f1fb4cda7be2776dc6dfa21029fd1b8d68b48efd
|
20005616be153015d71a9853f789db427b9e753b
|
refs/heads/master
| 2021-03-27T13:24:29.141698
| 2018-07-30T04:53:21
| 2018-07-30T04:53:21
| 87,222,468
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 454
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-24 04:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('viz', '0002_auto_20170924_0014'),
]
operations = [
migrations.AlterField(
model_name='modelanswer',
name='direction',
field=models.CharField(max_length=1),
),
]
|
[
"cephei.1313@gmail.com"
] |
cephei.1313@gmail.com
|
9b8cfc58c987bce1af4a5e147b49af7f7b096e33
|
2c872fedcdc12c89742d10c2f1c821eed0470726
|
/pbase/day04/code/while_qiantao1.py
|
c12a856d18d1b1539bf2ad72d88c61dbf3017ff7
|
[] |
no_license
|
zuigehulu/AID1811
|
581c3c7a37df9fa928bc632e4891fc9bafe69201
|
10cab0869875290646a9e5d815ff159d0116990e
|
refs/heads/master
| 2020-04-19T16:33:04.174841
| 2019-01-30T07:58:24
| 2019-01-30T07:58:24
| 168,307,918
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 179
|
py
|
num = int(input("请输入正方形的宽度:"))
i = 1
while i <= num:
j = 1
while j <= num:
print(j,end = " ")
j += 1
else:
print()
i += 1
|
[
"442315617@qq.com"
] |
442315617@qq.com
|
e4247d34a3e43a9024946c14f468f1b5215719b4
|
8263e388d00e1beaaac587df6d2e5b20c0ba2981
|
/4.py
|
ae5fc1397d85132af7f4db047819d498c4e41a0e
|
[] |
no_license
|
shivamdattapurkayastha99/natrural-language-processing
|
3064c0a2fb2b830579565f8157d7d3208cf1a884
|
b47ab27eb468469cc9e5ec07c6580d2c8a959124
|
refs/heads/master
| 2023-07-04T12:50:00.282883
| 2021-08-13T18:04:10
| 2021-08-13T18:04:10
| 395,746,985
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 244
|
py
|
import nltk
from nltk.corpus import wordnet
# syn=wordnet.synsets('computer')
# print(syn[0].definition())
synonyms=[]
for syn in wordnet.synsets('computer'):
for lemma in syn.lemmas():
synonyms.append(lemma.name())
print(synonyms)
|
[
"shivamdatta465@gmail.com"
] |
shivamdatta465@gmail.com
|
2e9e94d73080d69d4190c219e5d655c8823d94d1
|
935b9efca392b124d571319568c08ba45446d2a0
|
/lino_book/projects/lydia/tests/dumps/18.8.0/cal_guestrole.py
|
1b937b29d05f60388ba0afed921493063edf56be
|
[
"BSD-2-Clause"
] |
permissive
|
wallento/book
|
6efba2baa1e42bb99514a937342000271dfe798b
|
8c5a68f30f9ab65479a988608bda66ea6209afd8
|
refs/heads/master
| 2020-04-06T10:58:01.629671
| 2018-11-07T09:41:54
| 2018-11-07T09:41:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 303
|
py
|
# -*- coding: UTF-8 -*-
logger.info("Loading 2 objects to table cal_guestrole...")
# fields: id, ref, name
loader.save(create_cal_guestrole(1,None,['Attendee', 'Teilnehmer', 'Attendee']))
loader.save(create_cal_guestrole(2,None,['Colleague', 'Colleague', 'Colleague']))
loader.flush_deferred_objects()
|
[
"luc.saffre@gmail.com"
] |
luc.saffre@gmail.com
|
54f1a14fc79a4ff7d2e664ba0f98eb3bdba4474f
|
af717d07cb2bb9c6d9fcc7ba4290cf02a0890815
|
/homework-05-09/homework_07_import.py
|
b2d4827ccdbdf606454ddeed0ed0b45b9b0b560f
|
[] |
no_license
|
liuluyang/homework
|
0070d39640de8777f0656f0346adc1a5a6cfa1ab
|
e65db68e96bbfe1d987b2809321e59e303ab5ee8
|
refs/heads/master
| 2020-09-25T18:44:45.368491
| 2019-12-05T09:38:17
| 2019-12-05T09:38:17
| 226,066,124
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 444
|
py
|
from homework_07 import *
def func_08():
"""
将上述函数放在一个模块中,再写一个源程序文件,并在该源程序中实现对模块中函数的调用
:return:
"""
print(func_01())
print(func_02(100, 80))
print(func_03())
print(func_04('hello', 'e'))
print(func_05(100))
print(func_06(5))
print(func_07([1, 2, 3, 4, 5], 2))
if __name__ == '__main__':
# func_08()
pass
|
[
"1120773382@qq.com"
] |
1120773382@qq.com
|
f660b301415bf623ca90a9372bf5662b4783352b
|
8a497f9e412eb74d9eca41488fae3f1947bdc87c
|
/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/middleware.py
|
56cdd1fe1420c4de35e14e90fe745cd8bb7f9138
|
[] |
no_license
|
bwarren2/cookiecutter-simple-django
|
012a788512d969f1a5f34cc0e51d26d65ad9ff18
|
08ca73e55e133ad097e3551b0af258b29cbb3ab9
|
refs/heads/master
| 2020-05-29T12:19:34.691916
| 2015-07-25T17:32:59
| 2015-07-25T17:32:59
| 39,597,383
| 0
| 0
| null | 2015-07-23T22:39:45
| 2015-07-23T22:39:45
|
Python
|
UTF-8
|
Python
| false
| false
| 510
|
py
|
from django.http import HttpResponseRedirect
class ForceHttps(object):
def process_request(self, request):
secure_request = (
# settings.DEBUG,
request.is_secure(),
request.META.get("HTTP_X_FORWARDED_PROTO", "").lower() == "https",
)
if not any(secure_request):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace("http://", "https://")
return HttpResponseRedirect(secure_url)
|
[
"bwarren2@gmail.com"
] |
bwarren2@gmail.com
|
b72b5b0739c393c93728b3588b7836d89dfab62a
|
bc6f0f731f7ad72fd11c6a332f47b972d1d14cb3
|
/codewars-challenges/6 kyu/does-points-form-square.py
|
c2b92005bc0eb951e130b19fa6bdcd1d7d5d29a0
|
[] |
no_license
|
greatertomi/problem-solving
|
ee8d35f5f8bf76d9942adec79479c36585f7b90b
|
a2507fa8fa649ba70f8994d8bc36b07d28512861
|
refs/heads/master
| 2023-09-03T20:49:22.759696
| 2021-11-11T22:41:39
| 2021-11-11T22:41:39
| 283,445,532
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,142
|
py
|
# Problem Link: https://www.codewars.com/kata/618688793385370019f494ae
import math
def distanceBetweenTwoPoints(pointA, pointB):
valueA = (pointB[1] - pointA[1]) ** 2
valueB = (pointB[0] - pointA[0]) ** 2
return math.sqrt(valueA + valueB)
def isSquare(points):
if len(points) < 4:
return False
result1 = distanceBetweenTwoPoints(points[0], points[1])
result2 = distanceBetweenTwoPoints(points[1], points[2])
result3 = distanceBetweenTwoPoints(points[2], points[3])
result4 = distanceBetweenTwoPoints(points[3], points[0])
print(result1, result2, result3, result4)
if result1 == result2 == result3 == result4 == 0:
return False
return result1 == result2 == result3 == result4
value1 = ((1, 1), (3, 3), (1, 3), (3, 1))
value2 = ((0, 0), (0, 2), (2, 0), (2, 1))
value3 = ((0, 2), (0, -2), (1, 0), (-1, 0))
value4 = ((2, 6), (5, 1), (0, -2), (-3, 3))
value5 = ((0, 0), (0, 0), (0, 0), (0, 0))
value6 = ((1, 1), (3, 3), (1, 3), (3, 1))
value7 = [(0, 0), (0, 0), (2, 0), (2, 0)]
# print(isSquare(value1))
# print(isSquare(value2))
# print(isSquare(value3))
print(isSquare(value7))
|
[
"oshalusijohn@gmail.com"
] |
oshalusijohn@gmail.com
|
95f8d3d0b927460d31612a2870b9c41833aee495
|
dd3b8bd6c9f6f1d9f207678b101eff93b032b0f0
|
/basis/AbletonLive10.1_MIDIRemoteScripts/AxiomPro/TransportViewModeSelector.py
|
cac299bfde53b7b762969e7cce8ddb19dea81a2c
|
[] |
no_license
|
jhlax/les
|
62955f57c33299ebfc4fca8d0482b30ee97adfe7
|
d865478bf02778e509e61370174a450104d20a28
|
refs/heads/master
| 2023-08-17T17:24:44.297302
| 2019-12-15T08:13:29
| 2019-12-15T08:13:29
| 228,120,861
| 3
| 0
| null | 2023-08-03T16:40:44
| 2019-12-15T03:02:27
|
Python
|
UTF-8
|
Python
| false
| false
| 2,827
|
py
|
# uncompyle6 version 3.4.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.16 (v2.7.16:413a49145e, Mar 2 2019, 14:32:10)
# [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
# Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/AxiomPro/TransportViewModeSelector.py
# Compiled at: 2019-04-09 19:23:44
from __future__ import absolute_import, print_function, unicode_literals
from _Framework.ModeSelectorComponent import ModeSelectorComponent
from _Framework.ButtonElement import ButtonElement
from _Framework.TransportComponent import TransportComponent
from _Framework.SessionComponent import SessionComponent
class TransportViewModeSelector(ModeSelectorComponent):
u""" Class that reassigns specific buttons based on the views visible in Live """
def __init__(self, transport, session, ffwd_button, rwd_button, loop_button):
assert isinstance(transport, TransportComponent)
assert isinstance(session, SessionComponent)
assert isinstance(ffwd_button, ButtonElement)
assert isinstance(rwd_button, ButtonElement)
assert isinstance(loop_button, ButtonElement)
ModeSelectorComponent.__init__(self)
self._transport = transport
self._session = session
self._ffwd_button = ffwd_button
self._rwd_button = rwd_button
self._loop_button = loop_button
self.application().view.add_is_view_visible_listener('Session', self._on_view_changed)
self.update()
def disconnect(self):
ModeSelectorComponent.disconnect(self)
self._transport = None
self._session = None
self._ffwd_button = None
self._rwd_button = None
self._loop_button = None
self.application().view.remove_is_view_visible_listener('Session', self._on_view_changed)
return
def update(self):
super(TransportViewModeSelector, self).update()
if self.is_enabled():
if self._mode_index == 0:
self._transport.set_seek_buttons(self._ffwd_button, self._rwd_button)
self._transport.set_loop_button(self._loop_button)
self._session.set_select_buttons(None, None)
self._session.selected_scene().set_launch_button(None)
else:
self._transport.set_seek_buttons(None, None)
self._transport.set_loop_button(None)
self._session.set_select_buttons(self._ffwd_button, self._rwd_button)
self._session.selected_scene().set_launch_button(self._loop_button)
return
def _on_view_changed(self):
if self.application().view.is_view_visible('Session'):
self._mode_index = 1
else:
self._mode_index = 0
self.update()
|
[
"jharrington@transcendbg.com"
] |
jharrington@transcendbg.com
|
2132f8724d3ff2cfd875cfaad4696b09f7eea6dd
|
a04c9e34c8abb6eb5857cb6e35fbbed0743ea8d4
|
/Week3/BackspaceStringCompare.py
|
edeac380910ae744782c39a51d5bbe99f7102a5a
|
[] |
no_license
|
SrikanthAmudala/PythonWorkShopConcordia
|
a2fd0a3103524733913c00767907bafecd1c6ad6
|
d2e383a89bc995d96313fd0723c064a0a45db6f9
|
refs/heads/master
| 2021-05-19T13:02:42.173832
| 2020-05-27T21:48:34
| 2020-05-27T21:48:34
| 251,713,287
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 200
|
py
|
S = "###c#ab###fs#j"
T = "ad#c"
def stringComp(S):
temp = []
for i in S:
if i=="#" and len(temp)!=0:
temp.pop(-1)
elif i!="#":
temp.append(i)
return "".join(temp)
print(stringComp(S))
|
[
"srikanthamudala95@gmail.com"
] |
srikanthamudala95@gmail.com
|
ab98f101089e6c3bcd638d092b91b731d7669ba7
|
2da6b95fe4237cc00014f80c45d268ab62fc90cd
|
/backbones/cifar/lenet2.py
|
bafe3e227b2332d56de8d4a8c6585b7880269478
|
[] |
no_license
|
lvzongyao/Open-Set-Recognition-1
|
7e26cd1d97f67b6c075f4e64296ce7a82d479168
|
26a8a1cca199f4e23df98abca6893e3eef3307da
|
refs/heads/master
| 2023-08-19T09:15:16.119377
| 2021-09-13T04:21:18
| 2021-09-13T04:21:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,673
|
py
|
'''LeNetPlus in PyTorch.
Specifically, designed for MNIST dataset.
Reference:
[1] Wen, Yandong, et al. "A discriminative feature learning approach for deep face recognition."
European conference on computer vision. Springer, Cham, 2016.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['LeNetHiera']
class LeNetHiera(nn.Module):
def __init__(self, num_classes=10, backbone_fc=True):
super(LeNetHiera, self).__init__()
self.conv1_1 = nn.Conv2d(1, 32, 5, stride=1, padding=2)
self.prelu1_1 = nn.PReLU()
self.conv1_2 = nn.Conv2d(32, 32, 5, stride=1, padding=2)
self.prelu1_2 = nn.PReLU()
self.conv2_1 = nn.Conv2d(32, 64, 5, stride=1, padding=2)
self.prelu2_1 = nn.PReLU()
self.conv2_2 = nn.Conv2d(64, 64, 5, stride=1, padding=2)
self.prelu2_2 = nn.PReLU()
self.conv3_1 = nn.Conv2d(64, 128, 5, stride=1, padding=2)
self.prelu3_1 = nn.PReLU()
self.conv3_2 = nn.Conv2d(128, 128, 5, stride=1, padding=2)
self.prelu3_2 = nn.PReLU()
self.gap_prelu = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.PReLU()
)
self.extractor1 = nn.Conv2d(32, 128 * 3 * 3, 1)
self.extractor2 = nn.Conv2d(64, 128 * 3 * 3, 1)
self.fuse = nn.Parameter(torch.Tensor([[[[0.], [0.], [1.]]]]))
if backbone_fc:
self.linear = nn.Sequential(
nn.Linear(128 * 3 * 3, 2),
nn.PReLU(),
nn.Linear(2, num_classes)
)
def forward(self, x):
x = self.prelu1_1(self.conv1_1(x))
x = self.prelu1_2(self.conv1_2(x))
extractor1 = self.extractor1(self.gap_prelu(x))
x = F.max_pool2d(x, 2)
x = self.prelu2_1(self.conv2_1(x))
x = self.prelu2_2(self.conv2_2(x))
extractor2 = self.extractor2(self.gap_prelu(x))
x = F.max_pool2d(x, 2)
x = self.prelu3_1(self.conv3_1(x))
x = self.prelu3_2(self.conv3_2(x))
x = F.max_pool2d(x, 2)
x = x.view(-1, 128 * 3 * 3)
# for unified style for DFPNet
out = x.unsqueeze(dim=-1).unsqueeze(dim=-1)
out = torch.cat([extractor1,extractor2, out],dim=2)
out = (out*self.fuse).sum(dim=2,keepdim=True)
# return the original feature map if no FC layers.
if hasattr(self, 'linear'):
out = F.adaptive_avg_pool2d(out, 1)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
def demo():
net = LeNetHiera(num_classes=10, backbone_fc=False)
y = net(torch.randn(2, 1, 28, 28))
print(y.size())
# demo()
|
[
"xuma@my.unt.edu"
] |
xuma@my.unt.edu
|
c24f833353ca7bf80df320a57b2d8f201a33bb6a
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02900/s596241684.py
|
d8b236ea95aa163221e6926aa26888658463f2cb
|
[] |
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
| 445
|
py
|
from math import*
def factrization_prime(number):
factor = {}
div = 2
s = sqrt(number)
while div < s:
div_cnt = 0
while number % div == 0:
div_cnt += 1
number //= div
if div_cnt != 0:
factor[div] = div_cnt
div += 1
if number > 1:
factor[number] = 1
return factor
A, B = map(int, input().split())
f = factrization_prime(gcd(A,B))
print(len(f)+1)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
560839c298d5303d6e8119983b822f06ccf876e7
|
13b46582bb6bbfe08a2e24127198ded24e6c0ad3
|
/server/lighthouse/admin.py
|
83201ba793fb89885f899a2319619cbac73b3426
|
[] |
no_license
|
dmetrosoft/seo-audits-toolkit
|
9b12735d8345ef5075e87e6ea09440e01e32746f
|
c3e95fc4bf51d72e61c0507c14bd384d2368f475
|
refs/heads/master
| 2023-08-25T06:11:54.055464
| 2021-04-08T15:51:23
| 2021-04-08T15:51:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 290
|
py
|
from django.contrib import admin
from .models import Lighthouse, Lighthouse_Result
# Register your models here.
admin.site.register(Lighthouse)
admin.site.register(Lighthouse_Result)
# Allows the Model to be administered via the /admin interface
# Highly recommendeded for easier debug
|
[
"stan@primates.dev"
] |
stan@primates.dev
|
af66740e6d1849e019c0ffdd525e58709a401252
|
50dd2a43daa8316fc11e0c176b5872738fcc5dde
|
/Learning/130_Fluent_Python/fp2-utf8/blocinteractive/example 16-9.py
|
3234ee9c3d215d29019fad27ad046ceb874110fa
|
[] |
no_license
|
FrenchBear/Python
|
58204d368e3e72071eef298ff00d06ff51bd7914
|
b41ab4b6a59ee9e145ef2cd887a5fe306973962b
|
refs/heads/master
| 2023-08-31T18:43:37.792427
| 2023-08-26T15:53:20
| 2023-08-26T15:53:20
| 124,466,047
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 506
|
py
|
# Example 16-9. Vector.__add__ method needs an iterable with numeric items
>>> v1 + 'ABC'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "vector_v6.py", line 329, in __add__
return Vector(a + b for a, b in pairs)
File "vector_v6.py", line 243, in __init__
self._components = array(self.typecode, components)
File "vector_v6.py", line 329, in <genexpr>
return Vector(a + b for a, b in pairs)
TypeError: unsupported operand type(s) for +: 'float' and 'str'
|
[
"FrenchBear38@outlook.com"
] |
FrenchBear38@outlook.com
|
54154c6ac7f3eb42bb9745b4c24314cd78ab21af
|
da85d4caf3e5e1c9df8839fafd51f960f02daadd
|
/develop/io/async.py
|
28958d34db443cb715939f72ced88e07280fcfd0
|
[
"Apache-2.0"
] |
permissive
|
shuaih7/FabricUI
|
6efe58f3dbefebbd49607094a28bf2d7bc9314ca
|
6501e8e6370d1f90174002f5768b5ef63e8412bc
|
refs/heads/main
| 2023-04-13T10:07:42.090043
| 2021-04-13T02:55:12
| 2021-04-13T02:55:12
| 314,152,777
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 525
|
py
|
import asyncio
import time
from threading import Thread
def start_loop(loop):
asyncio.set_event_loop(loop)
print("start loop", time.time())
loop.run_forever()
async def do_some_work(x):
print('start {}'.format(x))
await asyncio.sleep(x)
print('Done after {}s'.format(x))
new_loop = asyncio.new_event_loop()
t = Thread(target=start_loop, args=(new_loop,))
t.start()
asyncio.run_coroutine_threadsafe(do_some_work(6), new_loop)
asyncio.run_coroutine_threadsafe(do_some_work(4), new_loop)
|
[
"shuaih7@gmail.com"
] |
shuaih7@gmail.com
|
230c7c268af9b219156f9bd55fbfdead55bdde13
|
a5698f82064aade6af0f1da21f504a9ef8c9ac6e
|
/huaweicloud-sdk-projectman/huaweicloudsdkprojectman/v4/model/list_projects_v4_response.py
|
5b0873986a953ab7fb205e092a7cdb760a8bd5b4
|
[
"Apache-2.0"
] |
permissive
|
qizhidong/huaweicloud-sdk-python-v3
|
82a2046fbb7d62810984399abb2ca72b3b47fac6
|
6cdcf1da8b098427e58fc3335a387c14df7776d0
|
refs/heads/master
| 2023-04-06T02:58:15.175373
| 2021-03-30T10:47:29
| 2021-03-30T10:47:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,634
|
py
|
# coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class ListProjectsV4Response(SdkResponse):
"""
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 = {
'projects': 'list[ListProjectsV4ResponseBodyProjects]',
'total': 'int'
}
attribute_map = {
'projects': 'projects',
'total': 'total'
}
def __init__(self, projects=None, total=None):
"""ListProjectsV4Response - a model defined in huaweicloud sdk"""
super().__init__()
self._projects = None
self._total = None
self.discriminator = None
if projects is not None:
self.projects = projects
if total is not None:
self.total = total
@property
def projects(self):
"""Gets the projects of this ListProjectsV4Response.
项目信息列表
:return: The projects of this ListProjectsV4Response.
:rtype: list[ListProjectsV4ResponseBodyProjects]
"""
return self._projects
@projects.setter
def projects(self, projects):
"""Sets the projects of this ListProjectsV4Response.
项目信息列表
:param projects: The projects of this ListProjectsV4Response.
:type: list[ListProjectsV4ResponseBodyProjects]
"""
self._projects = projects
@property
def total(self):
"""Gets the total of this ListProjectsV4Response.
项目总数
:return: The total of this ListProjectsV4Response.
:rtype: int
"""
return self._total
@total.setter
def total(self, total):
"""Sets the total of this ListProjectsV4Response.
项目总数
:param total: The total of this ListProjectsV4Response.
:type: int
"""
self._total = total
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"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListProjectsV4Response):
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
|
229153641d7110152bf260eee9651fafce2aa55c
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_2/209.py
|
ed64df919f88a28c7ad0f8764bf7151e0b04cfe0
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,054
|
py
|
import time
input = open("B-large.in", "r")
output = open("B-large.out", "w")
i = int(input.readline().strip())
for case in range(i):
turnaroundTime = int(input.readline().strip())
(AtoBNumber, BtoANumber) = map(int, input.readline().strip().split(" "))
timeList = []
for j in range(AtoBNumber):
(departureString, arrivalString) = input.readline().strip().split(" ")
departure = time.strptime(departureString + " 1971", "%H:%M %Y")
#print str(departure)
departure = time.localtime(time.mktime(departure))
arrival = time.strptime(arrivalString + " 1971", "%H:%M %Y")
arrival = time.localtime(time.mktime(arrival) + 60*turnaroundTime)
timeList.append((departure, "A", "departure"))
timeList.append((arrival, "B", "arrival"))
for j in range(BtoANumber):
(departureString, arrivalString) = input.readline().strip().split(" ")
departure = time.strptime(departureString + " 1971", "%H:%M %Y")
departure = time.localtime(time.mktime(departure))
arrival = time.strptime(arrivalString + " 1971", "%H:%M %Y")
arrival = time.localtime(time.mktime(arrival) + 60*turnaroundTime)
timeList.append((departure, "B", "departure"))
timeList.append((arrival, "A", "arrival"))
timeList.sort();
tmpAtoB = 0
tmpBtoA = 0
AtoB = 0
BtoA = 0
for timeTable in timeList:
if timeTable[2] == "arrival":
if timeTable[1] == "A":
tmpAtoB += 1
else:
tmpBtoA += 1
else:
if timeTable[1] == "A":
if tmpAtoB > 0:
tmpAtoB -= 1
else:
AtoB +=1
else:
if tmpBtoA > 0:
tmpBtoA -=1
else:
BtoA += 1
output.write("Case #%d: %d %d\n" %(case+1, AtoB, BtoA))
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
69cf7fe229d5d1e49c81cb3e5ff63cc464e78512
|
ff7c392e46baa2774b305a4999d7dbbcf8a3c0b3
|
/ask-sdk-model/ask_sdk_model/interfaces/alexa/presentation/apl/rotate_transform_property.py
|
7723824c757f66b7e1818dc1f7fa549b10be7f77
|
[
"Apache-2.0"
] |
permissive
|
rivamarco/alexa-apis-for-python
|
83d035ba5beb5838ae977777191fa41cbe4ea112
|
62e3a9057a26003e836fa09aa12a2e1c8b62d6e0
|
refs/heads/master
| 2021-01-03T20:44:12.977804
| 2020-02-13T10:27:27
| 2020-02-13T10:29:24
| 240,229,385
| 2
| 0
|
Apache-2.0
| 2020-02-13T10:05:45
| 2020-02-13T10:05:45
| null |
UTF-8
|
Python
| false
| false
| 3,428
|
py
|
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 pprint
import re # noqa: F401
import six
import typing
from enum import Enum
from ask_sdk_model.interfaces.alexa.presentation.apl.transform_property import TransformProperty
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union
from datetime import datetime
class RotateTransformProperty(TransformProperty):
"""
:param rotate: Rotation angle, in degrees. Positive angles rotate in the clockwise direction.
:type rotate: float
"""
deserialized_types = {
'rotate': 'float'
} # type: Dict
attribute_map = {
'rotate': 'rotate'
} # type: Dict
supports_multiple_types = False
def __init__(self, rotate=0.0):
# type: (Union[float, str, None]) -> None
"""
:param rotate: Rotation angle, in degrees. Positive angles rotate in the clockwise direction.
:type rotate: float
"""
self.__discriminator_value = None # type: str
super(RotateTransformProperty, self).__init__()
self.rotate = rotate
def to_dict(self):
# type: () -> Dict[str, object]
"""Returns the model properties as a dict"""
result = {} # type: Dict
for attr, _ in six.iteritems(self.deserialized_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 if isinstance(x, Enum) else x,
value
))
elif isinstance(value, Enum):
result[attr] = value.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[0], item[1].value)
if isinstance(item[1], Enum) else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
# type: () -> str
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
# type: () -> str
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
# type: (object) -> bool
"""Returns true if both objects are equal"""
if not isinstance(other, RotateTransformProperty):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
# type: (object) -> bool
"""Returns true if both objects are not equal"""
return not self == other
|
[
"ask-pyth@dev-dsk-ask-sdk-python-2b-85d79f62.us-west-2.amazon.com"
] |
ask-pyth@dev-dsk-ask-sdk-python-2b-85d79f62.us-west-2.amazon.com
|
cf6792f25eabe0aa2d1f7706d4894f2eb5107393
|
21aff79a45a410c69a17f6b6aa6623b0001559f3
|
/apps/mapserver/apps.py
|
611581e596df8ffa82e1ca00fb9b561109d3e675
|
[] |
no_license
|
jqchang/TamagotchiServer
|
1e7c721894c0e38da9583f8887b032cec192e6a1
|
31667e7997f71f3aec38b25ced1359bab67f780a
|
refs/heads/master
| 2021-01-23T01:07:01.638012
| 2017-03-23T02:58:07
| 2017-03-23T02:58:07
| 85,871,192
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 134
|
py
|
from __future__ import unicode_literals
from django.apps import AppConfig
class MapserverConfig(AppConfig):
name = 'mapserver'
|
[
"jqchang@gmail.com"
] |
jqchang@gmail.com
|
15a31b23ac174a1fa304a180f2caa0648df99bf6
|
3dab01e032134fd5cde6d29a127a8e8d93d48796
|
/accounts/migrations/0003_auto_20210205_1107.py
|
b9490de61d22c0e9ea5dc7f6764010c42648a609
|
[] |
no_license
|
mariachacko93/FoacloidBankProject
|
41baa9433814087f2e45d458bcfccc3c3bc44d6e
|
fbbb424ef4534c549ea74bfbe0d7d367a70802a1
|
refs/heads/master
| 2023-03-01T18:58:50.768867
| 2021-02-08T08:50:34
| 2021-02-08T08:50:34
| 337,012,353
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 394
|
py
|
# Generated by Django 3.1.6 on 2021-02-05 07:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20210205_1107'),
]
operations = [
migrations.AlterField(
model_name='createaccount',
name='accno',
field=models.IntegerField(unique=True),
),
]
|
[
"mariachacko93@gmail.com"
] |
mariachacko93@gmail.com
|
cc2c5970cfe0af932efe8fe15b1f9437d823c6b5
|
d2845579ea6aa51a2e150f0ffe6ccfda85d035ce
|
/kernel/examples/handler/component/horz_pearson.py
|
88694a0dc34a7576b3327fff3c49a1214411c858
|
[
"Apache-2.0"
] |
permissive
|
as23187/WeFe
|
d8de9ff626f9f3e5d98e0850b0b717a80fd73e72
|
ba92871d4b1d2eef6c606c34795f4575e84703bd
|
refs/heads/main
| 2023-08-22T12:01:06.718246
| 2021-10-28T01:54:05
| 2021-10-28T01:54:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,052
|
py
|
# Copyright 2021 Tianmian Tech. 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.
# Copyright 2019 The FATE 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.
from common.python.utils import log_utils
from kernel.components.correlation.horzpearson.param import HorzPearsonParam
from kernel.examples.handler.component.component_base import Component
from kernel.examples.handler.interface import Input
from kernel.examples.handler.interface import Output
LOGGER = log_utils.get_logger()
class HorzPearson(Component, HorzPearsonParam):
def __init__(self, **kwargs):
Component.__init__(self, **kwargs)
# print (self.name)
LOGGER.debug(f"{self.name} component created")
new_kwargs = self.erase_component_base_param(**kwargs)
HorzPearsonParam.__init__(self, **new_kwargs)
self.input = Input(self.name, data_type="multi")
self.output = Output(self.name)
self._module_name = "HorzPearson"
self._param_name = "HorzPearsonParam"
|
[
"winter.zou@welab-inc.com"
] |
winter.zou@welab-inc.com
|
5c59092aef917fb302c3a4ee9334f5b75ac50252
|
dbf81359567f718f43e513891a4e761a2d8c7c5a
|
/users/forms.py
|
2e13681d309d10c36e01e3bdd25217cd480c0bcd
|
[] |
no_license
|
peterbe/w91011
|
675e5cbed1847010ab5ddb27c1fe56b935b1a26f
|
b816c8dacb246db730db3e678248c32cf021fc36
|
refs/heads/master
| 2021-01-01T17:31:27.595419
| 2011-05-20T22:10:51
| 2011-05-20T22:10:51
| 1,371,606
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 136
|
py
|
# python
import re
# django
from django import forms
from django.contrib.auth.models import User
from models import UserProfile
# app
|
[
"peter@fry-it.com"
] |
peter@fry-it.com
|
8661a95e0c4ade5cddd4f3acd778ce88a3e17a6d
|
9d6218ca6c75a0e1ec1674fe410100d93d6852cb
|
/app/notifier/virtualenvs/notifier/bin/dynamodb_load
|
f7ed5a0cb31e695fab50e6b5e6b33df3a0797d40
|
[] |
no_license
|
bopopescu/uceo-2015
|
164694268969dd884904f51b00bd3dc034695be8
|
5abcbfc4ff32bca6ca237d71cbb68fab4b9f9f91
|
refs/heads/master
| 2021-05-28T21:12:05.120484
| 2015-08-05T06:46:36
| 2015-08-05T06:46:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,503
|
#!/edx/app/notifier/virtualenvs/notifier/bin/python
import argparse
import os
import boto
from boto.compat import json
from boto.dynamodb.schema import Schema
DESCRIPTION = """Load data into one or more DynamoDB tables.
For each table, data is read from two files:
- {table_name}.metadata for the table's name, schema and provisioned
throughput (only required if creating the table).
- {table_name}.data for the table's actual contents.
Both files are searched for in the current directory. To read them from
somewhere else, use the --in-dir parameter.
This program does not wipe the tables prior to loading data. However, any
items present in the data files will overwrite the table's contents.
"""
def _json_iterload(fd):
"""Lazily load newline-separated JSON objects from a file-like object."""
buffer = ""
eof = False
while not eof:
try:
# Add a line to the buffer
buffer += fd.next()
except StopIteration:
# We can't let that exception bubble up, otherwise the last
# object in the file will never be decoded.
eof = True
try:
# Try to decode a JSON object.
json_object = json.loads(buffer.strip())
# Success: clear the buffer (everything was decoded).
buffer = ""
except ValueError:
if eof and buffer.strip():
# No more lines to load and the buffer contains something other
# than whitespace: the file is, in fact, malformed.
raise
# We couldn't decode a complete JSON object: load more lines.
continue
yield json_object
def create_table(metadata_fd):
"""Create a table from a metadata file-like object."""
def load_table(table, in_fd):
"""Load items into a table from a file-like object."""
for i in _json_iterload(in_fd):
# Convert lists back to sets.
data = {}
for k, v in i.iteritems():
if isinstance(v, list):
data[k] = set(v)
else:
data[k] = v
table.new_item(attrs=data).put()
def dynamodb_load(tables, in_dir, create_tables):
conn = boto.connect_dynamodb()
for t in tables:
metadata_file = os.path.join(in_dir, "%s.metadata" % t)
data_file = os.path.join(in_dir, "%s.data" % t)
if create_tables:
with open(metadata_file) as meta_fd:
metadata = json.load(meta_fd)
table = conn.create_table(
name=t,
schema=Schema(metadata["schema"]),
read_units=metadata["read_units"],
write_units=metadata["write_units"],
)
table.refresh(wait_for_active=True)
else:
table = conn.get_table(t)
with open(data_file) as in_fd:
load_table(table, in_fd)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog="dynamodb_load",
description=DESCRIPTION
)
parser.add_argument(
"--create-tables",
action="store_true",
help="Create the tables if they don't exist already (without this flag, attempts to load data into non-existing tables fail)."
)
parser.add_argument("--in-dir", default=".")
parser.add_argument("tables", metavar="TABLES", nargs="+")
namespace = parser.parse_args()
dynamodb_load(namespace.tables, namespace.in_dir, namespace.create_tables)
|
[
"root@uceociputra.com"
] |
root@uceociputra.com
|
|
39ecf8a6bf6320ef772e70a2165129e85befec7b
|
26d6c34df00a229dc85ad7326de6cb5672be7acc
|
/msgraph-cli-extensions/v1_0/devicescorpmgt_v1_0/azext_devicescorpmgt_v1_0/vendored_sdks/devicescorpmgt/operations/_device_app_management_device_app_management_operations.py
|
a2163d104f46288f513f0a9b6c9009c40e5b4402
|
[
"MIT"
] |
permissive
|
BrianTJackett/msgraph-cli
|
87f92471f68f85e44872939d876b9ff5f0ae6b2c
|
78a4b1c73a23b85c070fed2fbca93758733f620e
|
refs/heads/main
| 2023-06-23T21:31:53.306655
| 2021-07-09T07:58:56
| 2021-07-09T07:58:56
| 386,993,555
| 0
| 0
|
NOASSERTION
| 2021-07-17T16:56:05
| 2021-07-17T16:56:05
| null |
UTF-8
|
Python
| false
| false
| 7,111
|
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 TYPE_CHECKING
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 HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class DeviceAppManagementDeviceAppManagementOperations(object):
"""DeviceAppManagementDeviceAppManagementOperations 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: ~devices_corporate_management.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):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get_device_app_management(
self,
select=None, # type: Optional[List[Union[str, "models.Get0ItemsItem"]]]
expand=None, # type: Optional[List[Union[str, "models.Get1ItemsItem"]]]
**kwargs # type: Any
):
# type: (...) -> "models.MicrosoftGraphDeviceAppManagement"
"""Get deviceAppManagement.
Get deviceAppManagement.
:param select: Select properties to be returned.
:type select: list[str or ~devices_corporate_management.models.Get0ItemsItem]
:param expand: Expand related entities.
:type expand: list[str or ~devices_corporate_management.models.Get1ItemsItem]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MicrosoftGraphDeviceAppManagement, or the result of cls(response)
:rtype: ~devices_corporate_management.models.MicrosoftGraphDeviceAppManagement
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.MicrosoftGraphDeviceAppManagement"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.get_device_app_management.metadata['url'] # type: ignore
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if select is not None:
query_parameters['$select'] = self._serialize.query("select", select, '[str]', div=',')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, '[str]', div=',')
# 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 = 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)
error = self._deserialize(models.OdataError, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('MicrosoftGraphDeviceAppManagement', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_device_app_management.metadata = {'url': '/deviceAppManagement'} # type: ignore
def update_device_app_management(
self,
body, # type: "models.MicrosoftGraphDeviceAppManagement"
**kwargs # type: Any
):
# type: (...) -> None
"""Update deviceAppManagement.
Update deviceAppManagement.
:param body: New property values.
:type body: ~devices_corporate_management.models.MicrosoftGraphDeviceAppManagement
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update_device_app_management.metadata['url'] # type: ignore
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'MicrosoftGraphDeviceAppManagement')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.OdataError, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
update_device_app_management.metadata = {'url': '/deviceAppManagement'} # type: ignore
|
[
"japhethobalak@gmail.com"
] |
japhethobalak@gmail.com
|
a2cc0d8b9ee7768ddb30a445139a75e96b07c107
|
7a42d40a351824464a3c78dc0c3e78bbd8e0a92f
|
/RestProject/API/models.py
|
d5633eab44e77e7fc0bc778eae43c34180e41df2
|
[] |
no_license
|
AhMay/DerekBlogLearn
|
6595063eafbc237b932e187b5cb3ad8ff32637fc
|
fdd5ea2fc5732cdc82ad006f7be0a2a1f30d0ba9
|
refs/heads/master
| 2020-07-09T05:20:33.283672
| 2019-09-29T10:10:23
| 2019-09-29T10:10:23
| 203,891,215
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 751
|
py
|
from django.db import models
# Create your models here.
class UserInfo(models.Model):
USER_TYPE = (
(1,'普通用户'),
(2,'VIP'),
(3,'SVIP')
)
user_type = models.IntegerField(choices=USER_TYPE)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
group = models.ForeignKey('UserGroup', on_delete=models.CASCADE, null=True, blank=True)
roles = models.ManyToManyField('Role')
class UserToken(models.Model):
user = models.OneToOneField(UserInfo,on_delete=models.CASCADE)
token = models.CharField(max_length=64)
class UserGroup(models.Model):
title = models.CharField(max_length=32)
class Role(models.Model):
title = models.CharField(max_length=32)
|
[
"meizi111082@hotmail.com"
] |
meizi111082@hotmail.com
|
dfbba17d8c8e485a34a89c32f8fe71b59d124f0a
|
0f504dab15e85d95695999eb7ad6fb5d0fedf627
|
/backend/course/api/v1/urls.py
|
ac318e9affa6f0ceb6d946ccd239fb5f8e476bdb
|
[] |
no_license
|
crowdbotics-apps/quiz2-21690
|
e4ac495291069051c2750b4d520a7e783c422525
|
b9839d7cc02f631877ae7625f7ec32355d0bc90e
|
refs/heads/master
| 2022-12-30T18:40:06.017656
| 2020-10-18T23:49:48
| 2020-10-18T23:49:48
| 305,218,317
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 944
|
py
|
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .viewsets import (
RecordingViewSet,
EventViewSet,
SubscriptionViewSet,
CourseViewSet,
GroupViewSet,
ModuleViewSet,
PaymentMethodViewSet,
SubscriptionTypeViewSet,
EnrollmentViewSet,
LessonViewSet,
CategoryViewSet,
)
router = DefaultRouter()
router.register("category", CategoryViewSet)
router.register("paymentmethod", PaymentMethodViewSet)
router.register("subscriptiontype", SubscriptionTypeViewSet)
router.register("subscription", SubscriptionViewSet)
router.register("course", CourseViewSet)
router.register("recording", RecordingViewSet)
router.register("event", EventViewSet)
router.register("module", ModuleViewSet)
router.register("enrollment", EnrollmentViewSet)
router.register("lesson", LessonViewSet)
router.register("group", GroupViewSet)
urlpatterns = [
path("", include(router.urls)),
]
|
[
"team@crowdbotics.com"
] |
team@crowdbotics.com
|
67dbc7b5ac7b949db359a0aecf1cf5b6cae00c61
|
2df82b931c89ac70d49b0716d642d8e355926d50
|
/product/migrations/0001_initial.py
|
3716702e72959b27f723bc7d805418f6cdc9c2ad
|
[] |
no_license
|
khanansha/producthunt
|
1a638104e83803b9afc4a51ff3ead438ae47cab6
|
03b8d45091c88a2ff142f0a3082910ac1fa0ba41
|
refs/heads/master
| 2021-05-26T03:21:35.246011
| 2020-04-08T08:41:17
| 2020-04-08T08:41:17
| 254,031,608
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,086
|
py
|
# Generated by Django 2.2.10 on 2020-04-02 15:30
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),
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('pub_date', models.DateTimeField()),
('body', models.TextField()),
('url', models.TextField()),
('image', models.ImageField(upload_to='images/')),
('icon', models.ImageField(upload_to='images/')),
('votes_total', models.IntegerField(default=1)),
('hunter', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
[
"anjumkhan88987@gmail.com"
] |
anjumkhan88987@gmail.com
|
649ccaa41cf34423f7cb4ea871756bc46167d0e9
|
34b7e1ec50f0ebf3c0389baebd0940801cb49016
|
/get_update_gaps.py
|
4491613af1df28cd30e2e76e230ea6f17586d52b
|
[] |
no_license
|
chenc10/TensorFlow-RRSP-INFOCOM19
|
c5827378dfd3fe4cbe6b85c4f1d6aee4615b6e4e
|
131eb664f91111646bccf5b7490f5d1e9562ebeb
|
refs/heads/master
| 2020-04-29T22:18:40.729132
| 2019-03-19T06:52:51
| 2019-03-19T06:52:51
| 176,443,203
| 8
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 413
|
py
|
import sys
num = 16
update_times = []
for i in range(num):
f = open(sys.argv[1] + '/slave'+str(i)+'.log', 'r')
d = f.readlines()
f.close()
for i in range(len(d)):
if 'loss =' in d[i]:
tmp = d[i].split('time:')[1].split(';')[0]
update_times.append(float(tmp))
update_times.sort()
gaps = []
for i in range(len(update_times)-1):
gaps.append(update_times[i+1] - update_times[i])
gaps.sort()
print gaps
|
[
"chenc10@126.com"
] |
chenc10@126.com
|
35948d5e5ca5054abf5106ee59c00b4eefdda3da
|
c404b4da78b1ceed2f8dfa50425a04ad68f8d34e
|
/2_route/request.py
|
7b9aca4b9c7a386fe85c96c83cd46b3bc3b43f34
|
[] |
no_license
|
ydPro-G/Flask
|
9bca2db3d19193f07c86cd628cbebaade65451dd
|
d34a9577901dabf4018ba1050263709f2d69e6a8
|
refs/heads/master
| 2022-12-15T22:11:39.391134
| 2020-09-17T07:43:55
| 2020-09-17T07:43:55
| 285,768,905
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,317
|
py
|
# HTTP请求方法设置,Get,Post,Put,Delete
from flask import request
from flask import Flask
# 创建Web应用实例
app = Flask(__name__)
# 指定路由与HTTP请求方法,不同的请求方法可以返回不同的数据
@app.route('/login',methods=['GET','POST'])
# 路由函数
def login():
# 请求路由为什么就反什么数据
if request.method == 'POST':
return 'This is a POST request'
else:
return 'This is a GET request'
# 启动 Web服务器
if __name__ == '__main__':
app.run()
# 2.URL构建方法
# Flask提供了【url_for()】方法来快速获取及构建URL,方法第一个参数指向函数名(被@app.route注解的函数),
# 后续的参数对应要构建的URL变量
url_for('login') # 返回/login
url_for('login',id='1') # 将id作为URL参数,返回/login?id=1
url_for('hello',name='man') # 适配hello函数的name参数 返回/hello/man
url_for('static') # 获取静态文件目录
url_for('static',filename='style.css') # 静态文件地址,返回/static/style.css
#3. 静态文件位置
# 一个web应用的静态文件包括了JS,CSS,图片等,将所有文件放进static子目录中
# 使用url_for('static')来获取静态文件目录
# 改变静态目录位置;
app = Flask(__name__, static_folder='files')
|
[
"46178109+ydPro-G@users.noreply.github.com"
] |
46178109+ydPro-G@users.noreply.github.com
|
51d687d3a65ca402d94f83473d89873f6bc053ea
|
c4f01eec090833762b884c2078161df087d09b0d
|
/Calculation methods/CalcMethods_Lab_3_V15_Task_5_3_1/venv/Scripts/pip-script.py
|
2a4c7ff61e1d675d875a14a4d4569cdd48595e73
|
[] |
no_license
|
areyykarthik/Zhukouski_Pavel_BSU_Projects
|
47a30144c5614b10af521a78fba538a0e9184efa
|
3540979e680732d38e25a6b39f09338985de6743
|
refs/heads/master
| 2023-08-07T02:49:34.736155
| 2021-10-05T21:57:03
| 2021-10-05T21:57:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 435
|
py
|
#!C:\Users\user\PycharmProjects\CalcMethods_Lab_3_V15_Task_5_3_1\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip')()
)
|
[
"shist.pupust@mail.ru"
] |
shist.pupust@mail.ru
|
696900b90a3dc9d880cb3d1bb40e987430548ae4
|
8d2a124753905fb0455f624b7c76792c32fac070
|
/pytnon-month01/month01-class notes/day17-fb/demo02.py
|
f3a3aa8c1778164bc8a83ee97e32c7c518ca0ef4
|
[] |
no_license
|
Jeremy277/exercise
|
f38e4f19aae074c804d265f6a1c49709fd2cae15
|
a72dd82eb2424e4ae18e2f3e9cc66fc4762ec8fa
|
refs/heads/master
| 2020-07-27T09:14:00.286145
| 2019-09-17T11:31:44
| 2019-09-17T11:31:44
| 209,041,629
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,193
|
py
|
"""
迭代器 --> yield
练习: exercise04-装饰器.py
目标:让自定义类所创建的对象,可以参与for.
iter价值:可以被for
next价值:返回数据/抛出异常
class 自定义类的迭代器:
def __next__(self):
pass
class 自定义类:
def __iter__(self):
pass
for item in 自定义类():
pass
"""
# class SkillIterator:
# def __init__(self,data):
# self.__target = data
# self.__index = -1
#
# def __next__(self):
# # 如果没有数据则抛出异常
# if self.__index >= len(self.__target)-1:
# raise StopIteration
# # 返回数据
# self.__index += 1
# return self.__target[self.__index]
class SkillManager:
"""
技能管理器 可迭代对象
"""
def __init__(self):
self.__skills = []
def add_skill(self,str_skill):
self.__skills.append(str_skill)
def __iter__(self):
# return SkillIterator(self.__skills)
# 执行过程:
# 1. 调用__iter__()不执行
# 2. 调用__next__()才执行当前代码
# 3. 执行到yield语句暂时离开
# 4. 再次调用__next__()继续执行
# ....
# yield作用:标记着下列代码会自动转换为迭代器代码.
# 转换大致过程:
# 1. 将yield关键字以前的代码,放到next方法中。
# 2. 将yield关键字后面的数据,作为next返回值.
# print("准备数据:")
# yield "降龙十八掌"
#
# print("准备数据:")
# yield "黑虎掏心"
#
# print("准备数据:")
# yield "六脉神剑"
for item in self.__skills:
yield item
manager = SkillManager()
manager.add_skill("降龙十八掌")
manager.add_skill("黑虎掏心")
manager.add_skill("六脉神剑")
# 错误:manager必须是可迭代对象__iter__(),
# for item in manager:
# print(item)
iterator = manager.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
|
[
"13572093824@163.com"
] |
13572093824@163.com
|
6dd671548eb54a66d884c51832342a6f633a2883
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/9cuQrhEMwiESfKznk_22.py
|
4beda351a6e7e00fbc28e2b58d5e33dbf762429c
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213
| 2021-04-06T20:17:44
| 2021-04-06T20:17:44
| 355,318,759
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 635
|
py
|
def eng2nums(s):
ans=''
nums=[('zero'),('one'),('two','twenty'),('three','thirty'),('four','forty'),\
('five','fifty'),('six','sixty'),('seven','seventy'),('eight','eighty'),\
('nine','ninety'),('ten'),('eleven'),('twelve'),('thirteen'),('fourteen'),\
('fifteen'),('sixteen'),('seventeen'),('eighteen'),('nineteen')]
sl=s.split()
for i in sl:
for j in range(len(nums)):
if i in nums[j]:
ans+=str(j)
break
if s[-2:]=='ty':
ans+='0'
elif 'hundred' in s:
ans=ans[0]+'0'*abs(len(ans)-3)+ans[1:]
return int(ans)
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
bb54248f5b5ab49021f8e14e557a7e1a0f7253cb
|
d190750d6cb34e9d86ae96724cf4b56a2f57a74a
|
/tests/r/test_wine.py
|
fde49d1570f4c69b88eb7454a338809439bfce4b
|
[
"Apache-2.0"
] |
permissive
|
ROAD2018/observations
|
a119f61a48213d791de0620804adb8d21c2ad9fb
|
2c8b1ac31025938cb17762e540f2f592e302d5de
|
refs/heads/master
| 2021-09-24T04:28:02.725245
| 2018-09-16T23:06:30
| 2018-09-16T23:06:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 496
|
py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.wine import wine
def test_wine():
"""Test module wine.py by downloading
wine.csv and testing shape of
extracted data has 21 rows and 5 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = wine(test_path)
try:
assert x_train.shape == (21, 5)
except:
shutil.rmtree(test_path)
raise()
|
[
"dustinviettran@gmail.com"
] |
dustinviettran@gmail.com
|
8a78ad47f05a803e2d09a235e1e6dd69439e958c
|
8787b2fbb5017b61dcf6075a5261071b403847bf
|
/Programmers/피보나치 수.py
|
fa2b3172cfb8dd924d6d630734bc34a370b3b1fd
|
[] |
no_license
|
khw5123/Algorithm
|
a6fe0009e33289813959553c2366d77c93d7b4b9
|
323a829f17a10276ab6f1aec719c496a3e76b974
|
refs/heads/master
| 2023-01-02T00:12:21.848924
| 2020-10-23T06:37:41
| 2020-10-23T06:37:41
| 282,162,235
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 584
|
py
|
def matmul(a, b, mod):
result = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
for k in range(2):
result[i][j] = (result[i][j] + a[i][k] * b[k][j]) % mod
return result
def fibonacci_matrix(n, mod):
arr, constant = [[1, 0], [0, 1]], [[1, 1], [1, 0]]
while n > 0:
if n % 2 == 1:
arr = matmul(arr, constant, mod)
constant = matmul(constant, constant, mod)
n = n // 2
return arr[0][0]
def solution(n):
answer = fibonacci_matrix(n-1, 1234567)
return answer
|
[
"5123khw@hknu.ac.kr"
] |
5123khw@hknu.ac.kr
|
27422c5a1f0ff024ae1c6f90a890aee82bc4fcdb
|
c56ddcc2807151a5c44d3a1d65a1984bc8fd9b84
|
/6 кю/Multiples of 3 or 5.py
|
d64d9b66c2b54376f88bf68fe0a418f6c91a6640
|
[] |
no_license
|
kelpasa/Code_Wars_Python
|
2cd18dd404603a6535887e8e6ed2d08da19562ba
|
939ec1dd08ffc7939bb9a139bf42901d6f24fbdd
|
refs/heads/master
| 2022-12-17T02:00:28.319351
| 2020-09-23T09:11:20
| 2020-09-23T09:11:20
| 246,642,898
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 134
|
py
|
def solution(number):
lst = []
for i in range(number):
if i % 3 == 0 or i % 5 == 0: lst.append(i)
return sum(lst)
|
[
"noreply@github.com"
] |
kelpasa.noreply@github.com
|
820f6939597b6231ca028aa4cfb0446606990eae
|
511b7b19ec49be34bec240ee7c7cf4178cd36ca3
|
/gasolinestation/migrations/0005_auto_20200228_0841.py
|
24b1e028159d61f88186ceefaefa79403001fad9
|
[] |
no_license
|
francisguchie/360POS
|
58de516fe52e83d6b99bd195d22c8aa902daee18
|
68f9e20ac263c75ec0c9b0fe75d7f648b8744ea8
|
refs/heads/master
| 2023-02-08T16:38:42.667538
| 2020-03-12T16:05:00
| 2020-03-12T16:05:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 563
|
py
|
# Generated by Django 3.0.3 on 2020-02-28 08:41
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('gasolinestation', '0004_auto_20200228_0832'),
]
operations = [
migrations.AlterField(
model_name='gasstations',
name='site_staff',
field=models.ManyToManyField(blank=True, related_name='site_staffs', to=settings.AUTH_USER_MODEL),
),
]
|
[
"monde.lacanlalay@gmail.com"
] |
monde.lacanlalay@gmail.com
|
2d59e32a6dcbc39603ae17ab49edec7087cf3ec4
|
f68cd225b050d11616ad9542dda60288f6eeccff
|
/testscripts/RDKB/component/CosaCM/TS_COSACM_GetLoopDiagnosticsStart_WithInvalidBuffer.py
|
237d4cfa6fdc2e7d9e44c6fc5e9438d8bc5e5679
|
[
"Apache-2.0"
] |
permissive
|
cablelabs/tools-tdkb
|
18fb98fadcd169fa9000db8865285fbf6ff8dc9d
|
1fd5af0f6b23ce6614a4cfcbbaec4dde430fad69
|
refs/heads/master
| 2020-03-28T03:06:50.595160
| 2018-09-04T11:11:00
| 2018-09-05T00:24:38
| 147,621,410
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,628
|
py
|
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2016 RDK Management
#
# 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.
##########################################################################
'''
<?xml version="1.0" encoding="UTF-8"?><xml>
<id/>
<version>1</version>
<name>TS_COSACM_GetLoopDiagnosticsStart_WithInvalidBuffer</name>
<primitive_test_id/>
<primitive_test_name>CosaCM_GetLoopDiagnosticsStart</primitive_test_name>
<primitive_test_version>2</primitive_test_version>
<status>FREE</status>
<synopsis/>
<groups_id>4</groups_id>
<execution_time>1</execution_time>
<long_duration>false</long_duration>
<remarks/>
<skip>false</skip>
<box_types>
<box_type>Broadband</box_type>
</box_types>
<rdk_versions>
<rdk_version>RDKB</rdk_version>
</rdk_versions>
<test_cases>
<test_case_id>TC_COSACM_40</test_case_id>
<test_objective>To Validate Cable Modem
"CosaDmlCMGetLoopDiagnosticsStart" API under Negative scenario</test_objective>
<test_type>Positive</test_type>
<test_setup>Emulator,
XB3</test_setup>
<pre_requisite>1.Ccsp Components should be in a running state of DUT that includes component under test Cable Modem
2.TDK Agent should be in running state or invoke it through StartTdk.sh script
</pre_requisite>
<api_or_interface_used>None</api_or_interface_used>
<input_parameters>Json Interface:
API Name
CosaCM_GetLoopDiagnosticsStart
Input
N/A
</input_parameters>
<automation_approch>1.Configure the Function info in Test Manager GUI which needs to be tested
(CosaCM_GetLoopDiagnosticsStart - func name - "If not exists already" ( This is considered as default Primitive test case)
cosacm - module name
Necessary I/P args if needed as Mentioned in Input)
2.Create a Python Script in Test Manager with default primitive test case through add new rdkb script option (TS_COSACM_GetLoopDiagnosticsStart_WithInvalidBuffer.py)
3.Customize the generated script template to handle load/unload and pass/fail scenarios
3.Execute the generated Script(TS_COSACM_GetLoopDiagnosticsStart_WithInvalidBuffer.py) using execution page of Test Manager GUI
4.cosacmstub which is a part of TDK Agent process, will be in listening mode to execute TDK Component function named CosaCM_GetLoopDiagnosticsStart through registered TDK cosacmstub function along with necessary Entry Values as arguments
5.CosaCM_GetLoopDiagnosticsStart function will call ssp_CosaCMGetLoopDiagnosticsStart,that inturn will call relevant cm hal Function to get/set data model value
6.Responses(printf) from TDK Component,Ccsp Library function and cosacmstub would be logged in Agent Console log based on the debug info redirected to agent console
7.cosacmstub function CosaCM_GetLoopDiagnosticsStart will validate the available result (return value from ssp_CosaCMGetLoopDiagnosticsStart as success(0)) with expected result (success(0)) and the outpur argument value is updated in agent console log and json output variable along with return value
8.TestManager will publish the result in GUI as PASS/FAILURE based on the response from CosaCM_GetLoopDiagnosticsStart function</automation_approch>
<except_output>CheckPoint 1:
Cosa CM "Get Loop Diagnostics Start" success log from DUT should be available in Agent Console Log
CheckPoint 2:
TDK agent Test Function will log the test case result as PASS based on API response which will be available in Test Manager Result ( XLS)
CheckPoint 3:
TestManager GUI will publish the result as PASS in Execution/Console page of Test Manager</except_output>
<priority>High</priority>
<test_stub_interface>None</test_stub_interface>
<test_script>TS_COSACM_GetLoopDiagnosticsStart_WithInvalidBuffer</test_script>
<skipped>No</skipped>
<release_version/>
<remarks>None</remarks>
</test_cases>
</xml>
'''
#use tdklib library,which provides a wrapper for tdk testcase script
import tdklib;
import time;
#Test component to be tested
obj = tdklib.TDKScriptingLibrary("cosacm","RDKB");
#IP and Port of box, No need to change,
#This will be replaced with correspoing Box Ip and port while executing script
ip = <ipaddress>
port = <port>
obj.configureTestCase(ip,port,'TS_COSACM_GetLoopDiagnosticsStart_NegArg');
#Get the result of connection with test component and STB
loadmodulestatus =obj.getLoadModuleResult();
print "[LIB LOAD STATUS] : %s" %loadmodulestatus ;
if "SUCCESS" in loadmodulestatus.upper():
obj.setLoadModuleStatus("SUCCESS");
#Script to load the configuration file of the component
tdkTestObj = obj.createTestStep("CosaCM_GetLoopDiagnosticsStart");
tdkTestObj.addParameter("handleType",0);
tdkTestObj.addParameter("boolValue",1);
expectedresult="FAILURE";
tdkTestObj.executeTestCase(expectedresult);
actualresult = tdkTestObj.getResult();
if expectedresult in actualresult:
#Set the result status of execution
tdkTestObj.setResultStatus("SUCCESS");
details = tdkTestObj.getResultDetails();
print "TEST STEP 1: Should not get the loop diagonostics start details";
print "EXPECTED RESULT 1: Fail to get the loop diagnostics start details ";
print "ACTUAL RESULT 1: %s" %details;
#Get the result of execution
print "[TEST EXECUTION RESULT] : %s" %actualresult ;
else:
tdkTestObj.setResultStatus("FAILURE");
details = tdkTestObj.getResultDetails();
print "TEST STEP 1: Should not get the loop diagonostics start details";
print "EXPECTED RESULT 1: Fail to get the loop diagnostics start details ";
print "ACTUAL RESULT 1: %s" %details;
print "[TEST EXECUTION RESULT] : %s" %actualresult ;
obj.unloadModule("cosacm");
else:
print "Failed to load the module";
obj.setLoadModuleStatus("FAILURE");
print "Module loading failed";
|
[
"jim.lawton@accenture.com"
] |
jim.lawton@accenture.com
|
7cc65b6f39eee379bed59fe9296f6f4f7706dab0
|
a1615563bb9b124e16f4163f660d677f3224553c
|
/LI/lib/python3.8/site-packages/numpy/typing/tests/data/pass/array_constructors.py
|
63208f139c39667febc30a53fb13a4109a74d410
|
[
"BSD-3-Clause",
"GPL-3.0-or-later",
"BSD-3-Clause-Open-MPI",
"GPL-3.0-only",
"GCC-exception-3.1",
"MIT"
] |
permissive
|
honeybhardwaj/Language_Identification
|
2a247d98095bd56c1194a34a556ddfadf6f001e5
|
1b74f898be5402b0c1a13debf595736a3f57d7e7
|
refs/heads/main
| 2023-04-19T16:22:05.231818
| 2021-05-15T18:59:45
| 2021-05-15T18:59:45
| 351,470,447
| 5
| 4
|
MIT
| 2021-05-15T18:59:46
| 2021-03-25T14:42:26
|
Python
|
UTF-8
|
Python
| false
| false
| 2,362
|
py
|
from typing import List, Any
import numpy as np
class Index:
def __index__(self) -> int:
return 0
class SubClass(np.ndarray): ...
i8 = np.int64(1)
A = np.array([1])
B = A.view(SubClass).copy()
B_stack = np.array([[1], [1]]).view(SubClass)
C = [1]
def func(i: int, j: int, **kwargs: Any) -> SubClass:
return B
np.array(1, dtype=float)
np.array(1, copy=False)
np.array(1, order='F')
np.array(1, order=None)
np.array(1, subok=True)
np.array(1, ndmin=3)
np.array(1, str, copy=True, order='C', subok=False, ndmin=2)
np.asarray(A)
np.asarray(B)
np.asarray(C)
np.asanyarray(A)
np.asanyarray(B)
np.asanyarray(B, dtype=int)
np.asanyarray(C)
np.ascontiguousarray(A)
np.ascontiguousarray(B)
np.ascontiguousarray(C)
np.asfortranarray(A)
np.asfortranarray(B)
np.asfortranarray(C)
np.require(A)
np.require(B)
np.require(B, dtype=int)
np.require(B, requirements=None)
np.require(B, requirements="E")
np.require(B, requirements=["ENSUREARRAY"])
np.require(B, requirements={"F", "E"})
np.require(B, requirements=["C", "OWNDATA"])
np.require(B, requirements="W")
np.require(B, requirements="A")
np.require(C)
np.linspace(0, 2)
np.linspace(0.5, [0, 1, 2])
np.linspace([0, 1, 2], 3)
np.linspace(0j, 2)
np.linspace(0, 2, num=10)
np.linspace(0, 2, endpoint=True)
np.linspace(0, 2, retstep=True)
np.linspace(0j, 2j, retstep=True)
np.linspace(0, 2, dtype=bool)
np.linspace([0, 1], [2, 3], axis=Index())
np.logspace(0, 2, base=2)
np.logspace(0, 2, base=2)
np.logspace(0, 2, base=[1j, 2j], num=2)
np.geomspace(1, 2)
np.zeros_like(A)
np.zeros_like(C)
np.zeros_like(B)
np.zeros_like(B, dtype=np.int64)
np.ones_like(A)
np.ones_like(C)
np.ones_like(B)
np.ones_like(B, dtype=np.int64)
np.empty_like(A)
np.empty_like(C)
np.empty_like(B)
np.empty_like(B, dtype=np.int64)
np.full_like(A, i8)
np.full_like(C, i8)
np.full_like(B, i8)
np.full_like(B, i8, dtype=np.int64)
np.ones(1)
np.ones([1, 1, 1])
np.full(1, i8)
np.full([1, 1, 1], i8)
np.indices([1, 2, 3])
np.indices([1, 2, 3], sparse=True)
np.fromfunction(func, (3, 5))
np.identity(10)
np.atleast_1d(C)
np.atleast_1d(A)
np.atleast_1d(C, C)
np.atleast_1d(C, A)
np.atleast_1d(A, A)
np.atleast_2d(C)
np.atleast_3d(C)
np.vstack([C, C])
np.vstack([C, A])
np.vstack([A, A])
np.hstack([C, C])
np.stack([C, C])
np.stack([C, C], axis=0)
np.stack([C, C], out=B_stack)
np.block([[C, C], [C, C]])
np.block(A)
|
[
"honey.bhardwaj.18cse@bmu.edu.in"
] |
honey.bhardwaj.18cse@bmu.edu.in
|
5e736de360ea4a465167243925e0eb88349d59c9
|
7f7dd8b279a19b623c57723ffe8d788423bd359e
|
/Summary/WC2TPCEff/FlatEff/G4XSPiMinus_60A.py
|
5621c4610be96a1b387608af292c1e508dfaf8df
|
[] |
no_license
|
ElenaGramellini/LArIATPionXSAna
|
35925398b8f7d8ada14bf78664ca243a74b8e946
|
0fb26e915b987084f553d64560e5a4e6adcb65fa
|
refs/heads/master
| 2020-11-28T10:13:57.769651
| 2019-12-23T15:37:38
| 2019-12-23T15:37:38
| 229,779,168
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,899
|
py
|
from ROOT import *
import os
import math
import argparse
from ROOT import TEfficiency
from ROOT import gStyle , TCanvas , TGraphErrors
from array import array
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
def graphTruth():
fname = "PionMinusG4.txt"
kineticEnergy = []
crossSec = []
crossSec_el = []
crossSec_inel = []
zero = []
title = ""
with open(fname) as f:
for fLine in f.readlines():
w = fLine.split()
if is_number(w[0]):
runIn = int(w[0])
ke = float(w[1])
xstot = float(w[4])
kineticEnergy.append(ke)
crossSec.append(xstot)
zero.append(0.)
else:
if "for" not in fLine:
continue
title = fLine[9:]
#define some data points . . .
x = array('f', kineticEnergy )
y = array('f', crossSec)
y_el = array('f', crossSec_el)
y_inel = array('f', crossSec_inel)
exl = array('f', zero)
exr = array('f', zero)
nPoints=len(x)
# . . . and hand over to TGraphErros object
gr = TGraphErrors ( nPoints , x , y , exl, exr )
gr.SetTitle(title+"; Kinetic Energy [MeV]; Cross Section [barn]")
gr . GetXaxis().SetRangeUser(0,1000)
gr . GetYaxis().SetRangeUser(0,2.)
gr . SetLineWidth(2) ;
gr . SetLineColor(kGreen-2) ;
gr . SetFillColor(0)
return gr
c1=TCanvas("c1" ,"Data" ,200 ,10 ,700 ,700) #make nice
c1.SetGrid ()
gr = graphTruth()
f = TFile("../../FiducialVolumeStudy/askForInt/FidVol_Z90.0_19.0_-19.0_46.0_1.0_TrueInt_60A.root")
h = f.Get( "XS")
h.SetMarkerColor(kGreen-2)
h.SetLineColor(kGreen-2)
h.SetMarkerStyle(22)
h.SetMarkerSize(.72)
f3 = TFile("FlatEff0.8SameFidVol_Z86.0_19.0_-19.0_46.0_1.060.root")
h3 = f3.Get( "XS")
h3.SetMarkerColor(kBlack)
h3.SetLineColor(kBlack)
h3.SetMarkerStyle(22)
h3.SetMarkerSize(.72)
f5 = TFile("FlatEff0.5SameFidVol_Z86.0_19.0_-19.0_46.0_1.060.root")
h5 = f5.Get( "XS")
h5.SetMarkerColor(kRed)
h5.SetLineColor(kRed)
h5.SetMarkerStyle(22)
h5.SetMarkerSize(.72)
f4 = TFile("FlatEff0.3SameFidVol_Z86.0_19.0_-19.0_46.0_1.060.root")
h4 = f4.Get( "XS")
h4.SetMarkerColor(kOrange)
h4.SetLineColor(kOrange)
h4.SetMarkerStyle(22)
h4.SetMarkerSize(.72)
gr .Draw ( "APL" ) ;
h .Draw("same")
h3 .Draw("same")
h5 .Draw("same")
h4 .Draw("same")
legend = TLegend(.44,.70,.84,.89)
legend.AddEntry(gr,"G4 Prediction Tot XS")
legend.AddEntry(h,"True Interaction, Z [0., 90.] cm")
legend.AddEntry(h3,"Fid Vol, Z [0., 86.] cm, flat wc2tpc eff 0.8, 60A")
legend.AddEntry(h5,"Fid Vol, Z [0., 86.] cm, flat wc2tpc eff 0.5, 60A")
legend.AddEntry(h4,"Fid Vol, Z [0., 86.] cm, flat wc2tpc eff 0.3, 60A")
legend.Draw("same")
c1 . Update ()
raw_input()
|
[
"elena.gramellini@yale.edu"
] |
elena.gramellini@yale.edu
|
42aa2414994823c9aeed0028a4e7d2eed4a9863d
|
a01aec3906af00d3d40caf933b63d059043cd21d
|
/数据分析/数组快速挑选/布尔矩阵.py
|
51223ed4cc4d7e6c0b54921200b51f553ecf3247
|
[] |
no_license
|
liuaichao/python-work
|
d23dfcbffff95a50204ead88a809570304ba7995
|
a5dcd1d74f1a7c1728faaa60d26a3ddb9369f939
|
refs/heads/master
| 2021-07-04T16:03:16.443540
| 2020-09-27T06:51:09
| 2020-09-27T06:51:09
| 182,085,446
| 6
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 721
|
py
|
# -*- coding:utf-8 -*-
import numpy as np
from functools import reduce
a1 = ['我','你','他','她','他们','我们']
a2 = ['喜欢','想','拥有','练习','讨厌','学习']
a3 = ['豪车','别墅','python','数据分析','金钱','美酒']
arr_1 = np.column_stack(((np.column_stack((np.array(a1),np.array(a2)))),np.array(a3)))
arr_2 = np.column_stack(((np.column_stack((np.array(a1),np.array(a2)))),np.array(a3)))
np.random.shuffle(arr_1)
np.random.shuffle(arr_2)
random_ar = [[True if np.random.rand()>=0.5 else False for i in range(3)] for j in range(6)]
random_ar = np.array(random_ar)
print(arr_1)
print(arr_2)
print(random_ar)
al = np.where(random_ar,arr_1,arr_2)
print(al)
print(reduce(lambda x,y:x+y,al[2]))
|
[
"1395900558@qq.com"
] |
1395900558@qq.com
|
c7eb8d5964b35c8f24b6b4fd95646ca4e6d7ea49
|
e36c5a91306f8d8cf487368d3a1dfae4c03da3c0
|
/build/kobuki/kobuki_bumper2pc/catkin_generated/pkg.installspace.context.pc.py
|
3ffee9fd146d172cc2c7437ea17aeec32e5fdf02
|
[] |
no_license
|
DocDouze/RobMob
|
84ae5b96a16028586c9da2008f7c7772bdaa1334
|
6a2e7505eb2207d61b1c354cfd255075b1efbc73
|
refs/heads/master
| 2020-04-11T07:24:28.958201
| 2018-12-17T11:56:54
| 2018-12-17T11:56:54
| 161,607,677
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 574
|
py
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/aubailly/Bureau/RobMob/install/include".split(';') if "/home/aubailly/Bureau/RobMob/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;nodelet;pluginlib;sensor_msgs;kobuki_msgs".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lkobuki_bumper2pc_nodelet".split(';') if "-lkobuki_bumper2pc_nodelet" != "" else []
PROJECT_NAME = "kobuki_bumper2pc"
PROJECT_SPACE_DIR = "/home/aubailly/Bureau/RobMob/install"
PROJECT_VERSION = "0.7.6"
|
[
"quentin.aubailly@gmail.com"
] |
quentin.aubailly@gmail.com
|
dac3ebec146fc48e57be2d5e229e98045b9607a5
|
c0ad282ab743a315e2f252a627933cb168434c1d
|
/shapeworld/captioners/conjunction.py
|
5c6d9150477133f12ca4c36847ac38928275c407
|
[
"MIT"
] |
permissive
|
AlexKuhnle/ShapeWorld
|
6d1e16adc94e860abae99ade869f72575f573bc4
|
e720bf46e57fc01326d04d639fa6133d9c12158f
|
refs/heads/master
| 2021-07-09T00:02:33.808969
| 2021-04-19T11:10:52
| 2021-04-19T11:10:52
| 80,815,972
| 58
| 28
|
MIT
| 2021-04-19T11:10:53
| 2017-02-03T09:40:19
|
Python
|
UTF-8
|
Python
| false
| false
| 5,552
|
py
|
from copy import deepcopy
from shapeworld import util
from shapeworld.captions import Proposition
from shapeworld.captioners import WorldCaptioner
class ConjunctionCaptioner(WorldCaptioner):
# incorrect modes
# 0: first incorrect
# 1: second incorrect
# 2: both incorrect
def __init__(
self,
captioner,
pragmatical_redundancy_rate=1.0,
pragmatical_tautology_rate=0.0,
logical_redundancy_rate=0.0,
logical_tautology_rate=0.0,
logical_contradiction_rate=0.0,
incorrect_distribution=(1, 1, 1)
):
super(ConjunctionCaptioner, self).__init__(
internal_captioners=(captioner, deepcopy(captioner)),
pragmatical_redundancy_rate=pragmatical_redundancy_rate,
pragmatical_tautology_rate=pragmatical_tautology_rate,
logical_redundancy_rate=logical_redundancy_rate,
logical_tautology_rate=logical_tautology_rate,
logical_contradiction_rate=logical_contradiction_rate
)
self.captioner1, self.captioner2 = self.internal_captioners
self.incorrect_distribution = util.cumulative_distribution(incorrect_distribution)
def set_realizer(self, realizer):
if not super(ConjunctionCaptioner, self).set_realizer(realizer=realizer):
return False
assert 'conjunction' in realizer.propositions
return True
def pn_length(self):
return super(ConjunctionCaptioner, self).pn_length() * 2 + 1
def pn_symbols(self):
return super(ConjunctionCaptioner, self).pn_symbols() | \
{'{}-{}{}'.format(Proposition.__name__, 'conjunction', n) for n in range(2, 3)}
def pn_arity(self):
arity = super(ConjunctionCaptioner, self).pn_arity()
arity.update({'{}-{}{}'.format(Proposition.__name__, 'conjunction', n): n for n in range(2, 3)})
return arity
def sample_values(self, mode, predication):
assert predication.empty()
if not super(ConjunctionCaptioner, self).sample_values(mode=mode, predication=predication):
return False
predication1 = predication.copy()
predication2 = predication.copy()
if not self.captioner1.sample_values(mode=mode, predication=predication1):
return False
if not self.captioner2.sample_values(mode=mode, predication=predication2):
return False
for _ in range(self.__class__.MAX_SAMPLE_ATTEMPTS):
self.incorrect_mode = util.sample(self.incorrect_distribution)
if self.incorrect_mode in (0, 2) and not self.captioner1.incorrect_possible():
continue
elif self.incorrect_mode in (1, 2) and not self.captioner2.incorrect_possible():
continue
break
else:
return False
return True
def incorrect_possible(self):
return self.captioner1.incorrect_possible() or self.captioner2.incorrect_possible()
def model(self):
return util.merge_dicts(
dict1=super(ConjunctionCaptioner, self).model(),
dict2=dict(
incorrect_mode=self.incorrect_mode,
captioner1=self.captioner1.model(),
captioner2=self.captioner2.model()
)
)
def caption(self, predication, world):
assert predication.empty()
predication1 = predication.copy()
predication2 = predication1.sub_predication()
clause2 = self.captioner2.caption(predication=predication2, world=world)
if clause2 is None:
return None
clause1 = self.captioner1.caption(predication=predication1, world=world)
if clause1 is None:
return None
proposition = Proposition(proptype='conjunction', clauses=(clause1, clause2))
if not self.correct(caption=proposition, predication=predication):
return None
return proposition
def incorrect(self, caption, predication, world):
assert predication.empty()
if self.incorrect_mode == 0: # 0: first incorrect
predication1 = predication.copy()
if not self.captioner1.incorrect(caption=caption.clauses[0], predication=predication1, world=world):
return False
if caption.clauses[0].agreement(predication=predication1, world=world) >= 0.0:
return False
elif self.incorrect_mode == 1: # 1: second incorrect
predication2 = predication.copy()
if not self.captioner2.incorrect(caption=caption.clauses[1], predication=predication2, world=world):
return False
if caption.clauses[1].agreement(predication=predication2, world=world) >= 0.0:
return False
elif self.incorrect_mode == 2: # 2: both incorrect
predication1 = predication.copy()
if not self.captioner1.incorrect(caption=caption.clauses[0], predication=predication1, world=world):
return False
if caption.clauses[0].agreement(predication=predication1, world=world) >= 0.0:
return False
predication2 = predication.copy()
if not self.captioner2.incorrect(caption=caption.clauses[1], predication=predication2, world=world):
return False
if caption.clauses[1].agreement(predication=predication2, world=world) >= 0.0:
return False
return self.correct(caption=caption, predication=predication)
|
[
"aok25@cl.cam.ac.uk"
] |
aok25@cl.cam.ac.uk
|
3cf5de725a5578d429689fda8de9500589456d15
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03436/s889620274.py
|
7e3633505d9278af94081bda9da29bfc113148f5
|
[] |
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
| 672
|
py
|
H,W = map(int,input().split())
S = [input() for i in range(H)]
blk = sum(row.count('#') for row in S)
from collections import deque
dxy = [(0,1),(1,0),(0,-1),(-1,0)]
dist = [[0]*W for i in range(H)]
visited = [[0]*W for i in range(H)]
visited[0][0] = 1
q = deque([(0,0)])
while q:
x,y = q.popleft()
for dx,dy in dxy:
nx,ny = x+dx,y+dy
if not 0 <= nx < W: continue
if not 0 <= ny < H: continue
if visited[ny][nx]: continue
if S[ny][nx] == '#': continue
visited[ny][nx] = 1
dist[ny][nx] = dist[y][x] + 1
q.append((nx,ny))
if visited[-1][-1]:
print(H*W - blk - dist[-1][-1] - 1)
else:
print(-1)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
baec99e59f1be0ebe09c25bc8f1b105e189f52f4
|
e3c8f786d09e311d6ea1cab50edde040bf1ea988
|
/Incident-Response/Tools/grr/grr/server/grr_response_server/flows/general/checks_test.py
|
0be3d9152c25d7959746892d62bdb237f98c8a51
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
foss2cyber/Incident-Playbook
|
d1add8aec6e28a19e515754c6ce2e524d67f368e
|
a379a134c0c5af14df4ed2afa066c1626506b754
|
refs/heads/main
| 2023-06-07T09:16:27.876561
| 2021-07-07T03:48:54
| 2021-07-07T03:48:54
| 384,988,036
| 1
| 0
|
MIT
| 2021-07-11T15:45:31
| 2021-07-11T15:45:31
| null |
UTF-8
|
Python
| false
| false
| 4,368
|
py
|
#!/usr/bin/env python
"""Test the collector flows."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from absl import app
from grr_response_core import config
from grr_response_core.lib.parsers import config_file
from grr_response_core.lib.parsers import linux_file_parser
from grr_response_core.lib.rdfvalues import client as rdf_client
from grr_response_server.check_lib import checks
from grr_response_server.check_lib import checks_test_lib
from grr_response_server.flows.general import checks as flow_checks
from grr.test_lib import action_mocks
from grr.test_lib import flow_test_lib
from grr.test_lib import parser_test_lib
from grr.test_lib import test_lib
from grr.test_lib import vfs_test_lib
# pylint: mode=test
class TestCheckFlows(flow_test_lib.FlowTestsBaseclass,
checks_test_lib.HostCheckTest):
checks_loaded = False
def setUp(self):
super().setUp()
self.client_id = self.SetupClient(0)
# Only load the checks once.
if self.checks_loaded is False:
self.checks_loaded = self.LoadChecks()
if not self.checks_loaded:
raise RuntimeError("No checks to test.")
self.client_mock = action_mocks.FileFinderClientMock()
def SetupLinuxUser(self):
user = rdf_client.User(username="user1", homedir="/home/user1")
return self.SetupClient(0, system="Linux", users=[user], os_version="12.04")
def SetupWindowsUser(self):
return self.SetupClient(0, system="Windows", os_version="6.2")
def RunFlow(self, client_id):
with vfs_test_lib.FakeTestDataVFSOverrider():
session_id = flow_test_lib.TestFlowHelper(
flow_checks.CheckRunner.__name__,
client_mock=self.client_mock,
client_id=client_id,
creator=self.test_username)
results = flow_test_lib.GetFlowResults(client_id, session_id)
return session_id, {r.check_id: r for r in results}
def LoadChecks(self):
"""Load the checks, returning the names of the checks that were loaded."""
checks.CheckRegistry.Clear()
check_configs = ("sshd.yaml", "sw.yaml", "unix_login.yaml")
cfg_dir = os.path.join(config.CONFIG["Test.data_dir"], "checks")
chk_files = [os.path.join(cfg_dir, f) for f in check_configs]
checks.LoadChecksFromFiles(chk_files)
return list(checks.CheckRegistry.checks.keys())
def testSelectArtifactsForChecks(self):
client_id = self.SetupLinuxUser()
session_id, _ = self.RunFlow(client_id)
state = flow_test_lib.GetFlowState(self.client_id, session_id)
self.assertIn("DebianPackagesStatus", state.artifacts_wanted)
self.assertIn("SshdConfigFile", state.artifacts_wanted)
client_id = self.SetupWindowsUser()
session_id, _ = self.RunFlow(client_id)
state = flow_test_lib.GetFlowState(self.client_id, session_id)
self.assertIn("WMIInstalledSoftware", state.artifacts_wanted)
def testCheckFlowSelectsChecks(self):
"""Confirm the flow runs checks for a target machine."""
client_id = self.SetupLinuxUser()
_, results = self.RunFlow(client_id)
expected = ["SHADOW-HASH", "SSHD-CHECK", "SSHD-PERMS", "SW-CHECK"]
self.assertRanChecks(expected, results)
@parser_test_lib.WithParser("Sshd", config_file.SshdConfigParser)
@parser_test_lib.WithParser("Pswd", linux_file_parser.LinuxSystemPasswdParser)
def testChecksProcessResultContext(self):
"""Test the flow returns parser results."""
client_id = self.SetupLinuxUser()
_, results = self.RunFlow(client_id)
# Detected by result_context: PARSER
exp = "Found: Sshd allows protocol 1."
self.assertCheckDetectedAnom("SSHD-CHECK", results, exp)
# Detected by result_context: RAW
exp = "Found: The filesystem supports stat."
found = ["/etc/ssh/sshd_config"]
self.assertCheckDetectedAnom("SSHD-PERMS", results, exp, found)
# Detected by result_context: ANOMALY
exp = "Found: Unix system account anomalies."
found = [
"Accounts with invalid gid.", "Mismatched passwd and shadow files."
]
self.assertCheckDetectedAnom("ODD-PASSWD", results, exp, found)
# No findings.
self.assertCheckUndetected("SHADOW-HASH", results)
self.assertCheckUndetected("SW-CHECK", results)
def main(argv):
# Run the full test suite
test_lib.main(argv)
if __name__ == "__main__":
app.run(main)
|
[
"a.songer@protonmail.com"
] |
a.songer@protonmail.com
|
beb376cb4b79225dad11e14942e96e80e8dffa48
|
21f81fce20e657c175de388d5f6b8b8a78ac3ee9
|
/examples/bend-flux.py
|
f3fe0a3dd83abcba8e09c5d2080eb1d63e51f0b1
|
[] |
no_license
|
tnakaicode/pymeep-example
|
c23a9be827a37477a3328668a62b0486413a31d7
|
40c9c77d5e26cf43771b57af95c324a5225515ef
|
refs/heads/master
| 2021-01-08T02:01:47.641017
| 2020-02-20T14:22:07
| 2020-02-20T14:22:07
| 241,879,598
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,518
|
py
|
# -*- coding: utf-8 -*-
# transmission around a 90-degree waveguide bend in 2d
from __future__ import division
import meep as mp
import numpy as np
import matplotlib.pyplot as plt
resolution = 10 # pixels/um
sx = 16 # size of cell in X direction
sy = 32 # size of cell in Y direction
cell = mp.Vector3(sx, sy, 0)
dpml = 1.0
pml_layers = [mp.PML(dpml)]
pad = 4 # padding distance between waveguide and cell edge
w = 1 # width of waveguide
wvg_xcen = 0.5*(sx-w-2*pad) # x center of vert. wvg
wvg_ycen = -0.5*(sy-w-2*pad) # y center of horiz. wvg
geometry = [mp.Block(size=mp.Vector3(mp.inf, w, mp.inf),
center=mp.Vector3(0, wvg_ycen, 0),
material=mp.Medium(epsilon=12))]
fcen = 0.15 # pulse center frequency
df = 0.1 # pulse width (in frequency)
sources = [mp.Source(mp.GaussianSource(fcen, fwidth=df),
component=mp.Ez,
center=mp.Vector3(-0.5*sx+dpml, wvg_ycen, 0),
size=mp.Vector3(0, w, 0))]
sim = mp.Simulation(cell_size=cell,
boundary_layers=pml_layers,
geometry=geometry,
sources=sources,
resolution=resolution)
nfreq = 100 # number of frequencies at which to compute flux
# reflected flux
refl_fr = mp.FluxRegion(
center=mp.Vector3(-0.5*sx+dpml+0.5, wvg_ycen, 0), size=mp.Vector3(0, 2*w, 0))
refl = sim.add_flux(fcen, df, nfreq, refl_fr)
# transmitted flux
tran_fr = mp.FluxRegion(center=mp.Vector3(
0.5*sx-dpml, wvg_ycen, 0), size=mp.Vector3(0, 2*w, 0))
tran = sim.add_flux(fcen, df, nfreq, tran_fr)
pt = mp.Vector3(0.5*sx-dpml-0.5, wvg_ycen)
sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, pt, 1e-3))
# for normalization run, save flux fields data for reflection plane
straight_refl_data = sim.get_flux_data(refl)
# save incident power for transmission plane
straight_tran_flux = mp.get_fluxes(tran)
sim.reset_meep()
geometry = [mp.Block(mp.Vector3(sx-pad, w, mp.inf), center=mp.Vector3(-0.5*pad, wvg_ycen), material=mp.Medium(epsilon=12)),
mp.Block(mp.Vector3(w, sy-pad, mp.inf), center=mp.Vector3(wvg_xcen, 0.5*pad), material=mp.Medium(epsilon=12))]
sim = mp.Simulation(cell_size=cell,
boundary_layers=pml_layers,
geometry=geometry,
sources=sources,
resolution=resolution)
# reflected flux
refl = sim.add_flux(fcen, df, nfreq, refl_fr)
tran_fr = mp.FluxRegion(center=mp.Vector3(
wvg_xcen, 0.5*sy-dpml-0.5, 0), size=mp.Vector3(2*w, 0, 0))
tran = sim.add_flux(fcen, df, nfreq, tran_fr)
# for normal run, load negated fields to subtract incident from refl. fields
sim.load_minus_flux_data(refl, straight_refl_data)
pt = mp.Vector3(wvg_xcen, 0.5*sy-dpml-0.5)
sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, pt, 1e-3))
bend_refl_flux = mp.get_fluxes(refl)
bend_tran_flux = mp.get_fluxes(tran)
flux_freqs = mp.get_flux_freqs(refl)
wl = []
Rs = []
Ts = []
for i in range(nfreq):
wl = np.append(wl, 1/flux_freqs[i])
Rs = np.append(Rs, -bend_refl_flux[i]/straight_tran_flux[i])
Ts = np.append(Ts, bend_tran_flux[i]/straight_tran_flux[i])
if mp.am_master():
plt.figure()
plt.plot(wl, Rs, 'bo-', label='reflectance')
plt.plot(wl, Ts, 'ro-', label='transmittance')
plt.plot(wl, 1-Rs-Ts, 'go-', label='loss')
plt.axis([5.0, 10.0, 0, 1])
plt.xlabel("wavelength (μm)")
plt.legend(loc="upper right")
plt.show()
|
[
"tnakaicode@gmail.com"
] |
tnakaicode@gmail.com
|
78ab9aaea1b7def48a3918b228987989375f6fda
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/10/usersdata/137/10363/submittedfiles/testes.py
|
3f1eddb1bbd0d48889e66c57f0feb844589958e4
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 457
|
py
|
# -*- coding: utf-8 -*-
from __future__ import division
import math
a=input('a:')
b=input('b:')
c=input('c:')
d=input('d:')
if a>b and a>c and a>d:
maior=a
elif b>a and b>c and b>d:
maior=a
elif c>a and c>b and c>d:
maior=c
elif d>a and d>b and d>c:
maior=d
elif a<b and a<c and a<d:
menor=a
elif b<a and b<c and b<d:
menor=b
elif c<a and c<b and c<d:
menor=c
elif d<a and d<b and d<c:
menor=d
print ('%d,%d' %(menor,maior))
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
3678749b295aba294063b492e55f9765d25c127f
|
80f244addbd16914b3391f549670e7164b60e0cb
|
/Realestate4/Tagent4/migrations/0001_initial.py
|
7d6f31c659a77640ff373ae56d72c6f5532871f4
|
[] |
no_license
|
Jagadishbommareddy/agentrest
|
df3817bb08b63e95f985935ebe7853492594619e
|
4b5e7a2dcfc8a0f39e4a6a94fe3cde8232aece97
|
refs/heads/master
| 2021-06-27T05:03:30.703762
| 2017-09-14T15:37:57
| 2017-09-14T15:37:57
| 103,550,487
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,807
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-14 13:43
from __future__ import unicode_literals
import Tagent4.validations
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Address',
fields=[
('address_id', models.AutoField(primary_key=True, serialize=False)),
('address1', models.CharField(max_length=100)),
('address2', models.CharField(max_length=100)),
('city', models.CharField(max_length=20, validators=[Tagent4.validations.validate_city])),
('state', models.CharField(max_length=20, validators=[Tagent4.validations.validate_state])),
('landmark', models.CharField(max_length=20, validators=[Tagent4.validations.validate_landmark])),
('pincode', models.IntegerField()),
],
),
migrations.CreateModel(
name='AgentReferal',
fields=[
('referal_id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=30)),
('verified', models.BooleanField(default=True)),
],
),
migrations.CreateModel(
name='ContactInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mobile_number', models.CharField(max_length=15)),
('phone_number', models.CharField(max_length=15)),
('email_id', models.EmailField(max_length=254)),
],
),
migrations.CreateModel(
name='Location',
fields=[
('location_id', models.AutoField(primary_key=True, serialize=False)),
('city', models.CharField(blank=True, max_length=20, null=True)),
('state', models.CharField(blank=True, max_length=20, null=True)),
],
),
migrations.CreateModel(
name='Media',
fields=[
('media_id', models.AutoField(primary_key=True, serialize=False)),
('media_name', models.CharField(max_length=20)),
('media_path', models.FileField(upload_to='documents/')),
],
),
migrations.CreateModel(
name='PropertyType',
fields=[
('propert_type_id', models.AutoField(primary_key=True, serialize=False)),
('description', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='Agent',
fields=[
('media_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, to='Tagent4.Media')),
('contactinfo_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, to='Tagent4.ContactInfo')),
('agent_id', models.AutoField(primary_key=True, serialize=False)),
('first_name', models.CharField(max_length=20, validators=[Tagent4.validations.validate_first_name])),
('last_name', models.CharField(max_length=20, validators=[Tagent4.validations.validate_last_name])),
('age', models.IntegerField()),
('education', models.CharField(max_length=50, validators=[Tagent4.validations.validate_education])),
('company_name', models.CharField(max_length=50)),
('specialization', models.CharField(max_length=100, validators=[Tagent4.validations.validate_specelization])),
('experence', models.IntegerField()),
('agent_notes', models.TextField()),
('property_type', models.ManyToManyField(to='Tagent4.PropertyType')),
],
bases=('Tagent4.contactinfo', 'Tagent4.media'),
),
migrations.AddField(
model_name='location',
name='agent',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Tagent4.Agent'),
),
migrations.AddField(
model_name='agentreferal',
name='agent',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Tagent4.Agent'),
),
migrations.AddField(
model_name='address',
name='agent',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Tagent4.Agent'),
),
]
|
[
"noreply@github.com"
] |
Jagadishbommareddy.noreply@github.com
|
62c80f119ab5024fb4c6c1e5c2d0e6081efe14b8
|
3d19e1a316de4d6d96471c64332fff7acfaf1308
|
/Users/A/alokmaheshwari/follow-url.py
|
149494399874ca6fa3215219ddc76469be641698
|
[] |
no_license
|
BerilBBJ/scraperwiki-scraper-vault
|
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
|
65ea6a943cc348a9caf3782b900b36446f7e137d
|
refs/heads/master
| 2021-12-02T23:55:58.481210
| 2013-09-30T17:02:59
| 2013-09-30T17:02:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,246
|
py
|
import mechanize
import lxml.html
import scraperwiki
surl = "http://main.exoclick.com/click.php?data=eGhhbXN0ZXJ8MjQxMjQ3fDB8aHR0cCUzQSUyRiUyRnRyay5rbGlja3RyZWsuY29tJTJGYmFzZS5waHAlM0ZjJTNEODMlMjZrZXklM0Q4NzNkNTA5YWZiNTRjM2RiZjNiMjFiYTFjOGQyMzAxZiUyNnNvdXJjZSUzRHhoYW1zdGVyLmNvbXwzNDk1NHx8MHwxMDB8MTM1MDA3MDUxM3x4aGFtc3Rlci5jb218NDYuNDMuNTUuODd8MjQxMjQ3LTUyMDgxODR8NTIwODE4NHwxMDA2MzN8Mnw3fGE5MjgzZjg2MDBhMjJmNDc1NDI1NDVmODBlNDhmN2Ux&js=1"
br = mechanize.Browser()
#br.set_all_readonly(False) # allow everything to be written to
br.set_handle_robots(False) # no robots
br.set_handle_refresh(True) # can sometimes hang without this
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
response = br.open(surl)
print response.read()
br.form = list(br.forms())[0]
response = br.submit()
print response.geturl()
print response.read()
#br.set_handle_refresh(True) # can sometimes hang without this
#response1 = br.response() # get the response again
#print response1.read() # can apply lxml.html.fromstring()
import mechanize
import lxml.html
import scraperwiki
surl = "http://main.exoclick.com/click.php?data=eGhhbXN0ZXJ8MjQxMjQ3fDB8aHR0cCUzQSUyRiUyRnRyay5rbGlja3RyZWsuY29tJTJGYmFzZS5waHAlM0ZjJTNEODMlMjZrZXklM0Q4NzNkNTA5YWZiNTRjM2RiZjNiMjFiYTFjOGQyMzAxZiUyNnNvdXJjZSUzRHhoYW1zdGVyLmNvbXwzNDk1NHx8MHwxMDB8MTM1MDA3MDUxM3x4aGFtc3Rlci5jb218NDYuNDMuNTUuODd8MjQxMjQ3LTUyMDgxODR8NTIwODE4NHwxMDA2MzN8Mnw3fGE5MjgzZjg2MDBhMjJmNDc1NDI1NDVmODBlNDhmN2Ux&js=1"
br = mechanize.Browser()
#br.set_all_readonly(False) # allow everything to be written to
br.set_handle_robots(False) # no robots
br.set_handle_refresh(True) # can sometimes hang without this
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
response = br.open(surl)
print response.read()
br.form = list(br.forms())[0]
response = br.submit()
print response.geturl()
print response.read()
#br.set_handle_refresh(True) # can sometimes hang without this
#response1 = br.response() # get the response again
#print response1.read() # can apply lxml.html.fromstring()
|
[
"pallih@kaninka.net"
] |
pallih@kaninka.net
|
bf90aef5300e024c4e7977593d9d595e0838b6e1
|
c24212464eb84588edc7903a8905f2a881d578c4
|
/migrations/versions/9db4f46dd61b_private_messages.py
|
3f2b1c16b6007c7b1b7217c12ff58710f815a2b8
|
[] |
no_license
|
the-akira/Flask-Library
|
c533dc2fd1ac2d3d9e2732e7c7bed5b8cc7ca4bd
|
833e77660053b1e95975ccdf8bf41a035722975c
|
refs/heads/master
| 2023-05-25T12:08:15.898134
| 2023-02-07T23:36:50
| 2023-02-07T23:36:50
| 205,951,022
| 5
| 2
| null | 2023-02-15T22:08:36
| 2019-09-02T23:26:50
|
HTML
|
UTF-8
|
Python
| false
| false
| 1,724
|
py
|
"""private messages
Revision ID: 9db4f46dd61b
Revises: 46e80c86a0fb
Create Date: 2022-05-16 01:53:35.196659
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9db4f46dd61b'
down_revision = '46e80c86a0fb'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('message',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('sender_id', sa.Integer(), nullable=True),
sa.Column('recipient_id', sa.Integer(), nullable=True),
sa.Column('body', sa.Text(), nullable=False),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['recipient_id'], ['user.id'], ),
sa.ForeignKeyConstraint(['sender_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_message_timestamp'), 'message', ['timestamp'], unique=False)
op.create_foreign_key(None, 'analysis', 'user', ['user_id'], ['id'])
op.alter_column('book', 'image_book',
existing_type=sa.VARCHAR(length=20),
nullable=True)
op.add_column('user', sa.Column('last_message_read_time', sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user', 'last_message_read_time')
op.alter_column('book', 'image_book',
existing_type=sa.VARCHAR(length=20),
nullable=False)
op.drop_constraint(None, 'analysis', type_='foreignkey')
op.drop_index(op.f('ix_message_timestamp'), table_name='message')
op.drop_table('message')
# ### end Alembic commands ###
|
[
"gabrielfelippe90@gmail.com"
] |
gabrielfelippe90@gmail.com
|
15fbb58d1ab6e4d3ad5e71efc5289fb5538ba0c4
|
3ea99519e25ec1bb605947a94b7a5ceb79b2870a
|
/modern_python/modernpython/lib/python3.6/site-packages/mypy/erasetype.py
|
48cd31487038c3a7b492617d7348a7241574e77e
|
[] |
no_license
|
tech-cow/spazzatura
|
437c7502a0654a3d3db2fd1e96ce2e3e506243c0
|
45fc0932186d2ef0c5044745a23507a692cfcc26
|
refs/heads/master
| 2022-09-01T12:01:11.309768
| 2018-11-15T04:32:03
| 2018-11-15T04:32:03
| 130,414,653
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,635
|
py
|
from typing import Optional, Container, Callable
from mypy.types import (
Type, TypeVisitor, UnboundType, AnyType, NoneTyp, TypeVarId, Instance, TypeVarType,
CallableType, TupleType, TypedDictType, UnionType, Overloaded, ErasedType, PartialType,
DeletedType, TypeTranslator, TypeList, UninhabitedType, TypeType, TypeOfAny
)
from mypy import experiments
def erase_type(typ: Type) -> Type:
"""Erase any type variables from a type.
Also replace tuple types with the corresponding concrete types. Replace
callable types with empty callable types.
Examples:
A -> A
B[X] -> B[Any]
Tuple[A, B] -> tuple
Callable[...] -> Callable[[], None]
Type[X] -> Type[Any]
"""
return typ.accept(EraseTypeVisitor())
class EraseTypeVisitor(TypeVisitor[Type]):
def visit_unbound_type(self, t: UnboundType) -> Type:
assert False, 'Not supported'
def visit_any(self, t: AnyType) -> Type:
return t
def visit_none_type(self, t: NoneTyp) -> Type:
return t
def visit_uninhabited_type(self, t: UninhabitedType) -> Type:
return t
def visit_erased_type(self, t: ErasedType) -> Type:
# Should not get here.
raise RuntimeError()
def visit_partial_type(self, t: PartialType) -> Type:
# Should not get here.
raise RuntimeError()
def visit_deleted_type(self, t: DeletedType) -> Type:
return t
def visit_instance(self, t: Instance) -> Type:
return Instance(t.type, [AnyType(TypeOfAny.special_form)] * len(t.args), t.line)
def visit_type_var(self, t: TypeVarType) -> Type:
return AnyType(TypeOfAny.special_form)
def visit_callable_type(self, t: CallableType) -> Type:
# We must preserve the fallback type for overload resolution to work.
ret_type = NoneTyp() # type: Type
return CallableType([], [], [], ret_type, t.fallback)
def visit_overloaded(self, t: Overloaded) -> Type:
return t.items()[0].accept(self)
def visit_tuple_type(self, t: TupleType) -> Type:
return t.fallback.accept(self)
def visit_typeddict_type(self, t: TypedDictType) -> Type:
return t.fallback.accept(self)
def visit_union_type(self, t: UnionType) -> Type:
erased_items = [erase_type(item) for item in t.items]
return UnionType.make_simplified_union(erased_items)
def visit_type_type(self, t: TypeType) -> Type:
return TypeType.make_normalized(t.item.accept(self), line=t.line)
def erase_typevars(t: Type, ids_to_erase: Optional[Container[TypeVarId]] = None) -> Type:
"""Replace all type variables in a type with any,
or just the ones in the provided collection.
"""
def erase_id(id: TypeVarId) -> bool:
if ids_to_erase is None:
return True
return id in ids_to_erase
return t.accept(TypeVarEraser(erase_id, AnyType(TypeOfAny.special_form)))
def replace_meta_vars(t: Type, target_type: Type) -> Type:
"""Replace unification variables in a type with the target type."""
return t.accept(TypeVarEraser(lambda id: id.is_meta_var(), target_type))
class TypeVarEraser(TypeTranslator):
"""Implementation of type erasure"""
def __init__(self, erase_id: Callable[[TypeVarId], bool], replacement: Type) -> None:
self.erase_id = erase_id
self.replacement = replacement
def visit_type_var(self, t: TypeVarType) -> Type:
if self.erase_id(t.id):
return self.replacement
return t
|
[
"yuzhoujr@yuzhou-7480.internal.synopsys.com"
] |
yuzhoujr@yuzhou-7480.internal.synopsys.com
|
3bbe155023b3a97c5e91f1df5960570a3fcf09b0
|
154fd16fe7828cb6925ca8f90e049b754ce06413
|
/lino_book/projects/lydia/tests/dumps/18.12.0/finan_journalentryitem.py
|
d520f010ff31a28ccbf9549667aba2fb3c9447b9
|
[
"BSD-2-Clause"
] |
permissive
|
lino-framework/book
|
68de2f8d130266bd9d9de7576d30597b3cde1c91
|
4eab916832cd8f48ff1b9fc8c2789f0b437da0f8
|
refs/heads/master
| 2021-03-27T16:16:55.403940
| 2021-03-15T02:53:50
| 2021-03-15T02:53:50
| 58,830,342
| 3
| 9
|
BSD-2-Clause
| 2021-03-09T13:11:27
| 2016-05-14T21:02:17
|
Python
|
UTF-8
|
Python
| false
| false
| 205
|
py
|
# -*- coding: UTF-8 -*-
logger.info("Loading 0 objects to table finan_journalentryitem...")
# fields: id, seqno, match, amount, dc, remark, account, partner, date, voucher
loader.flush_deferred_objects()
|
[
"luc.saffre@gmail.com"
] |
luc.saffre@gmail.com
|
e4f283777aca8b53ab305f01ade13de7a4711d27
|
c7f4b7c79d8fc3491c01b46bb5c78192d3e0c5ae
|
/tests/test_UnweightedSearchTree___call__.py
|
29dbcb6640eb211d089579d2046068bc20a37184
|
[
"MIT"
] |
permissive
|
Abjad/abjad-ext-nauert
|
37d4ea2121b839d2c9388e925b241795cd5a0ae7
|
ad6c649c79d096ce905a7a8e80cf9d7154727424
|
refs/heads/main
| 2023-08-24T15:32:15.519856
| 2023-08-02T15:05:08
| 2023-08-02T15:05:08
| 132,930,780
| 4
| 2
|
MIT
| 2023-04-15T14:18:20
| 2018-05-10T17:05:23
|
Python
|
UTF-8
|
Python
| false
| false
| 1,648
|
py
|
import abjadext.nauert
def test_UnweightedSearchTree___call___01():
definition = {2: {2: {2: None}, 3: None}, 5: None}
search_tree = abjadext.nauert.UnweightedSearchTree(definition)
q_grid = abjadext.nauert.QGrid()
a = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent(0, ["A"], index=1), 0, 1
)
b = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 5), ["B"], index=2), 0, 1
)
c = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 4), ["C"], index=3), 0, 1
)
d = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 3), ["D"], index=4), 0, 1
)
e = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((2, 5), ["E"], index=5), 0, 1
)
f = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 2), ["F"], index=6), 0, 1
)
g = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((3, 5), ["G"], index=7), 0, 1
)
h = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((2, 3), ["H"], index=8), 0, 1
)
i = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((3, 4), ["I"], index=9), 0, 1
)
j = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((4, 5), ["J"], index=10), 0, 1
)
k = abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent(1, ["K"], index=11), 0, 1
)
q_grid.fit_q_events([a, b, c, d, e, f, g, h, i, j, k])
q_grids = search_tree(q_grid)
assert q_grids[0].root_node.rtm_format == "(1 (1 1))"
assert q_grids[1].root_node.rtm_format == "(1 (1 1 1 1 1))"
|
[
"josiah.oberholtzer@gmail.com"
] |
josiah.oberholtzer@gmail.com
|
62753c6572ceae98064f37c7803fd7fad44def88
|
fa99ad8197e9accce25ae31a197e11c84683daaf
|
/kakao/phone.py
|
42ffdb298d160f0792868d7216980fb6aed6bad9
|
[] |
no_license
|
vxda7/HomeAlgorithm
|
933c3afae5fb81dce2707790544c0f4c3cdc44f9
|
9a8437913ba579b9a584f16048be81ae1d17d3e6
|
refs/heads/master
| 2020-09-08T16:37:02.089305
| 2020-07-10T06:58:58
| 2020-07-10T06:58:58
| 221,185,705
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,273
|
py
|
def solution(numbers, hand):
answer = ''
rctonum = {"*":[0, 0], "#": [2, 0], 1:[0, 3], 2:[1, 3], 3: [2, 3], 4: [0, 2], 5: [1, 2], 6: [2, 2], 7:[0, 1], 8: [1, 1], 9:[2, 1], 0:[1, 0]}
nowleft = [0, 0]
nowright = [2, 0]
leftdis, rightdis = 0, 0
for one in numbers:
if one == 1 or one == 4 or one == 7:
answer += "L"
nowleft = rctonum[one]
elif one == 3 or one == 6 or one == 9:
answer += "R"
nowright = rctonum[one]
else: # 2, 5, 8, 0 일 때
leftdis = abs(rctonum[one][0] - nowleft[0]) + abs(rctonum[one][1] - nowleft[1])
rightdis = abs(rctonum[one][0] - nowright[0]) + abs(rctonum[one][1] - nowright[1])
if leftdis == rightdis:
if hand == "right":
answer += "R"
nowright = rctonum[one]
else:
answer += "L"
nowleft = rctonum[one]
elif leftdis > rightdis:
answer += "R"
nowright = rctonum[one]
elif leftdis < rightdis:
answer += "L"
nowleft = rctonum[one]
return answer
a = solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5], "right")
print(a)
|
[
"vxda77@gmail.com"
] |
vxda77@gmail.com
|
7fbc51dbe061ef625e5af45342ec77179b3f8c3f
|
e5e2b7da41fda915cb849f031a0223e2ac354066
|
/sdk/python/pulumi_azure_native/sql/v20190601preview/_enums.py
|
25bbca7a57d4b073a45cbd5b58f250f0b0307a61
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
johnbirdau/pulumi-azure-native
|
b7d3bdddeb7c4b319a7e43a892ddc6e25e3bfb25
|
d676cc331caa0694d8be99cb90b93fa231e3c705
|
refs/heads/master
| 2023-05-06T06:48:05.040357
| 2021-06-01T20:42:38
| 2021-06-01T20:42:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,026
|
py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'AdministratorType',
'CatalogCollationType',
'CreateMode',
'DatabaseLicenseType',
'DatabaseReadScale',
'IdentityType',
'ManagedDatabaseCreateMode',
'SampleName',
'ServerPublicNetworkAccess',
'StorageAccountType',
'SyncConflictResolutionPolicy',
'SyncDirection',
'SyncMemberDbType',
]
class AdministratorType(str, Enum):
"""
Type of the sever administrator.
"""
ACTIVE_DIRECTORY = "ActiveDirectory"
class CatalogCollationType(str, Enum):
"""
Collation of the metadata catalog.
"""
DATABAS_E_DEFAULT = "DATABASE_DEFAULT"
SQ_L_LATIN1_GENERAL_CP1_C_I_AS = "SQL_Latin1_General_CP1_CI_AS"
class CreateMode(str, Enum):
"""
Specifies the mode of database creation.
Default: regular database creation.
Copy: creates a database as a copy of an existing database. sourceDatabaseId must be specified as the resource ID of the source database.
Secondary: creates a database as a secondary replica of an existing database. sourceDatabaseId must be specified as the resource ID of the existing primary database.
PointInTimeRestore: Creates a database by restoring a point in time backup of an existing database. sourceDatabaseId must be specified as the resource ID of the existing database, and restorePointInTime must be specified.
Recovery: Creates a database by restoring a geo-replicated backup. sourceDatabaseId must be specified as the recoverable database resource ID to restore.
Restore: Creates a database by restoring a backup of a deleted database. sourceDatabaseId must be specified. If sourceDatabaseId is the database's original resource ID, then sourceDatabaseDeletionDate must be specified. Otherwise sourceDatabaseId must be the restorable dropped database resource ID and sourceDatabaseDeletionDate is ignored. restorePointInTime may also be specified to restore from an earlier point in time.
RestoreLongTermRetentionBackup: Creates a database by restoring from a long term retention vault. recoveryServicesRecoveryPointResourceId must be specified as the recovery point resource ID.
Copy, Secondary, and RestoreLongTermRetentionBackup are not supported for DataWarehouse edition.
"""
DEFAULT = "Default"
COPY = "Copy"
SECONDARY = "Secondary"
POINT_IN_TIME_RESTORE = "PointInTimeRestore"
RESTORE = "Restore"
RECOVERY = "Recovery"
RESTORE_EXTERNAL_BACKUP = "RestoreExternalBackup"
RESTORE_EXTERNAL_BACKUP_SECONDARY = "RestoreExternalBackupSecondary"
RESTORE_LONG_TERM_RETENTION_BACKUP = "RestoreLongTermRetentionBackup"
ONLINE_SECONDARY = "OnlineSecondary"
class DatabaseLicenseType(str, Enum):
"""
The license type to apply for this database. `LicenseIncluded` if you need a license, or `BasePrice` if you have a license and are eligible for the Azure Hybrid Benefit.
"""
LICENSE_INCLUDED = "LicenseIncluded"
BASE_PRICE = "BasePrice"
class DatabaseReadScale(str, Enum):
"""
The state of read-only routing. If enabled, connections that have application intent set to readonly in their connection string may be routed to a readonly secondary replica in the same region.
"""
ENABLED = "Enabled"
DISABLED = "Disabled"
class IdentityType(str, Enum):
"""
The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource.
"""
NONE = "None"
SYSTEM_ASSIGNED = "SystemAssigned"
USER_ASSIGNED = "UserAssigned"
class ManagedDatabaseCreateMode(str, Enum):
"""
Managed database create mode. PointInTimeRestore: Create a database by restoring a point in time backup of an existing database. SourceDatabaseName, SourceManagedInstanceName and PointInTime must be specified. RestoreExternalBackup: Create a database by restoring from external backup files. Collation, StorageContainerUri and StorageContainerSasToken must be specified. Recovery: Creates a database by restoring a geo-replicated backup. RecoverableDatabaseId must be specified as the recoverable database resource ID to restore. RestoreLongTermRetentionBackup: Create a database by restoring from a long term retention backup (longTermRetentionBackupResourceId required).
"""
DEFAULT = "Default"
RESTORE_EXTERNAL_BACKUP = "RestoreExternalBackup"
POINT_IN_TIME_RESTORE = "PointInTimeRestore"
RECOVERY = "Recovery"
RESTORE_LONG_TERM_RETENTION_BACKUP = "RestoreLongTermRetentionBackup"
class SampleName(str, Enum):
"""
The name of the sample schema to apply when creating this database.
"""
ADVENTURE_WORKS_LT = "AdventureWorksLT"
WIDE_WORLD_IMPORTERS_STD = "WideWorldImportersStd"
WIDE_WORLD_IMPORTERS_FULL = "WideWorldImportersFull"
class ServerPublicNetworkAccess(str, Enum):
"""
Whether or not public endpoint access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'
"""
ENABLED = "Enabled"
DISABLED = "Disabled"
class StorageAccountType(str, Enum):
"""
The storage account type used to store backups for this database.
"""
GRS = "GRS"
LRS = "LRS"
ZRS = "ZRS"
class SyncConflictResolutionPolicy(str, Enum):
"""
Conflict resolution policy of the sync group.
"""
HUB_WIN = "HubWin"
MEMBER_WIN = "MemberWin"
class SyncDirection(str, Enum):
"""
Sync direction of the sync member.
"""
BIDIRECTIONAL = "Bidirectional"
ONE_WAY_MEMBER_TO_HUB = "OneWayMemberToHub"
ONE_WAY_HUB_TO_MEMBER = "OneWayHubToMember"
class SyncMemberDbType(str, Enum):
"""
Database type of the sync member.
"""
AZURE_SQL_DATABASE = "AzureSqlDatabase"
SQL_SERVER_DATABASE = "SqlServerDatabase"
|
[
"noreply@github.com"
] |
johnbirdau.noreply@github.com
|
2bc19d1d207111ed43b63e5866fcca751932a569
|
f0bbca88acab9f75a534c8b228f04abac33735f3
|
/python/272.ClosestBinarySearchTreeValueII.py
|
bade89981c709daef2f4fb2d7f428729fef5917c
|
[] |
no_license
|
MaxPoon/Leetcode
|
e4327a60d581f715a7c818b8e8e8aa472ed776c1
|
15f012927dc34b5d751af6633caa5e8882d26ff7
|
refs/heads/master
| 2020-09-17T05:33:13.877346
| 2019-05-09T04:34:54
| 2019-05-09T04:34:54
| 67,481,937
| 15
| 8
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 954
|
py
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from heapq import heappush, heappop
class Solution(object):
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
:rtype: List[int]
"""
heap = []
self.closestRecursive(root, target, heap, k)
return [closest[1] for closest in heap]
def closestRecursive(self, node, target, heap, k):
diff = abs(node.val - target)
if len(heap) < k:
heappush(heap, (-diff, node.val))
elif diff < -heap[0][0]:
heappop(heap)
heappush(heap, (-diff, node.val))
if node.left and (len(heap)<k or diff < -heap[0][0] or node.val >= target):
self.closestRecursive(node.left, target, heap, k)
if node.right and (len(heap)<k or diff < -heap[0][0] or node.val<=target):
self.closestRecursive(node.right, target, heap, k)
|
[
"maxpanziyuan@gmail.com"
] |
maxpanziyuan@gmail.com
|
fc24a39a70270e955fe523e8fc7e16760c7f5e10
|
9009ad47bc1d6adf8ee6d0f2f2b3125dea44c0aa
|
/cf-999-a.py
|
4a0a9b2c17abfd11d87b3733bfd2c74232bfddd1
|
[] |
no_license
|
luctivud/Coding-Trash
|
42e880624f39a826bcaab9b6194add2c9b3d71fc
|
35422253f6169cc98e099bf83c650b1fb3acdb75
|
refs/heads/master
| 2022-12-12T00:20:49.630749
| 2020-09-12T17:38:30
| 2020-09-12T17:38:30
| 241,000,584
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,366
|
py
|
#~~~~~~~~~~~~~~~ JAI SHREE RAM ~~~~~~~~~~~~~~~~~~#
import math; from collections import *
import sys; from functools import reduce
# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().strip().split())
def get_list(): return list(get_ints())
def get_string(): return list(input().strip().split())
def printxsp(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")
DIRECTIONS = [[0, 1], [0, -1], [1, 0], [1, -1]] #up, down, right, left
NEIGHBOURS = [(i, j) for i in range(-1, 2) for j in range(-1, 2) if (i!=0 or j!=0)]
OrdUnicode_a = ord('a'); OrdUnicode_A = ord('A')
CAPS_ALPHABETS = {chr(i+OrdUnicode_A) : i for i in range(26)}
SMOL_ALPHABETS = {chr(i+OrdUnicode_a) : i for i in range(26)}
UGLYMOD = int(1e9)+7; SEXYMOD = 998244353; MAXN = int(1e5)+1; INFINITY = float('inf')
# sys.stdin=open("input.txt","r");sys.stdout=open("output.txt","w")
# for _testcases_ in range(int(input())):
n, k = get_ints()
li = get_list()
ans = 0
for i in li:
if i > k:
break
ans += 1
for i in li[::-1]:
if i > k:
break
ans += 1
print(min(ans, n))
'''
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA )
Link may be copy-pasted here if it's taken from other source.
DO NOT PLAGIARISE.
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
'''
|
[
"luctivud@gmail.com"
] |
luctivud@gmail.com
|
9ee3580b09c058e905d7716ebd7d3428447c0fa9
|
9680ba23fd13b4bc0fc3ce0c9f02bb88c6da73e4
|
/Brian Heinold (243) ile Python/p32406.py
|
48335db560c70401219a91d1793655a29c1366cb
|
[] |
no_license
|
mnihatyavas/Python-uygulamalar
|
694091545a24f50a40a2ef63a3d96354a57c8859
|
688e0dbde24b5605e045c8ec2a9c772ab5f0f244
|
refs/heads/master
| 2020-08-23T19:12:42.897039
| 2020-04-24T22:45:22
| 2020-04-24T22:45:22
| 216,670,169
| 0
| 0
| null | null | null | null |
ISO-8859-9
|
Python
| false
| false
| 1,030
|
py
|
# coding:iso-8859-9 Türkçe
from collections import Counter
import re
metin = open ("p32406x2.txt").read()
# İsterseniz "p32406x1.txt" Türkçe metin dosyasını da kullanabilirsiniz...
print ("Dosyadan okunan metin:\n", metin)
sayar1 = Counter (metin)
print ("\nMetnin karakterlerinin tekrarlanma sıklığı:\n", list (sayar1.items()) )
kelimeler = re.findall ("\w+", metin)
print ("\nMetnin kelimeler listesi:\n", kelimeler)
sayar2 = Counter (kelimeler)
print ("\nKelimelerin tekrar sıklığı:\n", list (sayar2.items()) )
#-----------------------------------------------------------------------------------------
print ("\nEn çok tekrarlanan 10 kelime azalan sırada:", sep="")
for (kelime, sıklık) in sayar2.most_common(10): print (kelime, ':', sıklık)
print ("\nEn çok tekrarlanan 10 kelime artan sırada:", sep="")
for (kelime, sıklık) in sayar2.most_common()[9::-1]: print (kelime, ':', sıklık)
# HATA: Çift tekrarlanma sıklığı tersi [10-->9] bir düşük gerektiriyor...
|
[
"noreply@github.com"
] |
mnihatyavas.noreply@github.com
|
c40a0d341aa647b4cc049e828e4eb7a914438513
|
d6e6ff3026b41f07c8c157420c988d3381fcd945
|
/src/justForReal/InsertionSortList.py
|
dd3ac3005e9c33d7a447f771133cc4585f7dab33
|
[] |
no_license
|
tongbc/algorithm
|
dbaeb354f167c7a7a10509ada9458eaaa5e7676e
|
cf0a007552caa121a656a3f42257de8fa8cc5b38
|
refs/heads/master
| 2022-05-17T15:25:32.915075
| 2022-04-02T06:23:31
| 2022-04-02T06:23:31
| 142,536,105
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 701
|
py
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
helper = ListNode(0) ##dummy node
cur = head
pre = helper
next = None
while(cur):
next = cur.next
while(pre.next is not None and pre.next.val<cur.val):
pre = pre.next
cur.next = pre.next
pre.next = cur
pre = helper
cur = next
return helper.next
|
[
"624360737@qq.com"
] |
624360737@qq.com
|
353ce03802c6f618b014782c3d1c547b23a61161
|
3cdb4faf34d8375d6aee08bcc523adadcb0c46e2
|
/web/env/lib/python3.6/site-packages/botocore/vendored/requests/api.py
|
85608b79d7979f08365897c0b8a17abc198f9cc9
|
[
"MIT",
"GPL-3.0-only"
] |
permissive
|
rizwansoaib/face-attendence
|
bc185d4de627ce5adab1cda7da466cb7a5fddcbe
|
59300441b52d32f3ecb5095085ef9d448aef63af
|
refs/heads/master
| 2020-04-25T23:47:47.303642
| 2019-09-12T14:26:17
| 2019-09-12T14:26:17
| 173,157,284
| 45
| 12
|
MIT
| 2020-02-11T23:47:55
| 2019-02-28T17:33:14
|
Python
|
UTF-8
|
Python
| false
| false
| 5,903
|
py
|
# -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
import warnings
from . import sessions
_WARNING_MSG = (
"You are using the {name}() function from 'botocore.vendored.requests'. "
"This is not a public API in botocore and will be removed in the future. "
"Additionally, this version of requests is out of date. We recommend "
"you install the requests package, 'import requests' directly, and use "
"the requests.{name}() function instead."
)
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a (`connect timeout, read timeout
<user/advanced.html#timeouts>`_) tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>
"""
warnings.warn(
_WARNING_MSG.format(name=method),
DeprecationWarning
)
session = sessions.Session()
response = session.request(method=method, url=url, **kwargs)
# By explicitly closing the session, we avoid leaving sockets open which
# can trigger a ResourceWarning in some cases, and look like a memory leak
# in others.
session.close()
return response
def get(url, params=None, **kwargs):
"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('get', url, params=params, **kwargs)
def options(url, **kwargs):
"""Sends a OPTIONS request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('options', url, **kwargs)
def head(url, **kwargs):
"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return request('head', url, **kwargs)
def post(url, data=None, json=None, **kwargs):
"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('put', url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('patch', url, data=data, **kwargs)
def delete(url, **kwargs):
"""Sends a DELETE request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('delete', url, **kwargs)
|
[
"rizwansoaib@gmail.com"
] |
rizwansoaib@gmail.com
|
8fff6bb03b004eade3f864943dfe58a1c0d4969b
|
4b9e30286d292a9702e5cca61ce1004f31d68529
|
/tests/weblogs/test_management_commands.py
|
69c120f9c198c9c8217407a623256276bd94cea6
|
[] |
no_license
|
philgyford/django-hines
|
2c69f18c39a19dc1488950e4948bde98427dcefc
|
af5ab91deae688ba67d1561cee31359b67b0d582
|
refs/heads/main
| 2023-08-11T15:30:34.796955
| 2023-08-07T10:09:04
| 2023-08-07T10:09:04
| 930,164
| 14
| 1
| null | 2023-09-11T14:44:43
| 2010-09-22T09:25:28
|
HTML
|
UTF-8
|
Python
| false
| false
| 2,113
|
py
|
from io import StringIO
from django.core.management import call_command
from django.test import TestCase
from freezegun import freeze_time
from hines.core.utils import make_datetime
from hines.weblogs.factories import DraftPostFactory, ScheduledPostFactory
from hines.weblogs.models import Post
class PublishScheduledPostsTestCase(TestCase):
def setUp(self):
self.out = StringIO()
@freeze_time("2018-05-16 12:00:00", tz_offset=0)
def test_publishes_posts(self):
"Should only set Scheduled posts, in the past, to LIVE."
draft = DraftPostFactory(time_published=make_datetime("2018-05-16 11:45:00"))
scheduled_not_ready = ScheduledPostFactory(
time_published=make_datetime("2018-05-16 12:15:00")
)
scheduled_ready = ScheduledPostFactory(
time_published=make_datetime("2018-05-16 11:45:00")
)
call_command("publish_scheduled_posts", stdout=self.out)
draft.refresh_from_db()
scheduled_not_ready.refresh_from_db()
scheduled_ready.refresh_from_db()
self.assertEqual(draft.status, Post.Status.DRAFT)
self.assertEqual(scheduled_not_ready.status, Post.Status.SCHEDULED)
self.assertEqual(scheduled_ready.status, Post.Status.LIVE)
@freeze_time("2018-05-16 12:00:00", tz_offset=0)
def test_sets_time_published(self):
"It should set the time_published to now"
scheduled_ready = ScheduledPostFactory(
time_published=make_datetime("2018-05-16 11:45:00")
)
call_command("publish_scheduled_posts", stdout=self.out)
scheduled_ready.refresh_from_db()
self.assertEqual(
scheduled_ready.time_published, make_datetime("2018-05-16 12:00:00")
)
@freeze_time("2018-05-16 12:00:00", tz_offset=0)
def test_success_output(self):
"Should output the correct message"
ScheduledPostFactory(time_published=make_datetime("2018-05-16 11:45:00"))
call_command("publish_scheduled_posts", stdout=self.out)
self.assertIn("1 Post published", self.out.getvalue())
|
[
"phil@gyford.com"
] |
phil@gyford.com
|
a16d263e0faed78d988cfcfe933d8d3375f77618
|
fa1aa08d57dc45e5095593b78d0f2b75243bc936
|
/wonderment/wsgi.py
|
f3dfbbd5aae7a55e8489dee92018ef819738d980
|
[] |
no_license
|
carljm/Wonderment
|
8c8d7e3fa6dd853aa150ae3f5addc430ee2070ee
|
7418864b7beaf73a9e1c0557b50904cf9a29d667
|
refs/heads/master
| 2021-04-24T15:32:21.634279
| 2019-01-14T04:33:19
| 2019-01-14T04:33:19
| 23,745,985
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 346
|
py
|
"""
WSGI config for wonderment project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
# flake8: noqa
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wonderment.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
|
[
"carl@oddbird.net"
] |
carl@oddbird.net
|
a88eb74aa375c7325e1c53caba26ecc15624f3cf
|
8c5a083a67858df0632ca5bb7804d1876255381b
|
/trustpay/admin.py
|
69ffdc341aec2c236e85b633429a41c304fd2649
|
[
"BSD-3-Clause"
] |
permissive
|
PragmaticMates/django-trustpay
|
5ef9a771fb1686b517211bd83181591b9e90e7b3
|
fdf1273081bf228ed9f2fbbe9507174c80a709af
|
refs/heads/master
| 2021-06-22T21:36:28.789306
| 2018-08-07T11:07:55
| 2018-08-07T11:07:55
| 16,167,006
| 1
| 1
|
BSD-3-Clause
| 2021-06-10T19:10:49
| 2014-01-23T08:39:51
|
Python
|
UTF-8
|
Python
| false
| false
| 903
|
py
|
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from models import Notification
class NotificationAdmin(admin.ModelAdmin):
date_hierarchy = 'created'
list_display = ['id', 'transaction_id', 'result', 'amount_and_currency', 'reference', 'signature',
#'trustpay_signature', 'merchant_signature',
'is_live', 'is_signed', 'is_safe', 'created']
list_filter = ['result', 'currency', 'is_test', 'is_signed', 'is_safe',]
search_fields = ['params_get', 'params_post']
def has_add_permission(self, request):
return False
def amount_and_currency(self, obj):
return u'%s %s' % (obj.amount, obj.currency)
def is_live(self, obj):
return not obj.is_test
is_live.boolean = True
is_live.short_description = _(u'Live')
admin.site.register(Notification, NotificationAdmin)
|
[
"erik.telepovsky@gmail.com"
] |
erik.telepovsky@gmail.com
|
27930989c4f710c63ba8fdbe07e1fe62f4767919
|
b6ee71c540af500c2938e78f928bfd2d88585eea
|
/threestrandcode/apps/api/tests/assignments.py
|
b02c4b86cdd02ef374a26b38a4bd90e174f9b095
|
[] |
no_license
|
3-strand-code/3sc-api
|
114e1c633cbb026a200fc74a065db39072b63763
|
1e4c051758aab85f0f6b6efa6c3aa713f05eb75e
|
refs/heads/master
| 2016-09-01T16:11:18.668787
| 2016-02-15T01:29:04
| 2016-02-15T01:29:04
| 48,534,175
| 0
| 0
| null | 2016-02-23T20:52:47
| 2015-12-24T08:41:32
|
Python
|
UTF-8
|
Python
| false
| false
| 1,284
|
py
|
import random
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from faker import Factory
from loremipsum import generate_paragraph
from model_mommy import mommy
from applicants.models import Applicant
from homework.models import Course, Recipe
from homework.recipes import MakeGHPage
class TestAssignments(TestCase):
def setUp(self):
self.admin = User.objects.create_superuser(username="admin", password="test", email="admin@admin.com")
self.user = User.objects.create_user(username="test", password="test", email="test@test.com")
self.application = Applicant.objects.create(email="test@test.com", user=self.user)
self.course = mommy.make(Course)
self.make_gh_page_recipe = Recipe.objects.create(
creator=self.admin,
instructions='',
module=MakeGHPage.get_name(),
course=self.course,
)
def test_create_assignment_hooks_github_repo(self):
# create user and all that shit
# post to assignment endpoint
# it should call "create_hook" on that repo
self.client.login(username="test", password="test")
self.client.post()
pass
|
[
"eric@ckcollab.com"
] |
eric@ckcollab.com
|
4e2de6d4cb15b3eb73b16ff6453fac402218a793
|
d94b6845aeeb412aac6850b70e22628bc84d1d6d
|
/dp_regression/experiment_test.py
|
a2e9967b9ad34b3318655ce57a3d11f4ad93f12c
|
[
"CC-BY-4.0",
"Apache-2.0"
] |
permissive
|
ishine/google-research
|
541aea114a68ced68736340e037fc0f8257d1ea2
|
c1ae273841592fce4c993bf35cdd0a6424e73da4
|
refs/heads/master
| 2023-06-08T23:02:25.502203
| 2023-05-31T01:00:56
| 2023-05-31T01:06:45
| 242,478,569
| 0
| 0
|
Apache-2.0
| 2020-06-23T01:55:11
| 2020-02-23T07:59:42
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 1,307
|
py
|
# coding=utf-8
# Copyright 2023 The Google Research 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.
"""Tests for experiment."""
from absl.testing import absltest
import numpy as np
from dp_regression import experiment
class ExperimentTest(absltest.TestCase):
def test_r_squared(self):
predictions = np.asarray([[3, -1, 2], [0, 2, 3]])
labels = np.asarray([1, 2, 3])
r_squared = experiment.r_squared(predictions, labels)
# residual_sum_squares:
# (3 - 1)^2 + (-1 - 2)^2 + (2 - 3)^2 = 14
# (0-1)^2 + (2-2)^2 + (3-3)^2 = 1
# total sum squares:
# (1 - 2)^2 + (2 - 2)^2 + (3 - 2)^2 = 2
# R^2:
# 1 - (14 / 2) = -6
# 1 - (1 / 2) = 0.5
np.testing.assert_array_almost_equal(r_squared, np.asarray([-6, 0.5]))
if __name__ == '__main__':
absltest.main()
|
[
"copybara-worker@google.com"
] |
copybara-worker@google.com
|
98a8aff95c45a2477fb0daa2102191e16e591101
|
de4c5ecaf541d67e7cbf02837d93cf303d23b5da
|
/src/app/model/flash_msg.py
|
11cca6b9e7356ac435f6b39c82155b57a7ea7b71
|
[
"Apache-2.0"
] |
permissive
|
shadowmint/py-test-watcher
|
d140064cafeb0b2efce8a403a3abd63322f812d0
|
36d33206b104c81e2d6acebdbed2dddee71fe2a7
|
refs/heads/master
| 2021-01-19T14:07:13.441335
| 2013-07-01T06:07:56
| 2013-07-01T06:07:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,083
|
py
|
# Copyright 2013 Douglas Linder
# 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.
from __future__ import absolute_import
from .base import Base
from nark import *
from base import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Sequence
from sqlalchemy import *
from sqlalchemy.orm import *
import datetime
import app
# Possible message types
FlashTypes = enum(NOTICE=1, SUCCESS=2, FAILURE=3)
class FlashMsg(Base):
__tablename__ = 'flash_msg'
id = Column(Integer, Sequence('flash_msg_id_seq'), primary_key=True)
created_on = Column(DateTime, nullable=False)
level = Column(Integer, nullable=False)
message = Column(String, nullable=False)
def __init__(self, level, message):
self.level = level
self.message = message
self.created_on = datetime.datetime.utcnow()
def __repr__(self):
return "<Flash('%s (%s, created on: %s)')>" % (self.message, self.level, self.created_on)
@resolve(app.scope)
class Flash(object):
""" Container for the prefs objects """
def __init__(self, db=IDb):
self.db = db
def session(self):
self.db.connect()
return self.db.session
def fail(self, message):
""" Post a new message to tell the user about """
session = self.session()
record = FlashMsg(FlashTypes.FAILURE, message)
session.add(record)
session.commit()
log.error("Flash! %s (FAILURE)" % message)
def success(self, message):
""" Post a new message to tell the user about """
session = self.session()
record = FlashMsg(FlashTypes.SUCCESS, message)
session.add(record)
session.commit()
log.info("Flash! %s (SUCCESS)" % message)
def notice(self, message):
""" Post a new message to tell the user about """
session = self.session()
record = FlashMsg(FlashTypes.NOTICE, message)
session.add(record)
session.commit()
log.info("Flash! %s (NOTICE)" % message)
def get(self):
""" Return the next pending flash message """
session = self.session()
if self.any():
rtn = session.query(FlashMsg).order_by(FlashMsg.created_on).first()
session.delete(rtn)
session.commit()
return rtn
return None
def any(self):
""" Return true if any pending messages """
session = self.session()
return session.query(FlashMsg).count() > 0
# Logging
log = Logging.get()
|
[
"linderd@iinet.net.au"
] |
linderd@iinet.net.au
|
d7d6b4cd87007c2c1eba4c550c67c0c1c1bddee4
|
cb062c48280311134fe22573a41f9c4d6631b795
|
/src/xm/core/TransactionInfo.py
|
00f218c97fc571e7a710ca83d842ded158650ac2
|
[
"MIT"
] |
permissive
|
xm-blockchain/xm-core
|
da1e6bb4ceb8ab642e5d507796e2cc630ed23e0f
|
2282b435a02f061424d656155756d8f50238bcfd
|
refs/heads/main
| 2023-01-15T19:08:31.399219
| 2020-11-19T03:54:19
| 2020-11-19T03:54:19
| 314,127,428
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,257
|
py
|
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from xm.core import config
from xm.core.misc import ntp
from xm.core.txs.Transaction import Transaction
class TransactionInfo:
def __init__(self, tx: Transaction, block_number: int, timestamp: int=None):
self._transaction = tx
self._block_number = block_number
self._timestamp = timestamp
if not self._timestamp:
self._timestamp = ntp.getTime()
def __lt__(self, tx_info):
if self.transaction.fee < tx_info.transaction.fee:
return True
return False
@property
def transaction(self):
return self._transaction
@property
def block_number(self):
return self._block_number
@property
def timestamp(self):
return self._timestamp
def is_stale(self, current_block_number: int):
if current_block_number > self._block_number + config.user.stale_transaction_threshold:
return True
# If chain recovered from a fork where chain height is reduced
# then update block_number of the transactions in pool
if current_block_number < self._block_number:
self.update_block_number(current_block_number)
return False
def update_block_number(self, current_block_number: int):
self._block_number = current_block_number
def validate(self, new_state_container, update_state_container, block_number) -> bool:
addresses_set = set()
self.transaction.set_affected_address(addresses_set)
state_container = new_state_container(addresses_set,
block_number,
False,
None)
if not update_state_container(self.transaction, state_container):
return False
# Nonce should not be checked during transaction validation,
# as the appropriate nonce can be set by miner before placing
# the txn into block
if not self.transaction.validate_all(state_container, False):
return False
return True
|
[
"74695206+xm-blockchain@users.noreply.github.com"
] |
74695206+xm-blockchain@users.noreply.github.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.