blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| 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 777
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 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0b11a394b645fdd4f2e368526624bb6177ad07cc | 92fd8a66047915437783185f3bd181e997745554 | /nonebot/drivers/fastapi.py | 841b82e5ad82fc9bda6b7da1a3b2b82c7f896be9 | [
"MIT"
] | permissive | pollidwtymje/nonebot2 | a14b357f258be51c6cde6693ae1f313893a6a03e | a068040cbfc1284943eb8a65f6256e850df258a3 | refs/heads/master | 2023-02-03T07:43:19.185069 | 2020-12-15T05:55:03 | 2020-12-15T05:55:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,401 | py | """
FastAPI 驱动适配
================
后端使用方法请参考: `FastAPI 文档`_
.. _FastAPI 文档:
https://fastapi.tiangolo.com/
"""
import hmac
import json
import asyncio
import logging
import uvicorn
from fastapi.responses import Response
from fastapi import Body, status, Header, Request, FastAPI, Depends, HTTPException
from starlette.websockets import WebSocketDisconnect, WebSocket as FastAPIWebSocket
from nonebot.log import logger
from nonebot.config import Env, Config
from nonebot.utils import DataclassEncoder
from nonebot.exception import RequestDenied
from nonebot.drivers import BaseDriver, BaseWebSocket
from nonebot.typing import Optional, Callable, overrides
def get_auth_bearer(access_token: Optional[str] = Header(
None, alias="Authorization")):
if not access_token:
return None
scheme, _, param = access_token.partition(" ")
if scheme.lower() not in ["bearer", "token"]:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"})
return param
class Driver(BaseDriver):
"""
FastAPI 驱动框架
:上报地址:
* ``/{adapter name}/``: HTTP POST 上报
* ``/{adapter name}/http/``: HTTP POST 上报
* ``/{adapter name}/ws``: WebSocket 上报
* ``/{adapter name}/ws/``: WebSocket 上报
"""
def __init__(self, env: Env, config: Config):
super().__init__(env, config)
self._server_app = FastAPI(
debug=config.debug,
openapi_url=None,
docs_url=None,
redoc_url=None,
)
self._server_app.post("/{adapter}/")(self._handle_http)
self._server_app.post("/{adapter}/http")(self._handle_http)
self._server_app.websocket("/{adapter}/ws")(self._handle_ws_reverse)
self._server_app.websocket("/{adapter}/ws/")(self._handle_ws_reverse)
@property
@overrides(BaseDriver)
def type(self) -> str:
"""驱动名称: ``fastapi``"""
return "fastapi"
@property
@overrides(BaseDriver)
def server_app(self) -> FastAPI:
"""``FastAPI APP`` 对象"""
return self._server_app
@property
@overrides(BaseDriver)
def asgi(self):
"""``FastAPI APP`` 对象"""
return self._server_app
@property
@overrides(BaseDriver)
def logger(self) -> logging.Logger:
"""fastapi 使用的 logger"""
return logging.getLogger("fastapi")
@overrides(BaseDriver)
def on_startup(self, func: Callable) -> Callable:
"""参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#startup-event>`_"""
return self.server_app.on_event("startup")(func)
@overrides(BaseDriver)
def on_shutdown(self, func: Callable) -> Callable:
"""参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#startup-event>`_"""
return self.server_app.on_event("shutdown")(func)
@overrides(BaseDriver)
def run(self,
host: Optional[str] = None,
port: Optional[int] = None,
*,
app: Optional[str] = None,
**kwargs):
"""使用 ``uvicorn`` 启动 FastAPI"""
super().run(host, port, app, **kwargs)
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"default": {
"class": "nonebot.log.LoguruHandler",
},
},
"loggers": {
"uvicorn.error": {
"handlers": ["default"],
"level": "INFO"
},
"uvicorn.access": {
"handlers": ["default"],
"level": "INFO",
},
},
}
uvicorn.run(app or self.server_app,
host=host or str(self.config.host),
port=port or self.config.port,
reload=bool(app) and self.config.debug,
debug=self.config.debug,
log_config=LOGGING_CONFIG,
**kwargs)
@overrides(BaseDriver)
async def _handle_http(self,
adapter: str,
request: Request,
data: dict = Body(...)):
if not isinstance(data, dict):
logger.warning("Data received is invalid")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
if adapter not in self._adapters:
logger.warning("Unknown adapter")
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="adapter not found")
# 创建 Bot 对象
BotClass = self._adapters[adapter]
headers = dict(request.headers)
try:
x_self_id = await BotClass.check_permission(self, "http", headers,
data)
except RequestDenied as e:
raise HTTPException(status_code=e.status_code,
detail=e.reason) from None
if x_self_id in self._clients:
logger.warning("There's already a reverse websocket connection,"
"so the event may be handled twice.")
bot = BotClass(self, "http", self.config, x_self_id)
asyncio.create_task(bot.handle_message(data))
return Response("", 204)
@overrides(BaseDriver)
async def _handle_ws_reverse(self, adapter: str,
websocket: FastAPIWebSocket):
ws = WebSocket(websocket)
if adapter not in self._adapters:
logger.warning("Unknown adapter")
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
return
# Create Bot Object
BotClass = self._adapters[adapter]
headers = dict(websocket.headers)
try:
x_self_id = await BotClass.check_permission(self, "websocket",
headers, None)
except RequestDenied:
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
return
if x_self_id in self._clients:
logger.warning("There's already a reverse websocket connection, "
f"<y>{adapter.upper()} Bot {x_self_id}</y> ignored.")
await ws.close(code=status.WS_1008_POLICY_VIOLATION)
bot = BotClass(self, "websocket", self.config, x_self_id, websocket=ws)
await ws.accept()
self._clients[x_self_id] = bot
logger.opt(colors=True).info(
f"WebSocket Connection from <y>{adapter.upper()} "
f"Bot {x_self_id}</y> Accepted!")
try:
while not ws.closed:
data = await ws.receive()
if not data:
continue
asyncio.create_task(bot.handle_message(data))
finally:
del self._clients[x_self_id]
class WebSocket(BaseWebSocket):
def __init__(self, websocket: FastAPIWebSocket):
super().__init__(websocket)
self._closed = None
@property
@overrides(BaseWebSocket)
def closed(self):
return self._closed
@overrides(BaseWebSocket)
async def accept(self):
await self.websocket.accept()
self._closed = False
@overrides(BaseWebSocket)
async def close(self, code: int = status.WS_1000_NORMAL_CLOSURE):
await self.websocket.close(code=code)
self._closed = True
@overrides(BaseWebSocket)
async def receive(self) -> Optional[dict]:
data = None
try:
data = await self.websocket.receive_json()
if not isinstance(data, dict):
data = None
raise ValueError
except ValueError:
logger.warning("Received an invalid json message.")
except WebSocketDisconnect:
self._closed = True
logger.error("WebSocket disconnected by peer.")
return data
@overrides(BaseWebSocket)
async def send(self, data: dict) -> None:
text = json.dumps(data, cls=DataclassEncoder)
await self.websocket.send({"type": "websocket.send", "text": text})
| [
"[email protected]"
] | |
52a7077c4a5e57e74351d2143f1de90345c7a686 | 75678ff3f7fb3af16b36d5ef952ce90c089336e1 | /legacy_folder/lspi.py | be9388df0bf5391f1256dbf20676302329ca1385 | [] | no_license | jeonggwanlee/LSTD-mu | 71cc530b7072aab9e515609fa61f0fefe1d53903 | b2d890ddba587ac01b722a4a6b21575b354dec9d | refs/heads/master | 2020-04-12T16:06:25.249480 | 2019-03-07T16:58:00 | 2019-03-07T16:58:00 | 162,602,354 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,535 | py | import numpy as np
from rbf import Basis_Function
from policy import Policy
import pickle
import ipdb
import os
"""
important property of LSPI is that it does not require an an approximate
policy representation, At each iteration, a different policy is evaluated
and certain sets of basis functions may be more appropriate than others
for representing the state-action value function for each of these
policies.
since LSPI approximates state-action value functions,
it can use samples from any policy to estimate the state-action value
function of another policy.
This focuses attention more clearly on the issue of exploration
since any policy can be followed while collecting samples.
"""
class LSPI:
""" Learns a policy from samples
D : source of samples (s, a, r, s`)
k : number of basis functions
phi : basis functions
gamma : discount factor
epsilon : stopping criterion
policy(pi) : initial policy
"""
#def __init__(self, num_actions=3, num_means=2, gamma=0.99):
def __init__(self, num_actions=2, state_dim=4, basis_function_dim=5, gamma=0.99, opt="sigmoid", saved_basis_use=True, center_opt="random"):
"""
num_actions. Number of actions. Int.
state_dim. Number of means. Int. (= state_dim)
gamma. Float.
"""
# num_features = state_dim + 1 # for convenience
basis_function_pickle_name = "LSPI_bf_#State{}_#Features{}_#Action{}_Opt{}_CenterOpt{}.pickle".format(
state_dim,
basis_function_dim,
num_actions,
opt,
center_opt)
print("basis_function_pickle_name : {}".format(basis_function_pickle_name))
# if os.path.exists(basis_function_pickle_name):
if False:
if saved_basis_use:
print("I found same basis function, and your option is \"saved_basis_use\"=True. So, If you want to use saved one, please enter \"y\"")
input_str = input()
if input_str != "y":
print("you didn't press \"y\"")
exit()
print("!!!load same psi basis function")
with open(basis_function_pickle_name, 'rb') as rf:
self.basis_function = pickle.load(rf)
else:
print("I found same psi basis function, If you want to use saved one, please \"saved_basis_use\"=True")
print("Do you want to re-create it?(CAUTION)")
input_str = input()
if input_str == "y":
self.basis_function = Basis_Function(state_dim, basis_function_dim, num_actions, gamma, opt, center_opt)
if opt != "deep_cartpole":
with open(basis_function_pickle_name, 'wb') as wf:
pickle.dump(self.basis_function, wf)
else:
exit()
else:
self.basis_function = Basis_Function(state_dim, basis_function_dim, num_actions, gamma, opt)
#if opt != "deep_cartpole":
# with open(basis_function_pickle_name, 'wb') as wf:
# pickle.dump(self.basis_function, wf)
#else:
# print("LSPI loads deep cartpole")
#self.basis_function = Basis_Function(state_dim, basis_function_dim, num_actions, gamma, opt)
self.num_basis = self.basis_function._num_basis()
self.actions = list(range(num_actions))
self.policy = Policy(self.basis_function, self.num_basis, self.actions)
self.lstdq = LSTDQ(self.basis_function, gamma)
self.stop_criterion = 10**-5
self.gamma = gamma
def initialize_policy(self):
self.policy = Policy(self.basis_function, self.num_basis, self.actions)
def act(self, state):
""" phi(s) = argmax_a Q(s, a) and pick first action
"""
index = self.policy.get_actions(state)
action = self.policy.actions[index[0]]
return action
def train(self, sample, w_important_sampling=False):
error = float('inf')
iter = 0
lspi_iteration = 20
epsilon = 0.00001
policy_list = []
error_list = []
while epsilon < error and iter < lspi_iteration:
policy_list.append(self.policy.weights)
if w_important_sampling:
new_weights = self.lstdq.train_weight_parameter(sample, self.policy)
else:
new_weights = self.lstdq.train_parameter(sample, self.policy)
error = np.linalg.norm((new_weights - self.policy.weights))
error_list.append(error)
#print("train error {} : {}".format(iter, error))
self.policy.update_weights(new_weights)
iter += 1
return error_list
class LSTDQ:
def __init__(self, basis_function, gamma):
self.basis_function = basis_function
self.gamma = gamma
def train_parameter(self, sample, greedy_policy):
""" Compute Q value function of current policy
to obtain the greedy policy
-> theta
"""
p = self.basis_function._num_basis()
A = np.zeros([p, p])
b = np.zeros([p, 1])
np.fill_diagonal(A, .1) # Singular matrix error
states = sample[0]
actions = sample[1]
rewards = sample[2]
next_states = sample[3]
SAMPLE_SIZE = len(states)
for i in range(SAMPLE_SIZE):
phi = self.basis_function.evaluate(states[i], actions[i])
greedy_action = greedy_policy.get_best_action(next_states[i])
phi_next = self.basis_function.evaluate(next_states[i], greedy_action)
loss = (phi - self.gamma * phi_next)
phi = np.reshape(phi, [p, 1])
loss = np.reshape(loss, [1, p])
A = A + np.dot(phi, loss)
b = b + (phi * rewards[i])
#end for i in range(len(states)):
inv_A = np.linalg.inv(A)
w = np.dot(inv_A, b)
return w
def train_weight_parameter(self, sample, greedy_policy):
""" Compute Q value function of current policy
to obtain the greedy policy
"""
p = self.basis_function._num_basis()
A = np.zeros([p, p])
b = np.zeros([p, 1])
np.fill_diagonal(A, .1)
states = sample[0]
actions = sample[1]
rewards = sample[2]
next_states = sample[3]
SAMPLE_SIZE = len(states)
sum_W = 0.0
W = 1.0
for i in range(SAMPLE_SIZE):
greedy_action = greedy_policy.get_best_action(states[i]) # pi(s)^{*} == argmax_{a} Q(s, a)
prob_target = greedy_policy.q_value_function(states[i], greedy_action) # Q(s, pi(s)^{*})
prob_behavior = greedy_policy.behavior(states[i], actions[i]) # \hat{Q}(s, a)
if prob_behavior == 0.0:
W = 0
else:
W = (prob_target / prob_behavior)
sum_W = sum_W + W
for i in range(SAMPLE_SIZE):
greedy_next_action = greedy_policy.get_best_action(next_states[i])
phi = self.basis_function.evaluate(states[i], actions[i])
phi_next = self.basis_function.evaluate(next_states[i], greedy_next_action)
greedy_action = greedy_policy.get_best_action(states[i]) # pi(s)^{*}
prob_target = greedy_policy.q_value_function(states[i], greedy_action) # Q(s, pi(s)^{*})
prob_behavior = greedy_policy.behavior(states[i], actions[i]) # \hat{Q}(s, a)
norm_W = (prob_target / prob_behavior) / sum_W # (Q(s, pi(s)^{*}) / \hat{Q}(s, a)) / sum_W
# important weighting on the whole transition
loss = norm_W * (phi - self.gamma * phi_next)
phi = np.resize(phi, [p, 1])
loss = np.resize(loss, [1, len(loss)])
A = A + np.dot(phi, loss)
b = b + (phi * rewards[i])
inv_A = np.linalg.inv(A)
theta = np.dot(inv_A, b)
return theta
| [
"[email protected]"
] | |
23469463dfbc6631814a0468add53c75df07336e | 7950c4faf15ec1dc217391d839ddc21efd174ede | /problems/0572.0_Subtree_of_Another_Tree.py | 04f22ba2c1aebcb28258a3c091754703156231d3 | [] | no_license | lixiang2017/leetcode | f462ecd269c7157aa4f5854f8c1da97ca5375e39 | f93380721b8383817fe2b0d728deca1321c9ef45 | refs/heads/master | 2023-08-25T02:56:58.918792 | 2023-08-22T16:43:36 | 2023-08-22T16:43:36 | 153,090,613 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,194 | py | '''
Success
Details
Runtime: 340 ms, faster than 10.24% of Python online submissions for Subtree of Another Tree.
Memory Usage: 14.6 MB, less than 53.07% of Python online submissions for Subtree of Another Tree.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if self.isIdentical(s, t):
return True
if s.left and self.isSubtree(s.left, t):
return True
if s.right and self.isSubtree(s.right, t):
return True
return False
def isIdentical(self, node1, node2):
if not node1 and not node2:
return True
elif not node1 or not node2:
return False
if node1.val != node2.val:
return False
return self.isIdentical(node1.left, node2.left) and self.isIdentical(node1.right, node2.right)
| [
"[email protected]"
] | |
6b070f4656d6fd36f68bc0dd598ac9f15b9f3123 | a7aabc5bd71b5ef6bdddee9908efcc840930e13c | /tests/testapp/tests/test_utils.py | 509c0a384f223b47432eab62359e52d05cb6b9c5 | [
"BSD-2-Clause"
] | permissive | enterstudio/towel | b7567261b325d19d621af126553ac33350f9a927 | 6892788527b8a111cbf5963e909964aabc96d740 | refs/heads/master | 2021-07-05T05:49:11.654374 | 2016-11-21T08:43:41 | 2016-11-21T08:43:41 | 85,775,854 | 0 | 0 | NOASSERTION | 2021-07-03T01:07:07 | 2017-03-22T02:25:57 | Python | UTF-8 | Python | false | false | 3,733 | py | from __future__ import absolute_import, unicode_literals
from django.template import Template, Context
from django.test import TestCase
from towel.utils import (
related_classes, safe_queryset_and, tryreverse, substitute_with)
from testapp.models import Person, EmailAddress
class UtilsTest(TestCase):
def test_related_classes(self):
"""Test the functionality of towel.utils.related_classes"""
person = Person.objects.create(
family_name='Muster',
given_name='Hans',
)
EmailAddress.objects.create(
person=person,
email='[email protected]',
)
self.assertEqual(
set(related_classes(person)),
set((Person, EmailAddress)),
)
def test_safe_queryset_and(self):
class AnyException(Exception):
pass
def _transform_nothing(queryset):
raise AnyException
qs1 = EmailAddress.objects.search('blub').transform(
_transform_nothing).select_related()
qs2 = EmailAddress.objects.distinct().reverse().select_related(
'person')
qs3 = EmailAddress.objects.all()
qs = safe_queryset_and(safe_queryset_and(qs1, qs2), qs3)
self.assertEqual(qs._transform_fns, [_transform_nothing])
self.assertFalse(qs.query.standard_ordering)
self.assertEqual(qs.query.select_related, {'person': {}})
self.assertTrue(qs.query.distinct)
self.assertEqual(qs.count(), 0)
self.assertRaises(AnyException, list, qs)
qs = safe_queryset_and(
EmailAddress.objects.select_related(),
EmailAddress.objects.select_related(),
)
self.assertTrue(qs.query.select_related)
self.assertFalse(qs.query.distinct)
qs = safe_queryset_and(
EmailAddress.objects.all(),
EmailAddress.objects.select_related(),
)
self.assertTrue(qs.query.select_related)
def test_tryreverse(self):
self.assertEqual(tryreverse('asdf42'), None)
self.assertEqual(tryreverse('admin:index'), '/admin/')
def test_substitute_with(self):
p1 = Person.objects.create()
p2 = Person.objects.create()
p1.emailaddress_set.create()
p1.emailaddress_set.create()
p1.emailaddress_set.create()
p2.emailaddress_set.create()
p2.emailaddress_set.create()
self.assertEqual(Person.objects.count(), 2)
self.assertEqual(EmailAddress.objects.count(), 5)
substitute_with(p1, p2)
p = Person.objects.get()
self.assertEqual(p2, p)
self.assertEqual(EmailAddress.objects.count(), 5)
def test_template_tag_helpers(self):
testcases = [
('', ''),
('{% testtag %}', 'ARGS: KWARGS:'),
('{% testtag 3 4 5 %}', 'ARGS: 3,4,5 KWARGS:'),
('{% testtag 3 "4" 5 %}', 'ARGS: 3,4,5 KWARGS:'),
('{% testtag abcd "42" %}', 'ARGS: yay,42 KWARGS:'),
('{% testtag "abcd" "42" %}', 'ARGS: abcd,42 KWARGS:'),
('{% testtag "abcd" "42" a=b %}', 'ARGS: abcd,42 KWARGS: a='),
('{% testtag "abcd" a="b" "42" %}', 'ARGS: abcd,42 KWARGS: a=b'),
('{% testtag bla="blub" blo="blob" %}',
'ARGS: KWARGS: bla=blub,blo=blob'),
('{% testtag bla=blub blo="blob" %}',
'ARGS: KWARGS: bla=blubber,blo=blob'),
]
for test, result in testcases:
t = Template('{% load testapp_tags %}' + test)
self.assertHTMLEqual(t.render(Context({
'abcd': 'yay',
'bla': 'blaaa',
'blub': 'blubber',
})), result)
| [
"[email protected]"
] | |
cb04ddbe159999dd98fe3bc062ec157af7e08e40 | f07a42f652f46106dee4749277d41c302e2b7406 | /Data Set/bug-fixing-1/36d056acd92ca2f7e97fec82fd09f36c42c05338-<input_producer>-bug.py | 3a7ddc7afac95a39d452b1dd75f57e4f08345d0f | [] | no_license | wsgan001/PyFPattern | e0fe06341cc5d51b3ad0fe29b84098d140ed54d1 | cc347e32745f99c0cd95e79a18ddacc4574d7faa | refs/heads/main | 2023-08-25T23:48:26.112133 | 2021-10-23T14:11:22 | 2021-10-23T14:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,712 | py |
def input_producer(input_tensor, element_shape=None, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, summary_name=None, name=None):
'Output the rows of `input_tensor` to a queue for an input pipeline.\n\n Args:\n input_tensor: A tensor with the rows to produce. Must be at\n one-dimensional. Must either have a fully-defined shape, or\n `element_shape` must be defined.\n element_shape: (Optional.) A `TensorShape` representing the shape of a\n row of `input_tensor`, if it cannot be inferred.\n num_epochs: (Optional.) An integer. If specified `input_producer` produces\n each row of `input_tensor` `num_epochs` times before generating an\n `OutOfRange` error. If not specified, `input_producer` can cycle through\n the rows of `input_tensor` an unlimited number of times.\n shuffle: (Optional.) A boolean. If true, the rows are randomly shuffled\n within each eopch.\n seed: (Optional.) An integer. The seed to use if `shuffle` is true.\n capacity: (Optional.) The capacity of the queue to be used for buffering\n the input.\n shared_name: (Optional.) If set, this queue will be shared under the given\n name across multiple sessions.\n summary_name: (Optional.) If set, a scalar summary for the current queue\n size will be generated, using this name as part of the tag.\n name: (Optional.) A name for queue.\n\n Returns:\n A queue with the output rows. A `QueueRunner` for the queue is\n added to the current `QUEUE_RUNNER` collection of the current\n graph.\n\n Raises:\n ValueError: If the shape of the input cannot be inferred from the arguments.\n '
with ops.op_scope([input_tensor], name, 'input_producer'):
input_tensor = ops.convert_to_tensor(input_tensor, name='input_tensor')
element_shape = input_tensor.get_shape()[1:].merge_with(element_shape)
if (not element_shape.is_fully_defined()):
raise ValueError('Either `input_tensor` must have a fully defined shape or `element_shape` must be specified')
if shuffle:
input_tensor = random_ops.random_shuffle(input_tensor, seed=seed)
input_tensor = limit_epochs(input_tensor, num_epochs)
q = data_flow_ops.FIFOQueue(capacity=capacity, dtypes=[input_tensor.dtype.base_dtype], shapes=[element_shape], shared_name=shared_name, name=name)
enq = q.enqueue_many([input_tensor])
queue_runner.add_queue_runner(queue_runner.QueueRunner(q, [enq]))
if (summary_name is not None):
logging_ops.scalar_summary(('queue/%s/%s' % (q.name, summary_name)), (math_ops.cast(q.size(), dtypes.float32) * (1.0 / capacity)))
return q
| [
"[email protected]"
] | |
b8a6d4b5c488151244256500ffaab2184cecdabc | c6eb52478346d4c0b272035f45f62f6b1dccf2c3 | /data_science_py/26_spark/lambda_expressions.py | e961135b4db95e1a1a503192e7ba57b3086ce7a9 | [] | no_license | antichown/udemy_courses | 88732eea17eac8614152aa815d57c64fa54d0104 | d308fe478a67cb7fc395d99d798ac58fdc1f58c4 | refs/heads/master | 2022-11-06T22:28:08.118570 | 2020-07-17T02:00:19 | 2020-07-17T02:00:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,652 | py | #!/usr/bin/env python
# coding: utf-8
# #lambda expressions
#
# One of Pythons most useful (and for beginners, confusing) tools is the lambda
# expression. lambda expressions allow us to create "anonymous" functions. This
# basically means we can quickly make ad-hoc functions without needing to properly
# define a function using def.
#
# Function objects returned by running lambda expressions work exactly the same
# as those created and assigned by defs. There is key difference that makes lambda
# useful in specialized roles:
#
# **lambda's body is a single expression, not a block of statements.**
#
# * The lambda's body is similar to what we would put in a def body's return
# statement. We simply type the result as an expression instead of explicitly
# returning it. Because it is limited to an expression, a lambda is less general
# that a def. We can only squeeze design, to limit program nesting. lambda is
# designed for coding simple functions, and def handles the larger tasks.
#
# Lets slowly break down a lambda expression by deconstructing a function:
def square(num):
result = num**2
return result
print(square(2))
# Continuing the breakdown:
def square2(num):
return num**2
print(square2(2))
# We can actually write this in one line (although it would be bad style to do so)
def square3(num): return num**2
print(square3(2))
# This is the form a function that a lambda expression intends to replicate. A
# lambda expression can then be written as:
print(lambda num: num**2)
# Note how we get a function back. We can assign this function to a label:
square4 = lambda num: num**2
print(square4(2))
# And there you have it! The breakdown of a function into a lambda expression!
# Lets see a few more examples:
#
# ##Example 1
# Check it a number is even
even = lambda x: x%2==0
print(even(3))
print(even(4))
# ##Example 2
# Grab first character of a string:
first = lambda s: s[0]
print(first('hello'))
# ##Example 3
# Reverse a string:
rev = lambda s: s[::-1]
print(rev('hello'))
# ##Example 4
# Just like a normal function, we can accept more than one function into a lambda expresssion:
adder = lambda x,y : x+y
print(adder(2,3))
# lambda expressions really shine when used in conjunction with map(),filter()
# and reduce(). Each of those functions has its own lecture, so feel free to explore
# them if your very itnerested in lambda.
# I highly recommend reading this blog post at [Python Conquers the Universe]
# (https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/)
# for a great breakdown on lambda expressions and some explanations of common confusions!
| [
"[email protected]"
] | |
2874f74de9f3de37544a1e61636acc55e31149f1 | 67d94cea8a4e48683e74ad7da26ab4b02ae37c19 | /demo/services/qotm.py | ab405266a3e4504b3d51242754b2179293a01958 | [
"Apache-2.0"
] | permissive | smoshtaghi/ambassador | fa39ec86acdde3b76706e37a5273c252b62fda66 | f653780befd65d72f955e94f5fac146d8794c712 | refs/heads/master | 2020-05-02T09:52:45.928453 | 2019-03-26T20:22:35 | 2019-03-26T20:22:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,956 | py | #!/usr/bin/env python
from flask import Flask, jsonify, request, Response
import datetime
import functools
import logging
import os
import random
import signal
import time
__version__ = "0.0.1"
PORT = int(os.getenv("PORT", "5000"))
HOSTNAME = os.getenv("HOSTNAME")
LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG")
app = Flask(__name__)
# Quote storage
#
# Obviously, this would more typically involve a persistent backing store. That's not
# really needed for a demo though.
quotes = [
"Abstraction is ever present.",
"A late night does not make any sense.",
"A principal idea is omnipresent, much like candy.",
"Nihilism gambles with lives, happiness, and even destiny itself!",
"The light at the end of the tunnel is interdependent on the relatedness of motivation, subcultures, and management.",
"Utter nonsense is a storyteller without equal.",
"Non-locality is the driver of truth. By summoning, we vibrate.",
"A small mercy is nothing at all?",
"The last sentence you read is often sensible nonsense.",
"668: The Neighbor of the Beast."
]
# Utilities
class RichStatus (object):
def __init__(self, ok, **kwargs):
self.ok = ok
self.info = kwargs
self.info['hostname'] = HOSTNAME
self.info['time'] = datetime.datetime.now().isoformat()
self.info['version'] = __version__
# Remember that __getattr__ is called only as a last resort if the key
# isn't a normal attr.
def __getattr__(self, key):
return self.info.get(key)
def __bool__(self):
return self.ok
def __nonzero__(self):
return bool(self)
def __contains__(self, key):
return key in self.info
def __str__(self):
attrs = ["%s=%s" % (key, self.info[key])
for key in sorted(self.info.keys())]
astr = " ".join(attrs)
if astr:
astr = " " + astr
return "<RichStatus %s%s>" % ("OK" if self else "BAD", astr)
def toDict(self):
d = {'ok': self.ok}
for key in self.info.keys():
d[key] = self.info[key]
return d
@classmethod
def fromError(self, error, **kwargs):
kwargs['error'] = error
return RichStatus(False, **kwargs)
@classmethod
def OK(self, **kwargs):
return RichStatus(True, **kwargs)
template = '''
<HTML><HEAD><Title>{title}</Title></Head>
<BODY>
<P><span style="color: {textcolor}">{message}</span><P>
</BODY>
</HTML>
'''
def standard_handler(f):
func_name = getattr(f, '__name__', '<anonymous>')
@functools.wraps(f)
def wrapper(*args, **kwds):
rc = RichStatus.fromError("impossible error")
session = request.headers.get('x-qotm-session', None)
username = request.headers.get('x-authenticated-as', None)
logging.debug("%s %s: session %s, username %s, handler %s" %
(request.method, request.path, session, username, func_name))
headers_string = ', '.join("{!s}={!r}".format(key, val)
for (key, val) in request.headers.items())
logging.debug("headers: %s" % (headers_string))
try:
rc = f(*args, **kwds)
except Exception as e:
logging.exception(e)
rc = RichStatus.fromError("%s: %s %s failed: %s" % (
func_name, request.method, request.path, e))
code = 200
# This, candidly, is a bit of a hack.
if session:
rc.info['session'] = session
if username:
rc.info['username'] = username
if not rc:
if 'status_code' in rc:
code = rc.status_code
else:
code = 500
if rc.json:
resp = jsonify(rc.toDict())
resp.status_code = code
else:
info = {
'title': "Quote of the Moment %s" % __version__,
'textcolor': 'pink',
'message': 'This moment is inadequate for a quote.',
}
if rc:
info['textcolor'] = 'black'
info['message'] = rc.quote
else:
info['textcolor'] = 'red'
info['message'] = rc.error
resp = Response(template.format(**info), code)
if session:
resp.headers['x-qotm-session'] = session
return resp
return wrapper
# REST endpoints
####
# GET /health does a basic health check. It always returns a status of 200
# with an empty body.
@app.route("/health", methods=["GET", "HEAD"])
@standard_handler
def health():
return RichStatus.OK(msg="QotM health check OK")
####
# GET / returns a random quote as the 'quote' element of a JSON dictionary. It
# always returns a status of 200.
@app.route("/", methods=["GET"])
@standard_handler
def statement():
return RichStatus.OK(quote=random.choice(quotes),
json=request.args.get('json', False))
####
# GET /quote/quoteid returns a specific quote. 'quoteid' is the integer index
# of the quote in our array above.
#
# - If all goes well, it returns a JSON dictionary with the requested quote as
# the 'quote' element, with status 200.
# - If something goes wrong, it returns a JSON dictionary with an explanation
# of what happened as the 'error' element, with status 400.
#
# PUT /quote/quotenum updates a specific quote. It requires a JSON dictionary
# as the PUT body, with the the new quote contained in the 'quote' dictionary
# element.
#
# - If all goes well, it returns the new quote as if you'd requested it using
# the GET verb for this endpoint.
# - If something goes wrong, it returns a JSON dictionary with an explanation
# of what happened as the 'error' element, with status 400.
@app.route("/quote/<idx>", methods=["GET", "PUT"])
@standard_handler
def specific_quote(idx):
try:
idx = int(idx)
except ValueError:
return RichStatus.fromError("quote IDs must be numbers", status_code=400)
if (idx < 0) or (idx >= len(quotes)):
return RichStatus.fromError("no quote ID %d" % idx, status_code=400)
if request.method == "PUT":
j = request.json
if (not j) or ('quote' not in j):
return RichStatus.fromError("must supply 'quote' via JSON dictionary", status_code=400)
quotes[idx] = j['quote']
return RichStatus.OK(quote=quotes[idx],
json=request.args.get('json', False))
####
# POST /quote adds a new quote to our list. It requires a JSON dictionary
# as the POST body, with the the new quote contained in the 'quote' dictionary
# element.
#
# - If all goes well, it returns a JSON dictionary with the new quote's ID as
# 'quoteid', and the new quote as 'quote', with a status of 200.
# - If something goes wrong, it returns a JSON dictionary with an explanation
# of what happened as the 'error' element, with status 400.
@app.route("/quote", methods=["POST"])
@standard_handler
def new_quote():
j = request.json
if (not j) or ('quote' not in j):
return RichStatus.fromError("must supply 'quote' via JSON dictionary", status_code=400)
quotes.append(j['quote'])
idx = len(quotes) - 1
return RichStatus.OK(quote=quotes[idx], quoteid=idx)
@app.route("/crash", methods=["GET"])
@standard_handler
def crash():
logging.warning("dying in 1 seconds")
time.sleep(1)
os.kill(os.getpid(), signal.SIGTERM)
time.sleep(1)
os.kill(os.getpid(), signal.SIGKILL)
# Mainline
def main():
app.run(debug=True, host="0.0.0.0", port=PORT)
if __name__ == "__main__":
logging.basicConfig(
# filename=logPath,
level=LOG_LEVEL, # if appDebug else logging.INFO,
format="%%(asctime)s demo-qotm %s %%(levelname)s: %%(message)s" % __version__,
datefmt="%Y-%m-%d %H:%M:%S"
)
logging.info("initializing on %s:%d" % (HOSTNAME, PORT))
main()
| [
"[email protected]"
] | |
6f537f2a2eb98ce9355e639f4b1a40938a2975e3 | 763d2f0a40c905bc9cbcd83e21c8d716072fcf90 | /chapter01/04.py | faf5d15b0528921cf23472e4699f4bf3a532a3d9 | [] | no_license | s19014/ProgrammingTraining2 | c707dc0a9dc1f4678f91fc05ded6bb1419db4f7a | c28b452d0a52c0e8481731bd1cda6b1aba88228d | refs/heads/master | 2022-11-08T18:27:36.692911 | 2020-06-29T03:36:51 | 2020-06-29T03:36:51 | 262,897,354 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 813 | py | '''
“Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also
Sign Peace Security Clause. Arthur King Can.”という文を単語に分解し,
1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に
2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への
連想配列(辞書型もしくはマップ型)を作成せよ.
'''
text = '''Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'''
text_list = text.split()
answer = {}
for index, word in enumerate(text_list, 1):
if index in [1, 5, 6, 7, 8, 9, 15, 16, 19]:
answer[index] = word[0]
else:
answer[index] = word[:2]
print(answer)
| [
"[email protected]"
] | |
d1b8b380409305b112615cc2f6a3b1f200a89b38 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_268/ch34_2020_03_29_20_16_22_997795.py | 7ac92c7d8b2fdc1116c6e200a907b413c1ee9f71 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 484 | py | def eh_primo(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def maior_primo_menor_que(n):
a=0
b=n-1
if n<=1:
return -1
while a>n:
if eh_primo(b):
return b
a+=1
b-=1
| [
"[email protected]"
] | |
ab59db052bdf4934ce86436713e6a01207d89d3c | 7b750c5c9df2fb05e92b16a43767c444404de7ae | /src/leetcode/python3/leetcode735.py | ba41f98ebc046b632377456faffcf0601cd24c7a | [] | no_license | renaissance-codes/leetcode | a68c0203fe4f006fa250122614079adfe6582d78 | de6db120a1e709809d26e3e317c66612e681fb70 | refs/heads/master | 2022-08-18T15:05:19.622014 | 2022-08-05T03:34:01 | 2022-08-05T03:34:01 | 200,180,049 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,394 | py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from typing import List
"""
行星碰撞
"""
# 暴力求解 292ms
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
tasteroids = asteroids
result = []
change = True
while change:
for x in tasteroids:
if len(result) == 0:
result.append(x)
else:
p = result.pop()
if p > 0 and x < 0:
if p > -x:
result.append(p)
elif p < -x:
result.append(x)
else:
result.append(p)
result.append(x)
if len(result) < len(tasteroids):
tasteroids = result
result = []
else:
change = False
return result
# 循环的位置不同
class Solution2:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
result = []
for x in asteroids:
while len(result) and result[-1] > 0 and x < 0:
p = result.pop()
if p > -x:
x = p
elif p == -x:
break
else:
result.append(x)
return result
| [
"[email protected]"
] | |
b7b874acea85c0c1c0b468fa63bfcdec322d8e33 | d4a874792cc86f64dba859392deacd9e7e6721fc | /monitor.py | 01ae60fc559113881e40b008bc3cc7858202075c | [] | no_license | tarungoyal1/python_scripts | a1b0e725813a0277b812f75a73fac330d92405cb | ac362c753d61c3430c46863235bb263ecc62a053 | refs/heads/master | 2020-03-28T14:23:26.896106 | 2018-11-13T00:49:17 | 2018-11-13T00:49:17 | 148,483,014 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 998 | py | import time
import glob
import shutil
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_created(self, event):
folder = "10_Practical Uses of S3"
current = glob.glob("*.mp4")
if len(current)!=0:
path = "S3_Master_class/"+folder+"/"
allFiles = glob.glob(path+"*.mp4")
count = len(allFiles)
currentname = current[0]
shutil.copy2(currentname, path+str(count+1)+"_"+currentname)
shutil.os.remove(currentname)
# print ("Got it!")
if __name__ == "__main__":
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
| [
"[email protected]"
] | |
2327e451efdb4a8666c843c8a91c238cd40c83c0 | 56169cc42c21baeb0773a11f9dc2d14bc873e094 | /sortowaniee/venv/bin/easy_install-3.6 | 40be963b14b45a1c26c3afd53c4dc64c948e96aa | [] | no_license | PROGRAMMINinGPYTHON/minilogia | cc1842bb1e5a388c6d7c71bb7b8412776c1ed26b | 346b97671a72046d45e1736b11ba360a92f32c6f | refs/heads/master | 2021-07-09T00:47:11.406056 | 2021-03-28T11:19:13 | 2021-03-28T11:19:13 | 234,959,810 | 0 | 0 | null | 2020-03-21T19:07:48 | 2020-01-19T20:19:22 | Python | UTF-8 | Python | false | false | 453 | 6 | #!/home/stas/Desktop/mini_logia/sortowaniee/venv/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.6'
__requires__ = 'setuptools==40.8.0'
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('setuptools==40.8.0', 'console_scripts', 'easy_install-3.6')()
)
| [
"[email protected]"
] | |
c7b1119f2e17232fefd85a261db1140a3847f62e | 9c85d132b2ed8c51f021f42ed9f20652827bca45 | /source/res/scripts/client/gui/shared/gui_items/customization/c11n_items.py | 61bc31e680cc7214b04d3f2dbc684bf2271ae9b3 | [] | no_license | Mododejl/WorldOfTanks-Decompiled | 0f4063150c7148184644768b55a9104647f7e098 | cab1b318a58db1e428811c41efc3af694906ba8f | refs/heads/master | 2020-03-26T18:08:59.843847 | 2018-06-12T05:40:05 | 2018-06-12T05:40:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,317 | py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/shared/gui_items/customization/c11n_items.py
import Math
from gui.Scaleform.locale.ITEM_TYPES import ITEM_TYPES
from gui.Scaleform.locale.RES_ICONS import RES_ICONS
from gui.Scaleform.locale.VEHICLE_CUSTOMIZATION import VEHICLE_CUSTOMIZATION
from gui.shared.gui_items import GUI_ITEM_TYPE_NAMES, GUI_ITEM_TYPE
from gui.shared.gui_items.fitting_item import FittingItem, RentalInfoProvider
from helpers import i18n, dependency
from items.components.c11n_constants import SeasonType
from shared_utils import first
from skeletons.gui.server_events import IEventsCache
_UNBOUND_VEH = 0
_CAMO_ICON_TEMPLATE = 'img://camouflage,{width},{height},"{texture}","{background}",{colors},{weights}'
_CAMO_SWATCH_WIDTH = 128
_CAMO_SWATCH_HEIGHT = 128
_CAMO_SWATCH_BACKGROUND = 'gui/maps/vehicles/camouflages/camo_back.dds'
STYLE_GROUP_ID_TO_GROUP_NAME_MAP = {VEHICLE_CUSTOMIZATION.STYLES_SPECIAL_STYLES: VEHICLE_CUSTOMIZATION.CAROUSEL_SWATCH_STYLE_SPECIAL,
VEHICLE_CUSTOMIZATION.STYLES_MAIN_STYLES: VEHICLE_CUSTOMIZATION.CAROUSEL_SWATCH_STYLE_MAIN,
VEHICLE_CUSTOMIZATION.STYLES_RENTED_STYLES: VEHICLE_CUSTOMIZATION.CAROUSEL_SWATCH_STYLE_RENTED}
def camoIconTemplate(texture, width, height, colors, background=_CAMO_SWATCH_BACKGROUND):
weights = Math.Vector4(*[ (color >> 24) / 255.0 for color in colors ])
return _CAMO_ICON_TEMPLATE.format(width=width, height=height, texture=texture, background=background, colors=','.join((str(color) for color in colors)), weights=','.join((str(weight) for weight in weights)))
class ConcealmentBonus(object):
__slots__ = ('_camouflageId', '_season')
def __init__(self, camouflageId, season):
self._camouflageId = camouflageId
self._season = season
def getValue(self, vehicle):
_, still = vehicle.descriptor.computeBaseInvisibility(crewFactor=0, camouflageId=self._camouflageId)
return still
def getFormattedValue(self, vehicle):
return '{:.0%}'.format(self.getValue(vehicle))
@property
def icon(self):
return RES_ICONS.getItemBonus42x42('camouflage')
@property
def iconSmall(self):
return RES_ICONS.getItemBonus16x16('camouflage')
@property
def description(self):
return i18n.makeString(VEHICLE_CUSTOMIZATION.BONUS_CONDITION_SEASON)
@property
def userName(self):
return i18n.makeString(VEHICLE_CUSTOMIZATION.getBonusName('camouflage'))
@property
def shortUserName(self):
return i18n.makeString(VEHICLE_CUSTOMIZATION.getShortBonusName('camouflage'))
class Customization(FittingItem):
__slots__ = ('_boundInventoryCount', '_bonus')
eventsCache = dependency.descriptor(IEventsCache)
def __init__(self, intCompactDescr, proxy=None):
super(Customization, self).__init__(intCompactDescr, proxy)
self._inventoryCount = 0
self._boundInventoryCount = {}
self._bonus = None
if proxy and proxy.inventory.isSynced():
invCount = proxy.inventory.getItems(GUI_ITEM_TYPE.CUSTOMIZATION, self.intCD)
for vehIntCD, count in invCount.iteritems():
self._boundInventoryCount[vehIntCD] = count
self._inventoryCount = self.boundInventoryCount.pop(_UNBOUND_VEH, 0)
self._isUnlocked = True
return
def __cmp__(self, other):
return cmp(self.userName, other.userName)
def __repr__(self):
return '{}<intCD:{}, id:{}>'.format(self.__class__.__name__, self.intCD, self.id)
@property
def id(self):
return self.descriptor.id
@property
def itemTypeName(self):
return GUI_ITEM_TYPE_NAMES[self.itemTypeID]
@property
def groupID(self):
return self.descriptor.parentGroup.itemPrototype.userKey
@property
def groupUserName(self):
return self.descriptor.parentGroup.itemPrototype.userString
@property
def userType(self):
return i18n.makeString(ITEM_TYPES.customization(self.itemTypeName))
@property
def boundInventoryCount(self):
return self._boundInventoryCount
@property
def tags(self):
return self.descriptor.tags
@property
def season(self):
return self.descriptor.season
@property
def seasons(self):
return [ season for season in SeasonType.SEASONS if season & self.season ]
@property
def requiredToken(self):
return self.descriptor.requiredToken
@property
def priceGroup(self):
return self.descriptor.priceGroup
@property
def priceGroupTags(self):
return self.descriptor.priceGroupTags
@property
def bonus(self):
return self._bonus
@property
def icon(self):
return self.descriptor.texture.replace('gui/', '../', 1)
def isHistorical(self):
return self.descriptor.historical
def isSummer(self):
return self.season & SeasonType.SUMMER
def isWinter(self):
return self.season & SeasonType.WINTER
def isDesert(self):
return self.season & SeasonType.DESERT
def isAllSeason(self):
return self.season == SeasonType.ALL
def isEvent(self):
return self.season & SeasonType.EVENT
def mayInstall(self, vehicle, _=None):
return True if not self.descriptor.filter else self.descriptor.filter.matchVehicleType(vehicle.descriptor.type)
def isWide(self):
return False
def isUnlocked(self):
return bool(self.eventsCache.questsProgress.getTokenCount(self.requiredToken)) if self.requiredToken else True
def isRare(self):
return self.descriptor.isRare()
def fullInventoryCount(self, vehicle):
return self.inventoryCount + self.boundInventoryCount.get(vehicle.intCD, 0)
def getGUIEmblemID(self):
pass
class Paint(Customization):
def __init__(self, *args, **kwargs):
super(Paint, self).__init__(*args, **kwargs)
self.itemTypeID = GUI_ITEM_TYPE.PAINT
@property
def color(self):
return self.descriptor.color
@property
def gloss(self):
return self.descriptor.gloss
@property
def metallic(self):
return self.descriptor.metallic
class Camouflage(Customization):
def __init__(self, *args, **kwargs):
super(Camouflage, self).__init__(*args, **kwargs)
self.itemTypeID = GUI_ITEM_TYPE.CAMOUFLAGE
self._bonus = ConcealmentBonus(camouflageId=self.id, season=self.season)
@property
def texture(self):
return self.descriptor.texture
@property
def icon(self):
return camoIconTemplate(self.texture, _CAMO_SWATCH_WIDTH, _CAMO_SWATCH_HEIGHT, first(self.palettes))
@property
def tiling(self):
return self.descriptor.tiling
@property
def scales(self):
return self.descriptor.scales
@property
def palettes(self):
return self.descriptor.palettes
class Modification(Customization):
def __init__(self, *args, **kwargs):
super(Modification, self).__init__(*args, **kwargs)
self.itemTypeID = GUI_ITEM_TYPE.MODIFICATION
def modValue(self, modType, default=0.0):
return self.descriptor.getEffectValue(modType, default=default)
@property
def effects(self):
return self.descriptor.effects
def isWide(self):
return True
class Decal(Customization):
@property
def texture(self):
return self.descriptor.texture
@property
def isMirrored(self):
return self.descriptor.isMirrored
class Emblem(Decal):
def __init__(self, *args, **kwargs):
super(Emblem, self).__init__(*args, **kwargs)
self.itemTypeID = GUI_ITEM_TYPE.EMBLEM
class Inscription(Decal):
def __init__(self, *args, **kwargs):
super(Inscription, self).__init__(*args, **kwargs)
self.itemTypeID = GUI_ITEM_TYPE.INSCRIPTION
def isWide(self):
return True
class Style(Customization):
__slots__ = ('_outfits',)
def __init__(self, intCompactDescr, proxy=None):
super(Style, self).__init__(intCompactDescr, proxy)
self.itemTypeID = GUI_ITEM_TYPE.STYLE
self._outfits = {}
for season, component in self.descriptor.outfits.iteritems():
outfitDescr = component.makeCompDescr()
self._outfits[season] = self.itemsFactory.createOutfit(outfitDescr, proxy=proxy)
@property
def isRentable(self):
return self.descriptor.isRent
@property
def isRented(self):
return False if not self.isRentable else bool(self.boundInventoryCount)
@property
def rentCount(self):
return self.descriptor.rentCount if self.isRentable else 0
@property
def modelsSet(self):
return self.descriptor.modelsSet
@property
def userType(self):
return i18n.makeString(STYLE_GROUP_ID_TO_GROUP_NAME_MAP[self.groupID])
def getRentInfo(self, vehicle):
if not self.isRentable:
return RentalInfoProvider()
battlesLeft = self.boundInventoryCount.get(vehicle.descriptor.type.compactDescr, 0)
return RentalInfoProvider(battles=battlesLeft)
def getOutfit(self, season):
return self._outfits.get(season)
def isWide(self):
return True
| [
"[email protected]"
] | |
b1a813aef6ba473bea7a5c2fd78a298593eb2d7a | cb70b467312f2fb8f8415bac03476d207acb990d | /study_case/crawler_7x24_study3.py | fe7a0ea1a66fd9f850e00e2ec518e92fe0c5fcf8 | [] | no_license | eddiewang-wgq/python-interface | ded532dbad1dc943420823e91ba5f00637fa978e | d232cfc3a7ffc27f8f186d577265bc93e89b9b54 | refs/heads/master | 2023-03-27T00:52:50.018082 | 2021-03-30T07:53:08 | 2021-03-30T07:53:08 | 352,916,495 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,741 | py | # !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author : pgsheng
@Time : 2018/8/13 9:31
"""
import sys
import time
import pandas
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWidgets import QApplication
from bs4 import BeautifulSoup
from public import config
class Sina_7x24(QWebEnginePage):
def __init__(self):
self.is_first = True
self.html = ''
self.task_time = []
self.task_info = []
self.app = QApplication(sys.argv) # PyQt5
QWebEnginePage.__init__(self) # PyQt5
def _sina(self):
url = 'http://finance.sina.com.cn/7x24/'
self.loadFinished.connect(self._on_load_finished) # PyQt5
self.load(QUrl(url)) # PyQt5
self.app.exec_() # PyQt5
data_list = self._news()
if self.is_first:
for data in data_list:
self.task_time.append(data['n_time'])
self.task_info.append(data['n_info'])
print(data['n_time'], data['n_info'])
time.sleep(0.1)
self.is_first = False
else:
for data in data_list:
if data['n_time'] in self.task_time:
pass
else:
self.task_time.append(data['n_time'])
self.task_info.append(data['n_info'])
print('-' * 30)
print('新消息', data['n_time'], data['n_info'])
total = {'Time': self.task_time[::-1], 'Content': self.task_info[::-1]}
# ( 运行起始点 )用pandas模块处理数据并转化为excel文档
df = pandas.DataFrame(total)
df.to_excel(config.study_case_path + r'data\7x24_3.xlsx', 'Sheet1')
time.sleep(15)
self._sina() # 每隔 N 秒跑一次
def _news(self): # 获取新闻函数
news_list = []
soup = BeautifulSoup(self.html, 'lxml')
info_list = soup.select('.bd_i_og')
for info in info_list: # 获取页面中自动刷新的新闻
n_time = info.select('p.bd_i_time_c')[0].text # 新闻时间及内容
n_info = info.select('p.bd_i_txt_c')[0].text
data = {
'n_time': n_time,
'n_info': n_info
}
news_list.append(data)
return news_list[::-1] # 这里倒序,这样打印时才会先打印旧新闻,后打印新新闻
def _on_load_finished(self):
self.html = self.toHtml(self.callable) # PyQt5
def callable(self, html_str):
self.html = html_str
self.app.quit() # PyQt5
def start(self):
self._sina()
if __name__ == '__main__':
mw = Sina_7x24()
mw.start()
| [
"[email protected]"
] | |
69240e74f4667dcc2eca03b64939ad5d07446fa2 | 0ffb18f4d58961ca675d8294eb2154f69061989f | /examples/pipeliner/fastqc_pipeline_example.py | 4a2c7ea0b317b3fd00e841734a13324343f5b38b | [] | no_license | nandr0id/auto_process_ngs | a794e904e6d24b0e0403941b44c884374f95850e | 9b09f20b344d0ee87227e8771a479aa7c04f1837 | refs/heads/master | 2020-06-26T03:23:53.225029 | 2019-06-12T12:11:32 | 2019-06-12T12:11:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,931 | py | #!/usr/bin/env python
#
# Example pipeline to run Fastqc on one or more Fastq files
# but ignoring any with zero reads
import os
import argparse
from bcftbx.FASTQFile import nreads
from auto_process_ngs.pipeliner import PipelineTask
from auto_process_ngs.pipeliner import PipelineFunctionTask
from auto_process_ngs.pipeliner import PipelineCommandWrapper
from auto_process_ngs.pipeliner import Pipeline
class RunFastqc(PipelineTask):
# Run Fastqc on multiple files
def init(self,fastqs,out_dir):
# Inputs:
# - fastqs: list of input Fastq files
# - out_dir: where to put the Fastqc outputs
# Outputs:
# - files: list of output Fastqc HTML files
self.add_output('files',list())
def setup(self):
if not os.path.exists(self.args.out_dir):
os.mkdir(self.args.out_dir)
for fq in self.args.fastqs:
self.add_cmd(
PipelineCommandWrapper("Run FastQC",
"fastqc",
"-o",self.args.out_dir,
fq))
def finish(self):
for fq in self.args.fastqs:
if fq.endswith(".gz"):
fq = os.path.splitext(fq)[0]
out_file = os.path.join(
self.args.out_dir,
os.path.splitext(
os.path.basename(fq))[0]+"_fastqc.html")
if not os.path.exists(out_file):
self.fail(message="Missing output file: %s" % out_file)
else:
self.output.files.append(out_file)
class FilterEmptyFastqs(PipelineFunctionTask):
# Filter Fastq files based on read count
def init(self,fastqs):
self.add_output('fastqs',list())
def setup(self):
for fq in self.args.fastqs:
self.add_call("Filter out empty fastqs",
self.filter_empty_fastqs,fq)
def filter_empty_fastqs(self,*fastqs):
filtered_fastqs = list()
for fq in fastqs:
if nreads(fq) > 0:
print "%s" % fq
filtered_fastqs.append(fq)
return filtered_fastqs
def finish(self):
for result in self.result():
for fq in result:
self.output.fastqs.append(fq)
if __name__ == "__main__":
# Command line
p = argparse.ArgumentParser()
p.add_argument("fastqs",nargs='+',metavar="FASTQ")
args = p.parse_args()
# Make and run a pipeline
ppl = Pipeline()
filter_empty_fastqs = FilterEmptyFastqs("Filter empty Fastqs",
args.fastqs)
run_fastqc = RunFastqc("Run Fastqc",
filter_empty_fastqs.output.fastqs,
os.getcwd())
ppl.add_task(filter_empty_fastqs)
ppl.add_task(run_fastqc,requires=(filter_empty_fastqs,))
ppl.run()
print run_fastqc.output()
| [
"[email protected]"
] | |
613fefd8380bf4435858fd0857c0dfb569fafb41 | 1dfba6d8c60a534d6bdeb985697fba913da5fe9b | /src/mceditlib/bench/time_loadsave.py | 52fb8a10945703382abccd3848abbce13e03efe2 | [
"BSD-3-Clause"
] | permissive | shipbiulder101/mcedit2 | 2d88a6933bac3010f5bedcdd65d542587841a19f | 44179472b7834c803da243a82d731f9ef555764d | refs/heads/master | 2021-01-12T21:52:56.581572 | 2015-10-20T21:30:34 | 2015-10-20T21:30:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,665 | py | """
time_loadall
"""
from __future__ import absolute_import, division, print_function
import logging
import timeit
from mceditlib.test import templevel
import gc
log = logging.getLogger(__name__)
def loadall():
ents = 0
for cPos in pos[cStart:cEnd]:
chunk = dim.getChunk(*cPos)
ents += len(chunk.Entities) + len(chunk.TileEntities)
# lc = len(editor._loadedChunks)
# if lc > 20:
# refs = gc.get_referrers(chunk)
# print("Referrers:\n%s" % refs)
# print("WorldEditor: _loadedChunks: %d (_pending_removals: %d)" % (lc, len(editor._loadedChunks._pending_removals)))
print("[Tile]Entities: ", ents)
def saveall():
for cPos in pos[cStart:cEnd]:
dim.getChunk(*cPos).dirty = True
editor.saveChanges()
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = "AnvilWorld_1.8"
editor = templevel.TempLevel(filename)
dim = editor.getDimension()
cStart = 0
cEnd = 10000
chunkCount = cEnd - cStart
pos = list(dim.chunkPositions())
loadTime = timeit.timeit(loadall, number=1)
print("Loaded %d chunks in %.02fms (%f cps)" % (chunkCount, loadTime * 1000, chunkCount/loadTime))
print("Cache hits: %d, misses: %d, rejects: %d, max rejects: %d, queue: %d" % (
editor._chunkDataCache.hits, editor._chunkDataCache.misses,
editor._chunkDataCache.rejects, editor._chunkDataCache.max_rejects,
len(editor._chunkDataCache.queue)))
print("WorldEditor: _loadedChunks: %d" % (len(editor._loadedChunks),))
#saveTime = timeit.timeit(saveall, number=1)
#print("Saved %d chunks in %.02fms (%f cps)" % (chunkCount, saveTime * 1000, chunkCount/saveTime))
| [
"[email protected]"
] | |
6f20ea4026405a9598e5facc2c46b3e34bc3f1db | 80579d5cf31edd31750b644d6eb46a2b29ff4972 | /CandidateApp/migrations/0004_auto_20191104_0734.py | 392e3a7ab7e8e002f5e272f8bbfeb223b6a9d073 | [] | no_license | Nigar-mr/Vacancies | fb2935202488d957a4cccece0ac68a3ec052aa87 | a8c4605e66cb4cf425abd6565b265df5b458e26d | refs/heads/master | 2023-01-27T11:36:32.836172 | 2020-12-02T14:41:50 | 2020-12-02T14:41:50 | 317,890,920 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 865 | py | # Generated by Django 2.2.6 on 2019-11-04 07:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('CandidateApp', '0003_citymodel_countrymodel'),
]
operations = [
migrations.RemoveField(
model_name='candidatecv',
name='location',
),
migrations.AddField(
model_name='candidatecv',
name='city',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='CandidateApp.CityModel'),
),
migrations.AddField(
model_name='candidatecv',
name='country',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='CandidateApp.CountryModel'),
),
]
| [
"[email protected]"
] | |
91de258357da03040a37deec4cce1b055beea036 | 4ce94e6fdfb55a889a0e7c4788fa95d2649f7bca | /User/apps/logreg/urls.py | 13f5528d4db332284dfc1f9219fa72fb983eed21 | [] | no_license | HaochengYang/Django-class-assignment | 4018d8eb0619a99ebe8c3e47346d29934aafc66b | cb8f920f432209f88c810407ca646ee7dec82e22 | refs/heads/master | 2021-06-08T20:05:22.876794 | 2016-12-19T23:39:22 | 2016-12-19T23:39:22 | 75,032,572 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 309 | py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index, name="index"),
url(r'^register$',views.register, name="register"),
url(r'^login$',views.login, name="login"),
url(r'^main$',views.main, name="main"),
url(r'^logout$',views.logout, name="logout")
]
| [
"[email protected]"
] | |
8644cb81bf0fcfd6f2c5b8dbf1b318cdfb99784c | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_370/ch120_2020_04_01_03_35_57_135848.py | 9d294a0499ab557c0f53778c9d2f27dd6b98aebe | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 839 | py | import random
dinheiro = 100
while dinheiro > 0:
print (dinheiro)
aposta= int(input("Quanto voce quer apostar? "))
if aposta != 0:
n_ou_p=input("Voce quer apostar em um numero (n) ou paridade(p)? ")
if n_ou_p == "n":
numero=int(input("Escolha um numero entre 1 e 36: "))
r1=random.randint(0,36)
if numero == r1:
dinheiro += 35 * aposta
else:
dinheiro -= aposta
else:
paridade = input("Escolha entre Par(p) ou Impar(i): ")
r1 = ramdom.randint (0,36)
if paridade == 'p' and r1 % 2 == 0:
dinheiro += aposta
elif paridade == "i" and r1 % 2 != 0:
dinheiro += aposta
else:
dinheiro -= aposta
else:
dinheiro=0 | [
"[email protected]"
] | |
cd114c83b9966d2daf5cee241b255c9ac3014f68 | 24fe1f54fee3a3df952ca26cce839cc18124357a | /servicegraph/lib/python2.7/site-packages/acimodel-4.0_3d-py2.7.egg/cobra/modelimpl/fabric/rstofabricpaths.py | 0659e77a7c7208ae475bd9c3100f3f18424e752b | [] | no_license | aperiyed/servicegraph-cloudcenter | 4b8dc9e776f6814cf07fe966fbd4a3481d0f45ff | 9eb7975f2f6835e1c0528563a771526896306392 | refs/heads/master | 2023-05-10T17:27:18.022381 | 2020-01-20T09:18:28 | 2020-01-20T09:18:28 | 235,065,676 | 0 | 0 | null | 2023-05-01T21:19:14 | 2020-01-20T09:36:37 | Python | UTF-8 | Python | false | false | 9,325 | py | # coding=UTF-8
# **********************************************************************
# Copyright (c) 2013-2019 Cisco Systems, Inc. All rights reserved
# written by zen warriors, do not modify!
# **********************************************************************
from cobra.mit.meta import ClassMeta
from cobra.mit.meta import StatsClassMeta
from cobra.mit.meta import CounterMeta
from cobra.mit.meta import PropMeta
from cobra.mit.meta import Category
from cobra.mit.meta import SourceRelationMeta
from cobra.mit.meta import NamedSourceRelationMeta
from cobra.mit.meta import TargetRelationMeta
from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory
from cobra.model.category import MoCategory, PropCategory, CounterCategory
from cobra.mit.mo import Mo
# ##################################################
class RsToFabricPathS(Mo):
"""
"""
meta = SourceRelationMeta("cobra.model.fabric.RsToFabricPathS", "cobra.model.fabric.APathS")
meta.cardinality = SourceRelationMeta.N_TO_M
meta.moClassName = "fabricRsToFabricPathS"
meta.rnFormat = "rstoFabricPathS-[%(tDn)s]"
meta.category = MoCategory.RELATIONSHIP_TO_LOCAL
meta.label = "Super Class for Relation from Node to Interface Path Selector"
meta.writeAccessMask = 0x1
meta.readAccessMask = 0x1
meta.isDomainable = False
meta.isReadOnly = True
meta.isConfigurable = False
meta.isDeletable = False
meta.isContextRoot = False
meta.childClasses.add("cobra.model.fabric.CreatedBy")
meta.childClasses.add("cobra.model.health.Inst")
meta.childClasses.add("cobra.model.fault.Counts")
meta.childNamesAndRnPrefix.append(("cobra.model.fabric.CreatedBy", "source-"))
meta.childNamesAndRnPrefix.append(("cobra.model.fault.Counts", "fltCnts"))
meta.childNamesAndRnPrefix.append(("cobra.model.health.Inst", "health"))
meta.parentClasses.add("cobra.model.fabric.NodeCfg")
meta.superClasses.add("cobra.model.fabric.NodeToPathOverridePolicy")
meta.superClasses.add("cobra.model.reln.To")
meta.superClasses.add("cobra.model.reln.Inst")
meta.rnPrefixes = [
('rstoFabricPathS-', True),
]
prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("deleteAll", "deleteall", 16384)
prop._addConstant("deleteNonPresent", "deletenonpresent", 8192)
prop._addConstant("ignore", "ignore", 4096)
meta.props.add("childAction", prop)
prop = PropMeta("str", "deplSt", "deplSt", 18176, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "none"
prop._addConstant("delivered", "delivered", 1)
prop._addConstant("node-not-ready", "node-not-ready", 1073741824)
prop._addConstant("none", "none", 0)
prop._addConstant("not-registered-for-atg", "node-cannot-deploy-epg", 64)
prop._addConstant("not-registered-for-fabric-ctrls", "node-not-controller", 16)
prop._addConstant("not-registered-for-fabric-leafs", "node-not-leaf-for-fabric-policies", 4)
prop._addConstant("not-registered-for-fabric-node-group", "node-not-registered-for-node-group-policies", 32)
prop._addConstant("not-registered-for-fabric-oleafs", "node-not-capable-of-deploying-fabric-node-leaf-override", 2048)
prop._addConstant("not-registered-for-fabric-ospines", "node-not-capable-of-deploying-fabric-node-spine-override", 4096)
prop._addConstant("not-registered-for-fabric-pods", "node-has-not-joined-pod", 8)
prop._addConstant("not-registered-for-fabric-spines", "node-not-spine", 2)
prop._addConstant("not-registered-for-infra-leafs", "node-not-leaf-for-infra-policies", 128)
prop._addConstant("not-registered-for-infra-oleafs", "node-not-capable-of-deploying-infra-node-leaf-override", 512)
prop._addConstant("not-registered-for-infra-ospines", "node-not-capable-of-deploying-infra-node-spine-override", 1024)
prop._addConstant("not-registered-for-infra-spines", "node-not-spine-for-infra-policies", 256)
prop._addConstant("pod-misconfig", "node-belongs-to-different-pod", 8192)
prop._addConstant("policy-deployment-failed", "policy-deployment-failed", 2147483648)
meta.props.add("deplSt", prop)
prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN)
prop.label = "None"
prop.isDn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("dn", prop)
prop = PropMeta("str", "forceResolve", "forceResolve", 107, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = True
prop.defaultValueStr = "yes"
prop._addConstant("no", None, False)
prop._addConstant("yes", None, True)
meta.props.add("forceResolve", prop)
prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "local"
prop._addConstant("implicit", "implicit", 4)
prop._addConstant("local", "local", 0)
prop._addConstant("policy", "policy", 1)
prop._addConstant("replica", "replica", 2)
prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3)
meta.props.add("lcOwn", prop)
prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "never"
prop._addConstant("never", "never", 0)
meta.props.add("modTs", prop)
prop = PropMeta("str", "monPolDn", "monPolDn", 18185, PropCategory.REGULAR)
prop.label = "Monitoring policy attached to this observable object"
prop.isImplicit = True
prop.isAdmin = True
meta.props.add("monPolDn", prop)
prop = PropMeta("str", "rType", "rType", 106, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 1
prop.defaultValueStr = "mo"
prop._addConstant("local", "local", 3)
prop._addConstant("mo", "mo", 1)
prop._addConstant("service", "service", 2)
meta.props.add("rType", prop)
prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN)
prop.label = "None"
prop.isRn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("rn", prop)
prop = PropMeta("str", "state", "state", 103, PropCategory.REGULAR)
prop.label = "State"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "unformed"
prop._addConstant("cardinality-violation", "cardinality-violation", 5)
prop._addConstant("formed", "formed", 1)
prop._addConstant("invalid-target", "invalid-target", 4)
prop._addConstant("missing-target", "missing-target", 2)
prop._addConstant("unformed", "unformed", 0)
meta.props.add("state", prop)
prop = PropMeta("str", "stateQual", "stateQual", 104, PropCategory.REGULAR)
prop.label = "State Qualifier"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "none"
prop._addConstant("default-target", "default-target", 2)
prop._addConstant("mismatch-target", "mismatch-target", 1)
prop._addConstant("none", "none", 0)
meta.props.add("stateQual", prop)
prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("created", "created", 2)
prop._addConstant("deleted", "deleted", 8)
prop._addConstant("modified", "modified", 4)
meta.props.add("status", prop)
prop = PropMeta("str", "tCl", "tCl", 18178, PropCategory.REGULAR)
prop.label = "Target-class"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 6090
prop.defaultValueStr = "fabricAPathS"
prop._addConstant("fabricAPathS", None, 6090)
prop._addConstant("fabricLFPathS", None, 6091)
prop._addConstant("fabricSFPathS", None, 6096)
prop._addConstant("infraHPathS", None, 6105)
prop._addConstant("infraSHPathS", None, 8244)
prop._addConstant("unspecified", "unspecified", 0)
meta.props.add("tCl", prop)
prop = PropMeta("str", "tDn", "tDn", 18177, PropCategory.REGULAR)
prop.label = "Target-dn"
prop.isConfig = True
prop.isAdmin = True
prop.isCreateOnly = True
prop.isNaming = True
meta.props.add("tDn", prop)
prop = PropMeta("str", "tType", "tType", 105, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 1
prop.defaultValueStr = "mo"
prop._addConstant("all", "all", 2)
prop._addConstant("mo", "mo", 1)
prop._addConstant("name", "name", 0)
meta.props.add("tType", prop)
meta.namingProps.append(getattr(meta.props, "tDn"))
getattr(meta.props, "tDn").needDelimiter = True
def __init__(self, parentMoOrDn, tDn, markDirty=True, **creationProps):
namingVals = [tDn]
Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps)
# End of package file
# ##################################################
| [
"[email protected]"
] | |
29a81e6881db1268d23434dc6980737b6eb640d4 | 52855d750ccd5f2a89e960a2cd03365a3daf4959 | /ABC/ABC102_A.py | 5b3e4fd37e2243daff35ceda1216e174bf71c576 | [] | no_license | takuwaaan/Atcoder_Study | b15d4f3d15d48abb06895d5938bf8ab53fb73c08 | 6fd772c09c7816d147abdc50669ec2bbc1bc4a57 | refs/heads/master | 2021-03-10T18:56:04.416805 | 2020-03-30T22:36:49 | 2020-03-30T22:36:49 | 246,477,394 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 189 | py | # 最大公約数
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# 最小公倍数
def lcm(a, b):
return a * b // gcd(a, b)
N = int(input())
print(lcm(2, N))
| [
"[email protected]"
] | |
bffb93f11e2d156068446b36e4f0a07a925befaa | 9efe98cd4e2c4b23230ba8af2b98609b0a8654a5 | /articles/urls.py | cc4823f2d18d59695b2fe6aa45fc3bc87e971e07 | [] | no_license | Jordan-Rob/django-news | f0855d10f9056ad491d90d9086284ed3de468227 | fc73862274522a16530d2fd3497d6e90b7b109c2 | refs/heads/master | 2021-09-25T11:37:50.529863 | 2020-02-26T13:50:42 | 2020-02-26T13:50:42 | 241,844,795 | 1 | 0 | null | 2021-09-22T18:45:20 | 2020-02-20T09:34:47 | Python | UTF-8 | Python | false | false | 551 | py | from django.urls import path
from .views import (
ArticleListView,
ArticleCreateView,
ArticleDeleteView,
ArticleDetailView,
ArticleUpdateView,
)
urlpatterns = [
path('', ArticleListView.as_view(), name='article_list'),
path('new/', ArticleCreateView.as_view(), name='article_new'),
path('<int:pk>/', ArticleDetailView.as_view(), name='article_detail'),
path('<int:pk>/edit/', ArticleUpdateView.as_view(), name='article_edit'),
path('<int:pk>/delete/', ArticleDeleteView.as_view(), name='article_delete'),
]
| [
"[email protected]"
] | |
8579c92447a21ce7b508108375db792656afff0a | 7357d367b0af4650ccc5b783b7a59090fdde47bb | /library/k8s_v1_config_map.py | f1f041f9632980fdd20118debaac00931c8b2207 | [
"MIT"
] | permissive | BarracudaPff/code-golf-data-python | fb0cfc74d1777c4246d56a5db8525432bf37ab1a | 42e8858c2ebc6a061012bcadb167d29cebb85c5e | refs/heads/main | 2023-05-29T05:52:22.856551 | 2020-05-23T22:12:48 | 2020-05-23T22:12:48 | 378,832,634 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,574 | py | DOCUMENTATION = """
module: k8s_v1_config_map
short_description: Kubernetes ConfigMap
description:
- Manage the lifecycle of a config_map object. Supports check mode, and attempts to
to be idempotent.
version_added: 2.3.0
author: OpenShift (@openshift)
options:
annotations:
description:
- Annotations is an unstructured key value map stored with a resource that may
be set by external tools to store and retrieve arbitrary metadata. They are
not queryable and should be preserved when modifying objects.
type: dict
api_key:
description:
- Token used to connect to the API.
cert_file:
description:
- Path to a certificate used to authenticate with the API.
type: path
context:
description:
- The name of a context found in the Kubernetes config file.
data:
description:
- Data contains the configuration data. Each key must consist of alphanumeric
characters, '-', '_' or '.'.
type: dict
debug:
description:
- Enable debug output from the OpenShift helper. Logging info is written to KubeObjHelper.log
default: false
type: bool
force:
description:
- If set to C(True), and I(state) is C(present), an existing object will updated,
and lists will be replaced, rather than merged.
default: false
type: bool
host:
description:
- Provide a URL for acessing the Kubernetes API.
key_file:
description:
- Path to a key file used to authenticate with the API.
type: path
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the openshift client will attempt to load the default
configuration file from I(~/.kube/config.json).
type: path
labels:
description:
- Map of string keys and values that can be used to organize and categorize (scope
and select) objects. May match selectors of replication controllers and services.
type: dict
name:
description:
- Name must be unique within a namespace. Is required when creating resources,
although some resources may allow a client to request the generation of an appropriate
name automatically. Name is primarily intended for creation idempotence and
configuration definition. Cannot be updated.
namespace:
description:
- Namespace defines the space within each name must be unique. An empty namespace
is equivalent to the "default" namespace, but "default" is the canonical representation.
Not all objects are required to be scoped to a namespace - the value of this
field for those objects will be empty. Must be a DNS_LABEL. Cannot be updated.
password:
description:
- Provide a password for connecting to the API. Use in conjunction with I(username).
resource_definition:
description:
- Provide the YAML definition for the object, bypassing any modules parameters
intended to define object attributes.
type: dict
src:
description:
- Provide a path to a file containing the YAML definition of the object. Mutually
exclusive with I(resource_definition).
type: path
ssl_ca_cert:
description:
- Path to a CA certificate used to authenticate with the API.
type: path
state:
description:
- Determines if an object should be created, patched, or deleted. When set to
C(present), the object will be created, if it does not exist, or patched, if
parameter values differ from the existing object's attributes, and deleted,
if set to C(absent). A patch operation results in merging lists and updating
dictionaries, with lists being merged into a unique set of values. If a list
contains a dictionary with a I(name) or I(type) attribute, a strategic merge
is performed, where individual elements with a matching I(name_) or I(type)
are merged. To force the replacement of lists, set the I(force) option to C(True).
default: present
choices:
- present
- absent
username:
description:
- Provide a username for connecting to the API.
verify_ssl:
description:
- Whether or not to verify the API server's SSL certificates.
type: bool
requirements:
- kubernetes == 4.0.0
"""
EXAMPLES = """
"""
RETURN = """
api_version:
description: Requested API version
type: string
config_map:
type: complex
returned: when I(state) = C(present)
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
type: str
data:
description:
- Data contains the configuration data. Each key must consist of alphanumeric
characters, '-', '_' or '.'.
type: complex
contains: str, str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to. Cannot
be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
"""
def main():
try:
module = KubernetesAnsibleModule("config_map", "v1")
except KubernetesAnsibleException as exc:
raise Exception(exc.message)
try:
module.execute_module()
except KubernetesAnsibleException as exc:
module.fail_json(msg="Module failed!", error=str(exc))
if __name__ == "__main__":
main() | [
"[email protected]"
] | |
a616047134756ed93653e3641eeadb7056c6d93e | 52b5773617a1b972a905de4d692540d26ff74926 | /.history/permutations_20200723155542.py | 0a2cb82160de953b2379765e3b9c3fe802252d19 | [] | no_license | MaryanneNjeri/pythonModules | 56f54bf098ae58ea069bf33f11ae94fa8eedcabc | f4e56b1e4dda2349267af634a46f6b9df6686020 | refs/heads/master | 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 293 | py | def perm(arr):
# sort the array
if len(arr) == 0:
return 0
else:
arr.sort()
perm = set(arr)
maxValue = max(arr)
if len(perm) == maxValue:
return 1
eli:
print(perm([1,1,1])) | [
"[email protected]"
] | |
20d466c872a9e9cc3e8c0d6993541a1ee769c0e9 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/verbs/_dissed.py | bfd39eb88b44f035eafe50cb7e30ebacde72a66b | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 226 | py |
from xai.brain.wordbase.verbs._diss import _DISS
#calss header
class _DISSED(_DISS, ):
def __init__(self,):
_DISS.__init__(self)
self.name = "DISSED"
self.specie = 'verbs'
self.basic = "diss"
self.jsondata = {}
| [
"[email protected]"
] | |
ca12d0553370be58a4e3f461d5eb2ef2d6995281 | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/nncanon.py | fbf0d87bad8b52f95da4ae2656a4b80d205e6358 | [] | no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 1,300 | py | ii = [('CookGHP3.py', 2), ('MarrFDI.py', 2), ('GodwWSL2.py', 1), ('ChanWS.py', 1), ('RogePAV.py', 1), ('SadlMLP.py', 2), ('WilbRLW.py', 1), ('WilbRLW4.py', 1), ('ProuWCM.py', 1), ('CookGHP.py', 1), ('LeakWTI2.py', 1), ('LeakWTI3.py', 1), ('PettTHE.py', 1), ('AubePRP.py', 2), ('AdamWEP.py', 1), ('ClarGE2.py', 2), ('CarlTFR.py', 2), ('LyttELD.py', 1), ('RoscTTI3.py', 1), ('KiddJAE.py', 1), ('RoscTTI2.py', 1), ('CoolWHM.py', 2), ('ClarGE.py', 19), ('BuckWGM.py', 2), ('IrviWVD.py', 1), ('LyelCPG.py', 4), ('DaltJMA.py', 92), ('WestJIT2.py', 1), ('DibdTRL2.py', 2), ('AinsWRR.py', 1), ('MedwTAI.py', 1), ('WadeJEB.py', 43), ('NewmJLP.py', 39), ('GodwWLN.py', 4), ('SoutRD2.py', 1), ('LeakWTI4.py', 4), ('SoutRD.py', 1), ('BuckWGM2.py', 1), ('MereHHB3.py', 6), ('HowiWRL2.py', 1), ('MereHHB.py', 13), ('WilkJMC.py', 1), ('HogaGMM.py', 6), ('MackCNH.py', 8), ('HallFAC.py', 1), ('RoscTTI.py', 1), ('ThomGLG.py', 1), ('MackCNH2.py', 3), ('BellCHM.py', 1), ('AinsWRR2.py', 2), ('MereHHB2.py', 19), ('BrewDTO.py', 2), ('JacoWHI.py', 2), ('ClarGE3.py', 11), ('RogeSIP.py', 2), ('DibdTRL.py', 7), ('FitzRNS2.py', 3), ('BeckWRE.py', 2), ('TaylIF.py', 25), ('WordWYR.py', 1), ('DibdTBR.py', 1), ('ChalTPW.py', 2), ('ThomWEC.py', 1), ('KeigTSS.py', 8), ('KirbWPW.py', 1), ('BentJDO.py', 1), ('ClarGE4.py', 19)] | [
"[email protected]"
] | |
7b7236e04ce84478b326d1bf5639d8e284d3c418 | 47175228ce25812549eb5203fc8b86b76fec6eb9 | /API_scripts/dfp/dfp_python3/v201411/custom_field_service/create_custom_fields.py | f810346ad2e1082080513f0a6bbf67f474035af9 | [] | no_license | noelleli/documentation | c1efe9c2bdb169baa771e9c23d8f4e2683c2fe20 | a375698b4cf0776d52d3a9d3c17d20143bd252e1 | refs/heads/master | 2021-01-10T05:41:30.648343 | 2016-02-13T05:46:31 | 2016-02-13T05:46:31 | 51,477,460 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,146 | py | #!/usr/bin/python
#
# Copyright 2014 Google Inc. 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.
"""This example creates custom fields.
To determine which custom fields exist, run get_all_custom_fields.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
Tags: CustomFieldService.createCustomFields
"""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
import uuid
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
custom_field_service = client.GetService(
'CustomFieldService', version='v201411')
# Create custom field objects.
custom_fields = [
{
'name': 'Customer comments #%s' % uuid.uuid4(),
'entityType': 'LINE_ITEM',
'dataType': 'STRING',
'visibility': 'FULL'
}, {
'name': 'Internal approval status #%s' % uuid.uuid4(),
'entityType': 'LINE_ITEM',
'dataType': 'DROP_DOWN',
'visibility': 'FULL'
}
]
# Add custom fields.
custom_fields = custom_field_service.createCustomFields(custom_fields)
# Display results.
for custom_field in custom_fields:
print(('Custom field with ID \'%s\' and name \'%s\' was created.'
% (custom_field['id'], custom_field['name'])))
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client)
| [
"[email protected]"
] | |
7f45e9874c2bec2f7cbb448475e5c45d63d5972f | 315450354c6ddeda9269ffa4c96750783963d629 | /CMSSW_7_0_4/src/TotemRawData/Readers/test/.svn/text-base/raw_data_example.py.svn-base | fe26aa920afdb0d2be6cac4e77ee9b7bb3cb236e | [] | no_license | elizamelo/CMSTOTEMSim | e5928d49edb32cbfeae0aedfcf7bd3131211627e | b415e0ff0dad101be5e5de1def59c5894d7ca3e8 | refs/heads/master | 2021-05-01T01:31:38.139992 | 2017-09-12T17:07:12 | 2017-09-12T17:07:12 | 76,041,270 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 934 | import FWCore.ParameterSet.Config as cms
process = cms.Process("rpReconstruction")
# minimum of logs
process.load("Configuration.TotemCommon.LoggerMin_cfi")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(2)
)
process.load('TotemRawData.Readers.RawDataSource_cfi')
process.source.verbosity = 10
process.source.printProgressFrequency = 1
process.source.fileNames.append('/castor/cern.ch/totem/LHCRawData/2015/Physics/run_EVB-wn10_9298.068.vmeb')
process.source.fileNames.append('/castor/cern.ch/totem/LHCRawData/2015/Physics/run_9487_EVB11_2.005.srs')
# raw to digi conversion
process.load('TotemCondFormats.DAQInformation.DAQMappingSourceXML_cfi')
process.DAQMappingSourceXML.mappingFileNames.append('TotemCondFormats/DAQInformation/data/rp_220.xml')
process.load('TotemRawData.RawToDigi.Raw2DigiProducer_cfi')
process.Raw2DigiProducer.verbosity = 0
process.p = cms.Path(
process.Raw2DigiProducer
)
| [
"[email protected]"
] | ||
ee93cddd16945c87b62476643878d8e30493b53a | 3db4afb573e6e82e9308c43ae13e9426c5c77c80 | /glue/conftest.py | 7ed2f145177687ccad2672345c69031f834095a5 | [
"BSD-3-Clause"
] | permissive | mariobuikhuizen/glue | af8a53498fd4e2365bf98e5089677efdcdb67127 | 6b968b352bc5ad68b95ad5e3bb25550782a69ee8 | refs/heads/master | 2023-01-08T07:33:03.006145 | 2020-09-20T09:25:06 | 2020-09-20T09:25:06 | 298,285,919 | 0 | 0 | NOASSERTION | 2020-09-24T13:22:37 | 2020-09-24T13:22:36 | null | UTF-8 | Python | false | false | 3,493 | py | import os
import sys
import warnings
import pytest
try:
from qtpy import PYSIDE2
except Exception:
PYSIDE2 = False
from glue.config import CFG_DIR as CFG_DIR_ORIG
try:
import objgraph
except ImportError:
OBJGRAPH_INSTALLED = False
else:
OBJGRAPH_INSTALLED = True
STDERR_ORIGINAL = sys.stderr
ON_APPVEYOR = os.environ.get('APPVEYOR', 'False') == 'True'
def pytest_runtest_teardown(item, nextitem):
sys.stderr = STDERR_ORIGINAL
global start_dir
os.chdir(start_dir)
def pytest_addoption(parser):
parser.addoption("--no-optional-skip", action="store_true", default=False,
help="don't skip any tests with optional dependencies")
start_dir = None
def pytest_configure(config):
global start_dir
start_dir = os.path.abspath('.')
os.environ['GLUE_TESTING'] = 'True'
if config.getoption('no_optional_skip'):
from glue.tests import helpers
for attr in helpers.__dict__:
if attr.startswith('requires_'):
# The following line replaces the decorators with a function
# that does noting, effectively disabling it.
setattr(helpers, attr, lambda f: f)
# Make sure we don't affect the real glue config dir
import tempfile
from glue import config
config.CFG_DIR = tempfile.mkdtemp()
# Start up QApplication, if the Qt code is present
try:
from glue.utils.qt import get_qapp
except Exception:
# Note that we catch any exception, not just ImportError, because
# QtPy can raise a PythonQtError.
pass
else:
get_qapp()
# Force loading of plugins
from glue.main import load_plugins
load_plugins()
def pytest_report_header(config):
from glue import __version__
glue_version = "%20s:\t%s" % ("glue", __version__)
from glue._deps import get_status
return os.linesep + glue_version + os.linesep + os.linesep + get_status()
def pytest_unconfigure(config):
os.environ.pop('GLUE_TESTING')
# Reset configuration directory to original one
from glue import config
config.CFG_DIR = CFG_DIR_ORIG
# Remove reference to QApplication to prevent segmentation fault on PySide
try:
from glue.utils.qt import app
app.qapp = None
except Exception: # for when we run the tests without the qt directories
# Note that we catch any exception, not just ImportError, because
# QtPy can raise a PythonQtError.
pass
if OBJGRAPH_INSTALLED and not ON_APPVEYOR:
# Make sure there are no lingering references to GlueApplication
obj = objgraph.by_type('GlueApplication')
if len(obj) > 0:
objgraph.show_backrefs(objgraph.by_type('GlueApplication'))
warnings.warn('There are {0} remaining references to GlueApplication'.format(len(obj)))
# Uncomment when checking for memory leaks
# objgraph.show_most_common_types(limit=100)
# With PySide2, tests can fail in a non-deterministic way with the following
# error:
#
# AttributeError: 'PySide2.QtGui.QStandardItem' object has no attribute 'connect'
#
# Until this can be properly debugged and fixed, we xfail any test that fails
# with this exception
if PYSIDE2:
def pytest_runtest_call(__multicall__):
try:
__multicall__.execute()
except AttributeError as exc:
if 'PySide2.QtGui.QStandardItem' in str(exc):
pytest.xfail()
| [
"[email protected]"
] | |
6d98ccacbdf0ae25f09883599e16712c57df834b | f350464b0ec1d2747a93ea533b04746c8ff68c18 | /setup.py | 0b1315dc2d83cf67c02b1f8d493b7614673acf85 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | erdogant/hgboost | ed4e0e31aff87fba2c9591b59b70ffc7a91c27b7 | 8492331b15b883918d2159a61563932ae82bf313 | refs/heads/master | 2023-08-17T14:08:01.729366 | 2023-08-15T17:01:03 | 2023-08-15T17:01:03 | 257,025,146 | 48 | 15 | NOASSERTION | 2020-09-11T08:09:36 | 2020-04-19T14:48:23 | Python | UTF-8 | Python | false | false | 1,549 | py | import setuptools
import re
# versioning ------------
VERSIONFILE="hgboost/__init__.py"
getversion = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", open(VERSIONFILE, "rt").read(), re.M)
if getversion:
new_version = getversion.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,))
# Setup ------------
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
install_requires=['datazets', 'pypickle', 'matplotlib','numpy','pandas','tqdm','hyperopt','lightgbm','catboost','xgboost','classeval','treeplot','df2onehot','colourmap','seaborn'],
python_requires='>=3',
name='hgboost',
version=new_version,
author="Erdogan Taskesen",
author_email="[email protected]",
description="hgboost is a python package for hyperparameter optimization for xgboost, catboost and lightboost for both classification and regression tasks.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://erdogant.github.io/hgboost",
download_url = 'https://github.com/erdogant/hgboost/archive/'+new_version+'.tar.gz',
packages=setuptools.find_packages(), # Searches throughout all dirs for files to include
include_package_data=True, # Must be true to include files depicted in MANIFEST.in
license_files=["LICENSE"],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
| [
"[email protected]"
] | |
b815002f092f7fa8b69f3b801a668fdef61e40b4 | d8edd97f8f8dea3f9f02da6c40d331682bb43113 | /networks848.py | f7be8eb4307013b16d110cd51277a2c9fe945916 | [] | no_license | mdubouch/noise-gan | bdd5b2fff3aff70d5f464150443d51c2192eeafd | 639859ec4a2aa809d17eb6998a5a7d217559888a | refs/heads/master | 2023-07-15T09:37:57.631656 | 2021-08-27T11:02:45 | 2021-08-27T11:02:45 | 284,072,311 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,798 | py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
__version__ = 205
# Number of wires in the CDC
n_wires = 3606
# Number of continuous features (E, t, dca)
n_features = 3
geom_dim = 3
def wire_hook(grad):
print('wg %.2e %.2e' % (grad.abs().mean().item(), grad.std().item()))
return grad
class Gen(nn.Module):
def __init__(self, ngf, latent_dims, seq_len, encoded_dim):
super().__init__()
self.ngf = ngf
self.seq_len = seq_len
self.version = __version__
# Input: (B, latent_dims, 1)
self.act = nn.ReLU()
n512 = 512
self.lin0 = nn.Linear(latent_dims, seq_len//32*n512, bias=True)
self.dropout = nn.Dropout(0.1)
self.n512 = n512
n256 = n512 // 2
n128 = n512 // 4
n64 = n512 // 8
n32 = n512 // 16
n16 = n512 // 32
class GBlock(nn.Module):
def __init__(self, in_c, out_c, k_s, stride, padding):
super().__init__()
self.bn0 = nn.InstanceNorm1d(in_c)
self.conv = nn.ConvTranspose1d(in_c, out_c, k_s, stride, padding)
self.bn = nn.InstanceNorm1d(out_c)
self.conv1 = nn.ConvTranspose1d(in_c + out_c, out_c, 1, 1, 0)
self.act = nn.ReLU()
def forward(self, x):
y = self.bn0(x)
y = self.conv(y)
y = self.bn(self.act(y))
x0 = F.interpolate(x, size=y.shape[2], mode='nearest')
y = self.act(self.conv1(torch.cat([x0, y], dim=1)))
return y
self.convu1 = GBlock(n512, n512, 4, 4, 0)
self.convu2 = GBlock(n512, n256, 4, 4, 0)
self.convu3 = GBlock(n256, n128, 2, 2, 0)
self.convw2 = GBlock(n128, n64, 3, 1, 1)
self.convw1 = nn.Conv1d(n64, n_wires, 1, 1, 0)
#self.linw1 = nn.Linear(n512, n256)
#self.linw2 = nn.Linear(n256, n128)
#self.linw3 = nn.Linear(n128, n_wires)
#self.convp4 = nn.ConvTranspose1d(n512, n256, 12, 4, 4)
#self.bnp4 = nn.BatchNorm1d(n256)
#self.convp3 = nn.ConvTranspose1d(n256, n128, 12, 4, 4)
#self.bnp3 = nn.BatchNorm1d(n512+n128)
#self.convp2 = nn.ConvTranspose1d(n512+n128, n64, 3, 1, 1)
#self.bnp2 = nn.BatchNorm1d(n64)
self.convp2 = GBlock(n128, n64, 3, 1, 1)
self.convp1 = nn.Conv1d(n64, n_features, 1, 1, 0)
#self.conv1 = nn.ConvTranspose1d(n128, n128, 32, 2, 15)
#self.bn1 = nn.BatchNorm1d(n128)
#self.convw1 = nn.ConvTranspose1d(n128, n_wires, 1, 1, 0, bias=True)
#self.convp1 = nn.ConvTranspose1d(n128, n_features, 1, 1, 0)
self.out = nn.Tanh()
self.max_its = 3000
self.temp_min = 1.0
self.gen_it = 3000
def forward(self, z, wire_to_xy):
#print('latent space %.2e %.2e' % (z.mean().item(), z.std().item()))
# z: random point in latent space
x = self.act(self.lin0(z).reshape(-1, self.n512, self.seq_len // 32))
x = self.convu1(x)
x = self.convu2(x)
x = self.convu3(x)
w = self.convw2(x)
w = self.convw1(w)
#print(w.unsqueeze(0).shape)
#print((w.unsqueeze(0) - wire_to_xy.view(n_wires, 1, geom_dim, 1)).shape)
# w: (b, 2, seq)
# wire_to_xy: (2, n_wires)
#print(wire_to_xy.unsqueeze(0).unsqueeze(2).shape)
#print(w.unsqueeze(3).shape)
#import matplotlib.pyplot as plt
#import matplotlib.lines as lines
#plt.figure()
#plt.scatter(w[:,0,:].detach().cpu(), w[:,1,:].detach().cpu(), s=1)
#_l = lines.Line2D(w[:,0,:].detach().cpu(), w[:,1,:].detach().cpu(), linewidth=0.1, color='gray', alpha=0.7)
#plt.gca().add_line(_l)
#plt.gca().set_aspect(1.0)
#plt.savefig('test.png')
#plt.close()
#import matplotlib.pyplot as plt
#plt.figure()
#plt.plot(w[0,:,0].detach().cpu())
#plt.savefig('testw.png')
#plt.close()
#wdist = torch.norm(w.unsqueeze(3) - wire_to_xy.unsqueeze(0).unsqueeze(2), dim=1)
#print(wdist.shape)
##print(1/wdist)
#plt.figure()
#plt.plot(wdist[0,0,:].detach().cpu())
#plt.savefig('test.png')
#plt.close()
#self.gen_it += 1
tau = 1. / ((1./self.temp_min)**(self.gen_it / self.max_its))
#print(tau)
wg = F.gumbel_softmax(w, dim=1, hard=True, tau=tau)
#wg = F.softmax(w, dim=1)
#print(wg.shape)
#exit(1)
#wg.register_hook(wire_hook)
#xy = torch.tensordot(wg, wire_to_xy, dims=[[1],[1]]).permute(0,2,1)
#p = self.act(self.bnp4(self.convp4(self.act(x))))
#p = self.convp3(p)
#p = torch.cat([p, F.interpolate(x, size=p.shape[2])], dim=1)
#p = self.act(self.bnp3(p))
#p = self.act(self.bnp2(self.convp2(p)))
p = self.convp2(x)
p = self.convp1(p)
#return torch.cat([self.out(p), xy], dim=1), wg
return self.out(p), wg
def xy_hook(grad):
print('xy %.2e %.2e' % (grad.abs().mean().item(), grad.std().item()))
return grad
class Disc(nn.Module):
def __init__(self, ndf, seq_len, encoded_dim):
super().__init__()
self.version = __version__
# (B, n_features, 256)
self.act = nn.LeakyReLU(0.2)
n768 = 768
n512 = 512
n256 = n512 // 2
n128 = n256 // 2
n64 = 32
self.convw0 = nn.Conv1d(n_wires, n64, 1, 1, 0, bias=False)
self.convw1 = nn.Conv1d(n64, n64, 1, 1, 0)
self.convw2 = nn.Conv1d(n64, n64, 1, 1, 0)
self.convw3 = nn.Conv1d(n64, n64, 1, 1, 0)
self.convg0 = nn.Conv1d(geom_dim, 4, 1, 1, 0, bias=False)
self.convg1 = nn.Conv1d(4, 8, 1, 1, 0)
self.convg2 = nn.Conv1d(8, 16, 1, 1, 0)
self.convg3 = nn.Conv1d(16, n64, 1, 1, 0)
self.convp0 = nn.Conv1d(n_features, n64, 1, 1, 0)
self.conv1 = nn.Conv1d(n64+n64+n64, n128, 2, 2, 0)
self.conv2 = nn.Conv1d(n128, n256, 2, 2, 0)
self.conv3 = nn.Conv1d(n256, n512, 2, 2, 0)
self.lin0 = nn.Linear(n512, 1)
self.dropout = nn.Dropout(0.1)
self.out = nn.Identity()
def forward(self, x_, w_, wire_sphere):
# x_ is concatenated tensor of p_ and w_, shape (batch, features+n_wires, seq_len)
# p_ shape is (batch, features, seq_len),
# w_ is AE-encoded wire (batch, encoded_dim, seq_len)
seq_len = x_.shape[2]
#dist = ((xy - nn.ConstantPad1d((1, 0), 0.0)(xy[:,:,:-1]))**2).sum(dim=1).unsqueeze(1)
p = x_
#xy = x[:,n_features:n_features+geom_dim]
wg = w_
xy = torch.tensordot(wg, wire_sphere, dims=[[1], [1]]).permute(0,2,1)
p0 = self.convp0(p)
w0 = self.convw3(self.act(self.convw2(self.act(self.convw1(self.convw0(wg))))))
g0 = self.convg3(self.act(self.convg2(self.act(self.convg1(self.convg0(xy))))))
#g0 = torch.cat([w0, xy], dim=1)
x0 = torch.cat([p0, w0, g0], dim=1)
x1 = self.conv1(self.dropout(x0))
#x0 = F.interpolate(x0, size=x1.shape[2], mode='nearest')
x2 = self.dropout(self.conv2(self.act(x1)))#self.act(torch.cat([x0, x1], dim=1)))
x3 = self.conv3(self.act(x2))
x = self.act(x3)
x = self.lin0(x.mean(2)).squeeze()
return self.out(x)
class VAE(nn.Module):
def __init__(self, encoded_dim):
super().__init__()
class Enc(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.act = nn.LeakyReLU(0.2)
self.lin1 = nn.Linear(n_wires, hidden_size)
self.lin2 = nn.Linear(hidden_size, encoded_dim)
self.out = nn.Tanh()
def forward(self, x):
x = self.act(self.lin1(x))
return self.out(self.lin2(x))
class Dec(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.act = nn.ReLU()
self.lin1 = nn.Linear(encoded_dim, hidden_size)
self.lin2 = nn.Linear(hidden_size, n_wires)
def forward(self, x):
x = self.act(self.lin1(x))
return self.lin2(x)
self.enc_net = Enc(512)
self.dec_net = Dec(512)
def enc(self, x):
return self.enc_net(x.permute(0, 2, 1)).permute(0,2,1)
def dec(self, x):
return self.dec_net(x.permute(0, 2, 1)).permute(0,2,1)
def forward(self, x):
y = self.dec_net(self.enc_net(x))
return y
def get_n_params(model):
return sum(p.reshape(-1).shape[0] for p in model.parameters())
| [
"[email protected]"
] | |
8830c2898a2a2fdf1585445d96bea0025756f561 | ed54290846b5c7f9556aacca09675550f0af4c48 | /salt/salt/modules/boto_kms.py | ec2ea5bc01595adf8767bcb4cf716358e7dc0430 | [
"Apache-2.0"
] | permissive | smallyear/linuxLearn | 87226ccd8745cd36955c7e40cafd741d47a04a6f | 342e5020bf24b5fac732c4275a512087b47e578d | refs/heads/master | 2022-03-20T06:02:25.329126 | 2019-08-01T08:39:59 | 2019-08-01T08:39:59 | 103,765,131 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17,620 | py | # -*- coding: utf-8 -*-
'''
Connection module for Amazon KMS
.. versionadded:: 2015.8.0
:configuration: This module accepts explicit kms credentials but can also utilize
IAM roles assigned to the instance trough Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More Information available at::
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
If IAM roles are not used you need to specify them either in a pillar or
in the minion's config file::
kms.keyid: GKTADJGHEIQSXMKKRBJ08H
kms.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
A region may also be specified in the configuration::
kms.region: us-east-1
If a region is not specified, the default is us-east-1.
It's also possible to specify key, keyid and region via a profile, either
as a passed in dict, or as a string to pull from pillars or minion config:
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
:depends: boto
'''
# keep lint from choking on _get_conn and _cache_id
# pylint: disable=E0602
from __future__ import absolute_import
# Import Python libs
import logging
from salt.serializers import json
from distutils.version import LooseVersion as _LooseVersion # pylint: disable=import-error,no-name-in-module
# Import Salt libs
import salt.utils.compat
import salt.utils.odict as odict
log = logging.getLogger(__name__)
# Import third party libs
try:
# pylint: disable=unused-import
import boto
# KMS added in version 2.38.0
required_boto_version = '2.38.0'
if (_LooseVersion(boto.__version__) <
_LooseVersion(required_boto_version)):
msg = 'boto_kms requires boto {0}.'.format(required_boto_version)
log.debug(msg)
raise ImportError()
import boto.kms
# pylint: enable=unused-import
logging.getLogger('boto').setLevel(logging.CRITICAL)
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def __virtual__():
'''
Only load if boto libraries exist.
'''
if not HAS_BOTO:
return False
return True
def __init__(opts):
salt.utils.compat.pack_dunder(__name__)
if HAS_BOTO:
__utils__['boto.assign_funcs'](__name__, 'kms', pack=__salt__)
def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None,
profile=None):
'''
Create a display name for a key.
CLI example::
salt myminion boto_kms.create_alias 'alias/mykey' key_id
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
conn.create_alias(alias_name, target_key_id)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
def create_grant(key_id, grantee_principal, retiring_principal=None,
operations=None, constraints=None, grant_tokens=None,
region=None, key=None, keyid=None, profile=None):
'''
Adds a grant to a key to specify who can access the key and under what
conditions.
CLI example::
salt myminion boto_kms.create_grant 'alias/mykey' 'arn:aws:iam::1111111:/role/myrole' operations='["Encrypt","Decrypt"]'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if key_id.startswith('alias/'):
key_id = _get_key_id(key_id)
r = {}
try:
r['grant'] = conn.create_grant(
key_id,
grantee_principal,
retiring_principal=retiring_principal,
operations=operations,
constraints=constraints,
grant_tokens=grant_tokens
)
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def create_key(policy=None, description=None, key_usage=None, region=None,
key=None, keyid=None, profile=None):
'''
Creates a master key.
CLI example::
salt myminion boto_kms.create_key '{"Statement":...}' "My master key"
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
_policy = json.serialize(policy)
try:
key_metadata = conn.create_key(
_policy,
description=description,
key_usage=key_usage
)
r['key_metadata'] = key_metadata['KeyMetadata']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None,
region=None, key=None, keyid=None, profile=None):
'''
Decrypt ciphertext.
CLI example::
salt myminion boto_kms.decrypt encrypted_ciphertext
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
plaintext = conn.decrypt(
ciphertext_blob,
encryption_context=encryption_context,
grant_tokens=grant_tokens
)
r['plaintext'] = plaintext['Plaintext']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def key_exists(key_id, region=None, key=None, keyid=None, profile=None):
'''
Check for the existence of a key.
CLI example::
salt myminion boto_kms.key_exists 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.describe_key(key_id)
# TODO: add to context cache
r['result'] = True
except boto.exception.BotoServerError as e:
if isinstance(e, boto.kms.exceptions.NotFoundException):
r['result'] = False
return r
r['error'] = __utils__['boto.get_error'](e)
return r
def _get_key_id(alias, region=None, key=None, keyid=None, profile=None):
'''
From an alias, get a key_id.
'''
key_metadata = describe_key(
alias, region, key, keyid, profile
)['key_metadata']
return key_metadata['KeyId']
def describe_key(key_id, region=None, key=None, keyid=None, profile=None):
'''
Get detailed information about a key.
CLI example::
salt myminion boto_kms.describe_key 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.describe_key(key_id)
# TODO: add to context cache
r['key_metadata'] = key['KeyMetadata']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def disable_key(key_id, region=None, key=None, keyid=None, profile=None):
'''
Mark key as disabled.
CLI example::
salt myminion boto_kms.disable_key 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.disable_key(key_id)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
def disable_key_rotation(key_id, region=None, key=None, keyid=None,
profile=None):
'''
Disable key rotation for specified key.
CLI example::
salt myminion boto_kms.disable_key_rotation 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.disable_key_rotation(key_id)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
def enable_key(key_id, region=None, key=None, keyid=None, profile=None):
'''
Mark key as enabled.
CLI example::
salt myminion boto_kms.enable_key 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.enable_key(key_id)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
def enable_key_rotation(key_id, region=None, key=None, keyid=None,
profile=None):
'''
Disable key rotation for specified key.
CLI example::
salt myminion boto_kms.enable_key_rotation 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.enable_key_rotation(key_id)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,
region=None, key=None, keyid=None, profile=None):
'''
Encrypt plaintext into cipher text using specified key.
CLI example::
salt myminion boto_kms.encrypt 'alias/mykey' 'myplaindata' '{"aws:username":"myuser"}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
ciphertext = conn.encrypt(
key_id,
plaintext,
encryption_context=encryption_context,
grant_tokens=grant_tokens
)
r['ciphertext'] = ciphertext['CiphertextBlob']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
key_spec=None, grant_tokens=None, region=None, key=None,
keyid=None, profile=None):
'''
Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
data_key = conn.generate_data_key(
key_id,
encryption_context=encryption_context,
number_of_bytes=number_of_bytes,
key_spec=key_spec,
grant_tokens=grant_tokens
)
r['data_key'] = data_key
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def generate_data_key_without_plaintext(
key_id, encryption_context=None, number_of_bytes=None, key_spec=None,
grant_tokens=None, region=None, key=None, keyid=None, profile=None
):
'''
Generate a secure data key without a plaintext copy of the key.
CLI example::
salt myminion boto_kms.generate_data_key_without_plaintext 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
data_key = conn.generate_data_key_without_plaintext(
key_id,
encryption_context=encryption_context,
number_of_bytes=number_of_bytes,
key_spec=key_spec,
grant_tokens=grant_tokens
)
r['data_key'] = data_key
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def generate_random(number_of_bytes=None, region=None, key=None, keyid=None,
profile=None):
'''
Generate a random string.
CLI example::
salt myminion boto_kms.generate_random number_of_bytes=1024
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
random = conn.generate_random(number_of_bytes)
r['random'] = random['Plaintext']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None,
profile=None):
'''
Get the policy for the specified key.
CLI example::
salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key_policy = conn.get_key_policy(key_id, policy_name)
r['key_policy'] = json.deserialize(
key_policy['Policy'],
object_pairs_hook=odict.OrderedDict
)
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def get_key_rotation_status(key_id, region=None, key=None, keyid=None,
profile=None):
'''
Get status of whether or not key rotation is enabled for a key.
CLI example::
salt myminion boto_kms.get_key_rotation_status 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key_rotation_status = conn.get_key_rotation_status(key_id)
r['result'] = key_rotation_status['KeyRotationEnabled']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def list_grants(key_id, limit=None, marker=None, region=None, key=None,
keyid=None, profile=None):
'''
List grants for the specified key.
CLI example::
salt myminion boto_kms.list_grants 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if key_id.startswith('alias/'):
key_id = _get_key_id(key_id)
r = {}
try:
grants = conn.list_grants(
key_id,
limit=limit,
marker=marker
)
# TODO: handle limit/marker automatically
r['grants'] = grants['Grants']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def list_key_policies(key_id, limit=None, marker=None, region=None, key=None,
keyid=None, profile=None):
'''
List key_policies for the specified key.
CLI example::
salt myminion boto_kms.list_key_policies 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if key_id.startswith('alias/'):
key_id = _get_key_id(key_id)
r = {}
try:
key_policies = conn.list_key_policies(
key_id,
limit=limit,
marker=marker
)
# TODO: handle limit, marker and truncation automatically.
r['key_policies'] = key_policies['PolicyNames']
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def put_key_policy(key_id, policy_name, policy, region=None, key=None,
keyid=None, profile=None):
'''
Attach a key policy to the specified key.
CLI example::
salt myminion boto_kms.put_key_policy 'alias/mykey' default '{"Statement":...}'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
conn.put_key_policy(key_id, policy_name, json.serialize(policy))
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
def re_encrypt(ciphertext_blob, destination_key_id,
source_encryption_context=None,
destination_encryption_context=None, grant_tokens=None,
region=None, key=None, keyid=None, profile=None):
'''
Reencrypt encrypted data with a new master key.
CLI example::
salt myminion boto_kms.re_encrypt 'encrypted_data' 'alias/mynewkey' default '{"Statement":...}'
'''
conn = _get_conn(
region=region,
key=key,
keyid=keyid,
profile=profile
)
r = {}
try:
ciphertext = conn.re_encrypt(
ciphertext_blob, destination_key_id, source_encryption_context,
destination_encryption_context, grant_tokens
)
r['ciphertext'] = ciphertext
except boto.exception.BotoServerError as e:
r['error'] = __utils__['boto.get_error'](e)
return r
def revoke_grant(key_id, grant_id, region=None, key=None, keyid=None,
profile=None):
'''
Revoke a grant from a key.
CLI example::
salt myminion boto_kms.revoke_grant 'alias/mykey' 8u89hf-j09j...
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if key_id.startswith('alias/'):
key_id = _get_key_id(key_id)
r = {}
try:
conn.revoke_grant(key_id, grant_id)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
def update_key_description(key_id, description, region=None, key=None,
keyid=None, profile=None):
'''
Update a key's description.
CLI example::
salt myminion boto_kms.update_key_description 'alias/mykey' 'My key'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
conn.update_key_description(key_id, description)
r['result'] = True
except boto.exception.BotoServerError as e:
r['result'] = False
r['error'] = __utils__['boto.get_error'](e)
return r
| [
"[email protected]"
] | |
d5baa1faff9f4d00231718d2daf693d838aae255 | 5537eec7f43098d216d2b550678c8d10b2a26f09 | /venv/tower/lib/python2.7/site-packages/openstackclient/identity/v3/group.py | df684c129b58ffd52b260bbe46cb320276c2f08a | [] | no_license | wipro-sdx/Automation | f0ae1512b8d9d491d7bacec94c8906d06d696407 | a8c46217d0fbe51a71597b5db87cbe98ed19297a | refs/heads/master | 2021-07-08T11:09:05.314435 | 2018-05-02T07:18:54 | 2018-05-02T07:18:54 | 131,812,982 | 0 | 1 | null | 2020-07-23T23:22:33 | 2018-05-02T07:15:28 | Python | UTF-8 | Python | false | false | 12,118 | py | # Copyright 2012-2013 OpenStack Foundation
#
# 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.
#
"""Group action implementations"""
import logging
import sys
from keystoneauth1 import exceptions as ks_exc
from osc_lib.command import command
from osc_lib import utils
import six
from openstackclient.i18n import _
from openstackclient.identity import common
LOG = logging.getLogger(__name__)
class AddUserToGroup(command.Command):
_description = _("Add user to group")
def get_parser(self, prog_name):
parser = super(AddUserToGroup, self).get_parser(prog_name)
parser.add_argument(
'group',
metavar='<group>',
help=_('Group to contain <user> (name or ID)'),
)
parser.add_argument(
'user',
metavar='<user>',
help=_('User to add to <group> (name or ID)'),
)
common.add_group_domain_option_to_parser(parser)
common.add_user_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
user_id = common.find_user(identity_client,
parsed_args.user,
parsed_args.user_domain).id
group_id = common.find_group(identity_client,
parsed_args.group,
parsed_args.group_domain).id
try:
identity_client.users.add_to_group(user_id, group_id)
except Exception:
msg = _("%(user)s not added to group %(group)s\n") % {
'user': parsed_args.user,
'group': parsed_args.group,
}
sys.stderr.write(msg)
else:
msg = _("%(user)s added to group %(group)s\n") % {
'user': parsed_args.user,
'group': parsed_args.group,
}
sys.stdout.write(msg)
class CheckUserInGroup(command.Command):
_description = _("Check user membership in group")
def get_parser(self, prog_name):
parser = super(CheckUserInGroup, self).get_parser(prog_name)
parser.add_argument(
'group',
metavar='<group>',
help=_('Group to check (name or ID)'),
)
parser.add_argument(
'user',
metavar='<user>',
help=_('User to check (name or ID)'),
)
common.add_group_domain_option_to_parser(parser)
common.add_user_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
user_id = common.find_user(identity_client,
parsed_args.user,
parsed_args.user_domain).id
group_id = common.find_group(identity_client,
parsed_args.group,
parsed_args.group_domain).id
try:
identity_client.users.check_in_group(user_id, group_id)
except Exception:
msg = _("%(user)s not in group %(group)s\n") % {
'user': parsed_args.user,
'group': parsed_args.group,
}
sys.stderr.write(msg)
else:
msg = _("%(user)s in group %(group)s\n") % {
'user': parsed_args.user,
'group': parsed_args.group,
}
sys.stdout.write(msg)
class CreateGroup(command.ShowOne):
_description = _("Create new group")
def get_parser(self, prog_name):
parser = super(CreateGroup, self).get_parser(prog_name)
parser.add_argument(
'name',
metavar='<group-name>',
help=_('New group name'),
)
parser.add_argument(
'--domain',
metavar='<domain>',
help=_('Domain to contain new group (name or ID)'),
)
parser.add_argument(
'--description',
metavar='<description>',
help=_('New group description'),
)
parser.add_argument(
'--or-show',
action='store_true',
help=_('Return existing group'),
)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
domain = None
if parsed_args.domain:
domain = common.find_domain(identity_client,
parsed_args.domain).id
try:
group = identity_client.groups.create(
name=parsed_args.name,
domain=domain,
description=parsed_args.description)
except ks_exc.Conflict:
if parsed_args.or_show:
group = utils.find_resource(identity_client.groups,
parsed_args.name,
domain_id=domain)
LOG.info(_('Returning existing group %s'), group.name)
else:
raise
group._info.pop('links')
return zip(*sorted(six.iteritems(group._info)))
class DeleteGroup(command.Command):
_description = _("Delete group(s)")
def get_parser(self, prog_name):
parser = super(DeleteGroup, self).get_parser(prog_name)
parser.add_argument(
'groups',
metavar='<group>',
nargs="+",
help=_('Group(s) to delete (name or ID)'),
)
parser.add_argument(
'--domain',
metavar='<domain>',
help=_('Domain containing group(s) (name or ID)'),
)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
for group in parsed_args.groups:
group_obj = common.find_group(identity_client,
group,
parsed_args.domain)
identity_client.groups.delete(group_obj.id)
class ListGroup(command.Lister):
_description = _("List groups")
def get_parser(self, prog_name):
parser = super(ListGroup, self).get_parser(prog_name)
parser.add_argument(
'--domain',
metavar='<domain>',
help=_('Filter group list by <domain> (name or ID)'),
)
parser.add_argument(
'--user',
metavar='<user>',
help=_('Filter group list by <user> (name or ID)'),
)
common.add_user_domain_option_to_parser(parser)
parser.add_argument(
'--long',
action='store_true',
default=False,
help=_('List additional fields in output'),
)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
domain = None
if parsed_args.domain:
domain = common.find_domain(identity_client,
parsed_args.domain).id
if parsed_args.user:
user = common.find_user(
identity_client,
parsed_args.user,
parsed_args.user_domain,
).id
else:
user = None
# List groups
if parsed_args.long:
columns = ('ID', 'Name', 'Domain ID', 'Description')
else:
columns = ('ID', 'Name')
data = identity_client.groups.list(
domain=domain,
user=user,
)
return (
columns,
(utils.get_item_properties(
s, columns,
formatters={},
) for s in data)
)
class RemoveUserFromGroup(command.Command):
_description = _("Remove user from group")
def get_parser(self, prog_name):
parser = super(RemoveUserFromGroup, self).get_parser(prog_name)
parser.add_argument(
'group',
metavar='<group>',
help=_('Group containing <user> (name or ID)'),
)
parser.add_argument(
'user',
metavar='<user>',
help=_('User to remove from <group> (name or ID)'),
)
common.add_group_domain_option_to_parser(parser)
common.add_user_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
user_id = common.find_user(identity_client,
parsed_args.user,
parsed_args.user_domain).id
group_id = common.find_group(identity_client,
parsed_args.group,
parsed_args.group_domain).id
try:
identity_client.users.remove_from_group(user_id, group_id)
except Exception:
msg = _("%(user)s not removed from group %(group)s\n") % {
'user': parsed_args.user,
'group': parsed_args.group,
}
sys.stderr.write(msg)
else:
msg = _("%(user)s removed from group %(group)s\n") % {
'user': parsed_args.user,
'group': parsed_args.group,
}
sys.stdout.write(msg)
class SetGroup(command.Command):
_description = _("Set group properties")
def get_parser(self, prog_name):
parser = super(SetGroup, self).get_parser(prog_name)
parser.add_argument(
'group',
metavar='<group>',
help=_('Group to modify (name or ID)'),
)
parser.add_argument(
'--domain',
metavar='<domain>',
help=_('Domain containing <group> (name or ID)'),
)
parser.add_argument(
'--name',
metavar='<name>',
help=_('New group name'),
)
parser.add_argument(
'--description',
metavar='<description>',
help=_('New group description'),
)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
group = common.find_group(identity_client, parsed_args.group,
parsed_args.domain)
kwargs = {}
if parsed_args.name:
kwargs['name'] = parsed_args.name
if parsed_args.description:
kwargs['description'] = parsed_args.description
identity_client.groups.update(group.id, **kwargs)
class ShowGroup(command.ShowOne):
_description = _("Display group details")
def get_parser(self, prog_name):
parser = super(ShowGroup, self).get_parser(prog_name)
parser.add_argument(
'group',
metavar='<group>',
help=_('Group to display (name or ID)'),
)
parser.add_argument(
'--domain',
metavar='<domain>',
help=_('Domain containing <group> (name or ID)'),
)
return parser
def take_action(self, parsed_args):
identity_client = self.app.client_manager.identity
group = common.find_group(identity_client,
parsed_args.group,
domain_name_or_id=parsed_args.domain)
group._info.pop('links')
return zip(*sorted(six.iteritems(group._info)))
| [
"[email protected]"
] | |
3b2ea560ffd065ec8ffed538873d800783745494 | 711756b796d68035dc6a39060515200d1d37a274 | /output_exocyst/initial_33419.py | 3e1f56e16e4a23c0c9bedf8bed739f07b94d46f8 | [] | no_license | batxes/exocyst_scripts | 8b109c279c93dd68c1d55ed64ad3cca93e3c95ca | a6c487d5053b9b67db22c59865e4ef2417e53030 | refs/heads/master | 2020-06-16T20:16:24.840725 | 2016-11-30T16:23:16 | 2016-11-30T16:23:16 | 75,075,164 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,950 | py | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_sets={}
surf_sets={}
if "Sec3_GFPN" not in marker_sets:
s=new_marker_set('Sec3_GFPN')
marker_sets["Sec3_GFPN"]=s
s= marker_sets["Sec3_GFPN"]
mark=s.place_marker((452.25, 542.286, 492.08), (0.15, 0.4, 0.6), 18.4716)
if "Sec3_0" not in marker_sets:
s=new_marker_set('Sec3_0')
marker_sets["Sec3_0"]=s
s= marker_sets["Sec3_0"]
mark=s.place_marker((64, 269, 605), (0.21, 0.49, 0.72), 17.1475)
if "Sec3_1" not in marker_sets:
s=new_marker_set('Sec3_1')
marker_sets["Sec3_1"]=s
s= marker_sets["Sec3_1"]
mark=s.place_marker((933, 219, 510), (0.21, 0.49, 0.72), 17.1475)
if "Sec3_2" not in marker_sets:
s=new_marker_set('Sec3_2')
marker_sets["Sec3_2"]=s
s= marker_sets["Sec3_2"]
mark=s.place_marker((606, 533, 290), (0.21, 0.49, 0.72), 17.1475)
if "Sec3_3" not in marker_sets:
s=new_marker_set('Sec3_3')
marker_sets["Sec3_3"]=s
s= marker_sets["Sec3_3"]
mark=s.place_marker((758, 463, 270), (0.21, 0.49, 0.72), 17.1475)
if "Sec3_4" not in marker_sets:
s=new_marker_set('Sec3_4')
marker_sets["Sec3_4"]=s
s= marker_sets["Sec3_4"]
mark=s.place_marker((658, 705, 755), (0.21, 0.49, 0.72), 17.1475)
if "Sec3_5" not in marker_sets:
s=new_marker_set('Sec3_5')
marker_sets["Sec3_5"]=s
s= marker_sets["Sec3_5"]
mark=s.place_marker((33, 658, 355), (0.21, 0.49, 0.72), 17.1475)
if "Sec3_6" not in marker_sets:
s=new_marker_set('Sec3_6')
marker_sets["Sec3_6"]=s
s= marker_sets["Sec3_6"]
mark=s.place_marker((667, 933, 739), (0.21, 0.49, 0.72), 17.1475)
if "Sec3_GFPC" not in marker_sets:
s=new_marker_set('Sec3_GFPC')
marker_sets["Sec3_GFPC"]=s
s= marker_sets["Sec3_GFPC"]
mark=s.place_marker((422.307, 518.031, 526.873), (0.3, 0.6, 0.8), 18.4716)
if "Sec3_Anch" not in marker_sets:
s=new_marker_set('Sec3_Anch')
marker_sets["Sec3_Anch"]=s
s= marker_sets["Sec3_Anch"]
mark=s.place_marker((497.009, 306.663, 486.71), (0.3, 0.6, 0.8), 18.4716)
if "Sec5_GFPN" not in marker_sets:
s=new_marker_set('Sec5_GFPN')
marker_sets["Sec5_GFPN"]=s
s= marker_sets["Sec5_GFPN"]
mark=s.place_marker((483.096, 528.551, 497.237), (0.5, 0.3, 0.6), 18.4716)
if "Sec5_0" not in marker_sets:
s=new_marker_set('Sec5_0')
marker_sets["Sec5_0"]=s
s= marker_sets["Sec5_0"]
mark=s.place_marker((293, 136, 410), (0.6, 0.31, 0.64), 17.1475)
if "Sec5_1" not in marker_sets:
s=new_marker_set('Sec5_1')
marker_sets["Sec5_1"]=s
s= marker_sets["Sec5_1"]
mark=s.place_marker((969, 278, 29), (0.6, 0.31, 0.64), 17.1475)
if "Sec5_2" not in marker_sets:
s=new_marker_set('Sec5_2')
marker_sets["Sec5_2"]=s
s= marker_sets["Sec5_2"]
mark=s.place_marker((788, 262, 791), (0.6, 0.31, 0.64), 17.1475)
if "Sec5_3" not in marker_sets:
s=new_marker_set('Sec5_3')
marker_sets["Sec5_3"]=s
s= marker_sets["Sec5_3"]
mark=s.place_marker((375, 609, 393), (0.6, 0.31, 0.64), 17.1475)
if "Sec5_4" not in marker_sets:
s=new_marker_set('Sec5_4')
marker_sets["Sec5_4"]=s
s= marker_sets["Sec5_4"]
mark=s.place_marker((418, 837, 972), (0.6, 0.31, 0.64), 17.1475)
if "Sec5_5" not in marker_sets:
s=new_marker_set('Sec5_5')
marker_sets["Sec5_5"]=s
s= marker_sets["Sec5_5"]
mark=s.place_marker((421, 521, 426), (0.6, 0.31, 0.64), 17.1475)
if "Sec5_GFPC" not in marker_sets:
s=new_marker_set('Sec5_GFPC')
marker_sets["Sec5_GFPC"]=s
s= marker_sets["Sec5_GFPC"]
mark=s.place_marker((399.085, 485.531, 510.933), (0.7, 0.4, 0.7), 18.4716)
if "Sec6_GFPN" not in marker_sets:
s=new_marker_set('Sec6_GFPN')
marker_sets["Sec6_GFPN"]=s
s= marker_sets["Sec6_GFPN"]
mark=s.place_marker((475.139, 500.646, 549.303), (1, 1, 0), 18.4716)
if "Sec6_0" not in marker_sets:
s=new_marker_set('Sec6_0')
marker_sets["Sec6_0"]=s
s= marker_sets["Sec6_0"]
mark=s.place_marker((912, 43, 150), (1, 1, 0.2), 17.1475)
if "Sec6_1" not in marker_sets:
s=new_marker_set('Sec6_1')
marker_sets["Sec6_1"]=s
s= marker_sets["Sec6_1"]
mark=s.place_marker((589, 12, 920), (1, 1, 0.2), 17.1475)
if "Sec6_2" not in marker_sets:
s=new_marker_set('Sec6_2')
marker_sets["Sec6_2"]=s
s= marker_sets["Sec6_2"]
mark=s.place_marker((700, 400, 33), (1, 1, 0.2), 17.1475)
if "Sec6_3" not in marker_sets:
s=new_marker_set('Sec6_3')
marker_sets["Sec6_3"]=s
s= marker_sets["Sec6_3"]
mark=s.place_marker((320, 708, 130), (1, 1, 0.2), 17.1475)
if "Sec6_4" not in marker_sets:
s=new_marker_set('Sec6_4')
marker_sets["Sec6_4"]=s
s= marker_sets["Sec6_4"]
mark=s.place_marker((593, 898, 487), (1, 1, 0.2), 17.1475)
if "Sec6_5" not in marker_sets:
s=new_marker_set('Sec6_5')
marker_sets["Sec6_5"]=s
s= marker_sets["Sec6_5"]
mark=s.place_marker((590, 176, 919), (1, 1, 0.2), 17.1475)
if "Sec6_GFPC" not in marker_sets:
s=new_marker_set('Sec6_GFPC')
marker_sets["Sec6_GFPC"]=s
s= marker_sets["Sec6_GFPC"]
mark=s.place_marker((463.163, 448.151, 366.263), (1, 1, 0.4), 18.4716)
if "Sec6_Anch" not in marker_sets:
s=new_marker_set('Sec6_Anch')
marker_sets["Sec6_Anch"]=s
s= marker_sets["Sec6_Anch"]
mark=s.place_marker((423.358, 589.653, 280.3), (1, 1, 0.4), 18.4716)
if "Sec8_0" not in marker_sets:
s=new_marker_set('Sec8_0')
marker_sets["Sec8_0"]=s
s= marker_sets["Sec8_0"]
mark=s.place_marker((822, 735, 46), (0.65, 0.34, 0.16), 17.1475)
if "Sec8_1" not in marker_sets:
s=new_marker_set('Sec8_1')
marker_sets["Sec8_1"]=s
s= marker_sets["Sec8_1"]
mark=s.place_marker((295, 867, 19), (0.65, 0.34, 0.16), 17.1475)
if "Sec8_2" not in marker_sets:
s=new_marker_set('Sec8_2')
marker_sets["Sec8_2"]=s
s= marker_sets["Sec8_2"]
mark=s.place_marker((540, 891, 967), (0.65, 0.34, 0.16), 17.1475)
if "Sec8_3" not in marker_sets:
s=new_marker_set('Sec8_3')
marker_sets["Sec8_3"]=s
s= marker_sets["Sec8_3"]
mark=s.place_marker((342, 587, 462), (0.65, 0.34, 0.16), 17.1475)
if "Sec8_4" not in marker_sets:
s=new_marker_set('Sec8_4')
marker_sets["Sec8_4"]=s
s= marker_sets["Sec8_4"]
mark=s.place_marker((596, 347, 50), (0.65, 0.34, 0.16), 17.1475)
if "Sec8_5" not in marker_sets:
s=new_marker_set('Sec8_5')
marker_sets["Sec8_5"]=s
s= marker_sets["Sec8_5"]
mark=s.place_marker((290, 818, 755), (0.65, 0.34, 0.16), 17.1475)
if "Sec8_GFPC" not in marker_sets:
s=new_marker_set('Sec8_GFPC')
marker_sets["Sec8_GFPC"]=s
s= marker_sets["Sec8_GFPC"]
mark=s.place_marker((397.481, 435.285, 396.787), (0.7, 0.4, 0), 18.4716)
if "Sec8_Anch" not in marker_sets:
s=new_marker_set('Sec8_Anch')
marker_sets["Sec8_Anch"]=s
s= marker_sets["Sec8_Anch"]
mark=s.place_marker((457.766, 312.114, 559.189), (0.7, 0.4, 0), 18.4716)
if "Sec10_GFPN" not in marker_sets:
s=new_marker_set('Sec10_GFPN')
marker_sets["Sec10_GFPN"]=s
s= marker_sets["Sec10_GFPN"]
mark=s.place_marker((461.37, 459.603, 334.456), (0.2, 0.6, 0.2), 18.4716)
if "Sec10_0" not in marker_sets:
s=new_marker_set('Sec10_0')
marker_sets["Sec10_0"]=s
s= marker_sets["Sec10_0"]
mark=s.place_marker((84, 213, 780), (0.3, 0.69, 0.29), 17.1475)
if "Sec10_1" not in marker_sets:
s=new_marker_set('Sec10_1')
marker_sets["Sec10_1"]=s
s= marker_sets["Sec10_1"]
mark=s.place_marker((908, 547, 775), (0.3, 0.69, 0.29), 17.1475)
if "Sec10_2" not in marker_sets:
s=new_marker_set('Sec10_2')
marker_sets["Sec10_2"]=s
s= marker_sets["Sec10_2"]
mark=s.place_marker((226, 142, 679), (0.3, 0.69, 0.29), 17.1475)
if "Sec10_3" not in marker_sets:
s=new_marker_set('Sec10_3')
marker_sets["Sec10_3"]=s
s= marker_sets["Sec10_3"]
mark=s.place_marker((994, 39, 970), (0.3, 0.69, 0.29), 17.1475)
if "Sec10_4" not in marker_sets:
s=new_marker_set('Sec10_4')
marker_sets["Sec10_4"]=s
s= marker_sets["Sec10_4"]
mark=s.place_marker((532, 967, 301), (0.3, 0.69, 0.29), 17.1475)
if "Sec10_5" not in marker_sets:
s=new_marker_set('Sec10_5')
marker_sets["Sec10_5"]=s
s= marker_sets["Sec10_5"]
mark=s.place_marker((549, 892, 532), (0.3, 0.69, 0.29), 17.1475)
if "Sec10_GFPC" not in marker_sets:
s=new_marker_set('Sec10_GFPC')
marker_sets["Sec10_GFPC"]=s
s= marker_sets["Sec10_GFPC"]
mark=s.place_marker((321.464, 463.925, 491.214), (0.4, 0.75, 0.3), 18.4716)
if "Sec10_Anch" not in marker_sets:
s=new_marker_set('Sec10_Anch')
marker_sets["Sec10_Anch"]=s
s= marker_sets["Sec10_Anch"]
mark=s.place_marker((549.906, 554.619, 331.935), (0.4, 0.75, 0.3), 18.4716)
if "Sec15_GFPN" not in marker_sets:
s=new_marker_set('Sec15_GFPN')
marker_sets["Sec15_GFPN"]=s
s= marker_sets["Sec15_GFPN"]
mark=s.place_marker((420.639, 516.57, 430.707), (0.9, 0.5, 0.7), 18.4716)
if "Sec15_0" not in marker_sets:
s=new_marker_set('Sec15_0')
marker_sets["Sec15_0"]=s
s= marker_sets["Sec15_0"]
mark=s.place_marker((631, 71, 580), (0.97, 0.51, 0.75), 17.1475)
if "Sec15_1" not in marker_sets:
s=new_marker_set('Sec15_1')
marker_sets["Sec15_1"]=s
s= marker_sets["Sec15_1"]
mark=s.place_marker((517, 23, 489), (0.97, 0.51, 0.75), 17.1475)
if "Sec15_2" not in marker_sets:
s=new_marker_set('Sec15_2')
marker_sets["Sec15_2"]=s
s= marker_sets["Sec15_2"]
mark=s.place_marker((931, 152, 341), (0.97, 0.51, 0.75), 17.1475)
if "Sec15_3" not in marker_sets:
s=new_marker_set('Sec15_3')
marker_sets["Sec15_3"]=s
s= marker_sets["Sec15_3"]
mark=s.place_marker((403, 945, 584), (0.97, 0.51, 0.75), 17.1475)
if "Sec15_4" not in marker_sets:
s=new_marker_set('Sec15_4')
marker_sets["Sec15_4"]=s
s= marker_sets["Sec15_4"]
mark=s.place_marker((105, 881, 804), (0.97, 0.51, 0.75), 17.1475)
if "Sec15_5" not in marker_sets:
s=new_marker_set('Sec15_5')
marker_sets["Sec15_5"]=s
s= marker_sets["Sec15_5"]
mark=s.place_marker((924, 445, 787), (0.97, 0.51, 0.75), 17.1475)
if "Sec15_GFPC" not in marker_sets:
s=new_marker_set('Sec15_GFPC')
marker_sets["Sec15_GFPC"]=s
s= marker_sets["Sec15_GFPC"]
mark=s.place_marker((361.302, 417.406, 366.31), (1, 0.6, 0.8), 18.4716)
if "Sec15_Anch" not in marker_sets:
s=new_marker_set('Sec15_Anch')
marker_sets["Sec15_Anch"]=s
s= marker_sets["Sec15_Anch"]
mark=s.place_marker((263.159, 551.133, 368.797), (1, 0.6, 0.8), 18.4716)
if "Exo70_GFPN" not in marker_sets:
s=new_marker_set('Exo70_GFPN')
marker_sets["Exo70_GFPN"]=s
s= marker_sets["Exo70_GFPN"]
mark=s.place_marker((414.232, 529.538, 502.19), (0.8, 0, 0), 18.4716)
if "Exo70_0" not in marker_sets:
s=new_marker_set('Exo70_0')
marker_sets["Exo70_0"]=s
s= marker_sets["Exo70_0"]
mark=s.place_marker((486, 892, 716), (0.89, 0.1, 0.1), 17.1475)
if "Exo70_1" not in marker_sets:
s=new_marker_set('Exo70_1')
marker_sets["Exo70_1"]=s
s= marker_sets["Exo70_1"]
mark=s.place_marker((727, 499, 947), (0.89, 0.1, 0.1), 17.1475)
if "Exo70_2" not in marker_sets:
s=new_marker_set('Exo70_2')
marker_sets["Exo70_2"]=s
s= marker_sets["Exo70_2"]
mark=s.place_marker((536, 734, 1), (0.89, 0.1, 0.1), 17.1475)
if "Exo70_3" not in marker_sets:
s=new_marker_set('Exo70_3')
marker_sets["Exo70_3"]=s
s= marker_sets["Exo70_3"]
mark=s.place_marker((605, 75, 982), (0.89, 0.1, 0.1), 17.1475)
if "Exo70_4" not in marker_sets:
s=new_marker_set('Exo70_4')
marker_sets["Exo70_4"]=s
s= marker_sets["Exo70_4"]
mark=s.place_marker((931, 358, 558), (0.89, 0.1, 0.1), 17.1475)
if "Exo70_GFPC" not in marker_sets:
s=new_marker_set('Exo70_GFPC')
marker_sets["Exo70_GFPC"]=s
s= marker_sets["Exo70_GFPC"]
mark=s.place_marker((395.034, 379.324, 364.988), (1, 0.2, 0.2), 18.4716)
if "Exo70_Anch" not in marker_sets:
s=new_marker_set('Exo70_Anch')
marker_sets["Exo70_Anch"]=s
s= marker_sets["Exo70_Anch"]
mark=s.place_marker((509.963, 703.963, 400.71), (1, 0.2, 0.2), 18.4716)
if "Exo84_GFPN" not in marker_sets:
s=new_marker_set('Exo84_GFPN')
marker_sets["Exo84_GFPN"]=s
s= marker_sets["Exo84_GFPN"]
mark=s.place_marker((484.167, 529.899, 466.221), (0.9, 0.4, 0), 18.4716)
if "Exo84_0" not in marker_sets:
s=new_marker_set('Exo84_0')
marker_sets["Exo84_0"]=s
s= marker_sets["Exo84_0"]
mark=s.place_marker((452, 211, 5), (1, 0.5, 0), 17.1475)
if "Exo84_1" not in marker_sets:
s=new_marker_set('Exo84_1')
marker_sets["Exo84_1"]=s
s= marker_sets["Exo84_1"]
mark=s.place_marker((848, 990, 553), (1, 0.5, 0), 17.1475)
if "Exo84_2" not in marker_sets:
s=new_marker_set('Exo84_2')
marker_sets["Exo84_2"]=s
s= marker_sets["Exo84_2"]
mark=s.place_marker((127, 974, 430), (1, 0.5, 0), 17.1475)
if "Exo84_3" not in marker_sets:
s=new_marker_set('Exo84_3')
marker_sets["Exo84_3"]=s
s= marker_sets["Exo84_3"]
mark=s.place_marker((182, 371, 751), (1, 0.5, 0), 17.1475)
if "Exo84_GFPC" not in marker_sets:
s=new_marker_set('Exo84_GFPC')
marker_sets["Exo84_GFPC"]=s
s= marker_sets["Exo84_GFPC"]
mark=s.place_marker((381.405, 457.09, 488.981), (1, 0.6, 0.1), 18.4716)
if "Exo84_Anch" not in marker_sets:
s=new_marker_set('Exo84_Anch')
marker_sets["Exo84_Anch"]=s
s= marker_sets["Exo84_Anch"]
mark=s.place_marker((292.706, 611.017, 387.815), (1, 0.6, 0.1), 18.4716)
for k in surf_sets.keys():
chimera.openModels.add([surf_sets[k]])
| [
"[email protected]"
] | |
2f10c0fc4429d0811c309e418f22f5c1c3ef9850 | 0a973640f0b02d7f3cf9211fcce33221c3a50c88 | /.history/src/check_update_20210125140228.py | 03eaacfa439dd94d42ef81213aea4ae61bc8634b | [] | no_license | JiajunChen123/IPO_under_review_crawler | 5468b9079950fdd11c5e3ce45af2c75ccb30323c | 031aac915ebe350ec816c05a29b5827fde588567 | refs/heads/main | 2023-02-26T08:23:09.622725 | 2021-02-04T10:11:16 | 2021-02-04T10:11:16 | 332,619,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,989 | py | import datetime
def check_update():
prjtypes = ['ipo','refinance','reproperty']
for prjtype in prjtypes:
proj_list_new = index_getter(prjtype)
proj_list_old = load_pickle(os.getcwd()+'/saved_config/sz_index'+'_'+'prjtype'+'.pkl')
updated_idx = [index for (index, d) in enumerate(proj_list_new) if d["updtdt"] == datetime.today().strftime('%Y-%m-%d')]
print("there are {} projects have been updated!".format(len(updatedidx)))
for new_idx in updated_idx:
# name,projid = proj_list_new[i]['cmpnm'],proj_list_new[i]['prjid']
# old_idx = next((index for (index, d) in enumerate(proj_list_old) if d["cmpnm"] == name), None)
# if old_idx is not None:
# # for key, value in proj_list_new[i].items():
# # if proj_list_old[old_index][key] != value:
# # print(key,value,proj_list_old[old_index][key])
# if proj_list_new[new_idx]['prjst'] != proj_list_old[old_idx]['prjst']:
raw_data = data_getter(proj_list_new[new_idx]['prjid'])
cleaned_data = data_process(raw_data)
directory = os.getcwd()+'/data/'+cleaned_data['prjType'] + '/' + cleaned_data['prjName']
save_obj(cleaned_data, directory +'/clean_info')
print('company:', cleaned_data['prjName'],'is updated')
def update_allStockInfo():
listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(os.getcwd()+):
listOfFiles += [os.path.join(dirpath, file) for file in filenames]
allStock_info = []
for i in listOfFiles:
if os.path.basename(i) == 'info.pkl':
print('clean up company:', os.path.dirname(i))
raw_data = load_pickle(i)
cleaned_data = data_process(raw_data)
allStock_info.append(cleaned_data)
save_obj(cleaned_data, os.path.dirname(i), 'clean_info')
print('clean up company:', os.path.dirname(i))
to_dataframe(allStock_info)
save_obj(allStock_info, os.getcwd(), 'allStock_info') | [
"[email protected]"
] | |
e943db374255cba583a06ae593626accc392a224 | 2b6a02a34ee6bf68820ad185245e2609b296e0aa | /182.py | 5cee2a650fbaa5cc1f8840e937e7c22e3defc6dc | [] | no_license | shants/LeetCodePy | 948e505b6fcb0edcb9a1cf63a245b61d448d6e27 | 2337b5031d4dfe033a471cea8ab4aa5ab66122d0 | refs/heads/master | 2020-03-28T08:43:04.606044 | 2019-11-25T05:03:15 | 2019-11-25T05:03:15 | 147,984,830 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 60 | py | #select Email from Person GROUP BY Email HAVING COUNT(*) > 1 | [
"[email protected]"
] | |
ec669664a01bd273b8ee1ae285da9a46c1b96850 | 781e2692049e87a4256320c76e82a19be257a05d | /all_data/exercism_data/python/rna-transcription/2569808f732d45a1a7c5dbd7f66d16e1.py | db46159bc52e0c46102481740258245a199f94aa | [] | no_license | itsolutionscorp/AutoStyle-Clustering | 54bde86fe6dbad35b568b38cfcb14c5ffaab51b0 | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | refs/heads/master | 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null | UTF-8 | Python | false | false | 213 | py | def to_rna(input):
dnaTypes = {"G":"C","C":"G","T":"A","A":"U"}
output = []
for each in input:
value = dnaTypes.get(each,'not found')
output.append(value)
return ''.join(output)
| [
"[email protected]"
] | |
4c5b98dcb0e5971fa8e16b9150b20e53eaa42687 | 90f729624737cc9700464532a0c67bcbfe718bde | /lino_xl/lib/invoicing/__init__.py | e4adea047c066bd0b4bff8eeb6e269f443914fa4 | [
"AGPL-3.0-only"
] | permissive | lino-framework/xl | 46ba6dac6e36bb8e700ad07992961097bb04952f | 642b2eba63e272e56743da2d7629be3f32f670aa | refs/heads/master | 2021-05-22T09:59:22.244649 | 2021-04-12T23:45:06 | 2021-04-12T23:45:06 | 52,145,415 | 1 | 5 | BSD-2-Clause | 2021-03-17T11:20:34 | 2016-02-20T09:08:36 | Python | UTF-8 | Python | false | false | 2,783 | py | # -*- coding: UTF-8 -*-
# Copyright 2016-2019 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
"""
Adds functionality for **invoicing**, i.e. automatically generating
invoices from data in the database.
See :doc:`/specs/invoicing`.
"""
from lino.api.ad import Plugin, _
from django.utils.text import format_lazy
class Plugin(Plugin):
verbose_name = _("Invoicing")
# needs_plugins = ['lino_xl.lib.ledger']
needs_plugins = ['lino_xl.lib.sales']
voucher_model = 'sales.VatProductInvoice'
item_model = 'sales.InvoiceItem'
"""
The database model into which invoiceable objects should create
invoice items. Default value refers to :class:`sales.InvoiceItem
<lino_xl.lib.sales.models.InvoiceItem>`.
This model will have an injected GFK field `invoiceable`.
"""
invoiceable_label = _("Invoiced object")
def on_site_startup(self, site):
from lino.core.utils import resolve_model
self.item_model = resolve_model(self.item_model)
# ivm = self.item_model._meta.get_field('voucher').remote_field.model
# if self.voucher_model != ivm:
# raise Exception("voucher_model is {} but should be {}".format(
# self.voucher_model, ivm))
self.voucher_model = resolve_model(self.voucher_model)
def get_voucher_type(self):
# from lino.core.utils import resolve_model
# model = resolve_model(self.voucher_model)
# return self.site.modules.ledger.VoucherTypes.get_for_model(model)
return self.site.models.ledger.VoucherTypes.get_for_model(
self.voucher_model)
def setup_main_menu(config, site, user_type, m):
mg = site.plugins.sales
m = m.add_menu(mg.app_label, mg.verbose_name)
m.add_action('invoicing.Plan', action='start_plan')
# Area = site.models.invoicing.Area
# # Areas = site.models.invoicing.Areas
# for obj in Area.objects.all():
# # m.add_instance_action(obj, action='start_invoicing')
# # m.add_action(obj, action='start_invoicing')
# m.add_action(
# 'invoicing.PlansByArea', 'start_invoicing',
# label=format_lazy(_("Create invoices {}"), obj),
# params=dict(master_instance=obj))
def setup_config_menu(self, site, user_type, m):
mg = site.plugins.sales
m = m.add_menu(mg.app_label, mg.verbose_name)
m.add_action('invoicing.Tariffs')
m.add_action('invoicing.Areas')
def setup_explorer_menu(self, site, user_type, m):
mg = site.plugins.sales
m = m.add_menu(mg.app_label, mg.verbose_name)
m.add_action('invoicing.AllPlans')
m.add_action('invoicing.SalesRules')
| [
"[email protected]"
] | |
0e98660cef8d593393fd7f5239d57526602a5f0e | a56252fda5c9e42eff04792c6e16e413ad51ba1a | /resources/usr/local/lib/python2.7/dist-packages/bx/seq/seq.py | 727c700f5b0caaf1da917454450ecd64e677025f | [
"Apache-2.0"
] | permissive | edawson/parliament2 | 4231e692565dbecf99d09148e75c00750e6797c4 | 2632aa3484ef64c9539c4885026b705b737f6d1e | refs/heads/master | 2021-06-21T23:13:29.482239 | 2020-12-07T21:10:08 | 2020-12-07T21:10:08 | 150,246,745 | 0 | 0 | Apache-2.0 | 2019-09-11T03:22:55 | 2018-09-25T10:21:03 | Python | UTF-8 | Python | false | false | 4,887 | py | """
Classes to support "biological sequence" files.
:Author: Bob Harris ([email protected])
"""
# DNA reverse complement table
DNA_COMP = " - " \
" TVGH CD M KN YSA BWXR tvgh cd m kn ysa bwxr " \
" " \
" "
class SeqFile(object):
"""
A biological sequence is a sequence of bytes or characters. Usually these
represent DNA (A,C,G,T), proteins, or some variation of those.
class attributes:
file: file object containing the sequence
revcomp: whether gets from this sequence should be reverse-complemented
False => no reverse complement
True => (same as "-5'")
"maf" => (same as "-5'")
"+5'" => minus strand is from plus strand's 5' end (same as "-3'")
"+3'" => minus strand is from plus strand's 3' end (same as "-5'")
"-5'" => minus strand is from its 5' end (as per MAF file format)
"-3'" => minus strand is from its 3' end (as per genome browser,
but with origin-zero)
name: usually a species and/or chromosome name (e.g. "mule.chr5"); if
the file contains a name, that overrides this one
gap: gap character that aligners should use for gaps in this sequence
"""
def __init__(self, file=None, revcomp=False, name="", gap=None):
self.file = file
if (revcomp == True): self.revcomp = "-5'"
elif (revcomp == "+3'"): self.revcomp = "-5'"
elif (revcomp == "+5'"): self.revcomp = "-3'"
elif (revcomp == "maf"): self.revcomp = "-5'"
else: self.revcomp = revcomp
self.name = name
if (gap == None): self.gap = "-"
else: self.gap = gap
self.text = None # (subclasses fill in text and
self.length = 0 # length or they most override get())
def close(self):
assert (self.file != None)
self.file.close()
self.file = None
def extract_name(self,line):
try:
return line.split()[0]
except:
return ""
def set_text(self,text):
self.text = text
self.length = len(text)
def __str__ (self):
text = ""
if (self.name != None): text += self.name + " "
text += self.get(0,self.length)
return text
def get(self, start, length):
"""
Fetch subsequence starting at position `start` with length `length`.
This method is picky about parameters, the requested interval must
have non-negative length and fit entirely inside the NIB sequence,
the returned string will contain exactly 'length' characters, or an
AssertionError will be generated.
"""
# Check parameters
assert length >= 0, "Length must be non-negative (got %d)" % length
assert start >= 0,"Start must be greater than 0 (got %d)" % start
assert start + length <= self.length, \
"Interval beyond end of sequence (%s..%s > %s)" % ( start, start + length, self.length )
# Fetch sequence and reverse complement if necesary
if not self.revcomp:
return self.raw_fetch( start, length )
if self.revcomp == "-3'":
return self.reverse_complement(self.raw_fetch(start,length))
assert self.revcomp == "-5'", "unrecognized reverse complement scheme"
start = self.length - (start+length)
return self.reverse_complement(self.raw_fetch(start,length))
def raw_fetch(self, start, length):
return self.text[start:start+length]
def reverse_complement(self,text):
comp = [ch for ch in text.translate(DNA_COMP)]
comp.reverse()
return "".join(comp)
class SeqReader(object):
"""Iterate over all sequences in a file in order"""
def __init__(self, file, revcomp=False, name="", gap=None):
self.file = file
self.revcomp = revcomp
self.name = name
self.gap = gap
self.seqs_read = 0
def close(self):
self.file.close()
def __iter__(self):
return SeqReaderIter(self)
def next(self): # subclasses should override this method and return the
return # .. next sequence (of type SeqFile or a subclass) read
# .. from self.file
class SeqReaderIter(object):
def __init__(self,reader):
self.reader = reader
def __iter__(self):
return self
def next(self):
v = self.reader.next()
if not v: raise StopIteration
return v
| [
"[email protected]"
] | |
9c85f5d5791d3d14ac61c80470e39516b5b5b94a | b162de01d1ca9a8a2a720e877961a3c85c9a1c1c | /389.find-the-difference.python3.py | 787bd1ca19ae6a5ffdf1788af2408a2944611bb1 | [] | no_license | richnakasato/lc | 91d5ff40a1a3970856c76c1a53d7b21d88a3429c | f55a2decefcf075914ead4d9649d514209d17a34 | refs/heads/master | 2023-01-19T09:55:08.040324 | 2020-11-19T03:13:51 | 2020-11-19T03:13:51 | 114,937,686 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 727 | py | #
# [389] Find the Difference
#
# https://leetcode.com/problems/find-the-difference/description/
#
# algorithms
# Easy (52.22%)
# Total Accepted: 126.9K
# Total Submissions: 243.1K
# Testcase Example: '"abcd"\n"abcde"'
#
#
# Given two strings s and t which consist of only lowercase letters.
#
# String t is generated by random shuffling string s and then add one more
# letter at a random position.
#
# Find the letter that was added in t.
#
# Example:
#
# Input:
# s = "abcd"
# t = "abcde"
#
# Output:
# e
#
# Explanation:
# 'e' is the letter that was added.
#
#
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
| [
"[email protected]"
] | |
5caec5d9a8ccca40938aa679181df75ee6367197 | 6d3ac655065e7592d7d8f6692b48546fb9adab75 | /VirtualEnvAndPagination/env/bin/pip-3.7 | f324b76b04fee41f8ec85adbfd6cbdd528e977ac | [] | no_license | lensherrggg/Django2Masterclass-BuildWebAppsWithPython-Django | 81aa3fe582801d887b526bf3e022539cc0c739f5 | 22631e46cf48cb4206f8b77da664685fa141fec3 | refs/heads/master | 2021-04-08T11:43:23.265987 | 2020-03-27T12:56:50 | 2020-03-27T12:56:50 | 248,772,215 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 292 | 7 | #!/Users/rui/Documents/Code/Learning/Django2MasterClass/VirtualEnvironment/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"[email protected]"
] | |
7753cb95d4466b610a3d6b8af4f2b00cc22c1d9b | a6f52b361be35ecd0b750289145d1dd5e5d1d48d | /src/profiler/formatters/SimpleTableFormatter.py | 34c51c4caadb51c8ef5c62c9146a34e98f4bf99b | [] | no_license | deeptiagrawa/Flow123d-python-utils | d360329d28b1c24d600e309fabf09539bce80dee | a80b2dd10eb77ed0fc6469c675dc400feffdcc09 | refs/heads/master | 2021-01-12T05:31:26.649733 | 2016-12-20T13:28:05 | 2016-12-20T13:28:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,009 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# author: Jan Hybs
from __future__ import absolute_import
import re
import os
from utils.dotdict import DotDict
from utils.logger import Logger
class SimpleTableFormatter (object):
"""
Class which takes json object from flow123d benchmark profiler report
and returns simple table-like text string
"""
def __init__(self):
self.json = None
self.output = ""
self.headerCols = []
self.maxNameSize = 11
self.bodyRows = []
self.maxBodySize = None
self.headerFields = ("tag", "call count (max)", "max T", "min/max T", "avg T", "total T", "source", "line")
self.styles = {
"linesep": os.linesep, "padding": 0,
"min_width": 9, "colsep": '',
"rowsep": '', "space_header": 3,
"leading_char": " . ",
"remove_prefix": "/src/"
}
self.totalDuration = None
self.totalDurationMeasured = None
def set_styles(self, styles):
"""Overrides default styles"""
self.styles.update(styles)
# make sure some values are actually ints
self.styles["min_width"] = int(self.styles["min_width"])
self.styles["padding"] = int(self.styles["padding"])
self.styles["space_header"] = int(self.styles["space_header"])
self.styles["colsep_start"] = self.styles["colsep"] + " "
self.styles["colsep_end"] = " " + self.styles["colsep"]
def convert_style(self):
self.set_styles(self.styles)
self.styles = DotDict(self.styles)
def format(self, json):
""""Formats given json object"""
self.convert_style()
self.json = json
self.process_header(json)
self.process_body(json, 0)
self.maxBodySize = [n + self.styles.padding for n in self.maxBodySize]
self.maxNameSize = self.maxNameSize + self.styles.space_header
lineDivider = (sum(self.maxBodySize) + 2 + len(self.maxBodySize) * 2) * self.styles.rowsep
fmtHead = "{{:{self.maxNameSize}s}}{{}}{self.styles.linesep}".format(self=self)
for pair in self.headerCols:
self.output += fmtHead.format(*pair)
self.output += lineDivider
self.output += self.styles.linesep
self.output += self.styles.colsep_start
for i in range(len(self.headerFields)):
fmt = "{{:^{maxBodySize}s}}{colsep}".format(maxBodySize=self.maxBodySize[i], colsep=self.styles.colsep_end)
self.output += fmt.format(self.headerFields[i])
self.output += self.styles.linesep
self.output += lineDivider
self.output += self.styles.linesep
for tup in self.bodyRows:
self.output += self.styles.colsep_start
fields = []
for i in range(len(self.maxBodySize)):
fields.append(("{:" + tup[i][0] + "" + str(self.maxBodySize[i]) + "s}").format(tup[i][1]))
self.output += self.styles.colsep_end.join(fields)
self.output += self.styles.colsep_end + self.styles.linesep
# self.output += fmtBody.format (*tup)
self.output += lineDivider
return self.output
def append_to_header(self, name, value=None, linebreak=False):
"""Appends entry to header column list, if no value was given
value from json object by given name will be taken
"""
value = value if value is not None else self.json[name.lower().replace(" ", "-")]
self.headerCols.append((name, str(value) + (linebreak if linebreak else "")))
if self.maxNameSize < len(str(name)):
self.maxNameSize = len(str(name))
def append_to_body(self, values):
"""Appends entry to body row list.
value is tupple of tupples, where inner tupper has two elements, first formatting character, and second value,
formatting character is used in string format() method
designating alignment
< for left
> for right
^ for center
"""
self.bodyRows.append(values)
# default empty array
if self.maxBodySize is None:
self.maxBodySize = [self.styles.min_width] * len(values)
# update max length
for i in range(len(self.maxBodySize)):
self.maxBodySize[i] = max(self.maxBodySize[i], len(str(values[i][1])))
def process_header(self, json):
"""Appends header information"""
self.append_to_header("Program name")
self.append_to_header("Program version")
self.append_to_header("Program branch")
self.append_to_header("Program revision")
self.append_to_header("Program build")
if 'source-dir' in json:
self.append_to_header("Source dir")
self.append_to_header("Timer resolution", linebreak=self.styles.linesep)
desc = re.sub("\s+", " ", json["task-description"], re.M)
self.append_to_header("Task description", desc)
self.append_to_header("Task size", linebreak=self.styles.linesep)
self.append_to_header("Run process count")
self.append_to_header("Run started", json["run-started-at"])
self.append_to_header("Run ended", json["run-finished-at"])
def process_body(self, json, level):
"""Recursive body processing"""
# first occurrence of cumul-time-sum is whole-program's measured time
if self.totalDurationMeasured is None and "cumul-time-sum" in json:
self.totalDurationMeasured = json['cumul-time-sum']
if level > 0:
abs_prc = (json["cumul-time-sum"] / self.totalDurationMeasured) * 100
rel_prc = json["percent"]
path = json["file-path"]
if str(json["file-path"]).startswith(self.styles.remove_prefix):
path = path[len(self.styles.remove_prefix):]
# safe average
if (json["call-count-sum"] != 0):
avg_cumul_time = json["cumul-time-sum"] / json["call-count-sum"]
else:
avg_cumul_time = json["cumul-time-sum"]
# safe min max ratio
cumul_time_max = max(json["cumul-time-max"], json["cumul-time-min"])
cumul_time_min = min(json["cumul-time-max"], json["cumul-time-min"])
if (json["cumul-time-max"] > 0):
min_max_ratio = cumul_time_min / cumul_time_max
else:
min_max_ratio = 0
self.append_to_body((
("<", "{abs_prc:6.2f} {leading} {rel_prc:5.2f} {tag}".format(
abs_prc=abs_prc, leading=self.styles.leading_char * (level - 1), rel_prc=rel_prc, tag=json["tag"])),
("^", "{:d}".format(json["call-count-max"])),
("^", "{:1.4f}".format(json["cumul-time-max"])),
("^", "{:1.4f}".format(min_max_ratio)),
("^", "{:1.4f}".format(avg_cumul_time)),
("^", "{:1.4f}".format(json["cumul-time-sum"])),
("<", "{path:s}, {function:s}()".format(function=json["function"], path=path)),
("^", "{line:5d}".format(line=json["file-line"]))
))
if 'children' in json:
for child in json["children"]:
try:
self.process_body(child, level + 1)
except Exception as e:
import json as j
if 'children' in child:
del child['children']
child_repr = j.dumps(child, indent=4)
Logger.instance().warning(
'Caught exception while processing profiler data: {e}'.format(e=e.message))
Logger.instance().warning('Exception', exc_info=e)
Logger.instance().warning('problem node (without children) is:\n{child}'.format(child=child_repr))
def timedelta_milliseconds(self, td):
return td.days * 86400000 + td.seconds * 1000 + td.microseconds / 1000
| [
"[email protected]"
] | |
e969a74760c8c4b91e8b2dcd06db47ff9cbccf46 | 10317d4492bcc5a85518c8c9c6edce56cccb7050 | /Document Scanner/transform_new.py | 012814806bec195d2e650f2d62128556692278b9 | [] | no_license | kishan/Image-Recognition-Test-Grader | 066a640adbc6bce5181cf0fb2d8c6f9a2a8d60e1 | 7b4e603f7a483cfed622df8d9896d9ff2719526a | refs/heads/master | 2021-01-01T19:43:07.716688 | 2015-08-25T20:00:56 | 2015-08-25T20:00:56 | 41,382,408 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,411 | py | # import the necessary packages
import numpy as np
import cv2
import math
################################################################################
## The following functions have been written by me but the approach is derived
## from the following link: http://www.pyimagesearch.com/2014/08/25/4-point-
## opencv-getperspective-transform-example/
################################################################################
# take in array of 4 coordinates and order coordinates so first coordinate
# is top-left corner and rest are in order moving clockwise
def order_points(points):
#create empty list of 4 coordinates
numOfPoints = 4
valuesPerPoint = 2
ordered_points = np.zeros((numOfPoints,valuesPerPoint), dtype= "float32")
# add x and y componenets of each coordinate
sumOfCoordinates = np.sum(points, axis = 1)
#find difference of x and y components of each coordinate
differenceOfCoordinates = np.diff(points, axis=1)
# find smallest sum and difference of coordinates
smallestSumIndex = np.argmin(sumOfCoordinates)
smallestDifferenceIndex = np.argmin(differenceOfCoordinates)
# find largest sum and difference of coordinates
largestSumIndex = np.argmax(sumOfCoordinates)
largestDifferenceIndex = np.argmax(differenceOfCoordinates)
# top-left coordinate has smallest coordinate sum
ordered_points[0] = points[smallestSumIndex]
# top-left coordinate has smallest coordinate difference
ordered_points[1] = points[smallestDifferenceIndex]
# top-left coordinate has largest coordinate sum
ordered_points[2] = points[largestSumIndex]
# top-left coordinate has largest coordinate difference
ordered_points[3] = points[largestDifferenceIndex]
return ordered_points
def distance_between_points(point1, point2):
x1 = point1[0]
y1 = point1[1]
x2 = point2[0]
y2 = point2[1]
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# takes in image and list of 4 coordinates for each corner of object in image,
# and returns image of object in vertical position with excess background
# removed
def four_point_transform(image, points):
# unpack points in order
ordered_points = order_points(points)
top_left, top_right = ordered_points[0], ordered_points[1]
bottom_right, bottom_left = ordered_points[2], ordered_points[3]
# find the max width of the object in the image
topWidth = int(distance_between_points(top_left, top_right))
bottomWidth = int(distance_between_points(bottom_left, bottom_right))
maxWidth = max(topWidth, bottomWidth)
# find the max height of the object in the image
topHeight = int(distance_between_points(top_left, bottom_left))
bottomHeight = int(distance_between_points(top_right, bottom_right))
maxHeight = max(topHeight, bottomHeight)
# create array of corner points for final image
new_top_left = [0, 0]
new_top_right = [maxWidth - 1, 0]
new_bottom_right = [maxWidth - 1, maxHeight - 1]
new_bottom_left = [0, maxHeight - 1]
new_coordinates = np.array([new_top_left, new_top_right, new_bottom_right,
new_bottom_left], dtype = "float32")
# calculate 3x3 matrix of a perspective transform
M = cv2.getPerspectiveTransform(ordered_points, new_coordinates)
# apply perspective transform matrix to image
transformed_image = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
# return the transformed image
return transformed_image
| [
"[email protected]"
] | |
94bf08a7ce82fd2b63625597118eb7bbeb7fe531 | f445450ac693b466ca20b42f1ac82071d32dd991 | /generated_tempdir_2019_09_15_163300/generated_part008601.py | faee6c6b3a4acdcb9b277c59692c5169f5000ac5 | [] | no_license | Upabjojr/rubi_generated | 76e43cbafe70b4e1516fb761cabd9e5257691374 | cd35e9e51722b04fb159ada3d5811d62a423e429 | refs/heads/master | 2020-07-25T17:26:19.227918 | 2019-09-15T15:41:48 | 2019-09-15T15:41:48 | 208,357,412 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,923 | py | from sympy.abc import *
from matchpy.matching.many_to_one import CommutativeMatcher
from matchpy import *
from matchpy.utils import VariableWithCount
from collections import deque
from multiset import Multiset
from sympy.integrals.rubi.constraints import *
from sympy.integrals.rubi.utility_function import *
from sympy.integrals.rubi.rules.miscellaneous_integration import *
from sympy import *
class CommutativeMatcher141898(CommutativeMatcher):
_instance = None
patterns = {
0: (0, Multiset({0: 1}), [
(VariableWithCount('i4.3.0', 1, 1, S(0)), Add)
])
}
subjects = {}
subjects_by_id = {}
bipartite = BipartiteGraph()
associative = Add
max_optional_count = 1
anonymous_patterns = set()
def __init__(self):
self.add_subject(None)
@staticmethod
def get():
if CommutativeMatcher141898._instance is None:
CommutativeMatcher141898._instance = CommutativeMatcher141898()
return CommutativeMatcher141898._instance
@staticmethod
def get_match_iter(subject):
subjects = deque([subject]) if subject is not None else deque()
subst0 = Substitution()
# State 141897
subst1 = Substitution(subst0)
try:
subst1.try_add_variable('i4.3.1.0_1', S(1))
except ValueError:
pass
else:
pass
# State 141899
if len(subjects) >= 1:
tmp2 = subjects.popleft()
subst2 = Substitution(subst1)
try:
subst2.try_add_variable('i4.3.1.0', tmp2)
except ValueError:
pass
else:
pass
# State 141900
if len(subjects) == 0:
pass
# 0: x*b
yield 0, subst2
subjects.appendleft(tmp2)
if len(subjects) >= 1 and isinstance(subjects[0], Mul):
tmp4 = subjects.popleft()
associative1 = tmp4
associative_type1 = type(tmp4)
subjects5 = deque(tmp4._args)
matcher = CommutativeMatcher141902.get()
tmp6 = subjects5
subjects5 = []
for s in tmp6:
matcher.add_subject(s)
for pattern_index, subst1 in matcher.match(tmp6, subst0):
pass
if pattern_index == 0:
pass
# State 141903
if len(subjects) == 0:
pass
# 0: x*b
yield 0, subst1
subjects.appendleft(tmp4)
return
yield
from matchpy.matching.many_to_one import CommutativeMatcher
from collections import deque
from .generated_part008602 import *
from matchpy.utils import VariableWithCount
from multiset import Multiset | [
"[email protected]"
] | |
d38095f6f65c9f07ad7abbb070590af3d8ef7a7d | ded10c2f2f5f91c44ec950237a59225e8486abd8 | /.history/2/path_integral_naive_sampling_20200419015912.py | 09700ceb920c45902a696fba97ea21eac5e153d9 | [] | no_license | jearistiz/Statistical-Physics-Projects | 276a86407b32ded4e06b32efb2fadbd8eff8daed | d9c5b16a50856e148dc8604d92b6de3ea21fc552 | refs/heads/master | 2022-11-05T03:41:23.623050 | 2020-06-28T06:36:05 | 2020-06-28T06:36:05 | 254,909,897 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,101 | py | # -*- coding: utf-8 -*-
from __future__ import division
import os
import numpy as np
import matplotlib.pyplot as plt
from time import time
import pandas as pd
# Author: Juan Esteban Aristizabal-Zuluaga
# date: 202004151200
def rho_free(x,xp,beta):
"""Uso: devuelve elemento de matriz dsnsidad para el caso de una partícula libre en un toro infinito."""
return (2.*np.pi*beta)**(-0.5) * np.exp(-(x-xp)**2 / (2 * beta) )
def harmonic_potential(x):
"""Devuelve valor del potencial armónico para una posición x dada"""
return 0.5* x**2
def anharmonic_potential(x):
"""Devuelve valor de potencial anarmónico para una posición x dada"""
# return np.abs(x)*(1+np.cos(x)) #el resultado de este potencial es interesante
return 0.5*x**2 - x**3 + x**4
def QHO_canonical_ensemble(x,beta):
"""
Uso: calcula probabilidad teórica cuántica de encontrar al oscilador armónico
(inmerso en un baño térmico a temperatura inversa beta) en la posición x.
Recibe:
x: float -> posición
beta: float -> inverso de temperatura en unidades reducidas beta = 1/T.
Devuelve:
probabilidad teórica cuántica en posición x para temperatura inversa beta.
"""
return (np.tanh(beta/2.)/np.pi)**0.5 * np.exp(- x**2 * np.tanh(beta/2.))
def path_naive_sampling( N_path = 10,beta = 4., N_iter = int(1e5), delta = 0.5,
potential = harmonic_potential, append_every = 1 ):
"""
Uso:
"""
dtau = beta/N_path
path_x = [0.] * N_path
pathss_x = [path_x[:]]
t_0 = time()
N_iter = int(N_iter)
for step in range(N_iter):
k = np.random.randint(0,N_path)
#Periodic boundary conditions
knext, kprev = (k+1) % N_path, (k-1) % N_path
x_new = path_x[k] + np.random.uniform(-delta,delta)
old_weight = ( rho_free(path_x[kprev],path_x[k],dtau) *
np.exp(- dtau * potential(path_x[k])) *
rho_free(path_x[k],path_x[knext],dtau) )
new_weight = ( rho_free(path_x[kprev],x_new,dtau) *
np.exp(- dtau * potential(x_new)) *
rho_free(x_new,path_x[knext],dtau) )
if np.random.uniform(0,1) < new_weight/old_weight:
path_x[k] = x_new
if step%append_every == 0:
pathss_x.append(path_x[:])
t_1 = time()
print('Path integral naive sampling: %d iterations -> %.2E seconds'%(N_iter,t_1-t_0))
pathss_x = np.array(pathss_x)
return pathss_x
def figures_fn( pathss_x, beta = 4 , N_plot = 201, x_max = 3, N_iter=int(1e5), append_every=1,
N_beta_ticks = 11, msq_file='file.csv', file_name='path-plot-prueba',
show_theory=True, show_matrix_squaring=True, show_path=True, save_plot=True,
show_plot=True, show_compare_hist=True, show_complete_path_hist=True):
pathss_x = np.array(pathss_x)
script_dir=os.path.dirname(os.path.abspath(__file__))
x_plot = np.linspace(-x_max,x_max,N_plot)
N_path = len(pathss_x[-1])
# Agranda letra en texto en figuras generadas
plt.rc('text', usetex=True) #usa latex en texto de figuras
plt.rcParams.update({'font.size':15,'text.latex.unicode':True})
# Crea figura
fig, ax1 = plt.subplots()
# Grafica histograma, teórico y si se pide un camino aleatorio
ax1.set_xlabel(u'$x$')
ax1.set_ylabel(u'$\pi^{(Q)} (x;\\beta)$')
if show_theory:
lns1 = ax1.plot(x_plot,QHO_canonical_ensemble(x_plot,beta),label=u'Teórico')
if show_matrix_squaring:
msq_file = script_dir + '/' + msq_file
matrix_squaring_data = pd.read_csv(msq_file, index_col=0, comment='#')
lns2 = ax1.plot( matrix_squaring_data['position_x'],matrix_squaring_data['prob_density'],
label = u'Algoritmo Matrix\nSquaring')
lns3 = ax1.hist(pathss_x[:,0], bins=int(np.sqrt(N_iter/append_every)), normed=True,
label=u'Integral de camino\nnaive sampling',alpha=.40)
if show_compare_hist:
lns5 = ax1.hist(pathss_x[:,np.random.choice(np.arange(1,N_path))], bins=int(np.sqrt(N_iter/append_every)), normed=True,
label=u'Comparación hist. $x[k]$',alpha=.40)
if show_complete_path_hist:
pathss_x2 = pathss_x.copy()
pathss_x2 = pathss_x2.flatten()
lns6 = ax1.hist(pathss_x2, bins=int(np.sqrt(N_iter*N_path/append_every)), normed=True,
label=u'Comparación tomando\npath completo $\{x[k]\}_k$',alpha=.40)
ax1.tick_params(axis='y')
ax1.set_ylim(bottom=0)
ax1.set_xlim(-x_max,x_max)
if not show_path:
plt.legend(loc = 'best', fontsize=12)
if save_plot:
plt.savefig(script_dir+'/'+file_name+'.eps')
if show_plot:
plt.show()
plt.close()
if show_path:
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.set_ylabel(u'$\\tau$') # we already handled the x-label with ax1
beta_plot = np.linspace(0,beta,N_path+1)
path_plot = list(pathss_x[-1])
path_plot.append(pathss_x[-1][0])
lns4 = ax2.plot(path_plot, beta_plot,'o-',c='k',label=u'Path')
ax2.tick_params(axis='y')
beta_ticks = np.linspace(0,beta,N_beta_ticks)
ax2.set_yticks(beta_ticks)
ax2.set_yticklabels(u'$%.2f$'%b for b in beta_ticks)
ax2.set_ylim(bottom=0)
ax2.set_xlim(-x_max,x_max)
# Solution for having legends that share two different scales
# if show_theory and show_matrix_squaring and show_compare_hist and show_complete_path_hist:
# leg = lns1 + lns2 + [lns3[2][0]] + lns4 + [lns5[2][0]] + [lns6[2][0]]
# elif show_theory and not show_matrix_squaring and show_compare_hist and show_complete_path_hist:
# leg = lns1 + [lns3[2][0]] + lns4 + [lns5[2][0]] + [lns6[2][0]]
# elif not show_theory and show_matrix_squaring and show_compare_hist and show_complete_path_hist:
# leg = lns2 + [lns3[2][0]] + lns4 + [lns5[2][0]] + [lns6[2][0]]
# elif not show_theory and not show_matrix_squaring and show_compare_hist and show_complete_path_hist:
# leg = [lns3[2][0]] + lns4 + [lns5[2][0]] + [lns6[2][0]]
if not show_theory:
lns1 = [0]
if not show_compare_hist:
lns5 = [0]
if not show_complete_path_hist:
lns6 = [0]
leg_test = lns1 + lns2 + [lns3[2][0]] + lns4 + [lns5[2][0]] + [lns6[2][0]]
labs = []
leg = []
for i,l in enumerate(leg_test):
try:
labs.append(l.get_label())
leg.append(leg_test[i])
except:
pass
ax1.legend(leg, labs, loc='best',title=u'$\\beta=%.2f$'%beta, fontsize=12)
fig.tight_layout() # otherwise the right y-label is slightly clipped
if save_plot:
plt.savefig(script_dir+'/'+file_name+'-path_true.eps')
if show_plot:
plt.show()
plt.close()
return 0
N_path = 10
beta = 4.
N_iter = int(1e4)
delta = 0.5
potential, potential_string = harmonic_potential, 'harmonic_potential'
append_every = 1
msq_file = 'pi_x-ms-harmonic_potential-x_max_5.000-nx_201-N_iter_7-beta_fin_4.000.csv'
N_plot = 201
x_max = 3
x_plot = np.linspace(-x_max,x_max,N_plot)
plot_file_name = 'pi_x-pi-plot-%s-x_max_%.3f-N_path_%d-N_iter_%d-beta_fin_%.3f'\
%(potential_string,x_max,N_path,N_iter,beta)
pathss_x = path_naive_sampling( N_path = N_path, beta = beta, N_iter = N_iter, delta = 0.5,
potential = harmonic_potential, append_every = 1 )
figures_fn( pathss_x, beta = beta , N_plot = N_plot, x_max = x_max, N_iter=N_iter,
append_every=1, N_beta_ticks = N_path+1, msq_file=msq_file,
file_name=plot_file_name, show_theory=True , show_matrix_squaring=True,
show_path=True, save_plot=True, show_plot=True) | [
"[email protected]"
] | |
74f2757220a88898a6e4b5dad3c63b866232286d | a37bf3343be428c453e480c7a411a91b125ab1d1 | /deb/openmediavault/usr/lib/python3/dist-packages/openmediavault/datamodel/datamodel.py | c25bf348fca4181454ad38ac5f9f7141e39083bb | [] | no_license | zys1310992814/openmediavault | 8e73ccd66fefaddd03385834137887614726812c | 337f37729783d9bf3a08866c0dbc8b25c53b9ca3 | refs/heads/master | 2020-04-20T14:18:57.505953 | 2019-02-02T15:18:07 | 2019-02-02T15:18:07 | 168,894,447 | 1 | 0 | null | 2019-02-03T00:41:55 | 2019-02-03T00:41:55 | null | UTF-8 | Python | false | false | 3,163 | py | # -*- coding: utf-8 -*-
#
# This file is part of OpenMediaVault.
#
# @license http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author Volker Theile <[email protected]>
# @copyright Copyright (c) 2009-2018 Volker Theile
#
# OpenMediaVault is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# OpenMediaVault is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OpenMediaVault. If not, see <http://www.gnu.org/licenses/>.
__all__ = ["Datamodel"]
import abc
import json
class Datamodel:
def __init__(self, model):
"""
:param model: The data model as Python dictionary or JSON string.
"""
# Convert into a JSON object if it is a string.
if isinstance(model, str):
model = json.loads(model)
else:
if not isinstance(model, dict):
raise TypeError("Expected dictionary.")
self._model = model
def as_dict(self):
"""
Get the data model as Python dictionary.
:returns: Returns the data model as Python dictionary.
"""
return self._model
@property
def model(self):
"""
Get the data model as Python dictionary.
:returns: Returns the data model as Python dictionary.
"""
return self.as_dict()
@property
def id(self): # pylint: disable=invalid-name
"""
Get the model identifier, e.g. 'conf.service.rsyncd.module'.
:returns: Returns the model identifier.
"""
if not "id" in self.model:
return ""
return self.model['id']
@property
def alias(self):
"""
Get the model identifier alias.
:returns: Returns the model identifier alias.
"""
if not "alias" in self.model:
return ""
return self._model['alias']
@property
def title(self):
"""
Get the model title, e.g. 'SSH certificate'.
:returns: Returns the model titel.
"""
if not "title" in self.model:
return ""
return self._model['title']
@property
def description(self):
"""
Get the model description.
:returns: Returns the model description.
"""
if not "description" in self.model:
return ""
return self._model['description']
@abc.abstractmethod
def validate(self, data):
"""
Validate the specified data against the data model.
:param data: The JSON data to validate.
:returns: None.
"""
def __str__(self):
"""
Return the data model as JSON string.
:returns: Returns a JSON string.
"""
return json.dumps(self.model)
| [
"[email protected]"
] | |
8e7c9117b9b08ed4a03b43f4ae8a2a8d9daa1d19 | ef4f9cfca5cc0fbeb5ac6547d607bd51c52d53cc | /UnityPy/EndianBinaryReader.py | a85fc05e554a4f5d912a0af360ccb2cc9e4d1324 | [
"MIT"
] | permissive | l3iggs/UnityPy | c1fe52719990817c00232834d9436dfb6a70ee57 | 01822260261e395565f357b33d5dab35e1a847b3 | refs/heads/master | 2021-03-27T22:56:13.402044 | 2020-03-03T12:12:49 | 2020-03-03T12:12:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,950 | py | import io
import struct
from .math import Color, Matrix4x4, Quaternion, Vector2, Vector3, Vector4, Rectangle
class EndianBinaryReader:
endian: str
Length: int
Position: int
stream: io.BufferedReader
def __init__(self, input_, endian='>'):
if isinstance(input_, (bytes, bytearray)):
self.stream = io.BytesIO(input_)
elif isinstance(input_, (io.BytesIO, io.BufferedReader)):
self.stream = input_
else:
# test if input is a streamable object
try:
p = input_.tell()
input_.read(1)
input_.seek(p)
assert (p == input_.tell())
self.stream = input_
except:
raise ValueError("Invalid input type - %s." % type(input_))
self.endian = endian
self.Length = self.stream.seek(0, 2)
self.Position = 0
def get_position(self):
return self.stream.tell()
def set_position(self, value):
self.stream.seek(value)
Position = property(get_position, set_position)
@property
def bytes(self):
last_pos = self.Position
self.Position = 0
ret = self.read()
self.Position = last_pos
return ret
def dispose(self):
self.stream.close()
pass
def read(self, *args):
return self.stream.read(*args)
def read_byte(self) -> int:
return struct.unpack(self.endian + "b", self.read(1))[0]
def read_u_byte(self) -> int:
return struct.unpack(self.endian + "B", self.read(1))[0]
def read_bytes(self, num) -> bytes:
return self.read(num)
def read_short(self) -> int:
return struct.unpack(self.endian + "h", self.read(2))[0]
def read_int(self) -> int:
return struct.unpack(self.endian + "i", self.read(4))[0]
def read_long(self) -> int:
return struct.unpack(self.endian + "q", self.read(8))[0]
def read_u_short(self) -> int:
return struct.unpack(self.endian + "H", self.read(2))[0]
def read_u_int(self) -> int:
return struct.unpack(self.endian + "I", self.read(4))[0]
def read_u_long(self) -> int:
return struct.unpack(self.endian + "Q", self.read(8))[0]
def read_float(self) -> float:
return struct.unpack(self.endian + "f", self.read(4))[0]
def read_double(self) -> float:
return struct.unpack(self.endian + "d", self.read(8))[0]
def read_boolean(self) -> bool:
return bool(struct.unpack(self.endian + "?", self.read(1))[0])
def read_string(self, size=None, encoding="utf-8") -> str:
if size is None:
ret = self.read_string_to_null()
else:
ret = struct.unpack(f"{self.endian}{size}is", self.read(size))[0]
try:
return ret.decode(encoding)
except UnicodeDecodeError:
return ret
def read_string_to_null(self, max_length=32767) -> str:
ret = []
c = b""
while c != b"\0" and len(ret) < max_length and self.Position != self.Length:
ret.append(c)
c = self.read(1)
if not c:
raise ValueError("Unterminated string: %r" % ret)
return b"".join(ret).decode('utf8', 'replace')
def read_aligned_string(self):
length = self.read_int()
if 0 < length <= self.Length - self.Position:
string_data = self.read_bytes(length)
result = string_data.decode('utf8', 'backslashreplace')
self.align_stream(4)
return result
return ""
def align_stream(self, alignment=4):
pos = self.Position
mod = pos % alignment
if mod != 0:
self.Position += alignment - mod
def read_quaternion(self):
return Quaternion(self.read_float(), self.read_float(), self.read_float(), self.read_float())
def read_vector2(self):
return Vector2(self.read_float(), self.read_float())
def read_vector3(self):
return Vector3(self.read_float(), self.read_float(), self.read_float())
def read_vector4(self):
return Vector4(self.read_float(), self.read_float(), self.read_float(), self.read_float())
def read_rectangle_f(self):
return Rectangle(self.read_float(), self.read_float(), self.read_float(), self.read_float())
def read_color4(self):
return Color(self.read_float(), self.read_float(), self.read_float(), self.read_float())
def read_matrix(self):
return Matrix4x4(self.read_float_array(16))
def read_array(self, command, length: int):
return [command() for i in range(length)]
def read_boolean_array(self):
return self.read_array(self.read_boolean, self.read_int())
def read_u_short_array(self):
return self.read_array(self.read_u_short, self.read_int())
def read_int_array(self, length=0):
return self.read_array(self.read_int, length if length else self.read_int())
def read_u_int_array(self, length=0):
return self.read_array(self.read_u_int, length if length else self.read_int())
def read_float_array(self, length=0):
return self.read_array(self.read_float, length if length else self.read_int())
def read_string_array(self):
return self.read_array(self.read_aligned_string, self.read_int())
def read_vector2_array(self):
return self.read_array(self.read_vector2, self.read_int())
def read_vector4_array(self):
return self.read_array(self.read_vector4, self.read_int())
def read_matrix_array(self):
return self.read_array(self.read_matrix, self.read_int())
| [
"[email protected]"
] | |
6d2ebfb0d5eca67a6c3677b695fb01da765358e8 | e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f | /indices/feeder.py | b081311b634e091e1371ab0183f9c9abded2626e | [] | no_license | psdh/WhatsintheVector | e8aabacc054a88b4cb25303548980af9a10c12a8 | a24168d068d9c69dc7a0fd13f606c080ae82e2a6 | refs/heads/master | 2021-01-25T10:34:22.651619 | 2015-09-23T11:54:06 | 2015-09-23T11:54:06 | 42,749,205 | 2 | 3 | null | 2015-09-23T11:54:07 | 2015-09-18T22:06:38 | Python | UTF-8 | Python | false | false | 432 | py | ii = [('LyelCPG2.py', 2), ('RogePAV2.py', 2), ('RogePAV.py', 1), ('RennJIT.py', 4), ('ProuWCM.py', 5), ('LeakWTI2.py', 2), ('PeckJNG.py', 6), ('LyelCPG.py', 2), ('WestJIT2.py', 5), ('KirbWPW2.py', 2), ('LeakWTI4.py', 1), ('LeakWTI.py', 1), ('BachARE.py', 3), ('SoutRD.py', 1), ('HowiWRL2.py', 1), ('WestJIT.py', 4), ('FitzRNS4.py', 4), ('StorJCC.py', 1), ('BellCHM.py', 2), ('BowrJMM2.py', 1), ('LyelCPG3.py', 1), ('WordWYR.py', 3)] | [
"[email protected]"
] | |
20a53a274d6d968a8915ec3cbcd0bfd96af6fe6b | 9f16e7e8a728bbe80599225a0b0209e66f90aa85 | /tensorflow/contrib/kfac/python/ops/estimator.py | 30d825cc74fba6937da7d6fd808f4928fa2472dd | [
"Apache-2.0"
] | permissive | dantkz/tensorflow | af2035a8c77e2672f9d4a243f6dd6af82fc6fc50 | 5333bbeb3142af2a06f1ebd971061fc4e28da743 | refs/heads/master | 2021-05-05T14:59:58.530607 | 2017-12-01T13:36:46 | 2017-12-01T13:36:46 | 105,175,518 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,030 | py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Defines the high-level Fisher estimator class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
from tensorflow.contrib.kfac.python.ops import utils
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.util import nest
class FisherEstimator(object):
"""Fisher estimator class supporting various approximations of the Fisher."""
def __init__(self,
variables,
cov_ema_decay,
damping,
layer_collection,
estimation_mode="gradients"):
"""Create a FisherEstimator object.
Args:
variables: A list of the variables for which to estimate the Fisher. This
must match the variables registered in layer_collection (if it is not
None).
cov_ema_decay: The decay factor used when calculating the covariance
estimate moving averages.
damping: The damping factor used to stabilize training due to errors in
the local approximation with the Fisher information matrix, and to
regularize the update direction by making it closer to the gradient.
(Higher damping means the update looks more like a standard gradient
update - see Tikhonov regularization.)
layer_collection: The layer collection object, which holds the fisher
blocks, kronecker factors, and losses associated with the
graph.
estimation_mode: The type of estimator to use for the Fishers. Can be
'gradients', 'empirical', 'curvature_prop', or 'exact'.
(Default: 'gradients'). 'gradients' is the basic estimation approach
from the original K-FAC paper. 'empirical' computes the 'empirical'
Fisher information matrix (which uses the data's distribution for the
targets, as opposed to the true Fisher which uses the model's
distribution) and requires that each registered loss have specified
targets. 'curvature_propagation' is a method which estimates the
Fisher using self-products of random 1/-1 vectors times "half-factors"
of the Fisher, as described here: https://arxiv.org/abs/1206.6464 .
Finally, 'exact' is the obvious generalization of Curvature
Propagation to compute the exact Fisher (modulo any additional
diagonal or Kronecker approximations) by looping over one-hot vectors
for each coordinate of the output instead of using 1/-1 vectors. It
is more expensive to compute than the other three options by a factor
equal to the output dimension, roughly speaking.
Raises:
ValueError: If no losses have been registered with layer_collection.
"""
self._variables = variables
self._damping = damping
self._estimation_mode = estimation_mode
self._layers = layer_collection
self._layers.create_subgraph()
self._check_registration(variables)
self._gradient_fns = {
"gradients": self._get_grads_lists_gradients,
"empirical": self._get_grads_lists_empirical,
"curvature_prop": self._get_grads_lists_curvature_prop,
"exact": self._get_grads_lists_exact
}
setup = self._setup(cov_ema_decay)
self.cov_update_op, self.inv_update_op, self.inv_updates_dict = setup
@property
def variables(self):
return self._variables
@property
def damping(self):
return self._damping
def _apply_transformation(self, vecs_and_vars, transform):
"""Applies an block-wise transformation to the corresponding vectors.
Args:
vecs_and_vars: List of (vector, variable) pairs.
transform: A function of the form f(fb, vec), where vec is the vector
to transform and fb is its corresponding block in the matrix, that
returns the transformed vector.
Returns:
A list of (transformed vector, var) pairs in the same order as
vecs_and_vars.
"""
vecs = utils.SequenceDict((var, vec) for vec, var in vecs_and_vars)
trans_vecs = utils.SequenceDict()
for params, fb in self._layers.fisher_blocks.items():
trans_vecs[params] = transform(fb, vecs[params])
return [(trans_vecs[var], var) for _, var in vecs_and_vars]
def multiply_inverse(self, vecs_and_vars):
"""Multiplies the vecs by the corresponding (damped) inverses of the blocks.
Args:
vecs_and_vars: List of (vector, variable) pairs.
Returns:
A list of (transformed vector, var) pairs in the same order as
vecs_and_vars.
"""
return self._apply_transformation(vecs_and_vars,
lambda fb, vec: fb.multiply_inverse(vec))
def multiply(self, vecs_and_vars):
"""Multiplies the vectors by the corresponding (damped) blocks.
Args:
vecs_and_vars: List of (vector, variable) pairs.
Returns:
A list of (transformed vector, var) pairs in the same order as
vecs_and_vars.
"""
return self._apply_transformation(vecs_and_vars,
lambda fb, vec: fb.multiply(vec))
def _check_registration(self, variables):
"""Checks that all variable uses have been registered properly.
Args:
variables: List of variables.
Raises:
ValueError: If any registered variables are not included in the list.
ValueError: If any variable in the list is not registered.
ValueError: If any variable in the list is registered with the wrong
number of "uses" in the subgraph recorded (vs the number of times that
variable is actually used in the subgraph).
"""
# Note that overlapping parameters (i.e. those that share variables) will
# be caught by layer_collection.LayerParametersDict during registration.
reg_use_map = self._layers.get_use_count_map()
error_messages = []
for var in variables:
total_uses = self._layers.subgraph.variable_uses(var)
reg_uses = reg_use_map[var]
if reg_uses == 0:
error_messages.append("Variable {} not registered.".format(var))
elif (not math.isinf(reg_uses)) and reg_uses != total_uses:
error_messages.append(
"Variable {} registered with wrong number of uses ({} "
"vs {} actual).".format(var, reg_uses, total_uses))
num_get_vars = len(reg_use_map)
if num_get_vars > len(variables):
error_messages.append("{} registered variables were not included in list."
.format(num_get_vars - len(variables)))
if error_messages:
error_messages = [
"Found the following errors with variable registration:"
] + error_messages
raise ValueError("\n\t".join(error_messages))
def _setup(self, cov_ema_decay):
"""Sets up the various operations.
Args:
cov_ema_decay: The decay factor used when calculating the covariance
estimate moving averages.
Returns:
A triple (covs_update_op, invs_update_op, inv_updates_dict), where
covs_update_op is the grouped Op to update all the covariance estimates,
invs_update_op is the grouped Op to update all the inverses, and
inv_updates_dict is a dict mapping Op names to individual inverse updates.
Raises:
ValueError: If estimation_mode was improperly specified at construction.
"""
fisher_blocks_list = self._layers.get_blocks()
tensors_to_compute_grads = [
fb.tensors_to_compute_grads() for fb in fisher_blocks_list
]
try:
grads_lists = self._gradient_fns[self._estimation_mode](
tensors_to_compute_grads)
except KeyError:
raise ValueError("Unrecognized value {} for estimation_mode.".format(
self._estimation_mode))
for grads_list, fb in zip(grads_lists, fisher_blocks_list):
fb.instantiate_factors(grads_list, self.damping)
cov_updates = [
factor.make_covariance_update_op(cov_ema_decay)
for factor in self._layers.get_factors()
]
inv_updates = {op.name: op for op in self._get_all_inverse_update_ops()}
return control_flow_ops.group(*cov_updates), control_flow_ops.group(
*inv_updates.values()), inv_updates
def _get_all_inverse_update_ops(self):
for factor in self._layers.get_factors():
for op in factor.make_inverse_update_ops():
yield op
def _get_grads_lists_gradients(self, tensors):
grads_flat = gradients_impl.gradients(self._layers.total_sampled_loss(),
nest.flatten(tensors))
grads_all = nest.pack_sequence_as(tensors, grads_flat)
return tuple((grad,) for grad in grads_all)
def _get_grads_lists_empirical(self, tensors):
grads_flat = gradients_impl.gradients(self._layers.total_loss(),
nest.flatten(tensors))
grads_all = nest.pack_sequence_as(tensors, grads_flat)
return tuple((grad,) for grad in grads_all)
def _get_transformed_random_signs(self):
transformed_random_signs = []
for loss in self._layers.losses:
transformed_random_signs.append(
loss.multiply_fisher_factor(
utils.generate_random_signs(loss.fisher_factor_inner_shape)))
return transformed_random_signs
def _get_grads_lists_curvature_prop(self, tensors):
loss_inputs = list(loss.inputs for loss in self._layers.losses)
transformed_random_signs = self._get_transformed_random_signs()
grads_flat = gradients_impl.gradients(
nest.flatten(loss_inputs),
nest.flatten(tensors),
grad_ys=nest.flatten(transformed_random_signs))
grads_all = nest.pack_sequence_as(tensors, grads_flat)
return tuple((grad,) for grad in grads_all)
def _get_grads_lists_exact(self, tensors):
# Loop over all coordinates of all losses.
grads_all = []
for loss in self._layers.losses:
for index in np.ndindex(*loss.fisher_factor_inner_static_shape[1:]):
transformed_one_hot = loss.multiply_fisher_factor_replicated_one_hot(
index)
grads_flat = gradients_impl.gradients(
loss.inputs, nest.flatten(tensors), grad_ys=transformed_one_hot)
grads_all.append(nest.pack_sequence_as(tensors, grads_flat))
return zip(*grads_all)
| [
"[email protected]"
] | |
81371c236c1b31b828834065ba1f4590cc065578 | 91948d5be26636f1f2b941cb933701ea626a695b | /problem002_uber_product.py | 43dee7ed290c090339c4cb64d1c47645fbcbabf7 | [
"MIT"
] | permissive | loghmanb/daily-coding-problem | 4ae7dd201fde5ee1601e0acae9e9fc468dcd75c9 | b2055dded4276611e0e7f1eb088e0027f603aa7b | refs/heads/master | 2023-08-14T05:53:12.678760 | 2023-08-05T18:12:38 | 2023-08-05T18:12:38 | 212,894,228 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,460 | py | '''
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i
of the new array is the product of all the numbers in the original array except
the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be
[2, 3, 6].
Follow-up: what if you can't use division?
'''
def solve(int_list):
all_product = 1
for x in int_list:
all_product *= x
return list(map(lambda x:int(all_product/x), int_list))
'''
for [a, b, c, d, e]
first step:
for each item is calculated from previous value to previous position value in main array
l1 = [1. a, (a)b, (ab)c, (abc)d]
second step;
repeat what happend before in reverse (from right to left)
l2 = [b(cde), c(de), d(e), e, 1]
and finally:
ans = l1[i]*l2[i] for each item
'''
def solve_without_division(int_list):
n = len(int_list)
#from left t right
l1 = [1]*n
for i in range(1, n):
l1[i] = l1[i-1] * int_list[i-1]
#from right to left
l2 = [1]*n
for i in range(1, n):
l2[n-i-1] = l2[n-i] * int_list[n-i]
ans = [l1[i]*l2[i] for i in range(n)]
return ans
if __name__ == '__main__':
test_list = [[1, 2, 3, 4, 5],
[3, 2, 1]]
for l in test_list:
print( 'list: ', l, ' output#1: ', solve(l), 'output#2: ', solve_without_division(l) ) | [
"[email protected]"
] | |
9186c66a5e468ddac1f6938a4ca7a42f605deadf | a6e4a6f0a73d24a6ba957277899adbd9b84bd594 | /sdk/python/pulumi_azure_native/servicefabricmesh/v20180701preview/get_volume.py | bf1e34036b579879a38e2e8ba7e5a4239246a83e | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | MisinformedDNA/pulumi-azure-native | 9cbd75306e9c8f92abc25be3f73c113cb93865e9 | de974fd984f7e98649951dbe80b4fc0603d03356 | refs/heads/master | 2023-03-24T22:02:03.842935 | 2021-03-08T21:16:19 | 2021-03-08T21:16:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,980 | 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! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetVolumeResult',
'AwaitableGetVolumeResult',
'get_volume',
]
@pulumi.output_type
class GetVolumeResult:
"""
This type describes a volume resource.
"""
def __init__(__self__, azure_file_parameters=None, description=None, id=None, location=None, name=None, provider=None, provisioning_state=None, tags=None, type=None):
if azure_file_parameters and not isinstance(azure_file_parameters, dict):
raise TypeError("Expected argument 'azure_file_parameters' to be a dict")
pulumi.set(__self__, "azure_file_parameters", azure_file_parameters)
if description and not isinstance(description, str):
raise TypeError("Expected argument 'description' to be a str")
pulumi.set(__self__, "description", description)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if provider and not isinstance(provider, str):
raise TypeError("Expected argument 'provider' to be a str")
pulumi.set(__self__, "provider", provider)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter(name="azureFileParameters")
def azure_file_parameters(self) -> Optional['outputs.VolumeProviderParametersAzureFileResponse']:
"""
This type describes a volume provided by an Azure Files file share.
"""
return pulumi.get(self, "azure_file_parameters")
@property
@pulumi.getter
def description(self) -> Optional[str]:
"""
User readable description of the volume.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter
def id(self) -> str:
"""
Fully qualified identifier for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def location(self) -> str:
"""
The geo-location where the resource lives
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the resource
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def provider(self) -> str:
"""
Provider of the volume.
"""
return pulumi.get(self, "provider")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> str:
"""
State of the resource.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
"""
The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts.
"""
return pulumi.get(self, "type")
class AwaitableGetVolumeResult(GetVolumeResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetVolumeResult(
azure_file_parameters=self.azure_file_parameters,
description=self.description,
id=self.id,
location=self.location,
name=self.name,
provider=self.provider,
provisioning_state=self.provisioning_state,
tags=self.tags,
type=self.type)
def get_volume(resource_group_name: Optional[str] = None,
volume_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVolumeResult:
"""
This type describes a volume resource.
:param str resource_group_name: Azure resource group name
:param str volume_name: The identity of the volume.
"""
__args__ = dict()
__args__['resourceGroupName'] = resource_group_name
__args__['volumeName'] = volume_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:servicefabricmesh/v20180701preview:getVolume', __args__, opts=opts, typ=GetVolumeResult).value
return AwaitableGetVolumeResult(
azure_file_parameters=__ret__.azure_file_parameters,
description=__ret__.description,
id=__ret__.id,
location=__ret__.location,
name=__ret__.name,
provider=__ret__.provider,
provisioning_state=__ret__.provisioning_state,
tags=__ret__.tags,
type=__ret__.type)
| [
"[email protected]"
] | |
9ceecd5538942099bab3b6551d6e2237a046eb14 | 44d4a051663179ddf4a87ef607070e8abed1b94f | /ntupleAnalysis/skim_select_events.py | 74870141f0dcdb8c5763db8776a54254cbf40845 | [] | no_license | mbandrews/h2aa | 458471abd90dc2a80d13ad2d2428cc0567d58c89 | de1549d472f0b815236598c9676c27719b949e67 | refs/heads/master | 2022-12-09T22:08:21.235484 | 2022-12-08T03:44:58 | 2022-12-08T03:44:58 | 232,382,628 | 0 | 1 | null | 2022-12-08T03:44:59 | 2020-01-07T17:49:35 | Jupyter Notebook | UTF-8 | Python | false | false | 9,874 | py | from __future__ import print_function
from collections import OrderedDict
import numpy as np
np.random.seed(0)
import os, re, glob
import time
import argparse
from hist_utils import *
from selection_utils import *
#from get_bkg_norm import *
import ROOT
# Register command line options
parser = argparse.ArgumentParser(description='Run h2aa bkg model.')
parser.add_argument('-s', '--sample', default='test', type=str, help='Sample name.')
parser.add_argument('-r', '--region', default='sb', type=str, help='mH-region: sr, sb, sblo, sbhi, all.')
parser.add_argument('-i', '--inputs', default=['MAntuples/Run2017F_mantuple.root'], nargs='+', type=str, help='Input MA ntuple.')
parser.add_argument('--inlist', default=None, type=str, help='Input MA ntuple file list.')
parser.add_argument('-o', '--outdir', default='Templates', type=str, help='Output directory.')
parser.add_argument('-w', '--wgtsdir', default='Weights', type=str, help='Weights output directory.')
parser.add_argument('-b', '--blind', default=None, type=str, help='Regions to blind.')
parser.add_argument('-n', '--norm', default=None, type=float, help='SB to SR normalization.')
parser.add_argument('-e', '--events', default=-1, type=int, help='Number of evts to process.')
parser.add_argument('--pt_rwgt', default=None, type=str, help='pt re-weighting file.')
parser.add_argument('--do_ptomGG', action='store_true', help='Switch to apply pt/mGG cuts.')
parser.add_argument('--write_pts', action='store_true', help='Write out photon pts.')
parser.add_argument('--systPhoIdSF', default=None, type=str, help='Syst, photon ID SF: None, nom, up, dn.')
parser.add_argument('--systPhoIdFile', default=None, type=str, help='Syst, photon ID input file.')
#parser.add_argument('--systScale', default=None, type=str, help='Syst, m_a energy scale: None, up, dn.')
#parser.add_argument('--systSmear', default=None, type=str, help='Syst, m_a energy smear: None, up, dn.')
parser.add_argument('--systScale', default=None, type=float, nargs=3, help='Syst, m_a energy scale: eta(cntr) eta(mid) eta(fwd)')
parser.add_argument('--systSmear', default=None, type=float, nargs=3, help='Syst, m_a energy smear: eta(cntr) eta(mid) eta(fwd)')
#parser.add_argument('--do_pu_rwgt', action='store_true', help='Apply PU reweighting')
parser.add_argument('--pu_file', default=None, help='PU reweighting file if to be applied.')
args = parser.parse_args()
ma_binw = 25. # MeV
diag_w = 200. # MeV
sample = args.sample
print('>> Doing sample:',sample)
year = re.findall('(201[6-8])', sample.split('-')[0])[0]
print('>> Doing year:',year)
region = args.region
print('>> Doing mH-region:',region)
blind = args.blind
print('>> Blinding mA:',blind)
norm = args.norm
outdir = args.outdir
print('>> Will output templates to:',outdir)
#wgtsdir = args.wgtsdir
if 'h4g' in sample:
# h4g2017-mA1p0GeV
magen = float(sample.split('-')[-1].replace('GeV','').replace('mA','').replace('p','.'))
else:
magen = None
print('>> mA,gen [GeV]:',str(magen))
do_ptomGG = args.do_ptomGG
#do_ptomGG = args.do_ptomGG if 'sb' not in region else False
if do_ptomGG:
print('>> Using pt/mGG cuts')
else:
assert region != 'sr'
#assert do_pt_rwgt
write_pts = args.write_pts
if write_pts:
#evtlist_f = open("Weights/%s_region_%s_blind_%s_selected_phoEt_list.txt"%(sample, region, blind), "w+")
evtlist_f = open("%s/%s_region_%s_blind_%s_selected_phoEt_list.txt"%(outdir, sample, region, blind), "w+")
do_pt_rwgt = True if args.pt_rwgt is not None else False
if do_pt_rwgt:
assert region != 'sr'
print('>> Applying pt re-weighting:', args.pt_rwgt)
fpt = ROOT.TFile.Open(args.pt_rwgt, "READ")
hpt = fpt.Get('pt0vpt1_ratio')
#nfpt = np.load("Weights/%s_%s_blind_%s_ptwgts.npz"%(s, r, None))
#nfpt = np.load("%s/%s_%s_blind_%s_ptwgts.npz"%(wgtsdir, s, r, None))
pu_file = args.pu_file
do_pu_rwgt = False
if pu_file is not None:
if 'data' not in sample:
do_pu_rwgt = True
print('>> Doing PU re-weighting: %s'%pu_file)
fpu = ROOT.TFile.Open(pu_file, "READ")
hpu = fpu.Get('pu_ratio')
#do_pu_rwgt = args.do_pu_rwgt
#if 'data' in sample: assert do_pu_rwgt is False
#if do_pu_rwgt:
# print('Doing PU re-weighting')
# year = str(2017)
# fpu = ROOT.TFile('PU/puwgts_Run%so%s.root'%(year, sample), "READ")
# hpu = fpu.Get('pu_ratio')
systPhoIdSF = args.systPhoIdSF
systPhoIdFile = args.systPhoIdFile
if 'data' in sample: assert systPhoIdSF is None
if systPhoIdSF is not None:
assert systPhoIdFile is not None, '!! Pho ID syst is %s but no syst file found!'%systPhoIdSF
print('>> Doing syst: photon ID SF shift:',systPhoIdSF)
print(' .. syst input file: %s'%systPhoIdFile)
fsf = ROOT.TFile(systPhoIdFile, "READ")
hsf = fsf.Get('EGamma_SF2D')
systScale = args.systScale
if 'data' in sample: assert systScale is None
print('>> Doing syst: energy scale shift:',systScale)
systSmear = args.systSmear
if 'data' in sample: assert systSmear is None
print('>> Doing syst: energy smear shift:',systSmear)
hists = {}
create_hists(hists)
#cuts = [str(None), 'npho', 'dR', 'ptomGG', 'bdt'] if do_ptomGG else [str(None), 'npho', 'dR', 'bdt']
#cuts = [str(None), 'npho', 'ptomGG'] if do_ptomGG else [str(None), 'npho']
#cuts = [str(None), 'npho', 'ptomGG', 'bdt'] if do_ptomGG else [str(None), 'npho', 'bdt']
#cuts = [str(None), 'npho', 'ptomGG'] if do_ptomGG else [str(None), 'npho']
#cuts = [str(None), 'ptomGG', 'bdt'] if do_ptomGG else [str(None), 'bdt']
#cuts = [str(None), 'ptomGG', 'chgiso'] if do_ptomGG else [str(None), 'chgiso']
#cuts = [str(None), 'ptomGG'] if do_ptomGG else [str(None)]
#cuts = [str(None), 'ptomGG', 'chgiso', 'bdt'] if do_ptomGG else [str(None), 'chgiso', 'bdt']
#cuts = [str(None), 'ptomGG', 'bdt', 'chgiso'] if do_ptomGG else [str(None), 'bdt', 'chgiso']
#cuts = [str(None), 'bdt', 'chgiso']
#cuts = [str(None), 'bdt', 'chgiso', 'phoEta'] # sg sel, post-skim
cuts = [str(None), 'trg', 'npho', 'presel', 'mgg', 'ptomGG', 'bdt', 'chgiso', 'phoEta'] # sg skim+sel
cut_hists = OrderedDict()
create_cut_hists(cut_hists, cuts)
counts = OrderedDict([(cut, 0) for cut in cuts])
print('>> Reading input maNtuples...')
if args.inlist is not None:
inlist = args.inlist
print(' .. input list file provided: %s'%inlist)
assert os.path.isfile(inlist), ' !! input maNtuple list not found!'
inputs = open(inlist).readlines()
inputs = [f.strip('\n') for f in inputs]
else:
inputs = args.inputs
print(' .. Nfiles:',len(inputs))
#print(' .. [ 0]:',inputs[0])
#print(' .. [-1]:',inputs[-1])
tree = ROOT.TChain('ggNtuplizer/EventTree')
for i,fh in enumerate(inputs):
tree.Add(fh)
print(' .. adding file: %s'%fh)
#if i > 10: break
nEvts = tree.GetEntries()
print(' .. Nevts: %d'%nEvts)
# Event range to process
iEvtStart = 0
iEvtEnd = nEvts if args.events == -1 else args.events
#iEvtEnd = 10000
'''
# Inject sg
#sgbr = 1.e-1 # *xsec(h)
#sgbr = 0. # *xsec(h)
#sgbr = 0.0047 # *xsec(h)
#sgbr = 0.0079 # *xsec(h)
#ma = '100MeV'
##sgbr = 0.0014 # *xsec(h)
#sgbr = 0.0024 # *xsec(h)
#ma = '400MeV'
#sgbr = 0.0026 # *xsec(h)
#sgbr = 0.0046 # *xsec(h)
#ma = '1GeV'
h24g_sample = 'h24gamma_1j_1M_%s'%ma
sginj_wgt = sgbr*get_sg_norm(h24g_sample)
#sginj_wgt = 1. # no sg scaling
print('sginj_wgt:',sginj_wgt)
'''
sginj_wgt = 0. # no sg injection
print(">> Processing entries: [",iEvtStart,"->",iEvtEnd,")")
nWrite = 0
sw = ROOT.TStopwatch()
sw.Start()
for iEvt in range(iEvtStart,iEvtEnd):
# Initialize event
#if iEvt%10e3==0: print(iEvt,'/',iEvtEnd-iEvtStart)
if iEvt%1e5==0: print(iEvt,'/',iEvtEnd-iEvtStart)
evt_statusf = tree.GetEntry(iEvt)
if evt_statusf <= 0: continue
# Apply event selection
outvars = {}
if not select_event(tree, cuts, cut_hists, counts, outvars, year): continue
# Analyze event
#if not analyze_event(tree, region, blind, do_ptomGG): continue
# Check if in mH-region
mgg = outvars['mgg'] if 'mgg' in outvars else tree.mgg
if not in_mh_region(region, mgg): continue
# Get event weight
#wgt = 1. if 'Data' in args.treename else tree.weight
wgt = 1. if tree.isData else tree.genWeight
#wgtPt, wgtSF, wgtPU = 1., 1., 1.
wgtPt, wgtTrgSF, wgtSF, wgtPU = 1., 1., 1., 1.
if do_pt_rwgt:
wgtPt = get_ptwgt(tree, hpt)
wgt = wgt*wgtPt
#if 'Run20' in sample and not tree.isData:
if 'data' in sample and not tree.isData:
wgt = wgt*sginj_wgt
if systPhoIdSF is not None and not tree.isData:
wgtSF = get_sftot(tree, hsf, systPhoIdSF)
wgt = wgt*wgtSF
if do_pu_rwgt and not tree.isData:
wgtPU = get_puwgt(tree, hpu)
wgt = wgt*wgtPU
# Fill histograms with appropriate weight
fill_hists(hists, tree, wgt, wgtPt, wgtPU, wgtSF, wgtTrgSF, systScale, systSmear, magen, outvars)
if write_pts:
evtId = '%f:%f:%f:%f:%f'%(tree.phoEt[0], tree.phoEt[1], tree.phoIDMVA[0], tree.phoIDMVA[1], tree.mgg)
evtlist_f.write('%s\n'%evtId)
nWrite += 1
sw.Stop()
print(">> N events written: %d / %d"%(nWrite, iEvtEnd-iEvtStart))
print(">> Real time:",sw.RealTime()/60.,"minutes")
print(">> CPU time: ",sw.CpuTime() /60.,"minutes")
if norm is not None:
print('Renormalizing to:',norm)
norm_hists(hists, norm)
print('h[ma0vma1].GetEntries():',hists['ma0vma1'].GetEntries())
print('h[ma0vma1].Integral():',hists['ma0vma1'].Integral())
# Initialize output ntuple
write_hists(hists, "%s/%s_%s_blind_%s_templates.root"%(outdir, sample, region, blind))
write_cut_hists(cut_hists, "%s/%s_%s_cut_hists.root"%(outdir, sample, region))
# Print cut flow summary
print_stats(counts, "%s/%s_%s_cut_stats.txt"%(outdir, sample, region))
if write_pts:
evtlist_f.close()
if counts['None'] != (iEvtEnd-iEvtStart):
print('!!! WARNING !!! Evt count mismatch !!! processed:%d vs. total:%d'%(counts['None'], (iEvtEnd-iEvtStart)))
| [
"[email protected]"
] | |
25854f44a5cc291fbdd5dfec90ae8bea919c44ef | 201356e09fb6dd82d36ed5b93b08a29482b68fb2 | /HD - Intro/Task 20/example.py | ddb49c8255c3ccf527b2f2d8dfdf08f3094bf33d | [] | no_license | M45t3rJ4ck/Py-Code | 5971bad5304ea3d06c1cdbd065941271c33e4254 | 32063d149824eb22163ea462937e4c26917a8b14 | refs/heads/master | 2020-04-08T05:03:44.772327 | 2018-11-26T06:41:03 | 2018-11-26T06:41:03 | 159,044,079 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,058 | py | #************* HELP *****************
#REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LOG IN TO www.hyperiondev.com/support TO:
#START A CHAT WITH YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL.
#*************************************
# *** IF YOU DID NOT INSTALL NOTEPAD++ AND PYTHON (VERSION 2.7.3 or 2.7.5) ***
# *** PLEASE STOP READING THIS NOW, OPEN THE INSTALLERS FOLDER IN THIS DIRECTORY,
# RUN BOTH FILES TO INSTALL NOTEPAD++ AND PYTHON. ***
# PLEASE ENSURE YOU OPEN THIS FILE IN NOTEPAD++ OR IDLE otherwise you will not be able to read it.
# *** NOTE ON COMMENTS ***
# This is a comment in Python.
# Comments can be placed anywhere in Python code and the computer ignores them - they are intended to be read by humans.
# Any line with a # in front of it is a comment.
# Please read all the comments in this example file and all others.
# ================= Consolidation Task ==================
# Everything you have been learning has been tested with application tasks for each section.
# Now however, you will now be utilising everything you have learnt so far to solve this problem.
# You've covered all the necessary content to solve a large real-life data problem.
# Data management is an extremely important component of the Computer Science field and this task will provide you with first hand experience.
# You may find it helpful to revise what you've learnt from your previous tasks.
# This task will also require you to do some individual research as this is an essential component to being a successful software developer.
# You now have all the tools for the compulsory task.
# ================= File Input and Output ==================
# ************ Example 1 ************
# Write a file
out_file = open("test.txt","w")
out_file.write("This Text is going to out file\nLook at it and see!")
out_file.close()
# ************ Example 2 ************
# Read a file
print("\nExample 2:")
in_file = open("test.txt","r")
text = in_file.read()
in_file.close()
print(text)
# ================= The split() Method ==================
# ************ Example 3 ************
print("\nExample 3:")
print("This is a bunch of words".split())
# prints out ['This', 'is', 'a', 'bunch', 'of', 'words']
text = "First batch, second batch, third, fourth"
print(text.split(","))
# prints out ['First batch', ' second batch', ' third', ' fourth']
# ************ Example 4 ************
print("\nExample 4:")
text = "First batch, second batch, third, fourth"
list = text.split(",")
print(len(list))
# prints out 4
print(list[-1])
# prints out 'fourth'
list = text.split(",",2)
print(list)
print(len(list))
# prints out 3
print(list[-1])
# prints out 'third, fourth'
# ****************** END OF EXAMPLE CODE ********************* #
# == Make sure you have read and understood all of the code in this Python file.
# == Please complete the compulsory task below to proceed to the next task ===
# == Ensure you complete your work in this folder so that one of our tutors can easily locate and mark it ===
# ================= Compulsory Task ==================
# After you've read and understand all of example.py, create a new Python file called amazon.py inside this folder.
# This programming problem is one posed to new software developer applicants to Amazon, the software development company you've probably bought a book or dvd from once in your life.
# Inside amazon.py, write Python code to read in the contents of the textfile 'input.txt', and for each line in input.txt.
# Write out a new line in a new text file output.txt that computes the answer to some operation on a list of numbers.
# If the input.txt file has the following:
# min: 1,2,3,5,6
# max: 1,2,3,5,6
# avg: 1,2,3,5,6
# Your program should generate an output.txt file as following:
# The min of [1, 2, 3, 5, 6] is 1
# The max of [1, 2, 3, 5, 6] is 6
# The avg of [1, 2, 3, 5, 6] is 3.4
# Assume that the only operations given in the input file are 'min', 'max' and 'avg', and that the operation is always followed by a list of comma separated integers.
# Your program should handle any combination of operations, any lengths of input numbers. You can assume that the list of input numbers are always valid ints, and is never empty.
# ================= BONUS Optional Task ==================
# Change your program to also handle the operation 'px' where x is a number from 10 to 90 and defines the x percentile of the list of numbers. For example:
# input.txt:
# min: 1,2,3,5,6
# max: 1,2,3,5,6
# avg: 1,2,3,5,6
# p90: 1,2,3,4,5,6,7,8,9,10
# sum: 1,2,3,5,6
# min: 1,5,6,14,24
# max: 2,3,9
# p70: 1,2,3
# Your output.txt should read:
# The min of [1, 2, 3, 5, 6] is 1
# The max of [1, 2, 3, 5, 6] is 6
# The avg of [1, 2, 3, 5, 6] is 3.4
# The 90th percentile of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] is 9
# The sum of [1, 2, 3, 5, 6] is 17
# The min of [1, 5, 6, 14, 24] is 1
# The max of [2, 3, 9] is 9
# The 70th percentile of [1, 2, 3] is 2
| [
"[email protected]"
] | |
ab9afc1e2ce503d83c3056e69b4288ec408dfa41 | b7b7b9976a33d7eab9bd1ac0da89465ce38c20b9 | /tests/0800_builder/03_get_globals.py | 730a75c907d48e302eb80b7ed158156ae55b66eb | [
"MIT"
] | permissive | sveetch/Optimus | 87070ae99890a2c69dc28d5582cd680cd7d516dc | 983aebeccd2ada7a5a0ab96f9296d4bba1112022 | refs/heads/master | 2021-10-12T00:11:33.012608 | 2021-10-09T22:54:29 | 2021-10-09T22:54:29 | 6,760,885 | 2 | 1 | null | 2013-12-16T18:08:42 | 2012-11-19T13:39:29 | Python | UTF-8 | Python | false | false | 1,572 | py | import os
from optimus.pages.builder import PageBuilder
def test_get_globals(minimal_basic_settings, fixtures_settings, caplog):
"""
Context should be correclty filled with context globals (SITE shortcut,
settings, optimus version)
"""
projectdir = os.path.join(fixtures_settings.fixtures_path, "basic_template")
settings = minimal_basic_settings(projectdir)
# Init builder with default environment
builder = PageBuilder(settings)
assert builder.jinja_env.globals["SITE"]["name"] == "basic"
assert builder.jinja_env.globals["debug"] is True
# Tamper settings to change context
settings.SITE_NAME = "Foobar"
settings.DEBUG = False
context = builder.get_globals()
assert context["SITE"]["name"] == "Foobar"
assert context["SITE"]["web_url"] == "http://localhost"
assert context["debug"] is False
assert "OPTIMUS" in context
assert "_SETTINGS" in context
assert context["_SETTINGS"]["LANGUAGE_CODE"] == "en_US"
def test_get_globals_https(minimal_basic_settings, fixtures_settings, caplog):
"""
When setting 'HTTPS_ENABLED' is enabled, 'SITE.web_url' should start with
'https://'.
"""
projectdir = os.path.join(fixtures_settings.fixtures_path, "basic_template")
settings = minimal_basic_settings(projectdir)
# Init builder with default environment
builder = PageBuilder(settings)
# Tamper settings to change context
settings.HTTPS_ENABLED = True
context = builder.get_globals()
assert context["SITE"]["web_url"] == "https://localhost"
| [
"[email protected]"
] | |
49e638f83de804b23bbf4d3eeae59f14e094fe55 | 641f6cc8f956b8c318b9d438e31ada4b6ebc1b5f | /models/qa.py | 2b1848e4b4adc5f78c9c9bdc5bb9bcf4ca74e13c | [
"Apache-2.0"
] | permissive | linkinpark213/quantization-networks-cifar10 | 61754f4beddc1da5c1b407c4e7880d54c172099c | 7214733beed2f1d661633baadabdb300150b15b1 | refs/heads/master | 2022-12-05T19:34:41.656292 | 2020-08-09T06:46:23 | 2020-08-09T06:46:23 | 286,180,844 | 9 | 3 | null | null | null | null | UTF-8 | Python | false | false | 7,469 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# qa.py is used to quantize the activation of model.
from __future__ import print_function, absolute_import
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.autograd import Variable
import numpy as np
from utils.cluster import params_cluster
class SigmoidT(torch.autograd.Function):
""" sigmoid with temperature T for training
we need the gradients for input and bias
for customization of function, refer to https://pytorch.org/docs/stable/notes/extending.html
"""
@staticmethod
def forward(ctx, input, scales, n, b, T):
"""
Sigmoid T forward propagation.
Formula:
\sum_i^N{ \frac{ 1 }{1 + e^{T * {x - b}}} }
Args:
ctx: A SigmoidTBackward context object.
input: The input tensor, which is a parameter in a network.
scales: A list of floating numbers with length = n. The scales of the unit step functions.
n: An integer. The number of possible quantization values - 1.
b: A list of integers with length = n. The biases of the unit step functions.
T: An integer. The temperature.
Returns:
A tensor with same shape as the input.
"""
ctx.save_for_backward(input)
ctx.T = T
ctx.b = b
ctx.scales = scales
ctx.n = n
# \sum_i^n{ sigmoid(T(beta * x_i - b_i)) }
buf = ctx.T * (input - ctx.b[0])
buf = torch.clamp(buf, min=-10.0, max=10.0)
output = ctx.scales[0] / (1.0 + torch.exp(-buf))
for k in range(1, ctx.n):
buf = ctx.T * (input - ctx.b[k])
buf = torch.clamp(buf, min=-10.0, max=10.0)
output += ctx.scales[k] / (1.0 + torch.exp(-buf))
return output
@staticmethod
def backward(ctx, grad_output):
"""
Backward propagation of the activation quantization.
Args:
ctx: A SigmoidTBackward context object.
grad_output: The gradients propagated backwards to this layer.
Returns:
A tuple of 5 elements. Gradients for input, scales, n, b and T.
However, none of scales, n, b and T require gradients so only the first element is not None.
"""
# set T = 1 when train binary model in the backward.
ctx.T = 1
input, = ctx.saved_tensors
b_buf = ctx.T * (input - ctx.b[0])
b_buf = torch.clamp(b_buf, min=-10.0, max=10.0)
b_output = ctx.scales[0] / (1.0 + torch.exp(-b_buf))
temp = b_output * (1 - b_output) * ctx.T
for j in range(1, ctx.n):
b_buf = ctx.T * (input - ctx.b[j])
b_buf = torch.clamp(b_buf, min=-10.0, max=10.0)
b_output = ctx.scales[j] / (1.0 + torch.exp(-b_buf))
temp += b_output * (1 - b_output) * ctx.T
grad_input = Variable(temp) * grad_output
# corresponding to grad_input
return grad_input, None, None, None, None
sigmoidT = SigmoidT.apply
def step(x, b):
"""
The step function for ideal quantization function in test stage.
"""
y = torch.zeros_like(x)
mask = torch.gt(x - b, 0.0)
y[mask] = 1.0
return y
class Quantization(nn.Module):
"""
Quantization Activation. Only used when activations are quantized too.
Args:
quant_values: the target quantized values, like [-4, -2, -1, 0, 1 , 2, 4]
quan_bias and init_beta: the data for initialization of quantization parameters (biases, beta)
- for activations, format as `N x 1` for biases and `1x1` for (beta)
we need to obtain the intialization values for biases and beta offline
Shape:
- Input: :math:`(N, C, H, W)`
- Output: :math:`(N, C, H, W)` (same shape as input)
Usage:
- for activations, just pending this module to the activations when build the graph
"""
def __init__(self, quant_values, outlier_gamma=0.001):
super(Quantization, self).__init__()
self.values = quant_values
self.outlier_gamma = outlier_gamma
# number of sigmoids
self.n = len(self.values) - 1
self.alpha = Parameter(torch.Tensor([1]))
self.beta = Parameter(torch.Tensor([1]))
self.register_buffer('biases', torch.zeros(self.n))
self.register_buffer('scales', torch.zeros(self.n))
# boundary = np.array(quan_bias)
self.init_scale_and_offset()
self.inited = False
# self.init_biases(boundary)
# self.init_alpha_and_beta(init_beta)
def init_scale_and_offset(self):
"""
Initialize the scale and offset of quantization function.
"""
for i in range(self.n):
gap = self.values[i + 1] - self.values[i]
self.scales[i] = gap
def init_biases(self, biases):
"""
Initialize the bias of quantization function.
init_data in numpy format.
"""
# activations initialization (obtained offline)
assert biases.size == self.n
self.biases.copy_(torch.from_numpy(biases))
# print('baises inited!!!')
def init_alpha_and_beta(self, beta):
"""
Initialize the alpha and beta of quantization function.
init_data in numpy format.
"""
# activations initialization (obtained offline)
self.beta.data = torch.Tensor([beta]).cuda()
self.alpha.data = torch.reciprocal(self.beta.data)
def forward(self, input, T=1):
if not self.inited:
print('Initializing activation quantization layer')
params = input.data.detach().cpu().numpy()
biases, (min_value, max_value) = params_cluster(params, self.values, gamma=self.outlier_gamma)
print('biases = {}'.format(biases))
self.init_biases(np.array(biases))
# Method in Quantization Networks
# self.init_alpha_and_beta((self.values[-1] * 5) / (4 * input.data.abs().max()))
# Method in Fully Quantized Networks
self.init_alpha_and_beta(self.values[-1] / max_value)
self.inited = True
return input
input = input.mul(self.beta)
if self.training:
output = sigmoidT(input, self.scales, self.n, self.biases, T)
else:
output = step(input, b=self.biases[0]) * self.scales[0]
for i in range(1, self.n):
output += step(input, b=self.biases[i]) * self.scales[i]
output = output.mul(self.alpha)
return output
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
alpha_key = prefix + 'alpha'
beta_key = prefix + 'beta'
if alpha_key in state_dict and beta_key in state_dict:
super()._load_from_state_dict(state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs)
self.inited = True
else:
error_msgs.append('Activation quantization parameters not found for {} '.format(prefix[:-1]))
def __repr__(self):
return 'Quantization(alpha={}, beta={}, values={}, n={})'.format(self.alpha.data, self.beta.data, self.values,
self.n)
| [
"[email protected]"
] | |
8c33daabcaf0a5c55bd5b54898f7859bf4bdf18e | 898e263e9264804df750fe24cc767e08856c9e09 | /storage/cloud-client/storage_get_metadata.py | e146e9321ad0dcce46c51ef75daccb4cf14ce381 | [
"Apache-2.0"
] | permissive | HoleCat/echarlosperros | 98da28d0fc76c57459ce4c9a53c89e62c350f754 | b67460de0467e05b42a763c4430b26ecfd97c2aa | refs/heads/main | 2023-01-21T15:29:13.091406 | 2020-12-03T01:33:00 | 2020-12-03T01:33:00 | 318,039,531 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,575 | py | #!/usr/bin/env python
# Copyright 2019 Google Inc. 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.
import sys
# [START storage_get_metadata]
from google.cloud import storage
def blob_metadata(bucket_name, blob_name):
"""Prints out a blob's metadata."""
# bucket_name = 'your-bucket-name'
# blob_name = 'your-object-name'
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.get_blob(blob_name)
print("Blob: {}".format(blob.name))
print("Bucket: {}".format(blob.bucket.name))
print("Storage class: {}".format(blob.storage_class))
print("ID: {}".format(blob.id))
print("Size: {} bytes".format(blob.size))
print("Updated: {}".format(blob.updated))
print("Generation: {}".format(blob.generation))
print("Metageneration: {}".format(blob.metageneration))
print("Etag: {}".format(blob.etag))
print("Owner: {}".format(blob.owner))
print("Component count: {}".format(blob.component_count))
print("Crc32c: {}".format(blob.crc32c))
print("md5_hash: {}".format(blob.md5_hash))
print("Cache-control: {}".format(blob.cache_control))
print("Content-type: {}".format(blob.content_type))
print("Content-disposition: {}".format(blob.content_disposition))
print("Content-encoding: {}".format(blob.content_encoding))
print("Content-language: {}".format(blob.content_language))
print("Metadata: {}".format(blob.metadata))
print("Custom Time: {}".format(blob.custom_time))
print("Temporary hold: ", "enabled" if blob.temporary_hold else "disabled")
print(
"Event based hold: ",
"enabled" if blob.event_based_hold else "disabled",
)
if blob.retention_expiration_time:
print(
"retentionExpirationTime: {}".format(
blob.retention_expiration_time
)
)
# [END storage_get_metadata]
if __name__ == "__main__":
blob_metadata(bucket_name=sys.argv[1], blob_name=sys.argv[2])
| [
"[email protected]"
] | |
7b8b55dc7677f2959a75c9ee3e91b6b7e9a29037 | d00e29c27d4d4cccbee8f3923d2d837a2d04eedb | /sush_utils/simpleFlask.py | ec4e06723bfd911d8136e309d7c2e9cc7c4b7c6b | [] | no_license | sush80/switcherPy | 23bfa054f0ed4ab636c5fd69ac70dd28a957747f | 6098431bf526a7ca46d659d73bb859d9fa163f5a | refs/heads/master | 2021-07-25T02:40:11.107318 | 2018-11-17T18:30:33 | 2018-11-17T18:30:33 | 112,855,804 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,566 | py | from flask import Flask
try:
from sush_utils.sush_utils import system_uptime #import if this file is a lib
except:
from sush_utils import system_uptime #import fallback if file runs locally
def start_simple_flask_not_returning():
app = Flask(__name__)
@app.route('/')
def hello_world():
uptime_hours = system_uptime.string_get()
return 'Hello, World! Uptime: ' + uptime_hours
#use_reloader = False is to prevent this file to be started multiple times, resulting in multiple threads
# and duplicated data structurs
app.run(host='0.0.0.0', port=5000, debug=False,use_reloader=False)
if __name__ == "__main__":
import logging
logger = logging.getLogger('simple_flask')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('simple_flask.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh) # FileHandler
logger.addHandler(ch)
logger.info("starting flask now...")
try:
start_simple_flask_not_returning()
except Exception as e:
logger.error("Exception : " + str(e))
logger.info("flask done - exit") | [
"[email protected]"
] | |
aa77403d7717ceaa7e15933bd49d9e1b209ced21 | f9426368ada2672a64a46449bf7c0a9ee23bb49d | /hearthbreaker/cards/spells/hunter.py | 21eb92acf78a28908b87ffe1cbf5cb9ba8bd520b | [
"MIT"
] | permissive | WabiWasabi/hearthbreaker | 301c0cf6ce95c403ecf81c8109d6e51e7f5fb2e4 | 3f7d39b99bb88ffec83d1c038c4ca0b1444882b6 | refs/heads/master | 2021-01-22T17:09:02.885750 | 2014-09-16T19:53:52 | 2014-09-16T19:53:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,076 | py | import copy
from hearthbreaker.effects.minion import Immune
import hearthbreaker.targeting
from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY, MINION_TYPE
from hearthbreaker.game_objects import Card, SecretCard, Minion, MinionCard
class HuntersMark(Card):
def __init__(self):
super().__init__("Hunter's Mark", 0, CHARACTER_CLASS.HUNTER,
CARD_RARITY.COMMON,
hearthbreaker.targeting.find_minion_spell_target)
def use(self, player, game):
super().use(player, game)
self.target.decrease_health(self.target.base_health - 1)
class ArcaneShot(Card):
def __init__(self):
super().__init__("Arcane Shot", 1, CHARACTER_CLASS.HUNTER,
CARD_RARITY.FREE,
hearthbreaker.targeting.find_spell_target)
def use(self, player, game):
super().use(player, game)
self.target.damage(player.effective_spell_damage(2), self)
class BestialWrath(Card):
def __init__(self):
super().__init__("Bestial Wrath", 1, CHARACTER_CLASS.HUNTER,
CARD_RARITY.EPIC,
hearthbreaker.targeting.find_minion_spell_target,
lambda minion: minion.card.minion_type is MINION_TYPE.BEAST and minion.spell_targetable())
def use(self, player, game):
super().use(player, game)
self.target.add_effect(Immune())
self.target.change_temp_attack(2)
class Flare(Card):
def __init__(self):
super().__init__("Flare", 1, CHARACTER_CLASS.HUNTER, CARD_RARITY.RARE)
def use(self, player, game):
super().use(player, game)
for minion in hearthbreaker.targeting.find_minion_spell_target(game, lambda m: m.stealth):
minion.stealth = False
for secret in game.other_player.secrets:
secret.deactivate(game.other_player)
game.other_player.secrets = []
player.draw()
class Tracking(Card):
def __init__(self):
super().__init__("Tracking", 1, CHARACTER_CLASS.HUNTER, CARD_RARITY.FREE)
def use(self, player, game):
super().use(player, game)
cards = []
for card_index in range(0, 3):
if player.can_draw():
cards.append(player.deck.draw(game.random))
if len(cards) > 0:
chosen_card = player.agent.choose_option(*cards)
player.hand.append(chosen_card)
player.trigger("card_drawn", chosen_card)
class ExplosiveTrap(SecretCard):
def __init__(self):
super().__init__("Explosive Trap", 2, CHARACTER_CLASS.HUNTER, CARD_RARITY.COMMON)
def activate(self, player):
player.hero.bind("attacked", self._reveal)
def deactivate(self, player):
player.hero.unbind("attacked", self._reveal)
def _reveal(self, minion):
enemies = copy.copy(minion.game.current_player.minions)
enemies.append(minion.game.current_player.hero)
for enemy in enemies:
enemy.damage(2, None)
minion.game.check_delayed()
super().reveal()
class FreezingTrap(SecretCard):
def __init__(self):
super().__init__("Freezing Trap", 2, CHARACTER_CLASS.HUNTER, CARD_RARITY.COMMON)
def activate(self, player):
player.game.current_player.bind("pre_attack", self._reveal)
def deactivate(self, player):
player.game.current_player.unbind("pre_attack", self._reveal)
def _reveal(self, attacker):
if isinstance(attacker, Minion) and not attacker.removed:
class Filter:
def __init__(self):
self.amount = -2
self.filter = lambda c: c is card
self.min = 0
card = attacker.card
attacker.bounce()
attacker.player.mana_filters.append(Filter())
super().reveal()
class Misdirection(SecretCard):
def __init__(self):
super().__init__("Misdirection", 2, CHARACTER_CLASS.HUNTER, CARD_RARITY.RARE)
def activate(self, player):
player.hero.bind("attacked", self._reveal)
def deactivate(self, player):
player.hero.unbind("attacked", self._reveal)
def _reveal(self, character):
game = character.player.game
if not character.removed:
def choose_random(targets):
possibilities = copy.copy(game.current_player.minions)
possibilities.extend(game.other_player.minions)
possibilities.append(game.current_player.hero)
possibilities.append(game.other_player.hero)
old_target = old_target_func(targets)
possibilities.remove(old_target)
game.current_player.agent.choose_target = old_target_func
return possibilities[game.random(0, len(possibilities) - 1)]
old_target_func = game.current_player.agent.choose_target
game.current_player.agent.choose_target = choose_random
super().reveal()
class Snipe(SecretCard):
def __init__(self):
super().__init__("Snipe", 2, CHARACTER_CLASS.HUNTER, CARD_RARITY.COMMON)
def activate(self, player):
player.game.current_player.bind("minion_played", self._reveal)
def deactivate(self, player):
player.game.current_player.unbind("minion_played", self._reveal)
def _reveal(self, minion):
minion.damage(4, None)
super().reveal()
class DeadlyShot(Card):
def __init__(self):
super().__init__("Deadly Shot", 3, CHARACTER_CLASS.HUNTER, CARD_RARITY.COMMON)
def use(self, player, game):
super().use(player, game)
targets = hearthbreaker.targeting.find_enemy_minion_battlecry_target(player.game, lambda x: True)
target = targets[player.game.random(0, len(targets) - 1)]
target.die(None)
game.check_delayed()
def can_use(self, player, game):
return super().can_use(player, game) and len(game.other_player.minions) >= 1
class MultiShot(Card):
def __init__(self):
super().__init__("Multi-Shot", 4, CHARACTER_CLASS.HUNTER, CARD_RARITY.FREE)
def use(self, player, game):
super().use(player, game)
targets = copy.copy(game.other_player.minions)
for i in range(0, 2):
target = targets.pop(game.random(0, len(targets) - 1))
target.damage(player.effective_spell_damage(3), self)
def can_use(self, player, game):
return super().can_use(player, game) and len(game.other_player.minions) >= 2
class ExplosiveShot(Card):
def __init__(self):
super().__init__("Explosive Shot", 5, CHARACTER_CLASS.HUNTER, CARD_RARITY.RARE,
hearthbreaker.targeting.find_minion_spell_target)
def use(self, player, game):
super().use(player, game)
index = self.target.index
if self.target.index < len(self.target.player.minions) - 1:
minion = self.target.player.minions[index + 1]
minion.damage(player.effective_spell_damage(2), self)
self.target.damage(player.effective_spell_damage(5), self)
if self.target.index > 0:
minion = self.target.player.minions[index - 1]
minion.damage(player.effective_spell_damage(2), self)
class KillCommand(Card):
def __init__(self):
super().__init__("Kill Command", 3, CHARACTER_CLASS.HUNTER, CARD_RARITY.COMMON,
hearthbreaker.targeting.find_spell_target)
def use(self, player, game):
super().use(player, game)
beasts = hearthbreaker.targeting.find_friendly_minion_battlecry_target(
player.game, lambda x: x.card.minion_type is MINION_TYPE.BEAST)
if beasts is None:
self.target.damage(player.effective_spell_damage(3), self)
else:
self.target.damage(player.effective_spell_damage(5), self)
class UnleashTheHounds(Card):
def __init__(self):
super().__init__("Unleash the Hounds", 3, CHARACTER_CLASS.HUNTER, CARD_RARITY.COMMON)
def use(self, player, game):
super().use(player, game)
class Hound(MinionCard):
def __init__(self):
super().__init__("Hound", 1, CHARACTER_CLASS.HUNTER, CARD_RARITY.SPECIAL)
def create_minion(self, player):
minion = Minion(1, 1, MINION_TYPE.BEAST)
minion.charge = True
return minion
for target in hearthbreaker.targeting.find_enemy_minion_spell_target(player.game, lambda x: True):
hound = Hound()
hound.summon(player, game, len(player.minions))
class AnimalCompanion(Card):
def __init__(self):
super().__init__("Animal Companion", 3, CHARACTER_CLASS.HUNTER, CARD_RARITY.COMMON)
def use(self, player, game):
super().use(player, game)
class Huffer(MinionCard):
def __init__(self):
super().__init__("Huffer", 3, CHARACTER_CLASS.HUNTER, CARD_RARITY.SPECIAL)
def create_minion(self, player):
minion = Minion(4, 2, MINION_TYPE.BEAST)
minion.charge = True
return minion
class Misha(MinionCard):
def __init__(self):
super().__init__("Misha", 3, CHARACTER_CLASS.HUNTER, CARD_RARITY.SPECIAL)
def create_minion(self, player):
minion = Minion(4, 4, MINION_TYPE.BEAST)
minion.taunt = True
return minion
class Leokk(MinionCard):
def __init__(self):
super().__init__("Leokk", 3, CHARACTER_CLASS.HUNTER, CARD_RARITY.SPECIAL)
def create_minion(self, player):
def add_effect(m, index):
m.add_aura(1, 0, [player], lambda mini: mini is not minion)
minion = Minion(2, 4, MINION_TYPE.BEAST)
minion.bind("added_to_board", add_effect)
return minion
beast_list = [Huffer(), Misha(), Leokk()]
card = beast_list[player.game.random(0, 2)]
card.summon(player, player.game, len(player.minions))
class SnakeTrap(SecretCard):
def __init__(self):
super().__init__("Snake Trap", 2, CHARACTER_CLASS.HUNTER, CARD_RARITY.EPIC)
def activate(self, player):
player.game.current_player.bind("attack", self._reveal)
def deactivate(self, player):
player.game.current_player.unbind("attack", self._reveal)
def _reveal(self, attacker, target):
if isinstance(target, Minion):
class Snake(MinionCard):
def __init__(self):
super().__init__("Snake", 1, CHARACTER_CLASS.HUNTER, CARD_RARITY.SPECIAL, MINION_TYPE.BEAST)
def create_minion(self, player):
return Minion(1, 1)
snake = Snake()
player = target.player.game.other_player
for i in range(0, 3):
snake.summon(player, player.game, len(player.minions))
super().reveal()
| [
"[email protected]"
] | |
a42bb018ff03bfd9a53342898564db3d33b7a2af | 9f2450da1c4fd7844e0e162a94c7edb53c27fe72 | /wm_compositional/assembly.py | 5cbdd69811fa36d2496a095452a9adb6fafe4cc5 | [] | no_license | sorgerlab/indra_apps | 6626a06dad9e7f820c71d7e03bdf42a6308746cc | 3f20ca3f7b3855636607c63b1956c404bfe1b16e | refs/heads/master | 2021-06-11T02:00:28.866305 | 2021-04-26T01:33:41 | 2021-04-26T01:33:41 | 128,094,623 | 1 | 8 | null | 2021-04-26T01:29:05 | 2018-04-04T17:10:11 | Jupyter Notebook | UTF-8 | Python | false | false | 5,614 | py | import os
import glob
import tqdm
import logging
from indra.sources import eidos, hume, cwms, sofia
from indra.statements import Influence, Event
from indra.tools import assemble_corpus as ac
from indra.ontology.world.ontology import WorldOntology
from indra.pipeline import register_pipeline, AssemblyPipeline
from indra_world.assembly.operations import *
from indra_world.sources.dart import process_reader_outputs
from indra_world.corpus import Corpus
from indra.statements import stmts_to_json_file
reader_versions = {'flat':
{'cwms': '2020.08.28',
'hume': 'r2020_08_19_4',
'sofia': '1.1',
'eidos': '1.0.3'},
'compositional':
{'cwms': '2020.09.03',
'hume': 'r2020_09_28_4',
'sofia': '1.1',
'eidos': '1.0.4'}}
ont_url = 'https://github.com/WorldModelers/Ontologies/blob/'\
'25690a258d02fdf1f35ce9140f7cd54145e2b30c/'\
'CompositionalOntology_v2.1_metadata.yml'
logger = logging.getLogger('wm_compositional.assembly')
def concept_matches_compositional(concept):
wm = concept.db_refs.get('WM')
if not wm:
return concept.name
wm_top = tuple(entry[0] if entry else None for entry in wm[0])
return wm_top
def matches_compositional(stmt):
if isinstance(stmt, Influence):
key = (stmt.__class__.__name__,
concept_matches_compositional(stmt.subj.concept),
concept_matches_compositional(stmt.obj.concept),
stmt.polarity_count(),
stmt.overall_polarity()
)
elif isinstance(stmt, Event):
key = (stmt.__class__.__name__,
concept_matches_compositional(stmt.concept),
stmt.delta.polarity)
return str(key)
@register_pipeline
def print_grounding_stats(statements):
logger.info('-----------------------------------------')
logger.info('Number of Influences: %s' % len([s for s in statements if
isinstance(s, Influence)]))
grs = []
gr_combos = []
evidences = 0
evidence_by_reader = defaultdict(int)
for stmt in statements:
if isinstance(stmt, Influence):
for concept in [stmt.subj.concept, stmt.obj.concept]:
grs.append(concept.get_grounding())
gr_combos.append((stmt.subj.concept.get_grounding(),
stmt.obj.concept.get_grounding()))
evidences += len(stmt.evidence)
for ev in stmt.evidence:
evidence_by_reader[ev.source_api] += 1
logger.info('Unique groundings: %d' % len(set(grs)))
logger.info('Unique combinations: %d' % len(set(gr_combos)))
logger.info('Number of evidences: %d' % evidences)
logger.info('Number of evidences by reader: %s' %
str(dict(evidence_by_reader)))
logger.info('-----------------------------------------')
return statements
if __name__ == '__main__':
readers = ['sofia', 'eidos', 'hume', 'cwms']
grounding = 'compositional'
do_upload = False
stmts = []
for reader in readers:
version = reader_versions[grounding][reader]
pattern = '*' if reader != 'sofia' \
else ('*_new' if grounding == 'compositional' else '*_old')
fnames = glob.glob('/Users/ben/data/dart/%s/%s/%s' % (reader, version,
pattern))
print('Found %d files for %s' % (len(fnames), reader))
for fname in tqdm.tqdm(fnames):
if reader == 'eidos':
pp = eidos.process_json_file(fname, grounding_mode=grounding)
elif reader == 'hume':
pp = hume.process_jsonld_file(fname, grounding_mode=grounding)
elif reader == 'cwms':
pp = cwms.process_ekb_file(fname, grounding_mode=grounding)
elif reader == 'sofia':
pp = sofia.process_json_file(fname, grounding_mode=grounding)
doc_id = os.path.basename(fname)[:32]
for stmt in pp.statements:
for ev in stmt.evidence:
if 'provenance' not in ev.annotations:
ev.annotations['provenance'] = [
{'document': {'@id': doc_id}}]
else:
prov = ev.annotations['provenance'][0]['document']
prov['@id'] = doc_id
stmts += pp.statements
if grounding == 'compositional':
validate_grounding_format(stmts)
ap = AssemblyPipeline.from_json_file('assembly_%s.json' % grounding)
assembled_stmts = ap.run(stmts)
if do_upload:
corpus_id = 'compositional_v4'
stmts_to_json_file(assembled_stmts, '%s.json' % corpus_id)
meta_data = {
'corpus_id': corpus_id,
'description': ('Assembly of 4 reader outputs with the '
'compositional ontology (%s).' % ont_url),
'display_name': 'Compositional ontology assembly v3',
'readers': readers,
'assembly': {
'level': 'grounding',
'grounding_threshold': 0.6,
},
'num_statements': len(assembled_stmts),
'num_documents': 382
}
corpus = Corpus(corpus_id, statements=assembled_stmts,
raw_statements=stmts,
meta_data=meta_data)
corpus.s3_put()
| [
"[email protected]"
] | |
b49b0aa10664dfb2a463c9db9a3ee3391a1bb550 | edd72c118fdca69cc58b6a85ac1b0f153f44d2f8 | /ruts/datasets/dataset.py | 3c7cf834387bd5281f7957adabb42f192ff10053 | [
"MIT"
] | permissive | webprogrammer77/ruTS | 7e459561aefd31ab1c0cfdc6503c9e90ea3392c7 | c3c95f99162115ea2c522ee7b90cfc1ee7de91e5 | refs/heads/master | 2022-12-12T11:12:01.423729 | 2020-09-04T14:08:21 | 2020-09-04T14:08:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,774 | py | from abc import ABCMeta, abstractmethod
from typing import Any, Dict, Generator
class Dataset(object, metaclass=ABCMeta):
"""
Абстрактный класс для работы с набором данных
Аргументы:
name (str): Наименование набора данных
meta (dict): Справочная информация о наборе данных
Методы:
check_data: Проверка наличия всех необходимых директорий и файлов в наборе данных
get_texts: Получение текстов (без заголовков) из набора данных
get_records: Получение записей (с заголовками) из набора данных
download: Загрузка набора данных из сети
"""
__test__ = False
@abstractmethod
def __init__(self, name, meta=None):
self.name = name
self.meta = meta or {}
def __repr__(self):
return f"Набор данных('{self.name}')"
@property
def info(self):
info = {'Наименование': self.name}
info.update(self.meta)
return info
@abstractmethod
def __iter__(self):
raise NotImplementedError
@abstractmethod
def check_data(self) -> bool:
raise NotImplementedError
@abstractmethod
def get_texts(self, *args: Any) -> Generator[str, None, None]:
raise NotImplementedError
@abstractmethod
def get_records(self, *args: Any) -> Generator[Dict[str, Any], None, None]:
raise NotImplementedError
@abstractmethod
def download(self, force: bool = False):
raise NotImplementedError | [
"[email protected]"
] | |
dbb50044dbe2f11200f23c22e4710f8b05fe4a41 | 97676f59bdd398f00bc0939c40a30c1f07e523c6 | /course-files/lectures/lecture11/answers/03_give_grade.py | a105e0a34f90cb9671110df7c99d3182aa0e2b81 | [] | no_license | eecs110/fall2020 | db1b0f9036f9a0036ff5cc6ba5c30ba6fa5cffed | 81363c4f1c192f8366456a44df8988298809146b | refs/heads/master | 2023-01-29T05:49:36.452055 | 2020-12-02T20:58:43 | 2020-12-02T20:58:43 | 289,575,477 | 1 | 3 | null | null | null | null | UTF-8 | Python | false | false | 436 | py | def give_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
print('65:', give_grade(65))
print('99:', give_grade(99))
print('84:', give_grade(84))
print('76:', give_grade(76))
print('20:', give_grade(20))
## Visualize this execution (a visual representation): https://goo.gl/RPqCLc
| [
"[email protected]"
] | |
7a1548852e88b61dbb309d1364c4a34dac13a657 | 105212e4d2d2175d5105e05552e29b300375e039 | /TensorFlow_tutorials/tf-example-api-master/stylenet-master/stylenet_patch.py | ec19c5a837402de8c6543f0803cac6e6b4e2c767 | [] | no_license | Asher-1/AI | 84f0c42651c0b07e6b7e41ebb354258db64dd0d1 | a70f63ebab3163f299f7f9d860a98695c0a3f7d5 | refs/heads/master | 2022-11-26T07:24:37.910301 | 2019-05-30T13:04:31 | 2019-05-30T13:04:31 | 160,031,310 | 7 | 1 | null | 2022-11-21T22:02:53 | 2018-12-02T09:19:03 | Jupyter Notebook | UTF-8 | Python | false | false | 17,492 | py | from __future__ import print_function
import time
import inspect
import os
import numpy as np
import skimage
import skimage.io
import skimage.transform
import tensorflow as tf
import custom_vgg19
import stylenet_core
output_path = 'G:/develop/PycharmProjects/datasets/result_outputs/stylenet_master_output/'
def get_filename(file):
return os.path.splitext(os.path.basename(file))[0]
def render(content_file, style_file,
content_region_file=None, style_region_file=None,
random_init=False, load_saved_mapping=True, load_trained_image=False, blur_mapping=True,
height=None, width=None,
content_ratio=0., style3_ratio=3., style4_ratio=1., gram_ratio=0.001, diff_ratio=0.,
epochs=300, output_file=output_path + "train/output%d.jpg"):
"""
Render the synthesis with single generation.
- Best used if style has high similarity with the content
- If any ratio is set to 0, the corresponding Tensor will not be generated
- Pure Gram Matrix synthesis is best for painting abstract style. (gram_ratio = 1 and all others 0)
:param content_file: String file path of content image
:param style_file: String file path of style image
:param content_region_file: String file path of region mapping of content
:param style_region_file: String file path of region mapping of image
:param random_init: True to init the image with random
:param load_saved_mapping: True to use saved mapping file
:param load_trained_image: True to use saved training
:param blur_mapping: True to blur the mapping before calculate the max argument
:param height: int of height of result image
:param width: int of width of result image. Leaving None with height will scaled
according aspect ratio
:param content_ratio: float32 of weight of content cost
:param style3_ratio: float32 of weight of patch cost of conv3 layer
:param style4_ratio: float32 of weight of patch cost of conv4 layer
:param gram_ratio: float32 of weight of gram matrix cost
:param diff_ratio: float32 of weight of local different cost
:param epochs: int of number of epochs to train
:param output_file: String file name of output file. %d will be replaced running number
"""
print("render started:")
# print info:
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
for i in args:
print(" %s = %s" % (i, values[i]))
content_np = stylenet_core.load_image(content_file, height, width)
style_np = stylenet_core.load_image(style_file, content_np.shape[0], content_np.shape[1])
content_batch = np.expand_dims(content_np, 0)
style_batch = np.expand_dims(style_np, 0)
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.6)
with tf.Session(config=tf.ConfigProto(gpu_options=(gpu_options), log_device_placement=False)) as sess:
start_time = time.time()
contents = tf.constant(content_batch, dtype=tf.float32, shape=content_batch.shape)
styles = tf.constant(style_batch, dtype=tf.float32, shape=style_batch.shape)
if random_init:
var_image = tf.Variable(tf.truncated_normal(content_batch.shape, 0.5, 0.1))
else:
var_image = tf.Variable(contents)
vgg_content = custom_vgg19.Vgg19()
with tf.name_scope("content_vgg"):
vgg_content.build(contents)
vgg_style = custom_vgg19.Vgg19()
with tf.name_scope("style_vgg"):
vgg_style.build(styles)
vgg_var = custom_vgg19.Vgg19()
with tf.name_scope("variable_vgg"):
vgg_var.build(var_image)
with tf.name_scope("cost"):
# style:
# TODO change file name based on out file name
style3file =output_path + "train/%s-style_map_3" % (
get_filename(content_file) + "-" + get_filename(style_file))
style4file =output_path + "train/%s-style_map_4" % (
get_filename(content_file) + "-" + get_filename(style_file))
if content_region_file is None or style_region_file is None:
if style3_ratio is 0:
style_cost_3 = tf.constant(0.0)
else:
style_cost_3 = stylenet_core.get_style_cost_patch2(sess, vgg_var.conv3_1,
vgg_content.conv3_1,
vgg_style.conv3_1,
style3file,
load_saved_mapping=load_saved_mapping)
if style4_ratio is 0:
style_cost_4 = tf.constant(0.0)
else:
style_cost_4 = stylenet_core.get_style_cost_patch2(sess, vgg_var.conv4_1,
vgg_content.conv4_1,
vgg_style.conv4_1,
style4file,
load_saved_mapping=load_saved_mapping)
else:
content_regions_np = stylenet_core.load_image(content_region_file, content_np.shape[0],
content_np.shape[1])
style_regions_np = stylenet_core.load_image(style_region_file, content_np.shape[0],
content_np.shape[1])
content_regions_batch = np.expand_dims(content_regions_np, 0)
style_regions_batch = np.expand_dims(style_regions_np, 0)
content_regions = tf.constant(content_regions_batch, dtype=tf.float32,
shape=content_regions_batch.shape)
style_regions = tf.constant(style_regions_batch, dtype=tf.float32,
shape=style_regions_batch.shape)
content_regions = vgg_var.avg_pool(content_regions, None)
content_regions = vgg_var.avg_pool(content_regions, None)
style_regions = vgg_var.avg_pool(style_regions, None)
style_regions = vgg_var.avg_pool(style_regions, None)
if style3_ratio is 0:
style_cost_3 = tf.constant(0.0)
else:
style_cost_3 = stylenet_core.get_style_cost_patch2(sess,
vgg_var.conv3_1,
vgg_content.conv3_1,
vgg_style.conv3_1,
style3file,
content_regions,
style_regions,
load_saved_mapping,
blur_mapping=blur_mapping)
content_regions = vgg_var.avg_pool(content_regions, None)
style_regions = vgg_var.avg_pool(style_regions, None)
if style4_ratio is 0:
style_cost_4 = tf.constant(0.0)
else:
style_cost_4 = stylenet_core.get_style_cost_patch2(sess,
vgg_var.conv4_1,
vgg_content.conv4_1,
vgg_style.conv4_1,
style4file,
content_regions,
style_regions,
load_saved_mapping,
blur_mapping=blur_mapping)
if gram_ratio is 0:
style_cost_gram = tf.constant(0.0)
else:
style_cost_gram = stylenet_core.get_style_cost_gram(sess, vgg_style, vgg_var)
# content:
if content_ratio is 0:
content_cost = tf.constant(.0)
else:
fixed_content = stylenet_core.get_constant(sess, vgg_content.conv4_2)
content_cost = stylenet_core.l2_norm_cost(vgg_var.conv4_2 - fixed_content)
# # smoothness:
if diff_ratio is 0:
diff_cost = tf.constant(.0)
else:
diff_filter_h = tf.constant([0, 0, 0, 0, -1, 1, 0, 0, 0], tf.float32, [3, 3, 1, 1])
diff_filter_h = tf.concat([diff_filter_h, diff_filter_h, diff_filter_h], 2)
diff_filter_v = tf.constant([0, 0, 0, 0, -1, 0, 0, 1, 0], tf.float32, [3, 3, 1, 1])
diff_filter_v = tf.concat([diff_filter_v, diff_filter_v, diff_filter_v], 2)
diff_filter = tf.concat([diff_filter_h, diff_filter_v], 3)
filtered_input = tf.nn.conv2d(var_image, diff_filter, [1, 1, 1, 1], "VALID")
diff_cost = stylenet_core.l2_norm_cost(filtered_input) * 1e7
content_cost = content_cost * content_ratio
style_cost_3 = style_cost_3 * style3_ratio
style_cost_4 = style_cost_4 * style4_ratio
style_cost_gram = style_cost_gram * gram_ratio
diff_cost = diff_cost * diff_ratio
cost = content_cost + style_cost_3 + style_cost_4 + style_cost_gram + diff_cost
with tf.name_scope("train"):
global_step = tf.Variable(0, name='global_step', trainable=False)
optimizer = tf.train.AdamOptimizer(learning_rate=0.02)
gvs = optimizer.compute_gradients(cost)
training = optimizer.apply_gradients(gvs, global_step=global_step)
print("Net generated:", (time.time() - start_time))
start_time = time.time()
with tf.name_scope("image_out"):
image_out = tf.clip_by_value(tf.squeeze(var_image, [0]), 0, 1)
saver = tf.train.Saver()
checkpoint = tf.train.get_checkpoint_state(output_path + "train")
if checkpoint and checkpoint.model_checkpoint_path and load_trained_image:
saver.restore(sess, checkpoint.model_checkpoint_path)
print("save restored:", checkpoint.model_checkpoint_path)
else:
tf.initialize_all_variables().run()
print("all variables init")
print("Var init: %d" % (time.time() - start_time))
step_out = 0
start_time = time.time()
for i in range(epochs):
if i % 5 == 0:
img = sess.run(image_out)
img_out_path = output_file % step_out
skimage.io.imsave(img_out_path, img)
print("img saved: ", img_out_path)
step_out, content_out, style_patch3_out, style_patch4_out, style_gram_out, diff_cost_out, cost_out \
, _ = sess.run(
[global_step, content_cost, style_cost_3, style_cost_4, style_cost_gram, diff_cost, cost,
training])
duration = time.time() - start_time
print("Step %d: cost:%.10f\t(%.1f sec)" % (step_out, cost_out, duration), \
"\t content:%.5f, style_3:%.5f, style_4:%.5f, gram:%.5f, diff_cost_out:%.5f" \
% (content_out, style_patch3_out, style_patch4_out, style_gram_out, diff_cost_out))
if (i + 1) % 10 == 0:
saved_path = saver.save(sess, output_path + "train/saves-" + get_filename(content_file),
global_step=global_step)
print("net saved: ", saved_path)
img = sess.run(image_out)
img_out_path = output_file % step_out
skimage.io.imsave(img_out_path, img)
print("img saved: ", img_out_path)
def render_gen(content_file, style_file,
content_region_file=None, style_region_file=None,
random_init=False, load_saved_mapping=True, load_trained_image=False, blur_mapping=True,
height=None, width=None,
content_ratio=0, style3_ratio=3., style4_ratio=1., gram_ratio=0.001, diff_ratio=0.,
gen_epochs=80, max_gen=3, pyramid=True, max_reduction_ratio=.8, final_epochs=200):
"""
Render the image by generation method.
- Best used if the style has low similarity with the content.
- max_reduction_ratio can be set to lower, e.g. 0.4, to improve synthesis effect, but less content will be
preserved
- content_ratio, gram_ratio will be set to 0 in final generation becuase of low effectiveness
- blur_mapping will be switched off except the last generation to prevent severe content destruction
:param content_file: String file path of content image
:param style_file: String file path of style image
:param content_region_file: String file path of region mapping of content
:param style_region_file: String file path of region mapping of image
:param random_init: True to init the image with random
:param load_saved_mapping: True to use saved mapping file
:param load_trained_image: True to use saved training
:param blur_mapping: True to blur the mapping before calculate the max argument. Only applied
to last generation
:param height: int of height of result image
:param width: int of width of result image. Leaving None with height will scaled
according aspect ratio
:param content_ratio: float32 of weight of content cost, will be 0 for last generation
:param style3_ratio: float32 of weight of patch cost of conv3 layer
:param style4_ratio: float32 of weight of patch cost of conv4 layer
:param gram_ratio: float32 of weight of gram matrix cost, will be 0 for last generation
:param diff_ratio: float32 of weight of local different cost
:param gen_epochs: int of epochs of each generations, except the last generation
:param max_gen: int of number of generations
:param pyramid: True to pre-scale the image based on reduction ration
:param max_reduction_ratio: float32 of 0.0 to 1.0 of percentage of first reduction ratio in pyramid
:param final_epochs: int of epoch of training last generation
"""
for gen in range(max_gen):
if gen is 0:
gen_content_file = content_file
height = stylenet_core.load_image(content_file, height, width).shape[0]
else:
gen_content_file = (output_path + "train/output-g" + str(gen - 1) + "-%d.jpg") % gen_epochs
output_file = output_path + "train/output-g" + str(gen) + "-%d.jpg"
output_file_final = output_file % gen_epochs
if os.path.isfile(output_file_final):
print(output_file_final, "exist. move to next generation")
continue
tf.reset_default_graph()
ot = time.time()
print("----------- %d generation started -----------" % gen)
if pyramid and gen == max_gen - 1:
h = height
epochs = final_epochs
cr = 0
gr = 0
bm = blur_mapping
else:
h = int(height * (gen * (1.0 - max_reduction_ratio) / max_gen + max_reduction_ratio))
epochs = gen_epochs
cr = content_ratio
gr = gram_ratio
bm = False
render(
content_file=gen_content_file,
style_file=style_file,
content_region_file=content_region_file,
style_region_file=style_region_file,
random_init=random_init,
load_saved_mapping=load_saved_mapping,
load_trained_image=load_trained_image,
blur_mapping=bm,
height=h,
width=width,
content_ratio=cr,
style3_ratio=style3_ratio,
style4_ratio=style4_ratio,
gram_ratio=gr,
diff_ratio=diff_ratio,
epochs=epochs,
output_file=output_file)
print("----------- %d generation finished in %d sec -----------\n" % (gen, time.time() - ot))
if __name__ == "__main__":
# for testing:
# no generation
# render("./test_data/cat_h.jpg", "./test_data/cat-water-colour.jpg", height=500)
# with generation
render_gen("./images/husky_paint.jpg", "test_data/husky_real.jpg",
"./images/husky_paint_region.jpg", "test_data/husky_real_region.jpg", height=500)
| [
"[email protected]"
] | |
4f82a4e97672d4f0c016b0d1b25590076f38187a | 847177b00a6d28a075b57f29ae37a3da7d9ce823 | /setup.py | d28ffb184f2b7fe85e528e37e1565693800c8b3b | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | pcdshub/recordits | 3faccfb76b3fdcabd575e21da3d6c81079b2daf0 | c89f6b59accd430f26ea38b1660f74350be8aa37 | refs/heads/master | 2021-11-12T10:33:25.038276 | 2021-10-29T16:56:22 | 2021-10-29T16:56:22 | 235,641,592 | 0 | 2 | NOASSERTION | 2021-04-15T18:27:18 | 2020-01-22T18:48:04 | Python | UTF-8 | Python | false | false | 2,101 | py | import sys
from os import path
from setuptools import find_packages, setup
import versioneer
min_version = (3, 6)
if sys.version_info < min_version:
error = """
recordits does not support Python {0}.{1}.
Python {2}.{3} and above is required. Check your Python version like so:
python3 --version
This may be due to an out-of-date pip. Make sure you have pip >= 9.0.1.
Upgrade pip like so:
pip install --upgrade pip
""".format(*sys.version_info[:2], *min_version)
sys.exit(error)
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as readme_file:
readme = readme_file.read()
with open(path.join(here, 'requirements.txt')) as requirements_file:
# Parse requirements.txt, ignoring any commented-out lines.
requirements = [line for line in requirements_file.read().splitlines()
if not line.startswith('#')]
git_requirements = [r for r in requirements if r.startswith('git+')]
if git_requirements:
print('User must install the following packages manually:')
print()
print("\n".join(f'* {r}' for r in git_requirements))
print()
setup(
name='recordits',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
license='BSD',
author='SLAC National Accelerator Laboratory',
packages=find_packages(exclude=['docs', 'tests']),
description='Recording points for LCLS-II',
long_description=readme,
url='https://github.com/pcdshub/recordits',
entry_points={
'console_scripts': [
# 'some.module:some_function',
],
},
include_package_data=True,
package_data={
'recordits': [
# When adding files here, remember to update MANIFEST.in as well,
# or else they will not be included in the distribution on PyPI!
# 'path/to/data_file',
]
},
install_requires=requirements,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Natural Language :: English',
'Programming Language :: Python :: 3',
],
)
| [
"[email protected]"
] | |
96f253385c98c35544ec68f6785f80678b6acdea | 4bd5e9b67d98bfcc9611bd8b774c9ab9f4f4d446 | /Python基础笔记/3/作业3/1.py | d2a733ff528865f5b1eea2cad44364b041c4a977 | [] | no_license | zhenguo96/test1 | fe21510aea7feb674e52fd7a86d4177666f841c5 | 0d8de7e73e7e635d26462a0bc53c773d999498be | refs/heads/master | 2020-05-03T13:09:53.592103 | 2019-04-06T07:08:47 | 2019-04-06T07:08:47 | 178,646,627 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 462 | py | # 1.根据(1-7)的数值不同。打印对应的星期英文
day = float(input("请输入1-7中的一个数:"))
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
elif day == 7:
print("Sunday")
else:
print("输入格式错误!")
| [
"[email protected]"
] | |
204e935385d1c4510ae07351fb087e2c6b689276 | 6e25c7af9e1b9e5905ae9e839ff6f3f8fd4ed221 | /video_auto/二次剪辑/util/img_utils.py | bfebc3947b9e25a1f0635e409084a269d56eb759 | [
"Apache-2.0"
] | permissive | roceys/tools_python | 8dc6f2d21b68f682eec412beb56524e7d72d194c | 9c8d5c1c7c1ae4a4c857a65f5b5f14da1c90e425 | refs/heads/master | 2023-01-05T06:18:50.411999 | 2020-11-01T18:02:37 | 2020-11-01T18:02:37 | 271,776,767 | 0 | 0 | Apache-2.0 | 2020-11-01T18:02:38 | 2020-06-12T10:58:36 | null | UTF-8 | Python | false | false | 1,431 | py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: xag
@license: Apache Licence
@contact: [email protected]
@site: http://www.xingag.top
@software: PyCharm
@file: img_utils.py
@time: 2019-12-25 14:23
@description:图片工具类
"""
import cv2
from moviepy.video.VideoClip import ImageClip
from moviepy.editor import VideoFileClip
def one_pic_to_video(image_path, output_video_path, fps, time):
"""
一张图片合成视频
one_pic_to_video('./../source/1.jpeg', './../source/output.mp4', 25, 10)
:param path: 图片文件路径
:param output_video_path:合成视频的路径
:param fps:帧率
:param time:时长
:return:
"""
image_clip = ImageClip(image_path)
img_width, img_height = image_clip.w, image_clip.h
# 总共的帧数
frame_num = (int)(fps * time)
img_size = (int(img_width), int(img_height))
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
video = cv2.VideoWriter(output_video_path, fourcc, fps, img_size)
for index in range(frame_num):
frame = cv2.imread(image_path)
# 直接缩放到指定大小
frame_suitable = cv2.resize(frame, (img_size[0], img_size[1]), interpolation=cv2.INTER_CUBIC)
# 把图片写进视频
# 重复写入多少次
video.write(frame_suitable)
# 释放资源
video.release()
return VideoFileClip(output_video_path)
| [
"[email protected]"
] | |
3ec953a961a2bc4424f63679e9c480798492f6a2 | 72d010d00355fc977a291c29eb18aeb385b8a9b0 | /LiveControl_2/os.py | 553680cbebdb60aea6426b50f01be8384942f877 | [] | no_license | maratbakirov/AbletonLive10_MIDIRemoteScripts | bf0749c5c4cce8e83b23f14f671e52752702539d | ed1174d9959b20ed05fb099f0461bbc006bfbb79 | refs/heads/master | 2021-06-16T19:58:34.038163 | 2021-05-09T11:46:46 | 2021-05-09T11:46:46 | 203,174,328 | 0 | 0 | null | 2019-08-19T13:04:23 | 2019-08-19T13:04:22 | null | UTF-8 | Python | false | false | 25,644 | py | r"""OS routines for Mac, NT, or Posix depending on what system we're on.
This exports:
- all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
- os.path is one of the modules posixpath, ntpath, or macpath
- os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
- os.curdir is a string representing the current directory ('.' or ':')
- os.pardir is a string representing the parent directory ('..' or '::')
- os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
- os.extsep is the extension separator ('.' or '/')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)
Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""
#'
import sys
_names = sys.builtin_module_names
# Note: more names are added to __all__ later.
__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
"defpath", "name", "path", "devnull",
"SEEK_SET", "SEEK_CUR", "SEEK_END"]
def _get_exports_list(module):
try:
return list(module.__all__)
except AttributeError:
return [n for n in dir(module) if n[0] != '_']
if 'posix' in _names:
name = 'posix'
linesep = '\n'
from posix import *
try:
from posix import _exit
except ImportError:
pass
import posixpath as path
import posix
__all__.extend(_get_exports_list(posix))
del posix
elif 'nt' in _names:
name = 'nt'
linesep = '\r\n'
from nt import *
try:
from nt import _exit
except ImportError:
pass
import ntpath as path
import nt
__all__.extend(_get_exports_list(nt))
del nt
elif 'os2' in _names:
name = 'os2'
linesep = '\r\n'
from os2 import *
try:
from os2 import _exit
except ImportError:
pass
if sys.version.find('EMX GCC') == -1:
import ntpath as path
else:
import os2emxpath as path
from _emx_link import link
import os2
__all__.extend(_get_exports_list(os2))
del os2
elif 'mac' in _names:
name = 'mac'
linesep = '\r'
from mac import *
try:
from mac import _exit
except ImportError:
pass
import macpath as path
import mac
__all__.extend(_get_exports_list(mac))
del mac
elif 'ce' in _names:
name = 'ce'
linesep = '\r\n'
from ce import *
try:
from ce import _exit
except ImportError:
pass
# We can use the standard Windows path.
import ntpath as path
import ce
__all__.extend(_get_exports_list(ce))
del ce
elif 'riscos' in _names:
name = 'riscos'
linesep = '\n'
from riscos import *
try:
from riscos import _exit
except ImportError:
pass
import riscospath as path
import riscos
__all__.extend(_get_exports_list(riscos))
del riscos
else:
raise ImportError, 'no os specific module found'
if sys.platform == "win32":
import ntpath
sys.modules['os.path'] = ntpath
from ntpath import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
devnull)
else:
import posixpath
sys.modules['os.path'] = posixpath
from posixpath import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
devnull)
del _names
# Python uses fixed values for the SEEK_ constants; they are mapped
# to native constants if necessary in posixmodule.c
SEEK_SET = 0
SEEK_CUR = 1
SEEK_END = 2
#'
# Super directory utilities.
# (Inspired by Eric Raymond; the doc strings are mostly his)
def makedirs(name, mode=0777):
"""makedirs(path [, mode=0777])
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist. This is
recursive.
"""
from errno import EEXIST
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
if head and tail and not path.exists(head):
try:
makedirs(head, mode)
except OSError, e:
# be happy if someone already created the path
if e.errno != EEXIST:
raise
if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists
return
mkdir(name, mode)
def removedirs(name):
"""removedirs(path)
Super-rmdir; remove a leaf directory and all empty intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs. Errors during this latter phase are
ignored -- they generally mean that a directory was not empty.
"""
rmdir(name)
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
while head and tail:
try:
rmdir(head)
except error:
break
head, tail = path.split(head)
def renames(old, new):
"""renames(old, new)
Super-rename; create directories as necessary and delete any left
empty. Works like rename, except creation of any intermediate
directories needed to make the new pathname good is attempted
first. After the rename, directories corresponding to rightmost
path segments of the old name will be pruned way until either the
whole path is consumed or a nonempty directory is found.
Note: this function can fail with the new directory structure made
if you lack permissions needed to unlink the leaf directory or
file.
"""
head, tail = path.split(new)
if head and tail and not path.exists(head):
makedirs(head)
rename(old, new)
head, tail = path.split(old)
if head and tail:
try:
removedirs(head)
except error:
pass
__all__.extend(["makedirs", "removedirs", "renames"])
def walk(top, topdown=True, onerror=None):
"""Directory tree generator.
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).
If optional arg 'topdown' is true or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top down). If topdown is false, the triple
for a directory is generated after the triples for all of its
subdirectories (directories are generated bottom up).
When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose names remain in dirnames; this can be used to prune
the search, or to impose a specific order of visiting. Modifying
dirnames when topdown is false is ineffective, since the directories in
dirnames have already been generated by the time dirnames itself is
generated.
By default errors from the os.listdir() call are ignored. If
optional arg 'onerror' is specified, it should be a function; it
will be called with one argument, an os.error instance. It can
report the error to continue with the walk, or raise the exception
to abort the walk. Note that the filename is available as the
filename attribute of the exception object.
Caution: if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk. walk never
changes the current directory, and assumes that the client doesn't
either.
Example:
from os.path import join, getsize
for root, dirs, files in walk('python/Lib/email'):
print root, "consumes",
print sum([getsize(join(root, name)) for name in files]),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
"""
from os.path import join, isdir, islink
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.path.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here.
try:
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = listdir(top)
except error, err:
if onerror is not None:
onerror(err)
return
dirs, nondirs = [], []
for name in names:
if isdir(join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
if topdown:
yield top, dirs, nondirs
for name in dirs:
path = join(top, name)
if not islink(path):
for x in walk(path, topdown, onerror):
yield x
if not topdown:
yield top, dirs, nondirs
__all__.append("walk")
# Make sure os.environ exists, at least
try:
environ
except NameError:
environ = {}
def execl(file, *args):
"""execl(file, *args)
Execute the executable file with argument list args, replacing the
current process. """
execv(file, args)
def execle(file, *args):
"""execle(file, *args, env)
Execute the executable file with argument list args and
environment env, replacing the current process. """
env = args[-1]
execve(file, args[:-1], env)
def execlp(file, *args):
"""execlp(file, *args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process. """
execvp(file, args)
def execlpe(file, *args):
"""execlpe(file, *args, env)
Execute the executable file (which is searched for along $PATH)
with argument list args and environment env, replacing the current
process. """
env = args[-1]
execvpe(file, args[:-1], env)
def execvp(file, args):
"""execp(file, args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process.
args may be a list or tuple of strings. """
_execvpe(file, args)
def execvpe(file, args, env):
"""execvpe(file, args, env)
Execute the executable file (which is searched for along $PATH)
with argument list args and environment env , replacing the
current process.
args may be a list or tuple of strings. """
_execvpe(file, args, env)
__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
def _execvpe(file, args, env=None):
from errno import ENOENT, ENOTDIR
if env is not None:
func = execve
argrest = (args, env)
else:
func = execv
argrest = (args,)
env = environ
head, tail = path.split(file)
if head:
func(file, *argrest)
return
if 'PATH' in env:
envpath = env['PATH']
else:
envpath = defpath
PATH = envpath.split(pathsep)
saved_exc = None
saved_tb = None
for dir in PATH:
fullname = path.join(dir, file)
try:
func(fullname, *argrest)
except error, e:
tb = sys.exc_info()[2]
if (e.errno != ENOENT and e.errno != ENOTDIR
and saved_exc is None):
saved_exc = e
saved_tb = tb
if saved_exc:
raise error, saved_exc, saved_tb
raise error, e, tb
# Change environ to automatically call putenv() if it exists
try:
# This will fail if there's no putenv
putenv
except NameError:
pass
else:
import UserDict
# Fake unsetenv() for Windows
# not sure about os2 here but
# I'm guessing they are the same.
if name in ('os2', 'nt'):
def unsetenv(key):
putenv(key, "")
if name == "riscos":
# On RISC OS, all env access goes through getenv and putenv
from riscosenviron import _Environ
elif name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE
# But we store them as upper case
class _Environ(UserDict.IterableUserDict):
def __init__(self, environ):
UserDict.UserDict.__init__(self)
data = self.data
for k, v in environ.items():
data[k.upper()] = v
def __setitem__(self, key, item):
putenv(key, item)
self.data[key.upper()] = item
def __getitem__(self, key):
return self.data[key.upper()]
try:
unsetenv
except NameError:
def __delitem__(self, key):
del self.data[key.upper()]
else:
def __delitem__(self, key):
unsetenv(key)
del self.data[key.upper()]
def has_key(self, key):
return key.upper() in self.data
def __contains__(self, key):
return key.upper() in self.data
def get(self, key, failobj=None):
return self.data.get(key.upper(), failobj)
def update(self, dict=None, **kwargs):
if dict:
try:
keys = dict.keys()
except AttributeError:
# List of (key, value)
for k, v in dict:
self[k] = v
else:
# got keys
# cannot use items(), since mappings
# may not have them.
for k in keys:
self[k] = dict[k]
if kwargs:
self.update(kwargs)
def copy(self):
return dict(self)
else: # Where Env Var Names Can Be Mixed Case
class _Environ(UserDict.IterableUserDict):
def __init__(self, environ):
UserDict.UserDict.__init__(self)
self.data = environ
def __setitem__(self, key, item):
putenv(key, item)
self.data[key] = item
def update(self, dict=None, **kwargs):
if dict:
try:
keys = dict.keys()
except AttributeError:
# List of (key, value)
for k, v in dict:
self[k] = v
else:
# got keys
# cannot use items(), since mappings
# may not have them.
for k in keys:
self[k] = dict[k]
if kwargs:
self.update(kwargs)
try:
unsetenv
except NameError:
pass
else:
def __delitem__(self, key):
unsetenv(key)
del self.data[key]
def copy(self):
return dict(self)
environ = _Environ(environ)
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
__all__.append("getenv")
def _exists(name):
try:
eval(name)
return True
except NameError:
return False
# Supply spawn*() (probably only for Unix)
if _exists("fork") and not _exists("spawnv") and _exists("execv"):
P_WAIT = 0
P_NOWAIT = P_NOWAITO = 1
# XXX Should we support P_DETACH? I suppose it could fork()**2
# and close the std I/O streams. Also, P_OVERLAY is the same
# as execv*()?
def _spawnvef(mode, file, args, env, func):
# Internal helper; func is the exec*() function to use
pid = fork()
if not pid:
# Child
try:
if env is None:
func(file, args)
else:
func(file, args, env)
except:
_exit(127)
else:
# Parent
if mode == P_NOWAIT:
return pid # Caller is responsible for waiting!
while 1:
wpid, sts = waitpid(pid, 0)
if WIFSTOPPED(sts):
continue
elif WIFSIGNALED(sts):
return -WTERMSIG(sts)
elif WIFEXITED(sts):
return WEXITSTATUS(sts)
else:
raise error, "Not stopped, signaled or exited???"
def spawnv(mode, file, args):
"""spawnv(mode, file, args) -> integer
Execute file with arguments from args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, None, execv)
def spawnve(mode, file, args, env):
"""spawnve(mode, file, args, env) -> integer
Execute file with arguments from args in a subprocess with the
specified environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, env, execve)
# Note: spawnvp[e] is't currently supported on Windows
def spawnvp(mode, file, args):
"""spawnvp(mode, file, args) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, None, execvp)
def spawnvpe(mode, file, args, env):
"""spawnvpe(mode, file, args, env) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, env, execvpe)
if _exists("spawnv"):
# These aren't supplied by the basic Windows code
# but can be easily implemented in Python
def spawnl(mode, file, *args):
"""spawnl(mode, file, *args) -> integer
Execute file with arguments from args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return spawnv(mode, file, args)
def spawnle(mode, file, *args):
"""spawnle(mode, file, *args, env) -> integer
Execute file with arguments from args in a subprocess with the
supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
env = args[-1]
return spawnve(mode, file, args[:-1], env)
__all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",])
if _exists("spawnvp"):
# At the moment, Windows doesn't implement spawnvp[e],
# so it won't have spawnlp[e] either.
def spawnlp(mode, file, *args):
"""spawnlp(mode, file, *args) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return spawnvp(mode, file, args)
def spawnlpe(mode, file, *args):
"""spawnlpe(mode, file, *args, env) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
env = args[-1]
return spawnvpe(mode, file, args[:-1], env)
__all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",])
# Supply popen2 etc. (for Unix)
if _exists("fork"):
if not _exists("popen2"):
def popen2(cmd, mode="t", bufsize=-1):
"""Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
may be a sequence, in which case arguments will be passed directly to
the program without shell intervention (as with os.spawnv()). If 'cmd'
is a string it will be passed to the shell (as with os.system()). If
'bufsize' is specified, it sets the buffer size for the I/O pipes. The
file objects (child_stdin, child_stdout) are returned."""
import popen2
stdout, stdin = popen2.popen2(cmd, bufsize)
return stdin, stdout
__all__.append("popen2")
if not _exists("popen3"):
def popen3(cmd, mode="t", bufsize=-1):
"""Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
may be a sequence, in which case arguments will be passed directly to
the program without shell intervention (as with os.spawnv()). If 'cmd'
is a string it will be passed to the shell (as with os.system()). If
'bufsize' is specified, it sets the buffer size for the I/O pipes. The
file objects (child_stdin, child_stdout, child_stderr) are returned."""
import popen2
stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
return stdin, stdout, stderr
__all__.append("popen3")
if not _exists("popen4"):
def popen4(cmd, mode="t", bufsize=-1):
"""Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd'
may be a sequence, in which case arguments will be passed directly to
the program without shell intervention (as with os.spawnv()). If 'cmd'
is a string it will be passed to the shell (as with os.system()). If
'bufsize' is specified, it sets the buffer size for the I/O pipes. The
file objects (child_stdin, child_stdout_stderr) are returned."""
import popen2
stdout, stdin = popen2.popen4(cmd, bufsize)
return stdin, stdout
__all__.append("popen4")
import copy_reg as _copy_reg
def _make_stat_result(tup, dict):
return stat_result(tup, dict)
def _pickle_stat_result(sr):
(type, args) = sr.__reduce__()
return (_make_stat_result, args)
try:
_copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
except NameError: # stat_result may not exist
pass
def _make_statvfs_result(tup, dict):
return statvfs_result(tup, dict)
def _pickle_statvfs_result(sr):
(type, args) = sr.__reduce__()
return (_make_statvfs_result, args)
try:
_copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
_make_statvfs_result)
except NameError: # statvfs_result may not exist
pass
if not _exists("urandom"):
def urandom(n):
"""urandom(n) -> str
Return a string of n random bytes suitable for cryptographic use.
"""
try:
_urandomfd = open("/dev/urandom", O_RDONLY)
except (OSError, IOError):
raise NotImplementedError("/dev/urandom (or equivalent) not found")
bytes = ""
while len(bytes) < n:
bytes += read(_urandomfd, n - len(bytes))
close(_urandomfd)
return bytes
| [
"[email protected]"
] | |
bccfe4b14cd08e6d30e608d7a87f8575fbf1e692 | 32c56293475f49c6dd1b0f1334756b5ad8763da9 | /google-cloud-sdk/lib/googlecloudsdk/third_party/appengine/tools/appengine_rpc.py | 44e107bcdc9c9a31d86301a3c9041269954cdd22 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | permissive | bopopescu/socialliteapp | b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494 | 85bb264e273568b5a0408f733b403c56373e2508 | refs/heads/master | 2022-11-20T03:01:47.654498 | 2020-02-01T20:29:43 | 2020-02-01T20:29:43 | 282,403,750 | 0 | 0 | MIT | 2020-07-25T08:31:59 | 2020-07-25T08:31:59 | null | UTF-8 | Python | false | false | 24,563 | py | # Copyright 2016 Google LLC. 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.
"""Tool for performing authenticated RPCs against App Engine."""
import gzip
import hashlib
import io
import logging
import os
import re
import socket
import sys
import time
import urllib
from googlecloudsdk.third_party.appengine._internal import six_subset
# pylint:disable=g-import-not-at-top
# pylint:disable=invalid-name
# Inline these directly rather than placing in six_subset since importing
# urllib into six_subset seems to mess with the overridden version of
# urllib/httplib that the NaCl runtime sandbox inserts for SSL purposes.
if six_subset.PY3:
import http.cookiejar
import urllib.error
import urllib.request
BaseHandler = urllib.request.BaseHandler
HTTPError = urllib.error.HTTPError
HTTPHandler = urllib.request.HTTPHandler
HTTPDefaultErrorHandler = urllib.request.HTTPDefaultErrorHandler
HTTPCookieProcessor = urllib.request.HTTPCookieProcessor
HTTPSHandler = urllib.request.HTTPSHandler
HTTPErrorProcessor = urllib.request.HTTPErrorProcessor
MozillaCookieJar = http.cookiejar.MozillaCookieJar
ProxyHandler = urllib.request.ProxyHandler
LoadError = http.cookiejar.LoadError
OpenerDirector = urllib.request.OpenerDirector
Request = urllib.request.Request
UnknownHandler = urllib.request.UnknownHandler
addinfourl_fn = urllib.response.addinfourl
urlencode_fn = urllib.parse.urlencode
else:
import cookielib
import fancy_urllib
import urllib2
BaseHandler = urllib2.BaseHandler
HTTPError = urllib2.HTTPError
HTTPHandler = urllib2.HTTPHandler
HTTPSHandler = fancy_urllib.FancyHTTPSHandler
HTTPDefaultErrorHandler = urllib2.HTTPDefaultErrorHandler
HTTPCookieProcessor = urllib2.HTTPCookieProcessor
HTTPErrorProcessor = urllib2.HTTPErrorProcessor
ProxyHandler = fancy_urllib.FancyProxyHandler
MozillaCookieJar = cookielib.MozillaCookieJar
LoadError = cookielib.LoadError
OpenerDirector = urllib2.OpenerDirector
UnknownHandler = urllib2.UnknownHandler
Request = fancy_urllib.FancyRequest
addinfourl_fn = urllib2.addinfourl
urlencode_fn = urllib.urlencode
# Inlined from fancy_urllib
try:
import ssl # pylint:disable=unused-import
_CAN_VALIDATE_CERTS = True
except ImportError:
_CAN_VALIDATE_CERTS = False
def can_validate_certs():
"""Return True if we have the SSL package and can validate certificates."""
return _CAN_VALIDATE_CERTS
# pylint:disable=g-import-not-at-top
# pylint:disable=invalid-name
logger = logging.getLogger('googlecloudsdk.third_party.appengine.tools.appengine_rpc')
def GetPlatformToken(os_module=os, sys_module=sys, platform=sys.platform):
"""Returns a 'User-agent' token for the host system platform.
Args:
os_module, sys_module, platform: Used for testing.
Returns:
String containing the platform token for the host system.
"""
if hasattr(sys_module, "getwindowsversion"):
windows_version = sys_module.getwindowsversion()
version_info = ".".join(str(i) for i in windows_version[:4])
return platform + "/" + version_info
elif hasattr(os_module, "uname"):
uname = os_module.uname()
return "%s/%s" % (uname[0], uname[2])
else:
return "unknown"
def HttpRequestToString(req, include_data=True):
"""Converts a urllib2.Request to a string.
Args:
req: urllib2.Request
Returns:
Multi-line string representing the request.
"""
headers = ""
for header in req.header_items():
headers += "%s: %s\n" % (header[0], header[1])
template = ("%(method)s %(selector)s %(type)s/1.1\n"
"Host: %(host)s\n"
"%(headers)s")
if include_data:
template = template + "\n%(data)s"
req_selector = req.selector if hasattr(req, "selector") else req.get_selector
if req_selector is None:
req_selector = ""
req_type = req.type if hasattr(req, "type") else req.get_type()
if req_type is None:
req_type = ""
req_host = req.host if hasattr(req, "host") else req.get_host()
if req_host is None:
req_host = ""
req_data = req.data if hasattr(req, "data") else req.get_data()
if req_data is None:
req_data = ""
return template % {
"method": req.get_method(),
"selector": req_selector,
"type": req_type.upper(),
"host": req_host,
"headers": headers,
"data": req_data,
}
class ClientLoginError(HTTPError):
"""Raised to indicate there was an error authenticating with ClientLogin."""
def __init__(self, url, code, msg, headers, args):
HTTPError.__init__(self, url, code, msg, headers, None)
self.args = args
self._reason = args.get("Error")
self.info = args.get("Info")
def read(self):
return '%d %s: %s' % (self.code, self.msg, self.reason)
# In Python 2.7, the HTTPError was changed to have a property for 'reason'.
# So we can no longer just use an attribute and need to define this ourselves.
@property
def reason(self):
return self._reason
class AbstractRpcServer(object):
"""Provides a common interface for a simple RPC server."""
# This flag will dictate which documentation to point to for suggestions.
RUNTIME = "python"
def __init__(self, host, auth_function, user_agent, source,
host_override=None, extra_headers=None, save_cookies=False,
auth_tries=3, account_type=None, debug_data=True, secure=True,
ignore_certs=False, rpc_tries=3, options=None):
"""Creates a new HttpRpcServer.
Args:
host: The host to send requests to.
auth_function: A function that takes no arguments and returns an
(email, password) tuple when called. Will be called if authentication
is required.
user_agent: The user-agent string to send to the server. Specify None to
omit the user-agent header.
source: The source to specify in authentication requests.
host_override: The host header to send to the server (defaults to host).
extra_headers: A dict of extra headers to append to every request. Values
supplied here will override other default headers that are supplied.
save_cookies: If True, save the authentication cookies to local disk.
If False, use an in-memory cookiejar instead. Subclasses must
implement this functionality. Defaults to False.
auth_tries: The number of times to attempt auth_function before failing.
account_type: One of GOOGLE, HOSTED_OR_GOOGLE, or None for automatic.
debug_data: Whether debugging output should include data contents.
secure: If the requests sent using Send should be sent over HTTPS.
ignore_certs: If the certificate mismatches should be ignored.
rpc_tries: The number of rpc retries upon http server error (i.e.
Response code >= 500 and < 600) before failing.
options: the command line options (ignored in this implementation).
"""
if secure:
self.scheme = "https"
else:
self.scheme = "http"
self.ignore_certs = ignore_certs
self.host = host
self.host_override = host_override
self.auth_function = auth_function
self.source = source
self.authenticated = False
self.auth_tries = auth_tries
self.debug_data = debug_data
self.rpc_tries = rpc_tries
# TODO(user): Consider validating account_type?
self.account_type = account_type
self.extra_headers = {}
if user_agent:
self.extra_headers["User-Agent"] = user_agent
if extra_headers:
self.extra_headers.update(extra_headers)
self.save_cookies = save_cookies
# By default there are no cookies to use or save.
self.cookie_jar = MozillaCookieJar()
self.opener = self._GetOpener()
if self.host_override:
logger.debug("Server: %s; Host: %s", self.host, self.host_override)
else:
logger.debug("Server: %s", self.host)
# If we're being run against localhost, set the dev_appserver cookie.
if ((self.host_override and self.host_override == "localhost") or
self.host == "localhost" or self.host.startswith("localhost:")):
self._DevAppServerAuthenticate()
def _GetOpener(self):
"""Returns an OpenerDirector for making HTTP requests.
Returns:
A urllib2.OpenerDirector object.
"""
raise NotImplementedError
def _CreateRequest(self, url, data=None):
"""Creates a new urllib request."""
req = Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.items():
req.add_header(key, value)
return req
def _GetAuthToken(self, email, password):
"""Uses ClientLogin to authenticate the user, returning an auth token.
Args:
email: The user's email address
password: The user's password
Raises:
ClientLoginError: If there was an error authenticating with ClientLogin.
HTTPError: If there was some other form of HTTP error.
Returns:
The authentication token returned by ClientLogin.
"""
account_type = self.account_type
if not account_type:
# self.host is really hostport.
if (self.host.split(':')[0].endswith(".google.com")
or (self.host_override
and self.host_override.split(':')[0].endswith(".google.com"))):
# Needed for use inside Google.
account_type = "HOSTED_OR_GOOGLE"
else:
account_type = "GOOGLE"
data = {
"Email": email,
"Passwd": password,
"service": "ah",
"source": self.source,
"accountType": account_type
}
req = self._CreateRequest(
url=("https://%s/accounts/ClientLogin" %
os.getenv("APPENGINE_AUTH_SERVER", "www.google.com")),
data=urlencode_fn(data))
try:
response = self.opener.open(req)
response_body = response.read()
response_dict = dict(x.split("=")
for x in response_body.split("\n") if x)
if os.getenv("APPENGINE_RPC_USE_SID", "0") == "1":
self.extra_headers["Cookie"] = (
'SID=%s; Path=/;' % response_dict["SID"])
return response_dict["Auth"]
except HTTPError as e:
if e.code == 403:
body = e.read()
response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
raise ClientLoginError(req.get_full_url(), e.code, e.msg,
e.headers, response_dict)
else:
raise
def _GetAuthCookie(self, auth_token):
"""Fetches authentication cookies for an authentication token.
Args:
auth_token: The authentication token returned by ClientLogin.
Raises:
HTTPError: If there was an error fetching the authentication cookies.
"""
# This is a dummy value to allow us to identify when we're successful.
continue_location = "http://localhost/"
args = {"continue": continue_location, "auth": auth_token}
login_path = os.environ.get("APPCFG_LOGIN_PATH", "/_ah")
req = self._CreateRequest("%s://%s%s/login?%s" %
(self.scheme, self.host, login_path,
urlencode_fn(args)))
try:
response = self.opener.open(req)
except HTTPError as e:
response = e
if (response.code != 302 or
response.info()["location"] != continue_location):
raise HTTPError(req.get_full_url(), response.code, response.msg,
response.headers, response.fp)
self.authenticated = True
def _Authenticate(self):
"""Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_ah/login on the server to obtain an
authentication cookie. If login was successful, it tries to redirect
us to the URL we provided.
If we attempt to access the upload API without first obtaining an
authentication cookie, it returns a 401 response and directs us to
authenticate ourselves with ClientLogin.
"""
for unused_i in range(self.auth_tries):
credentials = self.auth_function()
try:
auth_token = self._GetAuthToken(credentials[0], credentials[1])
if os.getenv("APPENGINE_RPC_USE_SID", "0") == "1":
return
except ClientLoginError as e:
# TODO(user): some of these cases probably only pertain to the
# obsolete username/password authentication.
if e.reason == "CaptchaRequired":
print >>sys.stderr, (
"Please go to\n"
"https://www.google.com/accounts/DisplayUnlockCaptcha\n"
"and verify you are a human. Then try again.")
break
if e.reason == "NotVerified":
print >>sys.stderr, "Account not verified."
break
if e.reason == "TermsNotAgreed":
print >>sys.stderr, "User has not agreed to TOS."
break
if e.reason == "AccountDeleted":
print >>sys.stderr, "The user account has been deleted."
break
if e.reason == "AccountDisabled":
print >>sys.stderr, "The user account has been disabled."
break
if e.reason == "ServiceDisabled":
print >>sys.stderr, ("The user's access to the service has been "
"disabled.")
break
if e.reason == "ServiceUnavailable":
print >>sys.stderr, "The service is not available; try again later."
break
raise
self._GetAuthCookie(auth_token)
return
# TODO(user): refactor to share with devappserver2/login.py.
@staticmethod
def _CreateDevAppServerCookieData(email, admin):
"""Creates cookie payload data.
Args:
email: The user's email address.
admin: True if the user is an admin; False otherwise.
Returns:
String containing the cookie payload.
"""
if email:
user_id_digest = hashlib.md5(email.lower()).digest()
user_id = "1" + "".join(
["%02d" % x for x in six_subset.iterbytes(user_id_digest)])[:20]
else:
user_id = ""
return "%s:%s:%s" % (email, bool(admin), user_id)
def _DevAppServerAuthenticate(self):
"""Authenticates the user on the dev_appserver."""
credentials = self.auth_function()
value = self._CreateDevAppServerCookieData(credentials[0], True)
self.extra_headers["Cookie"] = ('dev_appserver_login="%s"; Path=/;' % value)
def Send(self, request_path, payload="",
content_type="application/octet-stream",
timeout=None,
**kwargs):
"""Sends an RPC and returns the response.
Args:
request_path: The path to send the request to, eg /api/appversion/create.
payload: The body of the request, or None to send an empty request.
content_type: The Content-Type header to use.
timeout: timeout in seconds; default None i.e. no timeout.
(Note: for large requests on OS X, the timeout doesn't work right.)
kwargs: Any keyword arguments are converted into query string parameters.
Returns:
The response body, as a string.
"""
old_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
try:
tries = 0
auth_tried = False
while True:
tries += 1
url = "%s://%s%s" % (self.scheme, self.host, request_path)
if kwargs:
# To make testing simpler, always sort the url params.
# Unfortunately we have no ordering information from the caller.
url += "?" + urlencode_fn(sorted(kwargs.items()))
req = self._CreateRequest(url=url, data=payload)
req.add_header("Content-Type", content_type)
# This header is necessary to prevent XSRF attacks, since the browser
# cannot include this header, that means the request had to come from
# another agent like appcfg.py.
req.add_header("X-appcfg-api-version", "1")
try:
logger.debug('Sending %s request:\n%s',
self.scheme.upper(),
HttpRequestToString(req, include_data=self.debug_data))
f = self.opener.open(req)
response = f.read()
f.close()
return response
except HTTPError as e:
logger.debug("Got http error, this is try %d: %s", tries, e)
# TODO(user): consider whether all of the e.code cases still apply
# now that we no longer have username/password authentication.
if tries > self.rpc_tries:
raise
elif e.code == 401:
# Unauthorized user.
if auth_tried:
raise
auth_tried = True
self._Authenticate()
elif e.code >= 500 and e.code < 600:
# Server Error - try again.
continue
elif e.code == 302:
# Server may also return a 302 redirect to indicate authentication
# is required.
if auth_tried:
raise
auth_tried = True
loc = e.info()["location"]
logger.debug("Got 302 redirect. Location: %s", loc)
if loc.startswith("https://www.google.com/accounts/ServiceLogin"):
self._Authenticate()
elif re.match(
r"https://www\.google\.com/a/[a-z0-9\.\-]+/ServiceLogin", loc):
self.account_type = os.getenv("APPENGINE_RPC_HOSTED_LOGIN_TYPE",
"HOSTED")
self._Authenticate()
elif loc.startswith("http://%s/_ah/login" % (self.host,)):
self._DevAppServerAuthenticate()
else:
raise
else:
raise
finally:
socket.setdefaulttimeout(old_timeout)
class ContentEncodingHandler(BaseHandler):
"""Request and handle HTTP Content-Encoding."""
def http_request(self, request):
# Tell Google that we <3 gzip.
request.add_header("Accept-Encoding", "gzip")
# Append ' gzip' to the User-Agent. We need this in order to convince
# GFE that we really do accept gzip-encoded responses, because the rest
# of our User-Agent string does not identify us as a "modern"
# browser. For the gory details of how GFE decides when it is OK to send
# gzip-encoded responses, see HTTPServerRequest::CanCompressFor,
# currently defined here:
#
#
# For additional background, read this:
#
for header in request.headers:
if header.lower() == "user-agent":
request.headers[header] += " gzip"
return request
https_request = http_request
def http_response(self, req, resp):
"""Handle encodings in the order that they are encountered."""
encodings = []
headers = resp.headers
encoding_header = None
for header in headers:
if header.lower() == "content-encoding":
encoding_header = header
for encoding in headers[header].split(","):
encoding = encoding.strip()
if encoding:
encodings.append(encoding)
break
if not encodings:
return resp
# encoding_header can't be None here as the above return on an empty list
# of encodings would have prevented this line from being reached.
del headers[encoding_header]
fp = resp
while encodings and encodings[-1].lower() == "gzip":
fp = io.BytesIO(fp.read())
fp = gzip.GzipFile(fileobj=fp, mode="r")
encodings.pop()
if encodings:
# Some unhandled encodings remain, leave them for other handlers.
# There may be further encodings that we can handle nested within the
# unhandled encoding.
# TODO(user): The only resolution is to support more encodings.
headers[encoding_header] = ", ".join(encodings)
logger.warning("Unrecognized Content-Encoding: %s", encodings[-1])
msg = resp.msg
if sys.version_info >= (2, 6):
resp = addinfourl_fn(fp, headers, resp.url, resp.code)
else:
response_code = resp.code
resp = addinfourl_fn(fp, headers, resp.url)
resp.code = response_code
resp.msg = msg
return resp
https_response = http_response
class HttpRpcServer(AbstractRpcServer):
"""Provides a simplified RPC-style interface for HTTP requests."""
DEFAULT_COOKIE_FILE_PATH = "~/.appcfg_cookies"
def __init__(self, *args, **kwargs):
self.certpath = os.path.normpath(os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'lib', 'cacerts',
'cacerts.txt'))
self.cert_file_available = ((not kwargs.get("ignore_certs", False))
and os.path.exists(self.certpath))
super(HttpRpcServer, self).__init__(*args, **kwargs)
def _CreateRequest(self, url, data=None):
"""Creates a new urllib request."""
req = super(HttpRpcServer, self)._CreateRequest(url, data)
if self.cert_file_available and can_validate_certs():
req.set_ssl_info(ca_certs=self.certpath)
return req
def _CheckCookie(self):
"""Warn if cookie is not valid for at least one minute."""
min_expire = time.time() + 60
for cookie in self.cookie_jar:
if cookie.domain == self.host and not cookie.is_expired(min_expire):
break
else:
print >>sys.stderr, "\nError: Machine system clock is incorrect.\n"
def _Authenticate(self):
"""Save the cookie jar after authentication."""
if self.cert_file_available and not can_validate_certs():
# TODO(user): This warning will not fire if the user is already logged
# in; we may also also want to warn on existing connections.
logger.warn("""ssl module not found.
Without the ssl module, the identity of the remote host cannot be verified, and
connections may NOT be secure. To fix this, please install the ssl module from
http://pypi.python.org/pypi/ssl .
To learn more, see https://developers.google.com/appengine/kb/general#rpcssl""")
super(HttpRpcServer, self)._Authenticate()
if self.cookie_jar.filename is not None and self.save_cookies:
logger.debug("Saving authentication cookies to %s",
self.cookie_jar.filename)
self.cookie_jar.save()
self._CheckCookie()
def _GetOpener(self):
"""Returns an OpenerDirector that supports cookies and ignores redirects.
Returns:
A urllib2.OpenerDirector object.
"""
opener = OpenerDirector()
opener.add_handler(ProxyHandler())
opener.add_handler(UnknownHandler())
opener.add_handler(HTTPHandler())
opener.add_handler(HTTPDefaultErrorHandler())
opener.add_handler(HTTPSHandler())
opener.add_handler(HTTPErrorProcessor())
opener.add_handler(ContentEncodingHandler())
if self.save_cookies:
self.cookie_jar.filename = os.path.expanduser(
HttpRpcServer.DEFAULT_COOKIE_FILE_PATH)
if os.path.exists(self.cookie_jar.filename):
try:
self.cookie_jar.load()
self.authenticated = True
logger.debug("Loaded authentication cookies from %s",
self.cookie_jar.filename)
except (OSError, IOError, LoadError) as e:
# Failed to load cookies. The target file path is bad.
logger.debug("Could not load authentication cookies; %s: %s",
e.__class__.__name__, e)
self.cookie_jar.filename = None
else:
# Create an empty cookie file. This must be created with the file
# permissions set upfront in order to be secure.
try:
fd = os.open(self.cookie_jar.filename, os.O_CREAT, 0o600)
os.close(fd)
except (OSError, IOError) as e:
# Failed to create cookie file. Don't try to save cookies.
logger.debug("Could not create authentication cookies file; %s: %s",
e.__class__.__name__, e)
self.cookie_jar.filename = None
opener.add_handler(HTTPCookieProcessor(self.cookie_jar))
return opener
| [
"[email protected]"
] | |
a031b359534527af9c62e7f20c4c627bb0f7dcca | 2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae | /python/python_27903.py | c51c1c14ea2cba4e5762137f75c1cd767b1c7fab | [] | no_license | AK-1121/code_extraction | cc812b6832b112e3ffcc2bb7eb4237fd85c88c01 | 5297a4a3aab3bb37efa24a89636935da04a1f8b6 | refs/heads/master | 2020-05-23T08:04:11.789141 | 2015-10-22T19:19:40 | 2015-10-22T19:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 74 | py | # invalid syntax when run cProfile
%run -m cProfile simple_test_script.py
| [
"[email protected]"
] | |
850c8eb11111bbb5c8b00fe7fb4a184d18a91817 | cc8dd1bf3ff193e24e636ef6aad54ce18e831270 | /进程和线程/进程/文件拷贝.py | 49ee1a03b083346d1c86568287e7ba80e75bb3c5 | [] | no_license | RelaxedDong/python_base | c27cbc1c06914826d3287dae46a9fe0dd2bff7b0 | 7f865c7d5bdb6454f3b20cd899dbaf19092fb360 | refs/heads/master | 2022-01-08T12:43:58.851895 | 2019-04-24T03:17:13 | 2019-04-24T03:17:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 915 | py | #encoding:utf-8
import os
import time
def Copyfile(path,topath):
pr = open(path,'rb')
pw = open(topath,'wb')
context = pr.read()
pw.write(context)
pr.close()
pw.close()
from multiprocessing import Process,Pool
if __name__ == '__main__':
path = r'E:\pycharm_pro\基础文件\tkinter'
rofile = r'E:\pycharm_pro\基础文件\进程和线程\tofile'
# start = time.time()
# pathlist = os.listdir(path)
# for file in pathlist:
# Copyfile(os.path.join(path,file),os.path.join(rofile,file))
# end = time.time()
# print('耗时:%0.002f'%(end-start))
filelist = os.listdir(path)
pp = Pool(4)
start = time.time()
for filename in filelist:
pp.apply_async(func=Copyfile,args=(os.path.join(path,filename),os.path.join(rofile,filename)))
pp.close()
pp.join()
end = time.time()
print('耗时:%0.002f'%(end-start))
| [
"[email protected]"
] | |
ef19bef3f3f58385df6d59152b0e87461237da4d | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/306/usersdata/296/69255/submittedfiles/poligono.py | 220500ef5bbfdbdbf1c5c788ea21add217eb2034 | [] | 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 | 92 | py | # -*- coding: utf-8 -*-
n = float(input("Digite n: "))
nd = (n*(n-3))/2
print ("%.1f" %(nd)) | [
"[email protected]"
] | |
de8b9176832903430ba8a05a2215df9f4216345b | 25ebc03b92df764ff0a6c70c14c2848a49fe1b0b | /daily/20210426/example_python/05fake.py | 50aa749d0e3b91197180026ae281b1887a96409f | [] | no_license | podhmo/individual-sandbox | 18db414fafd061568d0d5e993b8f8069867dfcfb | cafee43b4cf51a321f4e2c3f9949ac53eece4b15 | refs/heads/master | 2023-07-23T07:06:57.944539 | 2023-07-09T11:45:53 | 2023-07-09T11:45:53 | 61,940,197 | 6 | 0 | null | 2022-10-19T05:01:17 | 2016-06-25T11:27:04 | Python | UTF-8 | Python | false | false | 5,605 | py | import asyncio
import logging
import itertools
import sys
import time
from functools import partial
logger = logging.getLogger(__name__)
debug = True
logging.basicConfig(
level=logging.INFO, format="%(relativeCreated)-10d" + logging.BASIC_FORMAT
)
q = asyncio.Queue()
loop = asyncio.get_event_loop()
ev = asyncio.Event()
async def worker(client):
logger.info("init")
await ev.wait()
logger.info("start")
r = []
END = None
while True:
futs = []
items = []
async def bulk_get():
nonlocal items
while True:
item = await q.get()
if item is END:
q.task_done()
if len(items) > 0:
return
items = END # xxx
return
action, args = item
if debug:
logger.info("action %s -- %r", action, "") # )args)
else:
print(".", file=sys.stderr, end="")
sys.stderr.flush()
items.append((action, args))
try:
await asyncio.wait_for(bulk_get(), 0.1)
except asyncio.TimeoutError:
pass
if items is None:
if q.empty():
break
continue
if len(items) == 0:
print(":", q.empty(), q._unfinished_tasks)
continue
# print("@", len(items))
for action, args in items:
if action == list_clusters:
async def do_list_cluster():
clusters = await loop.run_in_executor(
None, partial(list_clusters, client)
)
for c in clusters:
q.put_nowait((list_services, (c, None)))
q.task_done()
futs.append(loop.create_task(do_list_cluster()))
elif action == list_services:
async def do_list_services(cluster, next_token):
services, new_next_token = await loop.run_in_executor(
None,
partial(list_services, client, cluster, next_token=next_token),
)
if new_next_token is not None:
await q.put((list_services, (cluster, new_next_token)))
for parts in _chunk(services, 10):
await q.put((describe_services, (cluster, parts)))
q.task_done()
futs.append(loop.create_task(do_list_services(*args)))
elif action == describe_services:
async def do_describe_services(cluster, services):
res = await loop.run_in_executor(
None,
partial(describe_services, client, cluster, services=services),
)
await q.put((None, (cluster, res)))
q.task_done()
futs.append(loop.create_task(do_describe_services(*args)))
elif action is None: # end
async def do_end(cluster, services):
for s in services:
r.append(s)
q.task_done()
return True # has end
futs.append(loop.create_task(do_end(*args)))
else:
raise RuntimeError(f"unexpected action {action}")
has_end = False
for is_end in await asyncio.gather(*futs):
if is_end is True:
has_end = True
if has_end:
await q.put(END)
await q.join()
return r
def _chunk(iterable, n):
it = iter(iterable)
while True:
chunk_it = itertools.islice(it, n)
try:
first_el = next(chunk_it)
except StopIteration:
return
yield tuple(itertools.chain((first_el,), chunk_it))
def list_clusters(client):
time.sleep(0.5)
return ["app", "spot-batch"]
def list_services(client, cluster, *, next_token=None):
time.sleep(0.5)
if cluster == "app":
if next_token is None:
return [f"app{i:02d}" for i in range(20)], "next_token_00"
elif next_token == "next_token_00":
return [f"app{i:02d}" for i in range(20, 40)], "next_token_01"
else:
return [f"app{i:02d}" for i in range(20, 60)], None
elif cluster == "spot-batch":
if next_token is None:
return [f"spot-batch{i:02d}" for i in range(20)], "next_token_00"
elif next_token == "next_token_00":
return [f"spot-batch{i:02d}" for i in range(20, 40)], "next_token_01"
elif next_token == "next_token_01":
return [f"spot-batch{i:02d}" for i in range(40, 60)], "next_token_02"
else:
return [f"spot-batch{i:02d}" for i in range(60, 80)], None
else:
raise NotImplementedError(f"unexpected cluster, {cluster}")
def describe_services(client, cluster, *, services):
time.sleep(0.5)
r = []
for name in services:
assert isinstance(name, str), name
r.append({"name": name, "desiredCount": 1, "runningCount": 1, "prefix": "O "})
return r
q.put_nowait((list_clusters, None))
ev.set()
loop.set_debug(debug)
client = None
res = loop.run_until_complete(worker(client))
for s in sorted(res, key=lambda s: s["name"]):
# if s["prefix"] == "O ":
# continue
print(f"""{s["prefix"]} {s["name"]} ({s["runningCount"]} / {s["desiredCount"]})""")
| [
"[email protected]"
] | |
87b0b6633115e323d2d9df2d3cafe146cffbe018 | bf769a3a3935a8e08f11fdf606f2e2e2bc6a5307 | /PyQt/chapter06_layout_management/qt06_vboxLayout.py | 707632895a91fb55826d20bc92403902d0124a20 | [] | no_license | metanoia1989/QTStudy | b71f2c8cf6fd001a14db3f1b5ece82c1cc7f7a93 | 29465c6bb9fc0ef2e50a9bf2f66d996ecbd086c0 | refs/heads/master | 2021-12-25T16:50:26.915441 | 2021-10-10T01:26:14 | 2021-10-10T01:26:14 | 193,919,811 | 3 | 2 | null | 2021-01-25T09:23:30 | 2019-06-26T14:22:41 | HTML | UTF-8 | Python | false | false | 856 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtCore import Qt
class Winform(QWidget):
def __init__(self, parent=None):
super(Winform, self).__init__(parent)
self.setWindowTitle("水平布局管理例子")
self.resize(330, 150)
# 水平布局按照从左到右的顺序进行添加按钮部件
hlayout = QVBoxLayout()
hlayout.addWidget(QPushButton(str(1)))
hlayout.addWidget(QPushButton(str(2)))
hlayout.addWidget(QPushButton(str(3)))
hlayout.addWidget(QPushButton(str(4)))
hlayout.addWidget(QPushButton(str(5)))
self.setLayout(hlayout)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Winform()
form.show()
sys.exit(app.exec_()) | [
"[email protected]"
] | |
52ecd2311054f37136b87690f02c021ad7a3aea2 | c0da8ad92777ec4379ee743c84361e986a05fd0a | /Girls21.2/Great/great.py | 1437ce80ec6cf250f193fded77c7e632579e8e70 | [] | no_license | EliteGirls/Camp2017 | 2e850994fa25ad330b351a557c0ef218aab2c334 | 7cbf0c9469954e9987b5d9835df5b69b5e82a411 | refs/heads/master | 2021-01-20T07:24:21.482465 | 2017-08-27T09:32:49 | 2017-08-27T09:32:49 | 101,535,832 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 26 | py | print "hello"
print "love" | [
"[email protected]"
] | |
2b689a5b3c3d0097066a25f9ba2cfac34a59247f | 7b60c68ddda39ef82f5d49404bbcf62cc83e4860 | /crawl/beautifuksoup_css_mu.py | 4289b4574115bb7d8aa6ac2ca49f2c85612e9e95 | [] | no_license | joycejhang/learningml | da802e0ab9cfb6cce89791561870c0078cfaaaf9 | 884ed0541bcb257bb82e77c126ab77c927fe9add | refs/heads/master | 2020-04-22T15:04:58.445844 | 2019-07-04T11:31:03 | 2019-07-04T11:31:03 | 170,466,049 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 524 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 28 11:03:06 2018
@author: Joyce
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
# if has Chinese, apply decode()
html = urlopen("https://morvanzhou.github.io/static/scraping/list.html").read().decode('utf-8')
#print(html)
soup = BeautifulSoup(html, features='lxml')
# use class to narrow search
month = soup.find_all('li', {"class": "month"})
for m in month:
print(m.get_text())
"""
一月
二月
三月
四月
五月
""" | [
"[email protected]"
] | |
93726b81910c6ad643b0e87010087cf632f63008 | 116967cd9f326d74a83c7ce01a826e1a83265ade | /nilearn/nilearn/_utils/logger.py | c7b48108880aadb0fd7d07ea94dba256dda0952f | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | bcipolli/nilearn-RSA | f73ea5e04ac94c0c2d4c7ac5f5219779a3067596 | 0ac8595c1ce3e44b6b5ec25d1906f558088ab297 | refs/heads/master | 2020-04-15T04:01:37.084977 | 2015-08-15T17:35:22 | 2015-08-15T17:35:22 | 31,421,013 | 4 | 2 | null | null | null | null | UTF-8 | Python | false | false | 3,467 | py | """Logging facility for nilearn"""
# Author: Philippe Gervais
# License: simplified BSD
import inspect
from sklearn.base import BaseEstimator
# The technique used in the log() function only applies to CPython, because
# it uses the inspect module to walk the call stack.
def log(msg, verbose=1, object_classes=(BaseEstimator, ),
stack_level=1, msg_level=1):
"""Display a message to the user, depending on the verbosity level.
This function allows to display some information that references an object
that is significant to the user, instead of a internal function. The goal
is to make user's code as simple to debug as possible.
Parameters
----------
msg: str
message to display
verbose: int
current verbosity level. Message is displayed if this value is greater
or equal to msg_level.
object_classes: tuple of type
classes that should appear to emit the message
stack_level: int
if no object in the call stack matches object_classes, go back that
amount in the call stack and display class/function name thereof.
msg_level: int
verbosity level at and above which message should be displayed to the
user. Most of the time this parameter can be left unchanged.
Notes
=====
This function does tricky things to ensure that the proper object is
referenced in the message. If it is called e.g. inside a function that is
called by a method of an object inheriting from any class in
object_classes, then the name of the object (and the method) will be
displayed to the user. If several matching objects exist in the call
stack, the highest one is used (first call chronologically), because this
is the one which is most likely to have been written in the user's script.
"""
if verbose >= msg_level:
stack = inspect.stack()
object_frame = None
for f in reversed(stack):
frame = f[0]
current_self = frame.f_locals.get("self", None)
if isinstance(current_self, object_classes):
object_frame = frame
func_name = f[3]
object_self = current_self
break
if object_frame is None: # no object found: use stack_level
if stack_level >= len(stack):
stack_level = -1
object_frame, _, _, func_name = stack[stack_level][:4]
object_self = object_frame.f_locals.get("self", None)
if object_self is not None:
func_name = "%s.%s" % (object_self.__class__.__name__, func_name)
print("[{func_name}] {msg}".format(func_name=func_name, msg=msg))
def _compose_err_msg(msg, **kwargs):
"""Append key-value pairs to msg, for display.
Parameters
==========
msg: string
arbitrary message
kwargs: dict
arbitrary dictionary
Returns
=======
updated_msg: string
msg, with "key: value" appended. Only string values are appended.
Example
=======
>>> _compose_err_msg('Error message with arguments...', arg_num=123, \
arg_str='filename.nii', arg_bool=True)
'Error message with arguments...\\narg_str: filename.nii'
>>>
"""
updated_msg = msg
for k, v in sorted(kwargs.items()):
if isinstance(v, basestring): # print only str-like arguments
updated_msg += "\n" + k + ": " + v
return updated_msg
| [
"[email protected]"
] | |
4077521437b981d8ff9757c2997464dde7df70b1 | a2d36e471988e0fae32e9a9d559204ebb065ab7f | /huaweicloud-sdk-cbr/huaweicloudsdkcbr/v1/model/create_vault_request.py | 2a2804e36925be33e00569a4aee8d8ffd6fbc9bc | [
"Apache-2.0"
] | permissive | zhouxy666/huaweicloud-sdk-python-v3 | 4d878a90b8e003875fc803a61414788e5e4c2c34 | cc6f10a53205be4cb111d3ecfef8135ea804fa15 | refs/heads/master | 2023-09-02T07:41:12.605394 | 2021-11-12T03:20:11 | 2021-11-12T03:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,898 | py | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class CreateVaultRequest:
"""
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 = {
'body': 'VaultCreateReq'
}
attribute_map = {
'body': 'body'
}
def __init__(self, body=None):
"""CreateVaultRequest - a model defined in huaweicloud sdk"""
self._body = None
self.discriminator = None
if body is not None:
self.body = body
@property
def body(self):
"""Gets the body of this CreateVaultRequest.
:return: The body of this CreateVaultRequest.
:rtype: VaultCreateReq
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this CreateVaultRequest.
:param body: The body of this CreateVaultRequest.
:type: VaultCreateReq
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CreateVaultRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
57eb43417bd20b75f6c126e37b186c8b79cdad4c | 1e6e3bb707920fdb01ebca23eaf81097c558d918 | /openslides_backend/action/actions/theme/create.py | cfc24dfc000b85bd1c397ed32265f40dd3f2792e | [
"MIT"
] | permissive | OpenSlides/openslides-backend | cbd24589f82a6f29bde02611610511870bb6abbf | d8511f5138db4cc5fe4fa35e2a0200f766bd49c5 | refs/heads/main | 2023-08-23T11:54:25.064070 | 2023-08-22T11:15:45 | 2023-08-22T11:15:45 | 231,757,840 | 6 | 22 | MIT | 2023-09-14T16:23:41 | 2020-01-04T12:17:38 | Python | UTF-8 | Python | false | false | 1,802 | py | from typing import Any, Dict
from ....action.mixins.archived_meeting_check_mixin import CheckForArchivedMeetingMixin
from ....models.models import Theme
from ....permissions.management_levels import OrganizationManagementLevel
from ....shared.util import ONE_ORGANIZATION_ID
from ...generics.create import CreateAction
from ...util.default_schema import DefaultSchema
from ...util.register import register_action
THEME_REQ_FIELDS = ["name", "primary_500", "accent_500", "warn_500"]
THEME_OPT_FIELDS = [
"primary_50",
"primary_100",
"primary_200",
"primary_300",
"primary_400",
"primary_600",
"primary_700",
"primary_800",
"primary_900",
"primary_a100",
"primary_a200",
"primary_a400",
"primary_a700",
"accent_50",
"accent_100",
"accent_200",
"accent_300",
"accent_400",
"accent_600",
"accent_700",
"accent_800",
"accent_900",
"accent_a100",
"accent_a200",
"accent_a400",
"accent_a700",
"warn_50",
"warn_100",
"warn_200",
"warn_300",
"warn_400",
"warn_600",
"warn_700",
"warn_800",
"warn_900",
"warn_a100",
"warn_a200",
"warn_a400",
"warn_a700",
"headbar",
"yes",
"no",
"abstain",
]
@register_action("theme.create")
class ThemeCreate(CreateAction, CheckForArchivedMeetingMixin):
"""
Action to create an theme.
"""
model = Theme()
schema = DefaultSchema(Theme()).get_create_schema(
required_properties=THEME_REQ_FIELDS,
optional_properties=THEME_OPT_FIELDS,
)
permission = OrganizationManagementLevel.CAN_MANAGE_ORGANIZATION
def update_instance(self, instance: Dict[str, Any]) -> Dict[str, Any]:
instance["organization_id"] = ONE_ORGANIZATION_ID
return instance
| [
"[email protected]"
] | |
db3e86a824e045824bd23d68cc9fa7e1171705e5 | f9d564f1aa83eca45872dab7fbaa26dd48210d08 | /huaweicloud-sdk-ugo/huaweicloudsdkugo/v1/model/show_evaluation_project_status_response.py | 32b633c65bfa9cdce52440b82e2516ca3572dfae | [
"Apache-2.0"
] | permissive | huaweicloud/huaweicloud-sdk-python-v3 | cde6d849ce5b1de05ac5ebfd6153f27803837d84 | f69344c1dadb79067746ddf9bfde4bddc18d5ecf | refs/heads/master | 2023-09-01T19:29:43.013318 | 2023-08-31T08:28:59 | 2023-08-31T08:28:59 | 262,207,814 | 103 | 44 | NOASSERTION | 2023-06-22T14:50:48 | 2020-05-08T02:28:43 | Python | UTF-8 | Python | false | false | 11,392 | py | # coding: utf-8
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ShowEvaluationProjectStatusResponse(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 = {
'evaluation_project_id': 'int',
'evaluation_project_name': 'str',
'evaluation_project_status': 'str',
'project_status_detail': 'ProjectStatusDetail',
'source_db_type': 'str',
'source_db_version': 'str',
'target_db_type': 'str',
'target_db_version': 'str'
}
attribute_map = {
'evaluation_project_id': 'evaluation_project_id',
'evaluation_project_name': 'evaluation_project_name',
'evaluation_project_status': 'evaluation_project_status',
'project_status_detail': 'project_status_detail',
'source_db_type': 'source_db_type',
'source_db_version': 'source_db_version',
'target_db_type': 'target_db_type',
'target_db_version': 'target_db_version'
}
def __init__(self, evaluation_project_id=None, evaluation_project_name=None, evaluation_project_status=None, project_status_detail=None, source_db_type=None, source_db_version=None, target_db_type=None, target_db_version=None):
"""ShowEvaluationProjectStatusResponse
The model defined in huaweicloud sdk
:param evaluation_project_id: 评估项目ID。
:type evaluation_project_id: int
:param evaluation_project_name: 评估项目名称。
:type evaluation_project_name: str
:param evaluation_project_status: 评估项目状态。
:type evaluation_project_status: str
:param project_status_detail:
:type project_status_detail: :class:`huaweicloudsdkugo.v1.ProjectStatusDetail`
:param source_db_type: 源数据库类型。
:type source_db_type: str
:param source_db_version: 源数据库版本。
:type source_db_version: str
:param target_db_type: 目标数据库类型。
:type target_db_type: str
:param target_db_version: 目标数据库版本。
:type target_db_version: str
"""
super(ShowEvaluationProjectStatusResponse, self).__init__()
self._evaluation_project_id = None
self._evaluation_project_name = None
self._evaluation_project_status = None
self._project_status_detail = None
self._source_db_type = None
self._source_db_version = None
self._target_db_type = None
self._target_db_version = None
self.discriminator = None
if evaluation_project_id is not None:
self.evaluation_project_id = evaluation_project_id
if evaluation_project_name is not None:
self.evaluation_project_name = evaluation_project_name
if evaluation_project_status is not None:
self.evaluation_project_status = evaluation_project_status
if project_status_detail is not None:
self.project_status_detail = project_status_detail
if source_db_type is not None:
self.source_db_type = source_db_type
if source_db_version is not None:
self.source_db_version = source_db_version
if target_db_type is not None:
self.target_db_type = target_db_type
if target_db_version is not None:
self.target_db_version = target_db_version
@property
def evaluation_project_id(self):
"""Gets the evaluation_project_id of this ShowEvaluationProjectStatusResponse.
评估项目ID。
:return: The evaluation_project_id of this ShowEvaluationProjectStatusResponse.
:rtype: int
"""
return self._evaluation_project_id
@evaluation_project_id.setter
def evaluation_project_id(self, evaluation_project_id):
"""Sets the evaluation_project_id of this ShowEvaluationProjectStatusResponse.
评估项目ID。
:param evaluation_project_id: The evaluation_project_id of this ShowEvaluationProjectStatusResponse.
:type evaluation_project_id: int
"""
self._evaluation_project_id = evaluation_project_id
@property
def evaluation_project_name(self):
"""Gets the evaluation_project_name of this ShowEvaluationProjectStatusResponse.
评估项目名称。
:return: The evaluation_project_name of this ShowEvaluationProjectStatusResponse.
:rtype: str
"""
return self._evaluation_project_name
@evaluation_project_name.setter
def evaluation_project_name(self, evaluation_project_name):
"""Sets the evaluation_project_name of this ShowEvaluationProjectStatusResponse.
评估项目名称。
:param evaluation_project_name: The evaluation_project_name of this ShowEvaluationProjectStatusResponse.
:type evaluation_project_name: str
"""
self._evaluation_project_name = evaluation_project_name
@property
def evaluation_project_status(self):
"""Gets the evaluation_project_status of this ShowEvaluationProjectStatusResponse.
评估项目状态。
:return: The evaluation_project_status of this ShowEvaluationProjectStatusResponse.
:rtype: str
"""
return self._evaluation_project_status
@evaluation_project_status.setter
def evaluation_project_status(self, evaluation_project_status):
"""Sets the evaluation_project_status of this ShowEvaluationProjectStatusResponse.
评估项目状态。
:param evaluation_project_status: The evaluation_project_status of this ShowEvaluationProjectStatusResponse.
:type evaluation_project_status: str
"""
self._evaluation_project_status = evaluation_project_status
@property
def project_status_detail(self):
"""Gets the project_status_detail of this ShowEvaluationProjectStatusResponse.
:return: The project_status_detail of this ShowEvaluationProjectStatusResponse.
:rtype: :class:`huaweicloudsdkugo.v1.ProjectStatusDetail`
"""
return self._project_status_detail
@project_status_detail.setter
def project_status_detail(self, project_status_detail):
"""Sets the project_status_detail of this ShowEvaluationProjectStatusResponse.
:param project_status_detail: The project_status_detail of this ShowEvaluationProjectStatusResponse.
:type project_status_detail: :class:`huaweicloudsdkugo.v1.ProjectStatusDetail`
"""
self._project_status_detail = project_status_detail
@property
def source_db_type(self):
"""Gets the source_db_type of this ShowEvaluationProjectStatusResponse.
源数据库类型。
:return: The source_db_type of this ShowEvaluationProjectStatusResponse.
:rtype: str
"""
return self._source_db_type
@source_db_type.setter
def source_db_type(self, source_db_type):
"""Sets the source_db_type of this ShowEvaluationProjectStatusResponse.
源数据库类型。
:param source_db_type: The source_db_type of this ShowEvaluationProjectStatusResponse.
:type source_db_type: str
"""
self._source_db_type = source_db_type
@property
def source_db_version(self):
"""Gets the source_db_version of this ShowEvaluationProjectStatusResponse.
源数据库版本。
:return: The source_db_version of this ShowEvaluationProjectStatusResponse.
:rtype: str
"""
return self._source_db_version
@source_db_version.setter
def source_db_version(self, source_db_version):
"""Sets the source_db_version of this ShowEvaluationProjectStatusResponse.
源数据库版本。
:param source_db_version: The source_db_version of this ShowEvaluationProjectStatusResponse.
:type source_db_version: str
"""
self._source_db_version = source_db_version
@property
def target_db_type(self):
"""Gets the target_db_type of this ShowEvaluationProjectStatusResponse.
目标数据库类型。
:return: The target_db_type of this ShowEvaluationProjectStatusResponse.
:rtype: str
"""
return self._target_db_type
@target_db_type.setter
def target_db_type(self, target_db_type):
"""Sets the target_db_type of this ShowEvaluationProjectStatusResponse.
目标数据库类型。
:param target_db_type: The target_db_type of this ShowEvaluationProjectStatusResponse.
:type target_db_type: str
"""
self._target_db_type = target_db_type
@property
def target_db_version(self):
"""Gets the target_db_version of this ShowEvaluationProjectStatusResponse.
目标数据库版本。
:return: The target_db_version of this ShowEvaluationProjectStatusResponse.
:rtype: str
"""
return self._target_db_version
@target_db_version.setter
def target_db_version(self, target_db_version):
"""Sets the target_db_version of this ShowEvaluationProjectStatusResponse.
目标数据库版本。
:param target_db_version: The target_db_version of this ShowEvaluationProjectStatusResponse.
:type target_db_version: str
"""
self._target_db_version = target_db_version
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ShowEvaluationProjectStatusResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
efc7e0e6f4eeae2a0226ec1569a0cea893878697 | 0a973640f0b02d7f3cf9211fcce33221c3a50c88 | /.history/src/csrc_reply_20210204142902.py | e86cb08dbc1e87888c905e9f2d8605734a986bf1 | [] | no_license | JiajunChen123/IPO_under_review_crawler | 5468b9079950fdd11c5e3ce45af2c75ccb30323c | 031aac915ebe350ec816c05a29b5827fde588567 | refs/heads/main | 2023-02-26T08:23:09.622725 | 2021-02-04T10:11:16 | 2021-02-04T10:11:16 | 332,619,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,784 | py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : csrc_reply.py
@Time : 2021/02/04 14:14:51
@Author : Jiajun Chen
@Version : 1.0
@Contact : [email protected]
@License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
'''
# 证监会发行监管部首次公开发行反馈意见爬虫
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import re
import requests
import time
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'}
baseUrl = 'http://www.csrc.gov.cn/pub/newsite/fxjgb/scgkfxfkyj/'
def download_page(nexturl):
r = requests.get(nexturl,headers= headers)
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text,'html.parser')
projList = soup.find(id='myul').findAll('a')
for proj in projList:
href= proj['href']
docUrl = baseUrl + href
title = proj.text
print('fetching: ',title)
pageInfo = requests.get(docUrl,headers=headers)
pageInfo.encoding='utf-8'
docLink = re.findall(r'file_appendix=\'<a href=\"(.*)\">',pageInfo.text)[0]
doc = requests.get(urljoin(docUrl,docLink),headers=headers,stream=True)
with open('C:/Users/chen/Desktop/IPO_info/data/证监会文件/{}.docx'.format(title),'wb') as f:
f.write(doc.content)
time.sleep(2)
def get_all():
r = requests.get(baseUrl,headers= headers)
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text,'html.parser')
numPage = re.findall(r'var countPage = (.*)//',soup.text)[0]
numPage = int(numPage)
download_page(baseUrl)
for i in range(1,numPage):
nextUrl = baseUrl + 'index_{}.html'.format(i)
download_page(nextUrl)
def check_update():
| [
"[email protected]"
] | |
d23facb8aa301aa21a5529a832694e258dc33e2e | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_138/ch82_2020_04_11_22_11_44_249634.py | 5db60cc74f33a51436b8f74d6967226febdf2be1 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 211 | py | def primeiras_ocorrencias(string):
dicionario={}
i=0
for a in string:
if a not in dicionario:
dicionario[a]=i
i+=1
else:
i+=1
return dicionario | [
"[email protected]"
] | |
2e7c9b3525bfa87a6aabdb81158e2cb030a87cbb | 2f9dd97f4b6f8bf164d8550b46bfe6313dc84c6c | /src/pmr2/bives/view.py | dd8eb581ac9f986ad1333cf04a74064e6054d2fd | [] | no_license | PMR2/pmr2.bives | 89ec960283883e218c9b35455a84ac1ad46e57c0 | d9273df7a8eb97d707ca14eeab6def3a5d01df3f | refs/heads/master | 2021-05-15T02:27:09.348400 | 2020-01-17T01:53:31 | 2020-01-17T01:54:37 | 34,535,404 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,156 | py | import json
import requests
import zope.component
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from plone.registry.interfaces import IRegistry
from pmr2.z3cform.page import SimplePage
from pmr2.app.workspace.browser.browser import FilePage
from .interfaces import ISettings
registry_prefix = 'pmr2.bives.settings'
def call_bives(files, commands, session=None):
if session is None:
session = requests.Session()
data = {
'files': files,
'commands': commands,
}
registry = zope.component.getUtility(IRegistry)
try:
settings = registry.forInterface(ISettings, prefix=registry_prefix)
except KeyError:
view.status = (u'Could not load settings for pmr2.bives. Please '
'check the installation status for this add-on.')
return
try:
r = session.post(settings.bives_endpoint, data=json.dumps(data))
results = r.json()
# It can be successfully decode so it should be safe(TM)
results = r.text
except ValueError:
results = '{"error": "Server returned unexpected results"}'
except requests.exceptions.ConnectionError:
results = '{"error": "Error connecting to BiVeS server."}'
except requests.exceptions.RequestException:
results = '{"error": "Unexpected exception when handling BiVeS."}'
return results
def apply_bives_view(view, files, commands, attributes):
results = call_bives(files, commands, view.session)
view.diff_view = view.diff_viewer(view.context, view.request)
view.diff_view.results = results
for k, v in attributes.items():
setattr(view.diff_view, k, v)
class BiVeSExposurePickFilePage(SimplePage):
template = ViewPageTemplateFile('bives_exposure_pick_file.pt')
label = ''
def physical_path(self):
return '/'.join(self.context.getPhysicalPath())
class BiVeSWorkspacePickFilePage(FilePage):
template = ViewPageTemplateFile('bives_workspace_pick_file.pt')
label = ''
def physical_path(self):
return '/'.join(self.context.getPhysicalPath())
class BiVeSDiffViewer(SimplePage):
template = ViewPageTemplateFile('bives_simple_diff.pt')
label = u'BiVeS Model Diff Viewer'
results = None
raw_source = None
raw_target = None
class BiVeSSingleViewer(SimplePage):
template = ViewPageTemplateFile('bives_single.pt')
label = u'BiVeS Model Viewer'
results = None
raw_source = None
class BiVeSBaseView(SimplePage):
label = u'BiVeS Viewer'
commands = ['singleCompHierarchyJson',]
diff_viewer = BiVeSSingleViewer
diff_view = None
def extract_file(self):
# return the file
return self.context.absolute_url()
def update(self):
self.request['disable_border'] = 1
super(BiVeSBaseView, self).update()
# post the data to BiVeS
files = (self.extract_file(),)
commands = self.commands
apply_bives_view(self, files, commands, {})
def render(self):
if not self.diff_view:
return super(BiVeSBaseView, self).render()
return self.diff_view()
| [
"[email protected]"
] | |
953907553899b6a1d9fd87afa1c6f70dd6cc6f31 | 589b5eedb71d83c15d44fedf60c8075542324370 | /stock/stcok_pool.py | e618017842cb50e51927821649c22bb60a2cee4e | [] | no_license | rlcjj/quant | 4c2be8a8686679ceb675660cb37fad554230e0d4 | c07e8f0f6e1580ae29c78c1998a53774a15a67e1 | refs/heads/master | 2020-03-31T07:15:48.111511 | 2018-08-27T05:29:00 | 2018-08-27T05:29:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,094 | py | import pandas as pd
from quant.param.param import Parameter
from datetime import datetime
from WindPy import w
w.start()
class StockPool(object):
"""
下载和得到当前所有的股票池
load_all_stock_code_now
get_all_stock_code_now
"""
def __init__(self):
self.name = "All_Stock_Code"
self.load_out_file = Parameter().get_load_out_file(self.name)
self.read_file = Parameter().get_read_file(self.name)
def load_all_stock_code_now(self, source="wind_terminal"):
if source == "wind_terminal":
today = datetime.today().strftime('%Y-%m-%d')
data = w.wset("sectorconstituent", "date=" + today + ";sectorid=a001010100000000")
data = pd.DataFrame(data.Data, index=data.Fields, columns=data.Codes).T
now_wind_list = list(data['wind_code'].values)
data = w.wset("sectorconstituent", "date=" + today + ";sectorid=a001010m00000000")
data = pd.DataFrame(data.Data, index=data.Fields, columns=data.Codes).T
delist_list = list(data['wind_code'].values)
now_list = self.get_all_stock_code_now()
update_list = list(set(now_list) | set(now_wind_list) | set(delist_list))
update_list.sort()
update_code = pd.DataFrame(update_list, columns=['code'])
update_code.to_csv(self.load_out_file)
print("################# Loading All Stock Code ############################################")
def get_all_stock_code_now(self, source="wind_terminal"):
if source == "wind_terminal":
code = pd.read_csv(self.read_file, encoding='gbk', index_col=[0])
now_list = list(code['code'].values)
else:
now_list = []
return now_list
if __name__ == '__main__':
# StockPool
################################################################################
StockPool().load_all_stock_code_now()
print(StockPool().get_all_stock_code_now())
################################################################################
| [
"[email protected]"
] | |
fd35c54e1fa82f624c63b4fa96fc49e7a4b26b09 | 9f112cd0aeb1447dee06ded576d99b61701cbdc3 | /ec-backend/src/ad/urls.py | a8546f87a5cd8ac17f23da1a35b3ed6db41309d3 | [] | no_license | ForeverDreamer/embarrassment-cyclopedia | 44e13fbd7210ebc634d0fbab321c0f4598072ff3 | f69bc88a6a8e734cbb3d37ab173f557708653789 | refs/heads/master | 2023-01-10T17:20:44.181077 | 2020-07-15T03:20:27 | 2020-07-15T03:20:27 | 206,903,622 | 0 | 0 | null | 2023-01-07T09:30:23 | 2019-09-07T02:22:09 | JavaScript | UTF-8 | Python | false | false | 251 | py | from django.urls import path
from .views import (
AdInfoListView,
AdInfoDetailView,
)
urlpatterns = [
path('', AdInfoListView.as_view(), name='adinfo-list'),
path('<str:pk>/', AdInfoDetailView.as_view(), name='adinfo-detail'),
]
| [
"[email protected]"
] | |
9dfeb0a328d15d9455aa51f046ccdb764f5f44c2 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/pa3/sample/object_attr_set_eval_order-228.py | a511e83aab6b4ea3a1fa28424a3b776260bdc205 | [] | 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 | 463 | py | class A(object):
a:int = 42
class B(A):
b:bool = True
def __init__(self:"B"):
print("B")
a:A = None
b:B = None
def get_b() -> B:
print("Getting B")
return b
def get_one() -> int:
print("Getting 1")
return 1
def get_false() -> bool:
print("Getting False")
return False
a = b = B()
get_b().a = get_one()
print("Assigned B.a")
get_b().b = get_false()
print("Assigned B.b")
print(a.a)
print($Parameters)
print(b.b)
| [
"[email protected]"
] | |
70b6f7ab540eaa8dcf83f872958f371a9adeaaac | 59da45955862686374e438b5367978856df7c284 | /component_services/metadata_searcher_service/metadata_search_service.py | 85492def977c190d6dd8568d7baf1a6f47ed24ee | [] | no_license | nguyentran0212/IoTSE-prototypes | 04531fb3a8d14d1eaa5eba712c773bd7531fd04d | 3c9dde27cf1818fbf74508520eec3f35778f60f5 | refs/heads/master | 2021-09-20T10:48:47.330873 | 2018-08-08T08:20:46 | 2018-08-08T08:20:46 | 116,230,859 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,223 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 3 13:22:31 2018
@author: nguyentran
"""
from ISEPLib.abstract_services import AbsSearcherService
import ISEPLib.entity as entity
import redis
import pickle
from pymongo import MongoClient
from pprint import pprint
class SearcherService(AbsSearcherService):
def __init__(self, redis_host = "localhost", redis_port = 6379, redis_db = 0, mongo_host = "localhost", mongo_port = 27017, query_type = "metadata_query", *args, **kwargs):
super().__init__(*args, **kwargs)
self.query_type = query_type
# Create client to redis database
self.redis_client = redis.StrictRedis(host = redis_host, port = int(redis_port), db = redis_db)
self.redis_query_id_key = "metadata_searcher:query_id:"
# Create client to mongo database
self.mongo_client = MongoClient(host = mongo_host, port = int(mongo_port))
self.mongo_db = self.mongo_client.sensor_metadata_db
self.mongo_col = self.mongo_db.sensor_metadata_collection
def _query(self, query, wf_id = ""):
"""
This function search the database to resolve the given query
and put search result into a storage space, and return the identifier
of that list of search results to the client
"""
# Extract the relevant query from the input query message
query_id = query.query_ID
query_content = query.query_content.get(self.query_type, {})
pprint(query_content)
# Perform the search to find sensors
result_curs = self.mongo_col.find(query_content)
mongo_count = self.mongo_col.find(query_content).count()
self.redis_client.set("DEBUG_metadata_mongo_count:" + query_id, mongo_count)
result_set = entity.ResultSet(query_ID = query_id, query_instance = query)
self.redis_client.set("DEBUG_metadata_init_result_count:" + query_id, len(result_set.results))
ite_num = 0
for result in result_curs:
score = {"score" : 100}
iot_content = entity.IoTContent(iot_content_dict=result)
result_set.add_IoTContent_score(iot_content.to_dict(), score)
ite_num += 1
self.redis_client.set("DEBUG_metadata_ite_count:" + query_id, ite_num)
self.redis_client.set("DEBUG_metadata_result_count:" + query_id, len(result_set.results))
# Store result set in Redis and return a key for client to retrieve results
p_result_set = pickle.dumps(result_set)
self.redis_client.set(self.redis_query_id_key + query_id, p_result_set)
return query_id
def _getResult(self, query_id, wf_id = ""):
"""
This function returns the set of results generated from a previous query
"""
# with open("test_cookie.txt", "a") as f:
# f.write("From %s: %s\n" % (self, wf_id))
p_result_set = self.redis_client.get(self.redis_query_id_key + query_id)
result_set = pickle.loads(p_result_set)
# Following lines are only for supporting the mockup data
result_set.query_ID = query_id
result_set.query_instance["query_ID"] = query_id
return result_set | [
"[email protected]"
] | |
156d38260734364e09599d002e1d41c6032814f4 | 4a78cc73d515226b74c274444eaf21052819a80e | /program/quadratic_eqn.py | 2955bf5f9f5a758cbf1b9bd872fcb7df3ce07358 | [] | no_license | jai-singhal/test_case_gen | bfb291b3cbbe41b721e5875b0ab0d7c88976ab0f | a2a102d5c4a415a180d35774ae793294f6209c32 | refs/heads/master | 2023-01-30T14:27:48.513266 | 2020-12-15T14:12:36 | 2020-12-15T14:12:36 | 321,667,556 | 11 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,405 | py | from model.graph import Graph
from model.chromosome import Chromosome
from model.paths import Paths
from model.path import Path
from math import sqrt
import logging
import logging.handlers
import os
handler = logging.handlers.WatchedFileHandler(os.environ.get("LOGFILE", "logs/quadratic.log"))
formatter = logging.Formatter(logging.BASIC_FORMAT)
handler.setFormatter(formatter)
root = logging.getLogger()
root.setLevel(os.environ.get("LOGLEVEL", "INFO"))
root.addHandler(handler)
class QuadraticEquationProgram:
def __init__(self):
self.complexity = 4
self.numberOfInputVariables = 3
self.range = 30
self.cfg = self.create_cfg()
self.cfgRoot = self.cfg.getNode(1)
self.cfg_end_node = self.cfg .getNode(15)
self.decisionTree = self.createDecisionTree()
self.decisionTreeRoot = self.decisionTree.getNode(1)
self.decisionTreePaths = self.decisionTreePathGeneration()
self.leaves = self.getLeaves()
def create_cfg(self):
cfg = Graph()
for lineNumber in range(1, 16):
cfg.newNode(lineNumber)
cfg.getNode(1).add_true_cond_node(cfg.getNode(2))
cfg.getNode(2).add_true_cond_node(cfg.getNode(3))
cfg.getNode(2).add_false_cond_node(cfg.getNode(4))
cfg.getNode(3).add_true_cond_node(cfg.getNode(15))
cfg.getNode(4).add_true_cond_node(cfg.getNode(5))
cfg.getNode(5).add_true_cond_node(cfg.getNode(6))
cfg.getNode(6).add_true_cond_node(cfg.getNode(7))
cfg.getNode(6).add_false_cond_node(cfg.getNode(8))
cfg.getNode(7).add_true_cond_node(cfg.getNode(14))
cfg.getNode(8).add_true_cond_node(cfg.getNode(9))
cfg.getNode(9).add_true_cond_node(cfg.getNode(10))
cfg.getNode(9).add_false_cond_node(cfg.getNode(11))
cfg.getNode(10).add_true_cond_node(cfg.getNode(13))
cfg.getNode(11).add_true_cond_node(cfg.getNode(12))
cfg.getNode(12).add_true_cond_node(cfg.getNode(13))
cfg.getNode(13).add_true_cond_node(cfg.getNode(14))
cfg.getNode(14).add_true_cond_node(cfg.getNode(15))
return cfg
def program(self, paths, variables):
A, B, C = variables[0], variables[1], variables[2]
discrimator = B**2 - 4*A*C
denominator = 2*A
if (A == 0):
return (paths.getPathNumberHavingNode(3))
else:
if (discrimator == 0):
logging.info("THE ROOTS ARE REPEATED ROOTS")
root1 = ((-1)*B)/denominator
logging.info("roots of given equation are: {} {}".format(root1, root1))
return (paths.getPathNumberHavingNode(7))
else:
if (discrimator > 0):
logging.info("THE ROOTS ARE REAL ROOTS")
root1 = ((-1)*B)/denominator + sqrt(discrimator)/denominator
root2 = ((-1)*B)/denominator - sqrt(discrimator)/denominator
logging.info("roots of given equation are: {} {}".format(root1, root2))
return (paths.getPathNumberHavingNode(10))
else:
logging.info("THE ROOTS ARE IMAGINARY ROOTS")
return (paths.getPathNumberHavingNode(12))
def getLeafByEvaluation(self, chromosome):
a = chromosome.realData.get(0).intValue()
b = chromosome.realData.get(1).intValue()
c = chromosome.realData.get(2).intValue()
d = 0
d = (b * b) - (4 * a * c)
if (a == 0):
return 3
else:
if (d == 0):
return 7
else:
if (d > 0):
return 10
else:
return 12
def createDecisionTree(self):
dtree = Graph()
for i in range(1, 16):
dtree.newNode(i)
dtree.getNode(1).add_true_cond_node(dtree.getNode(2))
dtree.getNode(2).add_true_cond_node(dtree.getNode(3))
dtree.getNode(2).add_neutral_cond_node(dtree.getNode(15))
dtree.getNode(2).add_false_cond_node(dtree.getNode(4))
dtree.getNode(4).add_true_cond_node(dtree.getNode(5))
dtree.getNode(5).add_true_cond_node(dtree.getNode(6))
dtree.getNode(6).add_true_cond_node(dtree.getNode(7))
dtree.getNode(6).add_neutral_cond_node(dtree.getNode(14))
dtree.getNode(6).add_false_cond_node(dtree.getNode(8))
dtree.getNode(8).add_true_cond_node(dtree.getNode(9))
dtree.getNode(9).add_true_cond_node(dtree.getNode(10))
dtree.getNode(9).add_neutral_cond_node(dtree.getNode(13))
dtree.getNode(9).add_false_cond_node(dtree.getNode(11))
dtree.getNode(11).add_true_cond_node(dtree.getNode(12))
return dtree
def decisionTreePathGeneration(self):
decisionTreePaths = Paths()
newPath = Path()
newPath.addNode(self.decisionTree.getNode(1))
newPath.addNode(self.decisionTree.getNode(2))
newPath.addNode(self.decisionTree.getNode(3))
decisionTreePaths.addPath(newPath)
newPath = Path()
newPath.addNode(self.decisionTree.getNode(1))
newPath.addNode(self.decisionTree.getNode(2))
newPath.addNode(self.decisionTree.getNode(15))
decisionTreePaths.addPath(newPath)
newPath = Path()
newPath.addNode(self.decisionTree.getNode(1))
newPath.addNode(self.decisionTree.getNode(2))
newPath.addNode(self.decisionTree.getNode(3))
newPath.addNode(self.decisionTree.getNode(4))
newPath.addNode(self.decisionTree.getNode(5))
newPath.addNode(self.decisionTree.getNode(6))
newPath.addNode(self.decisionTree.getNode(7))
decisionTreePaths.addPath(newPath)
newPath = Path()
newPath.addNode(self.decisionTree.getNode(1))
newPath.addNode(self.decisionTree.getNode(2))
newPath.addNode(self.decisionTree.getNode(3))
newPath.addNode(self.decisionTree.getNode(4))
newPath.addNode(self.decisionTree.getNode(5))
newPath.addNode(self.decisionTree.getNode(6))
newPath.addNode(self.decisionTree.getNode(14))
decisionTreePaths.addPath(newPath)
newPath = Path()
newPath.addNode(self.decisionTree.getNode(1))
newPath.addNode(self.decisionTree.getNode(2))
newPath.addNode(self.decisionTree.getNode(3))
newPath.addNode(self.decisionTree.getNode(4))
newPath.addNode(self.decisionTree.getNode(5))
newPath.addNode(self.decisionTree.getNode(6))
newPath.addNode(self.decisionTree.getNode(8))
newPath.addNode(self.decisionTree.getNode(9))
newPath.addNode(self.decisionTree.getNode(10))
decisionTreePaths.addPath(newPath)
newPath = Path()
newPath.addNode(self.decisionTree.getNode(1))
newPath.addNode(self.decisionTree.getNode(2))
newPath.addNode(self.decisionTree.getNode(3))
newPath.addNode(self.decisionTree.getNode(4))
newPath.addNode(self.decisionTree.getNode(5))
newPath.addNode(self.decisionTree.getNode(6))
newPath.addNode(self.decisionTree.getNode(8))
newPath.addNode(self.decisionTree.getNode(9))
newPath.addNode(self.decisionTree.getNode(13))
decisionTreePaths.addPath(newPath)
newPath = Path()
newPath.addNode(self.decisionTree.getNode(1))
newPath.addNode(self.decisionTree.getNode(2))
newPath.addNode(self.decisionTree.getNode(3))
newPath.addNode(self.decisionTree.getNode(4))
newPath.addNode(self.decisionTree.getNode(5))
newPath.addNode(self.decisionTree.getNode(6))
newPath.addNode(self.decisionTree.getNode(8))
newPath.addNode(self.decisionTree.getNode(9))
newPath.addNode(self.decisionTree.getNode(11))
newPath.addNode(self.decisionTree.getNode(12))
decisionTreePaths.addPath(newPath)
return decisionTreePaths
def getLeaves(self):
leaves = list()
leaves.append(self.decisionTree.getNode(3))
leaves.append(self.decisionTree.getNode(7))
leaves.append(self.decisionTree.getNode(10))
leaves.append(self.decisionTree.getNode(12))
leaves.append(self.decisionTree.getNode(13))
leaves.append(self.decisionTree.getNode(14))
leaves.append(self.decisionTree.getNode(15))
return leaves
| [
"[email protected]"
] | |
2546e39b763ccbbb1261c64dc52b2e08d7bbb98a | 2d34a6033884b22e41588c82ebe657546aef07c7 | /project/blog/models.py | bd36137f7fcbaa6e71aa0e0c0466252f28047d4d | [] | no_license | alifanov/jbm_boilerplate | 73c6c5f394f20a851e860328847d2ac45a174d6f | 7012885dbf1455c2ca2abf849bd36685c4a58286 | refs/heads/master | 2020-04-03T16:18:35.760013 | 2018-11-21T09:48:11 | 2018-11-21T09:48:11 | 155,399,665 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,531 | py | from django.db import models
from django.dispatch import receiver
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
class TimeItem(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Tag(models.Model):
name = models.CharField(max_length=30)
class Meta:
ordering = ["name"]
class Post(TimeItem):
title = models.CharField(max_length=255)
text = models.TextField()
tags = models.ManyToManyField(Tag, blank=True)
class Meta:
ordering = ["-updated_at"]
def send_msg_to_ws(text):
layer = get_channel_layer()
async_to_sync(layer.group_send)(
"notifications", {"type": "receive.json", "content": {"msg": text}}
)
@receiver(models.signals.post_save, sender=Post, weak=False)
def post_created_handler(sender, instance, created, *args, **kwargs):
if created:
send_msg_to_ws("New post created")
@receiver(models.signals.post_delete, sender=Post, weak=False)
def post_removed_handler(sender, instance, *args, **kwargs):
send_msg_to_ws("Post deleted")
@receiver(models.signals.post_save, sender=Tag, weak=False)
def tag_created_handler(sender, instance, created, *args, **kwargs):
if created:
send_msg_to_ws("New tag created")
@receiver(models.signals.post_delete, sender=Tag, weak=False)
def tag_removed_handler(sender, instance, *args, **kwargs):
send_msg_to_ws("Tag deleted")
| [
"[email protected]"
] | |
b727cabcd9bd3806c071a7cd260842269b8aba0a | fa7e75212e9f536eed7a78237a5fa9a4021a206b | /MASIR/python/masir/utils/webprivacy_gather.py | 1cc02f6f1aa6fb7dd5e9c09160e708d3db64575e | [] | no_license | kod3r/SMQTK | 3d40730c956220a3d9bb02aef65edc8493bbf527 | c128e8ca38c679ee37901551f4cc021cc43d00e6 | refs/heads/master | 2020-12-03T09:12:41.163643 | 2015-10-19T14:56:55 | 2015-10-19T14:56:55 | 44,916,678 | 1 | 0 | null | 2015-10-25T15:47:35 | 2015-10-25T15:47:35 | null | UTF-8 | Python | false | false | 2,728 | py | # coding=utf-8
import bson
import datetime
import logging
import os
import urllib2
from masir.utils.SimpleBoundingBox import SimpleBoundingBox
def wp_gather_image_and_info(output_dir, db_collection, region_bbox):
"""
Gather the imagery and metadata (as BSON) from the webprivacy database to an
output directory given date and region constraints.
:param output_dir: Directory to write files
:type output_dir: str
:param db_collection: pymongo database collection object
:type db_collection: pymongo.collection.Collection
:param region_bbox: Geographic region constraint.
:type region_bbox: SimpleBoundingBox
"""
log = logging.getLogger('gather_tweet_image_and_info')
if not os.path.exists(output_dir):
os.makedirs(output_dir)
log.info("Performing Query")
after = datetime.datetime(2014, 2, 1)
q = db_collection.find({
"$and": [
{"media": {"$gt": {"$size": 0}}},
{"media.0.type": "photo"},
{"created": {"$gte": after}},
{"geo.0": {"$gte": region_bbox.min_x, "$lte": region_bbox.max_x}},
{"geo.1": {"$gte": region_bbox.min_y, "$lte": region_bbox.max_y}},
]
}, timeout=False)
log.info("Scanning results")
count = 0
try:
for i, e in enumerate(q):
log.info("[%9d] %s -> %s %s", i, e['_id'], e['geo'],
e['media'][0]['media_url'])
media_path = e['media'][0]['media_url']
media_filetype = os.path.splitext(media_path)[1]
output_image = os.path.join(output_dir, str(e['_id']) + media_filetype)
output_bson = os.path.join(output_dir, str(e['_id']) + ".bson")
try:
with open(output_image, 'wb') as output_image_file:
output_image_file.write(urllib2.urlopen(media_path).read())
with open(output_bson, 'wb') as output_md_file:
output_md_file.write(bson.BSON.encode(e))
count += 1
except Exception, ex:
# Skip all files that cause errors anywhere. Remove anything
# written
log.info(" - ERROR: %s", str(ex))
log.info(" - Skipping")
if os.path.exists(output_image):
os.remove(output_image)
if os.path.exists(output_bson):
os.remove(output_bson)
finally:
# Since we checked out a cursor without a server-side timeout, make sure
# that we catch whatever and close the cursor when we're done / if
# things fail.
q.close()
log.info("Discovered %d matching entries with valid images.", count) | [
"[email protected]"
] | |
e1dee49a14067807a2a659197ce76a63a98252dd | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/40/usersdata/68/19112/submittedfiles/funcoes.py | ba6a46880a5b2a250478615ce64169b4cf2b8ded | [] | 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 | 1,018 | py | # -*- coding: utf-8 -*-
from __future__ import division
#Fatorial
def fatorial (m):
m_fat=1
for i in range (2,m+1,1):
m_fat=m_fat * i
return m_fat
#Pi
def calculaPi (m):
soma_pi=0
j=2
for i in range (0,m,1):
if i%2==0:
soma_pi=soma_pi+(4/(j*(j+1)*(j+2)))
else:
soma_pi=soma_pi-(4/(j*(j+1)*(j+2)))
j=j+2
pi=3+soma_pi
return pi
#Cosseno
def calculaCosseno (e):
soma_cosseno=0
i=1
j=2
a=(e**j)/fatorial(j) #TINHA UM ERRO AQUI <-------------------- ERRO
print ("primeiro a: %.4f" %a)
while a>e:
a=(e**j)/fatorial(j) # <-------------- TEM Q CALCULAR UM NOVO VALOR DE a A CADA REPETIÇÃO
if i%2!=0:
soma_cosseno=soma_cosseno-a
else:
soma_cosseno=soma_cosseno+a
j=j+2
i=i+1
print soma_cosseno
cosseno=1-soma_cosseno
return cosseno
#RazaoAurea
def calculaRazaoAurea (cosseno):
razaoAurea= 2*cosseno
return razaoAurea | [
"[email protected]"
] | |
d2807766442c8de2ee23a2b0a79a5f75b3617f38 | c98b383eeef0e7c12504270fe92071569fec9736 | /testMe/testone/tests.py | 24714ddf88517e0cfc1a201200d9e36cd5ef85fd | [
"MIT"
] | permissive | MyHiHi/test | 088048117346b81f7c51fadc00cce4d3f21496ac | 0cedfbbfad53021569faef933b9fdff20e897617 | refs/heads/master | 2020-03-09T02:10:03.949154 | 2019-06-12T09:44:42 | 2019-06-12T09:44:42 | 128,533,935 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,163 | py | from django.test import TestCase
import requests
def get_json(url):
headers = {
"Host": "www.lagou.com",
"Connection": "keep-alive",
"Origin": "https://www.lagou.com",
"X-Anit-Forge-Code": "0",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept": "application/json, text/javascript, */*; q=0.01",
"X-Requested-With": "XMLHttpRequest",
"X-Anit-Forge-Token": None,
"Referer": "https://www.lagou.com/jobs/list_%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90?labelWords=&fromSearch=true&suginput=",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
}
params={
"needAddtionalResult": "false"
}
data={
"first": "true",
"pn": "1",
"kd": "数据分析"
}
res=requests.post(url,headers=headers,data=data)
res.encoding='utf-8'
return res.json()
url='https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false'
data=get_json(url)
print(data) | [
"[email protected]"
] | |
6d5d099a2907453a5c13a6219c0d42b982c456a3 | 480e33f95eec2e471c563d4c0661784c92396368 | /CondTools/Ecal/python/copyTrivial_orcoff_LaserOnly.py | f1755f2e56183685dce9bf8a0127949e8bcbb272 | [
"Apache-2.0"
] | permissive | cms-nanoAOD/cmssw | 4d836e5b76ae5075c232de5e062d286e2026e8bd | 4eccb8a758b605875003124dd55ea58552b86af1 | refs/heads/master-cmsswmaster | 2021-01-23T21:19:52.295420 | 2020-08-27T08:01:20 | 2020-08-27T08:01:20 | 102,867,729 | 7 | 14 | Apache-2.0 | 2022-05-23T07:58:09 | 2017-09-08T14:03:57 | C++ | UTF-8 | Python | false | false | 2,360 | py | import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("CalibCalorimetry.EcalTrivialCondModules.EcalTrivialCondRetriever_cfi")
process.EcalTrivialConditionRetriever.laserAPDPNTime1 = cms.untracked.string('0')
process.EcalTrivialConditionRetriever.laserAPDPNTime2 = cms.untracked.string('1')
process.EcalTrivialConditionRetriever.laserAPDPNTime3 = cms.untracked.string('2')
process.load("CondCore.DBCommon.CondDBCommon_cfi")
#process.CondDBCommon.connect = 'oracle://cms_orcoff_prep/CMS_COND_ECAL'
process.CondDBCommon.DBParameters.authenticationPath = '/afs/cern.ch/cms/DB/conddb/'
process.CondDBCommon.connect = 'sqlite_file:DB.db'
process.MessageLogger = cms.Service("MessageLogger",
debugModules = cms.untracked.vstring('*'),
destinations = cms.untracked.vstring('cout')
)
process.source = cms.Source("EmptyIOVSource",
firstValue = cms.uint64(1),
lastValue = cms.uint64(1),
timetype = cms.string('runnumber'),
interval = cms.uint64(1)
)
# timetype = cms.untracked.string('timestamp'),
process.PoolDBOutputService = cms.Service("PoolDBOutputService",
process.CondDBCommon,
timetype = cms.untracked.string('timestamp'),
toPut = cms.VPSet(
cms.PSet(
record = cms.string('EcalLaserAlphasRcd'),
tag = cms.string('EcalLaserAlphas_mc')
),
cms.PSet(
record = cms.string('EcalLaserAPDPNRatiosRcd'),
tag = cms.string('EcalLaserAPDPNRatios_mc')
),
cms.PSet(
record = cms.string('EcalLaserAPDPNRatiosRefRcd'),
tag = cms.string('EcalLaserAPDPNRatiosRef_mc')
))
)
# timetype = cms.string('timestamp'),
process.dbCopy = cms.EDAnalyzer("EcalDBCopy",
timetype = cms.string('timestamp'),
toCopy = cms.VPSet(
cms.PSet(
record = cms.string('EcalLaserAlphasRcd'),
container = cms.string('EcalLaserAlphas')
),
cms.PSet(
record = cms.string('EcalLaserAPDPNRatiosRcd'),
container = cms.string('EcalLaserAPDPNRatios')
),
cms.PSet(
record = cms.string('EcalLaserAPDPNRatiosRefRcd'),
container = cms.string('EcalLaserAPDPNRatiosRef')
))
)
process.prod = cms.EDAnalyzer("EcalTrivialObjectAnalyzer")
process.p = cms.Path(process.prod*process.dbCopy)
| [
"[email protected]"
] | |
3c2e2d353cbbce71f6839c272c8aec8f4b16215a | 76e931912629c37beedf7c9b112b53e7de5babd7 | /3-mouth04/day03/mysite3/bookstore/migrations/0002_auto_20210110_1743.py | 6150a4cd907207df18066c991e6c09691c209a1c | [
"Apache-2.0"
] | permissive | gary-gggggg/gary | c59ac21d8e065f296ff986d11a0e4cbf186a1bc4 | d8ba30ea4bc2b662a2d6a87d247f813e5680d63e | refs/heads/main | 2023-02-23T06:54:34.500683 | 2021-02-01T10:17:02 | 2021-02-01T10:17:02 | 334,905,744 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 623 | py | # Generated by Django 2.2.12 on 2021-01-10 09:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bookstore', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='book',
name='market_price',
field=models.DecimalField(decimal_places=2, default=0.0, max_digits=7, verbose_name='零售价'),
),
migrations.AddField(
model_name='book',
name='pub',
field=models.CharField(default='', max_length=50, verbose_name='出版社'),
),
]
| [
"[email protected]"
] | |
d348aca8174320a1d59058b5bb76e9b425f38c2d | eed93ecbb01acb180085bed4960a4b2fd4a2322d | /wishbook/models.py | 372decb65cb08595289fd1a8658a2716acd51846 | [] | no_license | srakrn/happyearthday | beb8a52cdc73a19b48143e43154feaacf4ac174a | 0da2fd4ac31db1a7df13f12c78c65db641d13794 | refs/heads/master | 2022-05-17T19:33:00.219871 | 2021-06-10T10:24:22 | 2021-06-10T10:24:22 | 254,112,489 | 0 | 1 | null | 2022-04-22T23:22:12 | 2020-04-08T14:33:55 | Python | UTF-8 | Python | false | false | 560 | py | from django import forms
from django.db import models
# Create your models here.
class Wish(models.Model):
wish_text = models.CharField(verbose_name="ข้อความอวยพร", max_length=240)
wish_owner = models.CharField(verbose_name="ชื่อผู้อวยพร", max_length=50)
shown = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "{} from {}".format(
self.wish_text[: min(len(self.wish_text), 10)], self.wish_owner
)
| [
"[email protected]"
] | |
8f452a5b889844be254092881d4a66f1858cb6a7 | ebf4fd9e560fdd3b9b1acd4cdceabd19c70e57a7 | /turq.py | 3caf78e311a17ba14abd777c4c08b7b0a50fb270 | [
"ISC"
] | permissive | pombredanne/turq | a4e7eaab4bb261ec793f4774b1a518becb0d170e | 93cf2992da738b065292afec0444b298529e8db9 | refs/heads/master | 2021-01-15T13:37:06.931538 | 2015-07-21T21:08:29 | 2015-07-21T21:08:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 23,247 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '0.2.0'
import BaseHTTPServer
from cStringIO import StringIO
from datetime import datetime, timedelta
import email.message
import gzip
import httplib
import json
from optparse import OptionParser
import os.path
import random
import re
import socket
import string
import sys
import time
import traceback
import urllib2
import urlparse
DEFAULT_PORT = 13085
class Request(object):
"""An HTTP request.
.. attribute:: method
Request method.
.. attribute:: path
The request path, excluding the query string.
.. attribute:: query
A dictionary of parameters parsed from the query string.
An empty dictionary if none can be parsed.
.. attribute:: headers
An ``rfc822.Message``-like mapping of request headers.
.. attribute:: body
Request entity body as a `str` if there is one, otherwise `None`.
"""
def __init__(self, method, path, query, headers, body):
self.method = method
self.path = path
self.query = query
self.headers = headers
self.body = body
def p(self, x):
if callable(x):
return x(self)
else:
return x
class Response(object):
def __init__(self):
self.status = httplib.OK
self.headers = email.message.Message()
self.body = None
def set_header(self, name, value, **params):
del self.headers[name]
self.headers.add_header(name, value, **params)
def add_header(self, name, value, **params):
self.headers.add_header(name, value, **params)
def make_text(nbytes):
buf = StringIO()
written = 0
words = 'lorem ipsum dolor sit amet, consectetur adipisicing elit'.split()
while written < nbytes:
word = random.choice(words)
buf.write(word)
written += len(word)
if random.random() < 0.01:
buf.write('\n\n')
written += 2
else:
buf.write(' ')
written += 1
return buf.getvalue()
def html_escape(s):
return s.replace('&', '&').replace('"', '"'). \
replace('<', '<').replace('>', '>')
class Cheat(object):
items = []
@staticmethod
def entry(args='', comment=''):
def decorator(func):
Cheat.items.append((func.__name__, args, comment))
return func
return decorator
@staticmethod
def format():
code = (
'<p><code class="example">path(\'/products/*\').delay(1).html().'
'cookie(\'sessionid\', \'1234\', max_age=3600)</code></p>'
'<table><tbody>'
)
for name, args, comment in Cheat.items:
code += (
'<tr><th><code>%s(<span class="args">%s</span>)</code></th>'
'<td>%s</td></tr>' % (name, html_escape(args), comment)
)
code += '</tbody></table>'
return code
class Rule(object):
url_cache = {}
def __init__(self):
self._status = None
# Headers are tricky.
# We just store a sequence of (operation, name, value, params) tuples,
# a patch of sorts, and then apply this patch.
# Operation can be "set" (replacing) or "add".
self._headers = []
self._body = None
self._processor = None
self._delay = None
self._chain = []
self._final = None
self._counter = 0
self._maybe = []
self._enable_cors = False
self._allow = None
self._gzip = False
@Cheat.entry('code')
def status(self, code):
"""Set response status to `code`."""
self._status = code
return self
@Cheat.entry('name, value, **params', 'params are appended as k=v pairs')
def header(self, name, value, **params):
"""Set response header `name` to `value`.
If `params` are specified, they are appended as k=v pairs.
For example::
header('Content-Type', 'text/html', charset='utf-8')
produces::
Content-Type: text/html; charset="utf-8"
"""
self._headers.append(('set', name, value, params))
return self
@Cheat.entry('name, value, **params', 'added, not replaced')
def add_header(self, name, value, **params):
"""Same as :meth:`~Rule.header`, but add the header, not replace it.
This can be used to send multiple headers with the same name,
such as ``Via`` or ``Set-Cookie``
(but for the latter see :meth:`~Rule.cookie`).
"""
self._headers.append(('add', name, value, params))
return self
@Cheat.entry('data')
def body(self, data):
"""Set response entity body to `data`."""
self._body = data
return self
@Cheat.entry('path')
def body_file(self, path):
"""Set response entity body to the contents of `path`.
The file at `path` is read when the rules are posted.
`path` undergoes tilde expansion.
"""
return self.body(open(os.path.expanduser(path)).read())
@Cheat.entry('url', 'data from <var>url</var> is cached until Turq exits')
def body_url(self, url):
"""Set response entity body to the contents of `url`.
The resource at `url` is fetched once and cached until Turq exits.
Note that this method only sets the entity body.
HTTP status and headers are not copied from `url`.
"""
if url not in Rule.url_cache:
Rule.url_cache[url] = urllib2.urlopen(url).read()
return self.body(Rule.url_cache[url])
@Cheat.entry('seconds')
def delay(self, seconds):
"""Delay for `seconds` before serving the response."""
self._delay = seconds
return self
def __call__(self, proc):
self._processor = proc
return proc
@Cheat.entry('mime_type', 'content type')
def ctype(self, value):
"""Set response ``Content-Type`` to `value`."""
return self.header('Content-Type', value)
@Cheat.entry('[text]', 'plain text')
def text(self, text='Hello world!'):
"""Set up a ``text/plain`` response."""
return self.ctype('text/plain; charset=utf-8').body(text)
@Cheat.entry('[nbytes]', 'roughly <var>nbytes</var> of plain text')
def lots_of_text(self, nbytes=20000):
"""Set up a ``text/plain`` response with lots of text.
Lines of dummy text will be generated
so that the entity body is very roughly `nbytes` in length.
"""
return self.text(make_text(nbytes))
@Cheat.entry('[title], [text]', 'basic HTML page')
def html(self, title='Hello world!', text='This is Turq!'):
"""Set up a ``text/html`` response.
A basic HTML page with `title` and a paragraph of `text` is served.
"""
return self.ctype('text/html; charset=utf-8').body(lambda req: (
'''<!DOCTYPE html>
<html>
<head>
<title>%s</title>
</head>
<body>
<h1>%s</h1>
<p>%s</p>
</body>
</html>''' % (req.p(title), req.p(title), req.p(text))
))
@Cheat.entry('[nbytes]', 'roughly <var>nbytes</var> of HTML')
def lots_of_html(self, nbytes=20000, title='Hello world!'):
"""Set up a ``text/html`` response with lots of text.
Like :meth:`~Rule.lots_of_text`, but wrapped in HTML paragraphs.
"""
return self.html(
title=title,
text=make_text(nbytes - 100).replace('\n\n', '</p><p>')
)
@Cheat.entry('[data]',
'JSONP is handled automatically, '
'pass <code>jsonp=False</code> to disable')
def json(self, data={'result': 'turq'}, jsonp=True):
"""Set up a JSON or JSONP response.
`data` will be serialized into an ``application/json`` entity body.
But if the request has a ``callback`` query parameter,
`data` will be wrapped into a JSONP callback
and served as ``application/javascript``,
unless you set `jsonp` to `False`.
"""
self.ctype(lambda req: 'application/javascript'
if jsonp and 'callback' in req.query
else 'application/json')
self.body(lambda req: (
'%s(%s);' % (req.query['callback'], json.dumps(req.p(data)))
if jsonp and 'callback' in req.query
else json.dumps(req.p(data))
))
return self
@Cheat.entry('[code]', 'JavaScript')
def js(self, code='alert("Turq");'):
"""Set up an ``application/javascript`` response."""
return self.ctype('application/javascript').body(code)
@Cheat.entry('[code]')
def xml(self, code='<turq></turq>'):
"""Set up an ``application/xml`` response."""
return self.ctype('application/xml').body(code)
@Cheat.entry('location, [status=302]')
def redirect(self, location, status=httplib.FOUND):
"""Set up a redirection response."""
return self.status(status).header('Location', location)
@Cheat.entry('name, value, [max_age], [path]...')
def cookie(self, name, value, max_age=None, expires=None, path=None,
secure=False, http_only=False):
"""Add a cookie `name` with `value`.
The other arguments
correspond to parameters of the ``Set-Cookie`` header.
If specified, `max_age` and `expires` should be strings.
Nothing is escaped.
"""
def cookie_string(req):
data = '%s=%s' % (req.p(name), req.p(value))
if max_age is not None:
data += '; Max-Age=%s' % req.p(max_age)
if expires is not None:
data += '; Expires=%s' % req.p(expires)
if path is not None:
data += '; Path=%s' % req.p(path)
if secure:
data += '; Secure'
if http_only:
data += '; HttpOnly'
return data
return self.add_header('Set-Cookie', cookie_string)
@Cheat.entry('[realm]')
def basic_auth(self, realm='Turq'):
"""Demand HTTP basic authentication (status code 401)."""
self.status(httplib.UNAUTHORIZED)
self.header('WWW-Authenticate',
lambda req: 'Basic realm="%s"' % req.p(realm))
return self
@Cheat.entry('[realm], [nonce]')
def digest_auth(self, realm='Turq', nonce='twasbrillig'):
"""Demand HTTP digest authentication (status code 401)."""
self.status(httplib.UNAUTHORIZED)
self.header(
'WWW-Authenticate',
lambda req: 'Digest realm="%s", nonce="%s"' % (
req.p(realm), req.p(nonce)
)
)
return self
@Cheat.entry('*methods', 'otherwise send 405 with a text error message')
def allow(self, *methods):
"""Check the request method to be one of `methods` (case-insensitive).
If it isn’t, send 405 Method Not Allowed
with a plain-text error message.
"""
self._allow = set(m.lower() for m in methods)
return self
@Cheat.entry()
def cors(self):
"""Enable `CORS <http://www.w3.org/TR/cors/>`_ on the response.
Currently this just sets ``Access-Control-Allow-Origin: *``.
Preflight requests are not yet handled.
"""
self._enable_cors = True
return self.header('Access-Control-Allow-Origin', '*')
@Cheat.entry('when', '“10 minutes” or “5 h” or “1 day”')
def expires(self, when):
"""Set the expiration time of the response.
`when` should be a specification
of the number of minutes, hours or days,
counted from the moment the rules are posted.
Supported formats are: “10 min” or “10 minutes” or “5 h” or “5 hours”
or “1 d” or “1 day”.
"""
n, unit = when.split()
n = int(n)
dt = datetime.utcnow()
if unit in ('minute', 'minutes', 'min'):
dt += timedelta(seconds=(n * 60))
elif unit in ('hour', 'hours', 'h'):
dt += timedelta(seconds=(n * 3600))
elif unit in ('day', 'days', 'd'):
dt += timedelta(days=n)
else:
raise ValueError('unknown expires format: "%s"' % when)
return self.header('Expires', dt.strftime('%a, %d %b %Y %H:%M:%S GMT'))
@Cheat.entry()
def gzip(self):
"""Apply ``Content-Encoding: gzip`` to the entity body.
``Accept-Encoding`` of the request is ignored.
"""
self._gzip = True
return self
@Cheat.entry('', 'begin a sub-rule for the first hit...')
def first(self):
"""Add a sub-rule that will be applied on a first request."""
sub = Rule()
self._chain = [sub]
return sub
@Cheat.entry('', '...the next hit...')
def next(self):
"""Add a sub-rule that will be applied on a subsequent request."""
assert self._chain, 'next() without first()'
sub = Rule()
self._chain.append(sub)
return sub
@Cheat.entry('', '...and all subsequent hits')
def then(self):
"""Add a sub-rule that will be applied on all subsequent requests."""
assert self._chain, 'then() without first()'
self._final = Rule()
return self._final
@Cheat.entry('[probability]', 'start a stochastic sub-rule')
def maybe(self, probability=0.1):
"""Add a sub-rule that will be applied with `probability`."""
assert probability > 0
sub = Rule()
self._maybe.append((sub, probability))
assert sum(p for s, p in self._maybe) <= 1
return sub
@Cheat.entry('', 'complement all <code>maybe</code>s')
def otherwise(self):
"""Add a sub-rule that complements all :meth:`~Rule.maybe` rules.
This is just a shortcut
that adds a `maybe` sub-rule
with a probability equal to 1 minus all currently defined `maybe`.
Thus, it must come after all `maybe`.
"""
return self.maybe(1 - sum(p for s, p in self._maybe))
def __enter__(self):
return self
def __exit__(self, *args):
return False
def apply_normal(self, req, resp):
if self._delay is not None:
time.sleep(req.p(self._delay))
if self._status is not None:
resp.status = req.p(self._status)
if self._body is not None:
resp.body = req.p(self._body)
def apply_headers(self, req, resp):
for op, name, value, params in self._headers:
if op == 'set':
resp.set_header(req.p(name), req.p(value), **params)
elif op == 'add':
resp.add_header(req.p(name), req.p(value), **params)
def apply_chain(self, req, resp):
if self._counter >= len(self._chain):
if self._final is not None:
self._final.apply(req, resp)
else:
self._counter = 0
if self._counter < len(self._chain):
self._chain[self._counter].apply(req, resp)
self._counter += 1
def apply_maybe(self, req, resp):
x = random.random()
pos = 0
for sub, prob in self._maybe:
pos += prob
if x < pos:
sub.apply(req, resp)
return
def apply_processor(self, req, resp):
if self._processor is not None:
sub = Rule()
self._processor(req, sub)
sub.apply(req, resp)
def apply_allow(self, req, resp):
if self._allow is not None:
if req.method.lower() not in self._allow:
resp.status = httplib.METHOD_NOT_ALLOWED
resp.set_header('Content-Type', 'text/plain')
resp.body = 'Method %s not allowed here' % req.method
def apply_gzip(self, req, resp):
if self._gzip and resp.body:
zbuf = StringIO()
zfile = gzip.GzipFile(fileobj=zbuf, mode='w')
zfile.write(resp.body)
zfile.close()
resp.body = zbuf.getvalue()
resp.set_header('Content-Encoding', 'gzip')
def apply(self, req, resp):
self.apply_normal(req, resp)
self.apply_headers(req, resp)
self.apply_chain(req, resp)
self.apply_maybe(req, resp)
self.apply_allow(req, resp)
self.apply_gzip(req, resp)
self.apply_processor(req, resp)
class PathRule(Rule):
def __init__(self, path='*', trailing_slash=True):
self.regex = re.compile(
'^' + re.escape(path).replace('\\*', '.*') +
('/?' if trailing_slash else '') + '$')
super(PathRule, self).__init__()
def matches(self, req):
return bool(self.regex.search(req.path))
def parse_rules(code):
rules = []
def path(*args, **kwargs):
rule = PathRule(*args, **kwargs)
rules.append(rule)
return rule
exec code in {'path': path}
return rules
CONSOLE_TPL = string.Template('''
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Turq</title>
<script type="text/javascript">
window.onload = function() {
window.setTimeout(function() {
document.getElementById('okay').innerText = '';
}, 2000);
document.getElementById('codeEntry').focus();
};
</script>
<style type="text/css">
body { margin: 2em; font-family: sans-serif; }
#error { color: #FF0000; }
#okay { color: #0E7C00; }
#codeEntry { width: 55%; }
.example { font-weight: bold; }
#cheat {
float: right;
margin-left: 3em;
width: 40%;
padding-bottom: 3em;
}
#cheat th {
text-align: left;
padding-right: 0.5em;
}
#cheat th .args { font-weight: normal; }
#cheat td, th {
border-top: solid 1px #D8D8D8;
padding-top: 0.3em;
padding-bottom: 0.3em;
}
#cheat table { border-collapse: collapse; }
</style>
</head>
<body>
<div id="cheat">
<h2>Cheat sheet</h2>
$cheat
</div>
<h1>Turq</h1>
<pre id="error">$error</pre>
<form action="/+turq/" method="post">
<div>
<pre><textarea id="codeEntry" name="code"
rows="25" cols="80">$code</textarea></pre>
</div>
<div>
<input type="submit" value="Commit" accesskey="s">
<span id="okay">$okay</span>
</div>
</form>
<p>
<a href="https://github.com/vfaronov/turq">Turq</a> $version ·
<a href="https://turq.readthedocs.org/">docs</a>
</p>
</body>
</html>
''')
def render_console(code, okay='', error=''):
return CONSOLE_TPL.substitute(code=code, okay=okay, error=error,
cheat=Cheat.format(), version=__version__)
class TurqHandler(BaseHTTPServer.BaseHTTPRequestHandler):
code = ''
rules = []
@classmethod
def install_code(cls, code):
cls.code = code
cls.rules = parse_rules(code)
def __getattr__(self, attr):
if attr.startswith('do_'):
return lambda: self.do(attr[3:])
@property
def path_without_query(self):
return self.path.split('?')[0]
@property
def query(self):
parts = self.path.split('?')
if len(parts) > 1:
q = parts[1]
try:
q = urlparse.parse_qs(q)
except Exception:
q = urlparse.parse_qs('') # so it's still iterable
else:
q = urlparse.parse_qs('')
return dict((k, v[0]) for k, v in q.items())
@property
def body(self):
if 'Content-Length' in self.headers:
return self.rfile.read(int(self.headers['Content-Length']))
def do(self, method):
if self.path_without_query == '/+turq/':
self.do_console(method)
else:
self.do_mock(method)
def parse_form(self):
return urlparse.parse_qs(self.body)
def version_string(self):
return 'Turq/%s' % __version__
def do_console(self, method):
okay = error = ''
if method == 'POST':
try:
form = self.parse_form()
code = form.get('code', [''])[0].replace('\r\n', '\n')
self.install_code(code)
sys.stderr.write('--- New rules posted and activated ---\n')
okay = 'okay'
except Exception:
error = traceback.format_exc()
self.send_response(httplib.OK)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write(render_console(self.code, okay, error))
def do_mock(self, method):
req = Request(method, self.path_without_query, self.query,
self.headers, self.body)
resp = Response()
for rule in self.rules:
if rule.matches(req):
rule.apply(req, resp)
# Server and Date headers need special casing
if 'Server' in resp.headers:
self.version_string = lambda *args: resp.headers['Server']
if 'Date' in resp.headers:
self.date_time_string = lambda *args: resp.headers['Date']
self.send_response(resp.status)
for name, value in resp.headers.items():
if name.lower() not in ('server', 'date'):
self.send_header(name, value)
self.end_headers()
if resp.body and (method != 'HEAD'):
self.wfile.write(resp.body)
def main():
parser = OptionParser(usage='usage: %prog [-p PORT]')
parser.add_option('-p', '--port', dest='port', type='int',
default=DEFAULT_PORT,
help='listen on PORT', metavar='PORT')
options, args = parser.parse_args()
server = BaseHTTPServer.HTTPServer(('0.0.0.0', options.port), TurqHandler)
sys.stderr.write('Listening on port %d\n' % server.server_port)
sys.stderr.write('Try http://%s:%d/+turq/\n' %
(socket.getfqdn(), server.server_port))
try:
server.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
b86f4f23f1d96b44ef062edd59adb901d53cf7c7 | 3d7039903da398ae128e43c7d8c9662fda77fbdf | /database/面试/juejin_446.py | ada41a6791b155b757cb4bc67b7cc653b73bf8d7 | [] | no_license | ChenYongChang1/spider_study | a9aa22e6ed986193bf546bb567712876c7be5e15 | fe5fbc1a5562ff19c70351303997d3df3af690db | refs/heads/master | 2023-08-05T10:43:11.019178 | 2021-09-18T01:30:22 | 2021-09-18T01:30:22 | 406,727,214 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 70,312 | py | {"err_no": 0, "err_msg": "success", "data": [{"article_id": "6844904081828347912", "article_info": {"article_id": "6844904081828347912", "user_id": "1556564164489389", "category_id": "6809637767543259144", "tag_ids": [6809640402103042061, 6809640404791590919], "visible_level": 0, "link_url": "https://juejin.im/post/6844904081828347912", "cover_image": "", "is_gfw": 0, "title": "艰难一年经验美团前端面经分享", "brief_content": "我在 github 上新建了一个仓库 每日一题,每天一道面试题,欢迎交流。 时维七月,炎炎夏日,酷暑当头,而我已经在望京附近饶了半个小时。无论是天气,还是对于迟到以及面试的焦虑,都足以使我满头大汗了。 今天要去赶一个美团的面试,我恰好住在三元桥附近,查了地图离望京不太远,于是我…", "is_english": 0, "is_original": 1, "user_index": 11.011899064539, "original_type": 0, "original_author": "", "content": "", "ctime": "1583373068", "mtime": "1598849200", "rtime": "1583373068", "draft_id": "6845076659595378702", "view_count": 10103, "collect_count": 204, "digg_count": 133, "comment_count": 37, "hot_index": 675, "is_hot": 0, "rank_index": 0.002953, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1556564164489389", "user_name": "shanyue", "company": "", "job_title": "微信:shanyue94", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bdfecd06f90e24f88946.jpeg~tplv-t2oaga2asx-image.image", "level": 5, "description": "", "followee_count": 74, "follower_count": 15383, "post_article_count": 175, "digg_article_count": 540, "got_digg_count": 10096, "got_view_count": 515432, "post_shortmsg_count": 8, "digg_shortmsg_count": 28, "isfollowed": false, "favorable_author": 0, "power": 12342, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546522, "tag_id": "6809640402103042061", "tag_name": "前端框架", "color": "#F2AB5B", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/f7a198f1e1aeb6d79878.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435964339, "mtime": 1631690383, "id_type": 9, "tag_alias": "", "post_article_count": 4037, "concern_user_count": 256973}, {"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6844904081828347912, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6844903781704941576", "article_info": {"article_id": "6844903781704941576", "user_id": "2365804752420632", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "https://juejin.im/post/6844903781704941576", "cover_image": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/2/22/16912a1b4c3f0611~tplv-t2oaga2asx-image.image", "is_gfw": 0, "title": "前端面试查漏补缺--(十) 前端鉴权", "brief_content": "本系列最开始是为了自己面试准备的.后来发现整理越来越多,差不多有十二万字符,最后决定还是分享出来给大家. 这种认证方式是浏览器遵守http协议实现的基本授权方式,HTTP协议进行通信的过程中,HTTP协议定义了基本认证认证允许HTTP服务器对客户端进行用户身份证的方法。 目前基…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1550894808", "mtime": "1599811389", "rtime": "1551065611", "draft_id": "6845076182086451207", "view_count": 19576, "collect_count": 537, "digg_count": 333, "comment_count": 18, "hot_index": 1329, "is_hot": 0, "rank_index": 0.00293947, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2365804752420632", "user_name": "shotCat", "company": "某操作系统OS", "job_title": "高级前端攻城狮", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/2/19/169032066a8218fd~tplv-t2oaga2asx-image.image", "level": 4, "description": "E:[email protected] Born in nature.Born in free", "followee_count": 5, "follower_count": 2683, "post_article_count": 26, "digg_article_count": 362, "got_digg_count": 3581, "got_view_count": 237057, "post_shortmsg_count": 65, "digg_shortmsg_count": 195, "isfollowed": false, "favorable_author": 1, "power": 5951, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6844903781704941576, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6844904151013392398", "article_info": {"article_id": "6844904151013392398", "user_id": "1679709494854135", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "https://juejin.im/post/6844904151013392398", "cover_image": "", "is_gfw": 0, "title": "拼多多和酷家乐面试经历总结", "brief_content": "离职原因看我这篇文章吧:离开蘑菇街后,我最近的一些想法,然后不得不去找工作恰饭呀。 我目前面了五家公司:滴滴、蚂蚁、拼多多、酷家乐、字节跳动,拼多多和酷家乐基本已拿到 offer,蚂蚁二面完了,滴滴和字节即将三面,我先把我已经面过的面经先总结出来,其他的不管过没过,这周内我都会…", "is_english": 0, "is_original": 1, "user_index": 1.1437616971521, "original_type": 0, "original_author": "", "content": "", "ctime": "1588922632", "mtime": "1598953976", "rtime": "1588922632", "draft_id": "6845076765220536328", "view_count": 8677, "collect_count": 184, "digg_count": 125, "comment_count": 23, "hot_index": 581, "is_hot": 0, "rank_index": 0.00293715, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1679709494854135", "user_name": "桃翁", "company": "蚂蚁金服", "job_title": "前端打杂", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/e2555e88f5dc4323d23567f7e1010c09~300x300.image", "level": 4, "description": "", "followee_count": 40, "follower_count": 7531, "post_article_count": 37, "digg_article_count": 333, "got_digg_count": 3886, "got_view_count": 182486, "post_shortmsg_count": 10, "digg_shortmsg_count": 5, "isfollowed": false, "favorable_author": 1, "power": 5694, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6844904151013392398, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6959804920362958879", "article_info": {"article_id": "6959804920362958879", "user_id": "4019470243991799", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919, 6809640398105870343], "visible_level": 0, "link_url": "", "cover_image": "https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/1ac7bcd930f048cf840b76f19b2d744f~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "「敲黑板」JS 类型转换及访问拦截", "brief_content": "前言 面试的时候,你会遇到许多奇奇怪怪的问题。就好像上学的时候,你在数学课本里学习了等边三角形的三个内角都是等于 60 度,你很少能见到卷子里直接问你等边三角形的三个内角是多少度。多数情况下这个知识点", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1620455927", "mtime": "1620465515", "rtime": "1620458738", "draft_id": "6959804422129975327", "view_count": 1424, "collect_count": 14, "digg_count": 22, "comment_count": 9, "hot_index": 102, "is_hot": 0, "rank_index": 0.00292731, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "4019470243991799", "user_name": "尼克陈", "company": "某新媒体工具", "job_title": "全栈开发", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/12/14/16f022d3ac21237a~tplv-t2oaga2asx-image.image", "level": 4, "description": "开源仓库 https://github.com/newbee-ltd,\n掘金小册《Node + React 实战:从 0 到 1 实现记账本》作者。", "followee_count": 5, "follower_count": 1167, "post_article_count": 20, "digg_article_count": 161, "got_digg_count": 5367, "got_view_count": 142415, "post_shortmsg_count": 18, "digg_shortmsg_count": 32, "isfollowed": false, "favorable_author": 1, "power": 6791, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}], "user_interact": {"id": 6959804920362958879, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "7000768485718491167", "article_info": {"article_id": "7000768485718491167", "user_id": "131597123201608", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "前端必刷手写题系列 [23]", "brief_content": "这是我参与8月更文挑战的第24天,活动详情查看:8月更文挑战 33. 手写简单 Vue2.x 响应式原理 分析 首先响应式原理,请看官方文档,说的也是很清晰了,这个图非常好 基本原理就是: 每个组件实", "is_english": 0, "is_original": 1, "user_index": 4.21016839146274, "original_type": 0, "original_author": "", "content": "", "ctime": "1629993585", "mtime": "1630047539", "rtime": "1630047539", "draft_id": "7000759826389139492", "view_count": 74, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 4, "is_hot": 0, "rank_index": 0.00292611, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "131597123201608", "user_name": "文斌大大鸟", "company": "上海某一线", "job_title": "前端", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/6c07fa83b9117fc8e4a207e0c124293d~300x300.image", "level": 2, "description": "怕被说摸鱼,匿了", "followee_count": 163, "follower_count": 160, "post_article_count": 122, "digg_article_count": 139, "got_digg_count": 458, "got_view_count": 22010, "post_shortmsg_count": 2, "digg_shortmsg_count": 1, "isfollowed": false, "favorable_author": 0, "power": 678, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 7000768485718491167, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "7000979623836123166", "article_info": {"article_id": "7000979623836123166", "user_id": "571401775883117", "category_id": "6809637767543259144", "tag_ids": [6809640398105870343, 6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "前端面试之代码输出结果(四)", "brief_content": "这是我参与8月更文挑战的第20天,活动详情查看:8月更文挑战。 Proxy对数组 说明 JS对象和数组属性 说明 Object.getOwnPropertyNames 可以获取对象的属性和原生内置属性", "is_english": 0, "is_original": 1, "user_index": 4.1504567158464, "original_type": 0, "original_author": "", "content": "", "ctime": "1630042687", "mtime": "1630054806", "rtime": "1630054806", "draft_id": "7000977321498771492", "view_count": 61, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 4, "is_hot": 0, "rank_index": 0.00292189, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "571401775883117", "user_name": "馨迤Sine", "company": "", "job_title": "前端开发", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2017/8/13/3a6942116e3e7749ca292ee2c5bafb29~tplv-t2oaga2asx-image.image", "level": 2, "description": "", "followee_count": 95, "follower_count": 10, "post_article_count": 23, "digg_article_count": 174, "got_digg_count": 88, "got_view_count": 3127, "post_shortmsg_count": 16, "digg_shortmsg_count": 17, "isfollowed": false, "favorable_author": 0, "power": 119, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 7000979623836123166, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6844904100354588679", "article_info": {"article_id": "6844904100354588679", "user_id": "360295545713294", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "https://juejin.im/post/6844904100354588679", "cover_image": "", "is_gfw": 0, "title": "高频面试手写代码满分答案! (2w字)", "brief_content": "如果给一个变量赋值一个对象,那么两者的值会是同一个引用,其中一方改变,另一方也会相应改变。针对引用类型我们需要实现数据的拷贝。 用 ... 实现 通常浅拷贝就能解决大部分问题,但是只解决了第一层的问题,如果接下去的值中还有对象的话,那么我们需要使用深拷贝。 对于 functio…", "is_english": 0, "is_original": 1, "user_index": 9.8701860256919, "original_type": 0, "original_author": "", "content": "", "ctime": "1584944574", "mtime": "1598861288", "rtime": "1584946310", "draft_id": "6845076692793294861", "view_count": 9192, "collect_count": 320, "digg_count": 166, "comment_count": 15, "hot_index": 640, "is_hot": 0, "rank_index": 0.00291967, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "360295545713294", "user_name": "Mokou", "company": "前端进阶课", "job_title": "公众号", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/90479d421b1d35cfbf08b0d14f794c69~300x300.image", "level": 3, "description": "", "followee_count": 52, "follower_count": 530, "post_article_count": 29, "digg_article_count": 68, "got_digg_count": 1678, "got_view_count": 113471, "post_shortmsg_count": 5, "digg_shortmsg_count": 2, "isfollowed": false, "favorable_author": 0, "power": 2812, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6844904100354588679, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6986902403492773925", "article_info": {"article_id": "6986902403492773925", "user_id": "827309109290600", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919, 6809640398105870343, 6809640411473117197], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "ES6面试、复习干货知识点汇总", "brief_content": "作者:StevenLikeWatermelon https://juejin.cn/post/6844903734464495623 近期在复习ES6,针对ES6新的知识点,以问答形式整理一个全面知", "is_english": 0, "is_original": 1, "user_index": 1.114732475630142, "original_type": 0, "original_author": "", "content": "", "ctime": "1626765053", "mtime": "1626925619", "rtime": "1626925619", "draft_id": "6986901576833056799", "view_count": 488, "collect_count": 11, "digg_count": 7, "comment_count": 1, "hot_index": 32, "is_hot": 0, "rank_index": 0.00291646, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "827309109290600", "user_name": "李仁平", "company": "", "job_title": "web前端", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/mosaic-legacy/3791/5035712059~300x300.image", "level": 1, "description": "", "followee_count": 14, "follower_count": 9, "post_article_count": 17, "digg_article_count": 0, "got_digg_count": 26, "got_view_count": 2713, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 53, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546529, "tag_id": "6809640411473117197", "tag_name": "ECMAScript 6", "color": "#F46507", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/e384dbc6d1ab15f046cf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971773, "mtime": 1631685869, "id_type": 9, "tag_alias": "", "post_article_count": 3420, "concern_user_count": 176180}], "user_interact": {"id": 6986902403492773925, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6855649603497230350", "article_info": {"article_id": "6855649603497230350", "user_id": "289926799429704", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "互联网寒冬,一年经验字节跳动、虾皮、快手、拼多多前端面试总结", "brief_content": "年中的时候因个人原因,打算离开腾讯,到外面看看,投了若干简历,最终面试了字节跳动、虾皮、快手、拼多多这4家公司。有的喜有的忧,本文是对本次面试的一个总结。 快手是最早约的面试,在boss直聘上投完大概几天就约了。也是我本次第一家面试的公司。时间某个工作日的晚上8点,那天早早溜回…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1596205318", "mtime": "1596267790", "rtime": "1596267790", "draft_id": "6855649487533113357", "view_count": 6226, "collect_count": 160, "digg_count": 119, "comment_count": 21, "hot_index": 451, "is_hot": 0, "rank_index": 0.0029058, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "289926799429704", "user_name": "flytam", "company": "Bytedance", "job_title": "前端", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/851d1763a1dbdaeab3b4df133444ae84~300x300.image", "level": 3, "description": "github github.com/flytam。公众号 CodeForYou", "followee_count": 25, "follower_count": 119, "post_article_count": 25, "digg_article_count": 473, "got_digg_count": 869, "got_view_count": 36553, "post_shortmsg_count": 14, "digg_shortmsg_count": 5, "isfollowed": false, "favorable_author": 0, "power": 1234, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6855649603497230350, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6874710268094611469", "article_info": {"article_id": "6874710268094611469", "user_id": "2858385961407853", "category_id": "6809637767543259144", "tag_ids": [6809640398105870343, 6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "面试遇坎,每日一题我精选了这些题目与答案", "brief_content": "每日工作之余,我会将自己整理的一些前端面试题笔试题整理成每日一题,然后在公众号中推送给大家,每天仅需几分钟做一道题,经过日积月累,在换工作的时候一定能让你拿到一个比较好的offer。今天这篇文章是我将近期每日一题中比较好的题目及粉丝们分享的一些答案进行的整理,分享给更多的掘友,…", "is_english": 0, "is_original": 1, "user_index": 16.117421233368685, "original_type": 0, "original_author": "", "content": "", "ctime": "1600644104", "mtime": "1600644107", "rtime": "1600644107", "draft_id": "6874570179741745166", "view_count": 5402, "collect_count": 136, "digg_count": 88, "comment_count": 5, "hot_index": 363, "is_hot": 0, "rank_index": 0.00290289, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2858385961407853", "user_name": "前端进击者", "company": "腾讯", "job_title": "「前端有的玩」公众号", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/94334b7b74bcce3307040a87a2628835~300x300.image", "level": 5, "description": "不要吹灭你的灵感和你的想象力; 不要成为你的模型的奴隶", "followee_count": 44, "follower_count": 6791, "post_article_count": 28, "digg_article_count": 414, "got_digg_count": 13533, "got_view_count": 565293, "post_shortmsg_count": 13, "digg_shortmsg_count": 11, "isfollowed": false, "favorable_author": 1, "power": 19185, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6874710268094611469, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6844903704663949325", "article_info": {"article_id": "6844903704663949325", "user_id": "1415826704971918", "category_id": "6809637767543259144", "tag_ids": [6809640369764958215, 6809640398105870343, 6809640404791590919, 6809640407484334093], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "面试官问:能否模拟实现JS的new操作符", "brief_content": "用过Vuejs的同学都知道,需要用new操作符来实例化。 那么面试官可能会问是否想过new到底做了什么,怎么模拟实现呢。 从这里例子中,我们可以看出:一个函数用new操作符来调用后,生成了一个全新的对象。而且Student和Object都是函数,只不过Student是我们自定义…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1541408424", "mtime": "1604496539", "rtime": "1541409293", "draft_id": "6845075644548644878", "view_count": 23363, "collect_count": 346, "digg_count": 293, "comment_count": 57, "hot_index": 1518, "is_hot": 0, "rank_index": 0.00289836, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1415826704971918", "user_name": "若川", "company": "", "job_title": "「若川视野」公众号 源码系列作者", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/6/2/16b17bc6f37d2e4e~tplv-t2oaga2asx-image.image", "level": 4, "description": "", "followee_count": 214, "follower_count": 3802, "post_article_count": 31, "digg_article_count": 102, "got_digg_count": 4338, "got_view_count": 239099, "post_shortmsg_count": 15, "digg_shortmsg_count": 4, "isfollowed": false, "favorable_author": 1, "power": 6721, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 50, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546498, "tag_id": "6809640369764958215", "tag_name": "Vue.js", "color": "#41B883", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/7b5c3eb591b671749fee.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432234520, "mtime": 1631692660, "id_type": 9, "tag_alias": "", "post_article_count": 31256, "concern_user_count": 313520}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88827, "concern_user_count": 527704}], "user_interact": {"id": 6844903704663949325, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6999985372440559624", "article_info": {"article_id": "6999985372440559624", "user_id": "817692381812999", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "TypeScript面试题及答案收录[不断更新]", "brief_content": "本文只是个人对# 钉钉前端面试题 中 TypeScript 模块的面试题,根据网络中的答案进行补充、整理和拓展。", "is_english": 0, "is_original": 1, "user_index": 1.526738543039035, "original_type": 0, "original_author": "", "content": "", "ctime": "1629811253", "mtime": "1629860338", "rtime": "1629860338", "draft_id": "6988823191380590629", "view_count": 143, "collect_count": 1, "digg_count": 1, "comment_count": 0, "hot_index": 8, "is_hot": 0, "rank_index": 0.00288818, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "817692381812999", "user_name": "周姐日常事", "company": "X站", "job_title": "前端架构师", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/89c95fbb0269b669e8f886bbc401120f~300x300.image", "level": 1, "description": "", "followee_count": 43, "follower_count": 3, "post_article_count": 15, "digg_article_count": 113, "got_digg_count": 10, "got_view_count": 2127, "post_shortmsg_count": 1, "digg_shortmsg_count": 141, "isfollowed": false, "favorable_author": 0, "power": 31, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6999985372440559624, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6844903763568771080", "article_info": {"article_id": "6844903763568771080", "user_id": "641770489918542", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919, 6809640407484334093], "visible_level": 0, "link_url": "https://juejin.im/post/6844903763568771080", "cover_image": "", "is_gfw": 0, "title": "世界顶级公司的前端面试都问些什么", "brief_content": "在过去的几年里,我在亚马逊和雅虎面试过许多前端工程师。在这篇文章中,我想分享一些技巧,帮助大家做好准备。 免责声明:本文的目的并不是为你列出在前端面试中可能会被问到的问题,但是可以将其视为知识储备。 面试是一件很难的事情。作为候选人,通常会给你45分钟的时间来让你展示自己的技能…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1547798881", "mtime": "1598488662", "rtime": "1547800166", "draft_id": "6845076160376733710", "view_count": 16168, "collect_count": 597, "digg_count": 541, "comment_count": 25, "hot_index": 1374, "is_hot": 0, "rank_index": 0.00288612, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "641770489918542", "user_name": "前端先锋", "company": "公众号:前端先锋", "job_title": "佛系前端码农,公众号:前端先锋", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/c216b6d330e8833ba5491d606a8e5d3f~300x300.image", "level": 5, "description": "前端技术狂热(佛系)爱好者", "followee_count": 17, "follower_count": 8492, "post_article_count": 252, "digg_article_count": 29, "got_digg_count": 10086, "got_view_count": 831223, "post_shortmsg_count": 11, "digg_shortmsg_count": 3, "isfollowed": false, "favorable_author": 1, "power": 18646, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 15, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88827, "concern_user_count": 527704}], "user_interact": {"id": 6844903763568771080, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6911118171600584718", "article_info": {"article_id": "6911118171600584718", "user_id": "395479919102856", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f60a940b6e284dde81794afcec3a4ada~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "通俗易懂的理解函数节流和防抖", "brief_content": "1. 节流只在开始执行一次,未执行完成过程中触发的忽略,核心在于开关锁🔒。例如:多次点击按钮提交表单,第一次有效2. 防抖只执行最后一个被触发的,清除之前的异步任务,核心在于清零。例如:页面滚动处理事", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1609120144", "mtime": "1618814249", "rtime": "1609123404", "draft_id": "6911112125536534541", "view_count": 3720, "collect_count": 34, "digg_count": 48, "comment_count": 14, "hot_index": 248, "is_hot": 0, "rank_index": 0.00287596, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "395479919102856", "user_name": "alanyf", "company": "腾讯", "job_title": "前端", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/0df415c26ce5767088ea12245993360a~300x300.image", "level": 3, "description": "滴水穿石", "followee_count": 15, "follower_count": 619, "post_article_count": 66, "digg_article_count": 126, "got_digg_count": 2555, "got_view_count": 122610, "post_shortmsg_count": 2, "digg_shortmsg_count": 2, "isfollowed": false, "favorable_author": 0, "power": 3781, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6911118171600584718, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6873444336059711495", "article_info": {"article_id": "6873444336059711495", "user_id": "1099167356946829", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "一年前端面试分享", "brief_content": "毕业于广东某双非大学,校招进入奇安信(前360企业安全)工作,刚刚工作满一年(不好找工作,但人在江湖,身不由己)。 leetcode刷题200+,基本能应付面试了。墙裂建议做做算法题,真的很爽,而且很锻炼编码思维。 360企业安全,奇安信,360之间的关系?为什么学前端?平时怎…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1600348495", "mtime": "1600669021", "rtime": "1600664785", "draft_id": "6856746688104726535", "view_count": 5241, "collect_count": 128, "digg_count": 87, "comment_count": 26, "hot_index": 375, "is_hot": 0, "rank_index": 0.00287385, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "1099167356946829", "user_name": "喂。小欢", "company": "快手", "job_title": "FE", "avatar_large": "https://sf3-ttcdn-tos.pstatp.com/img/user-avatar/b3eca50794ae4287cb604acbe7d671d8~300x300.image", "level": 2, "description": "快手内推call我。On the front-end road,it will never return.", "followee_count": 65, "follower_count": 52, "post_article_count": 5, "digg_article_count": 11, "got_digg_count": 119, "got_view_count": 13567, "post_shortmsg_count": 4, "digg_shortmsg_count": 2, "isfollowed": false, "favorable_author": 0, "power": 254, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6873444336059711495, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "7000238703322857502", "article_info": {"article_id": "7000238703322857502", "user_id": "571401775883117", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "前端面试之代码输出结果(三)", "brief_content": "这是我参与8月更文挑战的第19天,活动详情查看:8月更文挑战。 立即执行函数和作用域 说明 立即执行函数 IIFE,可以模拟块级作用域,即在一个函数表达式内部声明变量,然后立即调用这个函数。这 样位于", "is_english": 0, "is_original": 1, "user_index": 4.204426122367245, "original_type": 0, "original_author": "", "content": "", "ctime": "1629870133", "mtime": "1629874274", "rtime": "1629874274", "draft_id": "7000217738132078599", "view_count": 83, "collect_count": 0, "digg_count": 1, "comment_count": 0, "hot_index": 5, "is_hot": 0, "rank_index": 0.00287382, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "571401775883117", "user_name": "馨迤Sine", "company": "", "job_title": "前端开发", "avatar_large": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2017/8/13/3a6942116e3e7749ca292ee2c5bafb29~tplv-t2oaga2asx-image.image", "level": 2, "description": "", "followee_count": 95, "follower_count": 10, "post_article_count": 23, "digg_article_count": 174, "got_digg_count": 88, "got_view_count": 3127, "post_shortmsg_count": 16, "digg_shortmsg_count": 17, "isfollowed": false, "favorable_author": 0, "power": 119, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 7000238703322857502, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6982533446304448543", "article_info": {"article_id": "6982533446304448543", "user_id": "2638458197397144", "category_id": "6809637767543259144", "tag_ids": [6809640407484334093, 6809640408797167623, 6809640398105870343, 6809640404791590919, 6809640369764958215], "visible_level": 0, "link_url": "", "cover_image": "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8c12bf22234a4a23acbd774a223bd6ce~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "新手入门第三课:2个文章进阶的知识点", "brief_content": "本节课主要带大家了解文章摘要和专栏的作用。这篇文章是本次活动的最后一课,希望大家有始有终,一起来学习!", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1625747818", "mtime": "1625800230", "rtime": "1625800230", "draft_id": "6982136236156829709", "view_count": 550, "collect_count": 3, "digg_count": 15, "comment_count": 1, "hot_index": 43, "is_hot": 0, "rank_index": 0.00287078, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "2638458197397144", "user_name": "来自格兰芬多的邦妮", "company": "掘金", "job_title": "沸点主理人|首席小秘书", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/d2e36b26cc51113c7f8451e1d4500e35~300x300.image", "level": 2, "description": "别惹我,我很凶的!", "followee_count": 52, "follower_count": 607, "post_article_count": 7, "digg_article_count": 4173, "got_digg_count": 125, "got_view_count": 10483, "post_shortmsg_count": 207, "digg_shortmsg_count": 1966, "isfollowed": false, "favorable_author": 0, "power": 229, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88827, "concern_user_count": 527704}, {"id": 2546527, "tag_id": "6809640408797167623", "tag_name": "后端", "color": "#C679FF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/d83da9d012ddb7ae85f4.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971556, "mtime": 1631692643, "id_type": 9, "tag_alias": "", "post_article_count": 71828, "concern_user_count": 422450}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}, {"id": 2546498, "tag_id": "6809640369764958215", "tag_name": "Vue.js", "color": "#41B883", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/7b5c3eb591b671749fee.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432234520, "mtime": 1631692660, "id_type": 9, "tag_alias": "", "post_article_count": 31256, "concern_user_count": 313520}], "user_interact": {"id": 6982533446304448543, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6844903678244028429", "article_info": {"article_id": "6844903678244028429", "user_id": "3843548383549214", "category_id": "6809637767543259144", "tag_ids": [6809640369764958215, 6809640398105870343, 6809640404791590919, 6809640407484334093, 6809640411473117197, 6809640715828592654, 6809640698183155719], "visible_level": 0, "link_url": "https://juejin.im/post/6844903678244028429", "cover_image": "", "is_gfw": 0, "title": "七年切图仔如何面试大厂web前端?(沟通软技能总结) | 掘金技术征文", "brief_content": "最近面了很多大厂的web前端岗位,都被刷了,在决定入职前,手里拿了几分待遇差不多的offer,后期的面试越来越顺,自己思考和总结了一下,原来面试也有好多技巧和方法可循,希望这些方法可以帮助到为找工作而且苦恼的你,可能每个人的方法不一样,不过至少可以提供一些参考。 先说明一下我的…", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1536707331", "mtime": "1599617784", "rtime": "1536707331", "draft_id": "6845075612839739406", "view_count": 16203, "collect_count": 353, "digg_count": 681, "comment_count": 97, "hot_index": 1588, "is_hot": 0, "rank_index": 0.00283962, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3843548383549214", "user_name": "愚坤", "company": "水滴", "job_title": "web前端", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/19ddf4496b19820b469f702b8cd87c1f~300x300.image", "level": 4, "description": "一点一点、一滴一滴的积累", "followee_count": 167, "follower_count": 6022, "post_article_count": 43, "digg_article_count": 84, "got_digg_count": 4610, "got_view_count": 182901, "post_shortmsg_count": 104, "digg_shortmsg_count": 12, "isfollowed": false, "favorable_author": 1, "power": 6403, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546498, "tag_id": "6809640369764958215", "tag_name": "Vue.js", "color": "#41B883", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/7b5c3eb591b671749fee.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1432234520, "mtime": 1631692660, "id_type": 9, "tag_alias": "", "post_article_count": 31256, "concern_user_count": 313520}, {"id": 2546519, "tag_id": "6809640398105870343", "tag_name": "JavaScript", "color": "#616161", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/5d70fd6af940df373834.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435884803, "mtime": 1631692583, "id_type": 9, "tag_alias": "", "post_article_count": 67405, "concern_user_count": 398956}, {"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}, {"id": 2546526, "tag_id": "6809640407484334093", "tag_name": "前端", "color": "#60ADFF", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/bac28828a49181c34110.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 1, "ctime": 1435971546, "mtime": 1631692835, "id_type": 9, "tag_alias": "", "post_article_count": 88827, "concern_user_count": 527704}, {"id": 2546529, "tag_id": "6809640411473117197", "tag_name": "ECMAScript 6", "color": "#F46507", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/e384dbc6d1ab15f046cf.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971773, "mtime": 1631685869, "id_type": 9, "tag_alias": "", "post_article_count": 3420, "concern_user_count": 176180}, {"id": 2546749, "tag_id": "6809640715828592654", "tag_name": "掘金技术征文", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/15541961813457c93d793d132eb6f090c15266807965a.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1481753122, "mtime": 1631691817, "id_type": 9, "tag_alias": "", "post_article_count": 658, "concern_user_count": 11586}, {"id": 2546736, "tag_id": "6809640698183155719", "tag_name": "求职", "color": "#000000", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/53bf55bd040bfd1877af.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1480964186, "mtime": 1631665580, "id_type": 9, "tag_alias": "", "post_article_count": 912, "concern_user_count": 23096}], "user_interact": {"id": 6844903678244028429, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6992370209961017380", "article_info": {"article_id": "6992370209961017380", "user_id": "3237437960366647", "category_id": "6809637767543259144", "tag_ids": [6809641167680962568, 6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "", "is_gfw": 0, "title": "前端面试题之性能优化高频面试题集锦", "brief_content": "前端性能优化基本上也是面试上必问的题,本篇文章将以性能优化为专题,罗列出面试中频率比较高的几道面试题.", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1628038104", "mtime": "1628131619", "rtime": "1628131619", "draft_id": "6992227667030310949", "view_count": 249, "collect_count": 7, "digg_count": 10, "comment_count": 0, "hot_index": 22, "is_hot": 0, "rank_index": 0.00283841, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3237437960366647", "user_name": "前端面试题宝典", "company": "", "job_title": "前端攻城拔寨狮", "avatar_large": "https://sf6-ttcdn-tos.pstatp.com/img/user-avatar/8c0835666f5a1e2f7f5de34bce57c8fb~300x300.image", "level": 2, "description": "JavaScript Node React Vue Typescript 前端面试相关文章不定期频繁更新 关于访问微信小程序[前端面试题宝典] 在线刷前端面试题", "followee_count": 2, "follower_count": 12, "post_article_count": 12, "digg_article_count": 14, "got_digg_count": 74, "got_view_count": 2753, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 101, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2547076, "tag_id": "6809641167680962568", "tag_name": "性能优化", "color": "", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/1552374613638f172b668f237482fee67f11b7ac8c181.jpg~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1548033194, "mtime": 1631687749, "id_type": 9, "tag_alias": "Performance optimization", "post_article_count": 2266, "concern_user_count": 7996}, {"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6992370209961017380, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}, {"article_id": "6990646499638001701", "article_info": {"article_id": "6990646499638001701", "user_id": "3800338594013437", "category_id": "6809637767543259144", "tag_ids": [6809640404791590919], "visible_level": 0, "link_url": "", "cover_image": "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/115c3e01efe04202b5d5f7c4183f3946~tplv-k3u1fbpfcp-watermark.image", "is_gfw": 0, "title": "周周特别篇:近期找工作+实习+字节前端提前批面试的心得分享", "brief_content": "刚结束字节提前批前端一面的我,本着可以咕咕但不能一直咕的想法,结合之前做的笔记和新鲜出炉的面试经验想和大家聊聊看我近期找工作+实习+字节前端提前批面试一面的心得,希望可以帮到和我一样在积极探索自己的你", "is_english": 0, "is_original": 1, "user_index": 0, "original_type": 0, "original_author": "", "content": "", "ctime": "1627636772", "mtime": "1627799204", "rtime": "1627641836", "draft_id": "6990619870261952525", "view_count": 322, "collect_count": 0, "digg_count": 9, "comment_count": 1, "hot_index": 26, "is_hot": 0, "rank_index": 0.00283349, "status": 2, "verify_status": 1, "audit_status": 2, "mark_content": ""}, "author_user_info": {"user_id": "3800338594013437", "user_name": "Superlit帆", "company": "", "job_title": "", "avatar_large": "https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/2b8e6b58c03cac01a34b5d8ba731bbd3~300x300.image", "level": 1, "description": "Not a coder or designer,just a person have a computer.", "followee_count": 12, "follower_count": 5, "post_article_count": 2, "digg_article_count": 50, "got_digg_count": 14, "got_view_count": 498, "post_shortmsg_count": 0, "digg_shortmsg_count": 0, "isfollowed": false, "favorable_author": 0, "power": 18, "study_point": 0, "university": {"university_id": "0", "name": "", "logo": ""}, "major": {"major_id": "0", "parent_id": "0", "name": ""}, "student_status": 0, "select_event_count": 0, "select_online_course_count": 0, "identity": 0, "is_select_annual": false, "select_annual_rank": 0, "annual_list_type": 0, "extraMap": {}, "is_logout": 0}, "category": {"category_id": "6809637767543259144", "category_name": "前端", "category_url": "frontend", "rank": 2, "back_ground": "https://lc-mhke0kuv.cn-n1.lcfile.com/8c95587526f346c0.png", "icon": "https://lc-mhke0kuv.cn-n1.lcfile.com/1c40f5eaba561e32.png", "ctime": 1457483942, "mtime": 1432503190, "show_type": 3, "item_type": 2, "promote_tag_cap": 4, "promote_priority": 2}, "tags": [{"id": 2546524, "tag_id": "6809640404791590919", "tag_name": "面试", "color": "#545454", "icon": "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/leancloud-assets/85dd1ce8008458ac220c.png~tplv-t2oaga2asx-image.image", "back_ground": "", "show_navi": 0, "ctime": 1435971430, "mtime": 1631692398, "id_type": 9, "tag_alias": "", "post_article_count": 15729, "concern_user_count": 349602}], "user_interact": {"id": 6990646499638001701, "omitempty": 2, "user_id": 0, "is_digg": false, "is_follow": false, "is_collect": false}, "org": {"org_info": null, "org_user": null, "is_followed": false}, "req_id": "20210915160244010212162168420040BE"}], "cursor": "eyJ2IjoiNzAwNzk5MTg0ODMwODMxMDAyNCIsImkiOjY4MH0=", "count": 2132, "has_more": true} | [
"[email protected]"
] | |
825e7a1384caaa635209d8fbde10c2ebc6fb3172 | 12485bb945ab8af6ff6a5f3d9d4c542a7bcf95f8 | /server/src/uds/core/util/decorators.py | 1996f00746c892461214b269ffa03dfe7a9366ad | [] | no_license | morfeuj/openuds | 6ef0c4bed624def0090efa6abdd2600b9be81a8b | 26e429019e5fe5b01ee1a476c879d8f8333b0ab0 | refs/heads/master | 2020-12-15T15:11:33.598430 | 2020-01-20T16:42:33 | 2020-01-20T16:42:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,264 | py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
@author: Adolfo Gómez, dkmaster at dkmon dot com
"""
from functools import wraps
import logging
import inspect
import typing
from uds.core.util.html import checkBrowser
from uds.web.util import errors
logger = logging.getLogger(__name__)
RT = typing.TypeVar('RT')
# Decorator that protects pages that needs at least a browser version
# Default is to deny IE < 9
def denyBrowsers(
browsers: typing.Optional[typing.List[str]] = None,
errorResponse: typing.Callable = lambda request: errors.errorView(request, errors.BROWSER_NOT_SUPPORTED)
) -> typing.Callable[[typing.Callable[..., RT]], typing.Callable[..., RT]]:
"""
Decorator to set protection to access page
Look for samples at uds.core.web.views
"""
denied: typing.List[str] = browsers or ['ie<9']
def wrap(view_func: typing.Callable[..., RT]) -> typing.Callable[..., RT]:
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs) -> RT:
"""
Wrapped function for decorator
"""
for b in denied:
if checkBrowser(request, b):
return errorResponse(request)
return view_func(request, *args, **kwargs)
return _wrapped_view
return wrap
def deprecated(func: typing.Callable[..., RT]) -> typing.Callable[..., RT]:
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used."""
@wraps(func)
def new_func(*args, **kwargs) -> RT:
try:
caller = inspect.stack()[1]
logger.warning('Call to deprecated function %s from %s:%s.', func.__name__, caller[1], caller[2])
except Exception:
logger.info('No stack info on deprecated function call %s', func.__name__)
return func(*args, **kwargs)
return new_func
# Decorator that allows us a "fast&clean" caching system on service providers
#
# Decorator for caching
# Decorator that tries to get from cache before executing
def allowCache(
cachePrefix: str,
cacheTimeout: int,
cachingArgs: typing.Optional[typing.Union[typing.List[int], typing.Tuple[int], int]] = None,
cachingKWArgs: typing.Optional[typing.Union[typing.List[str], typing.Tuple[str], str]] = None,
cachingKeyFnc: typing.Optional[typing.Callable[[typing.Any], str]] = None
) -> typing.Callable[[typing.Callable[..., RT]], typing.Callable[..., RT]]:
"""Decorator that give us a "quick& clean" caching feature on service providers.
Note: This decorator is intended ONLY for service providers
:param cachePrefix: the cache key "prefix" (prepended on generated key from args)
:param cacheTimeout: The cache timeout in seconds
:param cachingArgs: The caching args. Can be a single integer or a list.
First arg (self) is 0, so normally cachingArgs are 1, or [1,2,..]
"""
keyFnc = cachingKeyFnc or (lambda x: '')
def allowCacheDecorator(fnc: typing.Callable[..., RT]) -> typing.Callable[..., RT]:
@wraps(fnc)
def wrapper(*args, **kwargs) -> RT:
argList: typing.List[str] = []
if cachingArgs:
ar = [cachingArgs] if not isinstance(cachingArgs, (list, tuple)) else cachingArgs
argList = [args[i] if i < len(args) else '' for i in ar]
if cachingKWArgs:
kw = [cachingKWArgs] if not isinstance(cachingKWArgs, (list, tuple)) else cachingKWArgs
argList += [str(kwargs.get(i, '')) for i in kw]
if argList:
cacheKey = '{}-{}.{}'.format(cachePrefix, keyFnc(args[0]), argList)
else:
cacheKey = '{}-{}.gen'.format(cachePrefix, keyFnc(args[0]))
data: typing.Any = None
if kwargs.get('force', False) is False and args[0].cache:
data = args[0].cache.get(cacheKey)
if 'force' in kwargs:
# Remove force key
del kwargs['force']
if data is None and args[0].cache: # Not in cache and object can cache it
data = fnc(*args, **kwargs)
try:
# Maybe returned data is not serializable. In that case, cache will fail but no harm is done with this
args[0].cache.put(cacheKey, data, cacheTimeout)
except Exception as e:
logger.debug('Data for %s is not serializable on call to %s, not cached. %s (%s)', cacheKey, fnc.__name__, data, e)
return data
return wrapper
return allowCacheDecorator
| [
"[email protected]"
] | |
4e80ccd3f2e43b289698ef14d9347915c77924e7 | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/pa3/sample/list_set_element_oob_1-71.py | 58d3ed793879d1cc0c90830a3833ad543f01587e | [] | 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 | 83 | py | x:[int] = None
x = [1, 2, 3]
x[-1] = 4
print(x[0])
print(x[$Literal])
print(x[2])
| [
"[email protected]"
] | |
98ae6996aa0b587767198da68169589e426738f7 | 0be27c0a583d3a8edd5d136c091e74a3df51b526 | /reverse_each_word_except_first_and_last.py | 27fcc10079794e2ac868b8e8a9287aad8791a631 | [] | no_license | ssangitha/guvicode | 3d38942f5d5e27a7978e070e14be07a5269b01fe | ea960fb056cfe577eec81e83841929e41a31f72e | refs/heads/master | 2020-04-15T05:01:00.226391 | 2019-09-06T10:08:23 | 2019-09-06T10:08:23 | 164,405,935 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 171 | py | s=input()
l=list(s.split(" "))
a=[l[0]]
for i in range(1,len(l)):
if i==len(l)-1:
a.append(l[-1])
else:
c=l[i]
b=c[::-1]
a.append(b)
print(" ".join(a))
#reverse
| [
"[email protected]"
] | |
39af42d635ccc1f91a80e522b9a0754dc5d4b216 | f789a3b83af9830d28a3fc3cc5184be513caea74 | /tests/unit/test_middleware.py | 5ee1d91efcfa4516fbaabc162635690dfd9546a4 | [
"Apache-2.0"
] | permissive | anuo007/turnstile | 22701d4b8e1bd83af9dc4df38bf828bc8ff6f055 | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | refs/heads/master | 2021-01-22T00:24:37.821758 | 2013-09-20T23:21:02 | 2013-09-20T23:21:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 29,594 | py | # Copyright 2013 Rackspace
# 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.
import eventlet.semaphore
import mock
import unittest2
from turnstile import config
from turnstile import control
from turnstile import database
from turnstile import middleware
from turnstile import remote
from turnstile import utils
from tests.unit import utils as test_utils
class TestHeadersDict(unittest2.TestCase):
def test_init_sequence(self):
hd = middleware.HeadersDict([('Foo', 'value'), ('bAR', 'VALUE')])
self.assertEqual(hd.headers, dict(foo='value', bar='VALUE'))
def test_init_dict(self):
hd = middleware.HeadersDict(dict(Foo='value', bAR='VALUE'))
self.assertEqual(hd.headers, dict(foo='value', bar='VALUE'))
def test_init_kwargs(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
self.assertEqual(hd.headers, dict(foo='value', bar='VALUE'))
def test_get_item(self):
hd = middleware.HeadersDict(Foo='value')
self.assertEqual(hd['foo'], 'value')
self.assertEqual(hd['Foo'], 'value')
with self.assertRaises(KeyError):
foo = hd['bar']
def test_set_item(self):
hd = middleware.HeadersDict(Foo='value')
hd['fOO'] = 'bar'
self.assertEqual(hd.headers, dict(foo='bar'))
hd['bAr'] = 'blah'
self.assertEqual(hd.headers, dict(foo='bar', bar='blah'))
def test_del_item(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
del hd['fOO']
self.assertEqual(hd.headers, dict(bar='VALUE'))
del hd['bar']
self.assertEqual(hd.headers, {})
with self.assertRaises(KeyError):
del hd['baz']
def test_contains(self):
hd = middleware.HeadersDict(Foo='value')
self.assertTrue('foo' in hd)
self.assertTrue('fOO' in hd)
self.assertFalse('bAR' in hd)
def test_iter(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
result = sorted(list(iter(hd)))
self.assertEqual(result, ['bar', 'foo'])
def test_len(self):
hd = middleware.HeadersDict(Foo='value')
self.assertEqual(len(hd), 1)
hd['bAR'] = 'VALUE'
self.assertEqual(len(hd), 2)
def test_iterkeys(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
result = sorted(list(hd.iterkeys()))
self.assertEqual(result, ['bar', 'foo'])
def test_iteritems(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
result = sorted(list(hd.iteritems()))
self.assertEqual(result, [('bar', 'VALUE'), ('foo', 'value')])
def test_itervalues(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
result = sorted(list(hd.itervalues()))
self.assertEqual(result, ['VALUE', 'value'])
def test_keys(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
result = sorted(list(hd.keys()))
self.assertEqual(result, ['bar', 'foo'])
def test_items(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
result = sorted(list(hd.items()))
self.assertEqual(result, [('bar', 'VALUE'), ('foo', 'value')])
def test_values(self):
hd = middleware.HeadersDict(Foo='value', bAR='VALUE')
result = sorted(list(hd.values()))
self.assertEqual(result, ['VALUE', 'value'])
class TestTurnstileFilter(unittest2.TestCase):
@mock.patch.object(middleware, 'TurnstileMiddleware',
return_value='middleware')
@mock.patch.object(utils, 'find_entrypoint')
def test_filter_basic(self, mock_find_entrypoint,
mock_TurnstileMiddleware):
midware_class = middleware.turnstile_filter({})
self.assertFalse(mock_find_entrypoint.called)
self.assertFalse(mock_TurnstileMiddleware.called)
midware = midware_class('app')
mock_TurnstileMiddleware.assert_called_once_with('app', {})
self.assertEqual(midware, 'middleware')
@mock.patch.object(middleware, 'TurnstileMiddleware')
@mock.patch.object(utils, 'find_entrypoint',
return_value=mock.Mock(return_value='middleware'))
def test_filter_alt_middleware(self, mock_find_entrypoint,
mock_TurnstileMiddleware):
midware_class = middleware.turnstile_filter({}, turnstile='spam')
mock_find_entrypoint.assert_called_once_with(
'turnstile.middleware', 'spam', required=True)
self.assertFalse(mock_find_entrypoint.return_value.called)
self.assertFalse(mock_TurnstileMiddleware.called)
midware = midware_class('app')
mock_find_entrypoint.return_value.assert_called_once_with(
'app', dict(turnstile='spam'))
self.assertFalse(mock_TurnstileMiddleware.called)
self.assertEqual(midware, 'middleware')
class TestTurnstileMiddleware(unittest2.TestCase):
@mock.patch.object(utils, 'find_entrypoint')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(remote, 'RemoteControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
def test_init_basic(self, mock_info, mock_RemoteControlDaemon,
mock_ControlDaemon, mock_find_entrypoint):
midware = middleware.TurnstileMiddleware('app', {})
self.assertEqual(midware.app, 'app')
self.assertEqual(midware.limits, [])
self.assertEqual(midware.limit_sum, None)
self.assertEqual(midware.mapper, None)
self.assertIsInstance(midware.mapper_lock,
eventlet.semaphore.Semaphore)
self.assertEqual(midware.conf._config, {
None: dict(status='413 Request Entity Too Large'),
})
self.assertEqual(midware._db, None)
self.assertEqual(midware.preprocessors, [])
self.assertEqual(midware.postprocessors, [])
self.assertEqual(midware.formatter, midware.format_delay)
self.assertFalse(mock_RemoteControlDaemon.called)
mock_ControlDaemon.assert_has_calls([
mock.call(midware, midware.conf),
mock.call().start(),
])
mock_info.assert_called_once_with("Turnstile middleware initialized")
@mock.patch.object(utils, 'find_entrypoint', return_value=mock.Mock())
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(remote, 'RemoteControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
def test_init_formatter(self, mock_info, mock_RemoteControlDaemon,
mock_ControlDaemon, mock_find_entrypoint):
fake_formatter = mock_find_entrypoint.return_value
midware = middleware.TurnstileMiddleware('app',
dict(formatter='formatter'))
self.assertEqual(midware.app, 'app')
self.assertEqual(midware.limits, [])
self.assertEqual(midware.limit_sum, None)
self.assertEqual(midware.mapper, None)
self.assertIsInstance(midware.mapper_lock,
eventlet.semaphore.Semaphore)
self.assertEqual(midware.conf._config, {
None: {
'status': '413 Request Entity Too Large',
'formatter': 'formatter',
},
})
self.assertEqual(midware._db, None)
self.assertEqual(midware.preprocessors, [])
self.assertEqual(midware.postprocessors, [])
mock_find_entrypoint.assert_called_once_with(
'turnstile.formatter', 'formatter', required=True)
self.assertFalse(mock_RemoteControlDaemon.called)
mock_ControlDaemon.assert_has_calls([
mock.call(midware, midware.conf),
mock.call().start(),
])
mock_info.assert_called_once_with("Turnstile middleware initialized")
midware.formatter('delay', 'limit', 'bucket', 'environ', 'start')
fake_formatter.assert_called_once_with(
'413 Request Entity Too Large', 'delay', 'limit', 'bucket',
'environ', 'start')
@mock.patch.object(utils, 'find_entrypoint')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(remote, 'RemoteControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
def test_init_remote(self, mock_info, mock_RemoteControlDaemon,
mock_ControlDaemon, mock_find_entrypoint):
midware = middleware.TurnstileMiddleware('app', {
'control.remote': 'yes',
})
self.assertEqual(midware.app, 'app')
self.assertEqual(midware.limits, [])
self.assertEqual(midware.limit_sum, None)
self.assertEqual(midware.mapper, None)
self.assertIsInstance(midware.mapper_lock,
eventlet.semaphore.Semaphore)
self.assertEqual(midware.conf._config, {
None: dict(status='413 Request Entity Too Large'),
'control': dict(remote='yes'),
})
self.assertEqual(midware._db, None)
self.assertEqual(midware.preprocessors, [])
self.assertEqual(midware.postprocessors, [])
self.assertEqual(midware.formatter, midware.format_delay)
self.assertFalse(mock_ControlDaemon.called)
mock_RemoteControlDaemon.assert_has_calls([
mock.call(midware, midware.conf),
mock.call().start(),
])
mock_info.assert_called_once_with("Turnstile middleware initialized")
@mock.patch.object(utils, 'find_entrypoint')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(remote, 'RemoteControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
def test_init_enable(self, mock_info, mock_RemoteControlDaemon,
mock_ControlDaemon, mock_find_entrypoint):
entrypoints = {
'turnstile.preprocessor': {
'ep1': 'preproc1',
'ep3': 'preproc3',
'ep4': 'preproc4',
'ep6': 'preproc6',
},
'turnstile.postprocessor': {
'ep2': 'postproc2',
'ep4': 'postproc4',
'ep6': 'postproc6',
},
}
mock_find_entrypoint.side_effect = \
lambda x, y, compat=True: entrypoints[x].get(y)
midware = middleware.TurnstileMiddleware('app', {
'enable': 'ep1 ep2 ep3 ep4 ep5 ep6',
})
self.assertEqual(midware.app, 'app')
self.assertEqual(midware.limits, [])
self.assertEqual(midware.limit_sum, None)
self.assertEqual(midware.mapper, None)
self.assertIsInstance(midware.mapper_lock,
eventlet.semaphore.Semaphore)
self.assertEqual(midware.conf._config, {
None: dict(status='413 Request Entity Too Large',
enable='ep1 ep2 ep3 ep4 ep5 ep6'),
})
self.assertEqual(midware._db, None)
self.assertEqual(midware.preprocessors, [
'preproc1',
'preproc3',
'preproc4',
'preproc6',
])
self.assertEqual(midware.postprocessors, [
'postproc6',
'postproc4',
'postproc2',
])
self.assertEqual(midware.formatter, midware.format_delay)
self.assertFalse(mock_RemoteControlDaemon.called)
mock_ControlDaemon.assert_has_calls([
mock.call(midware, midware.conf),
mock.call().start(),
])
mock_info.assert_called_once_with("Turnstile middleware initialized")
@mock.patch.object(utils, 'find_entrypoint')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(remote, 'RemoteControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
def test_init_processors(self, mock_info, mock_RemoteControlDaemon,
mock_ControlDaemon, mock_find_entrypoint):
entrypoints = {
'turnstile.preprocessor': {
'ep1': 'preproc1',
'ep3': 'preproc3',
'ep4': 'preproc4',
'ep6': 'preproc6',
'preproc:ep5': 'preproc5',
},
'turnstile.postprocessor': {
'ep2': 'postproc2',
'ep4': 'postproc4',
'ep6': 'postproc6',
'postproc:ep5': 'postproc5',
},
}
mock_find_entrypoint.side_effect = \
lambda x, y, required=False: entrypoints[x].get(y)
midware = middleware.TurnstileMiddleware('app', {
'preprocess': 'ep1 ep3 ep4 preproc:ep5 ep6',
'postprocess': 'ep6 postproc:ep5 ep4 ep2',
})
self.assertEqual(midware.app, 'app')
self.assertEqual(midware.limits, [])
self.assertEqual(midware.limit_sum, None)
self.assertEqual(midware.mapper, None)
self.assertIsInstance(midware.mapper_lock,
eventlet.semaphore.Semaphore)
self.assertEqual(midware.conf._config, {
None: dict(status='413 Request Entity Too Large',
preprocess='ep1 ep3 ep4 preproc:ep5 ep6',
postprocess='ep6 postproc:ep5 ep4 ep2'),
})
self.assertEqual(midware._db, None)
self.assertEqual(midware.preprocessors, [
'preproc1',
'preproc3',
'preproc4',
'preproc5',
'preproc6',
])
self.assertEqual(midware.postprocessors, [
'postproc6',
'postproc5',
'postproc4',
'postproc2',
])
self.assertEqual(midware.formatter, midware.format_delay)
self.assertFalse(mock_RemoteControlDaemon.called)
mock_ControlDaemon.assert_has_calls([
mock.call(midware, midware.conf),
mock.call().start(),
])
mock_info.assert_called_once_with("Turnstile middleware initialized")
@mock.patch('traceback.format_exc', return_value='<traceback>')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware.LOG, 'exception')
@mock.patch.object(database, 'limits_hydrate', return_value=[
mock.Mock(),
mock.Mock(),
])
@mock.patch('routes.Mapper', return_value='mapper')
def test_recheck_limits_basic(self, mock_Mapper, mock_limits_hydrate,
mock_exception, mock_info,
mock_ControlDaemon, mock_format_exc):
limit_data = mock.Mock(**{
'get_limits.return_value': ('new_sum', ['limit1', 'limit2']),
})
mock_ControlDaemon.return_value = mock.Mock(**{
'get_limits.return_value': limit_data,
})
midware = middleware.TurnstileMiddleware('app', {})
midware.limits = ['old_limit1', 'old_limit2']
midware.limit_sum = 'old_sum'
midware.mapper = 'old_mapper'
midware._db = mock.Mock()
midware.recheck_limits()
mock_ControlDaemon.return_value.get_limits.assert_called_once_with()
limit_data.get_limits.assert_called_once_with('old_sum')
mock_limits_hydrate.assert_called_once_with(midware._db,
['limit1', 'limit2'])
mock_Mapper.assert_called_once_with(register=False)
for lim in mock_limits_hydrate.return_value:
lim._route.assert_called_once_with('mapper')
self.assertEqual(midware.limits, mock_limits_hydrate.return_value)
self.assertEqual(midware.limit_sum, 'new_sum')
self.assertEqual(midware.mapper, 'mapper')
self.assertFalse(mock_exception.called)
self.assertFalse(mock_format_exc.called)
self.assertEqual(len(midware._db.method_calls), 0)
@mock.patch('traceback.format_exc', return_value='<traceback>')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware.LOG, 'exception')
@mock.patch.object(database, 'limits_hydrate', return_value=[
mock.Mock(),
mock.Mock(),
])
@mock.patch('routes.Mapper', return_value='mapper')
def test_recheck_limits_unchanged(self, mock_Mapper, mock_limits_hydrate,
mock_exception, mock_info,
mock_ControlDaemon, mock_format_exc):
limit_data = mock.Mock(**{
'get_limits.side_effect': control.NoChangeException,
})
mock_ControlDaemon.return_value = mock.Mock(**{
'get_limits.return_value': limit_data,
})
midware = middleware.TurnstileMiddleware('app', {})
midware.limits = ['old_limit1', 'old_limit2']
midware.limit_sum = 'old_sum'
midware.mapper = 'old_mapper'
midware._db = mock.Mock()
midware.recheck_limits()
mock_ControlDaemon.return_value.get_limits.assert_called_once_with()
limit_data.get_limits.assert_called_once_with('old_sum')
self.assertFalse(mock_limits_hydrate.called)
self.assertFalse(mock_Mapper.called)
for lim in mock_limits_hydrate.return_value:
self.assertFalse(lim._route.called)
self.assertEqual(midware.limits, ['old_limit1', 'old_limit2'])
self.assertEqual(midware.limit_sum, 'old_sum')
self.assertEqual(midware.mapper, 'old_mapper')
self.assertFalse(mock_exception.called)
self.assertFalse(mock_format_exc.called)
self.assertEqual(len(midware._db.method_calls), 0)
@mock.patch('traceback.format_exc', return_value='<traceback>')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware.LOG, 'exception')
@mock.patch.object(database, 'limits_hydrate', return_value=[
mock.Mock(),
mock.Mock(),
])
@mock.patch('routes.Mapper', return_value='mapper')
def test_recheck_limits_exception(self, mock_Mapper, mock_limits_hydrate,
mock_exception, mock_info,
mock_ControlDaemon, mock_format_exc):
limit_data = mock.Mock(**{
'get_limits.side_effect': test_utils.TestException,
})
mock_ControlDaemon.return_value = mock.Mock(**{
'get_limits.return_value': limit_data,
})
midware = middleware.TurnstileMiddleware('app', {})
midware.limits = ['old_limit1', 'old_limit2']
midware.limit_sum = 'old_sum'
midware.mapper = 'old_mapper'
midware._db = mock.Mock()
midware.recheck_limits()
mock_ControlDaemon.return_value.get_limits.assert_called_once_with()
limit_data.get_limits.assert_called_once_with('old_sum')
self.assertFalse(mock_limits_hydrate.called)
self.assertFalse(mock_Mapper.called)
for lim in mock_limits_hydrate.return_value:
self.assertFalse(lim._route.called)
self.assertEqual(midware.limits, ['old_limit1', 'old_limit2'])
self.assertEqual(midware.limit_sum, 'old_sum')
self.assertEqual(midware.mapper, 'old_mapper')
mock_exception.assert_called_once_with("Could not load limits")
mock_format_exc.assert_called_once_with()
midware._db.assert_has_calls([
mock.call.sadd('errors', 'Failed to load limits: <traceback>'),
mock.call.publish('errors', 'Failed to load limits: <traceback>'),
])
@mock.patch('traceback.format_exc', return_value='<traceback>')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware.LOG, 'exception')
@mock.patch.object(database, 'limits_hydrate', return_value=[
mock.Mock(),
mock.Mock(),
])
@mock.patch('routes.Mapper', return_value='mapper')
def test_recheck_limits_exception_altkeys(self, mock_Mapper,
mock_limits_hydrate,
mock_exception, mock_info,
mock_ControlDaemon,
mock_format_exc):
limit_data = mock.Mock(**{
'get_limits.side_effect': test_utils.TestException,
})
mock_ControlDaemon.return_value = mock.Mock(**{
'get_limits.return_value': limit_data,
})
midware = middleware.TurnstileMiddleware('app', {
'control.errors_key': 'eset',
'control.errors_channel': 'epub',
})
midware.limits = ['old_limit1', 'old_limit2']
midware.limit_sum = 'old_sum'
midware.mapper = 'old_mapper'
midware._db = mock.Mock()
midware.recheck_limits()
mock_ControlDaemon.return_value.get_limits.assert_called_once_with()
limit_data.get_limits.assert_called_once_with('old_sum')
self.assertFalse(mock_limits_hydrate.called)
self.assertFalse(mock_Mapper.called)
for lim in mock_limits_hydrate.return_value:
self.assertFalse(lim._route.called)
self.assertEqual(midware.limits, ['old_limit1', 'old_limit2'])
self.assertEqual(midware.limit_sum, 'old_sum')
self.assertEqual(midware.mapper, 'old_mapper')
mock_exception.assert_called_once_with("Could not load limits")
mock_format_exc.assert_called_once_with()
midware._db.assert_has_calls([
mock.call.sadd('eset', 'Failed to load limits: <traceback>'),
mock.call.publish('epub', 'Failed to load limits: <traceback>'),
])
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware.TurnstileMiddleware, 'recheck_limits')
@mock.patch.object(middleware.TurnstileMiddleware, 'format_delay',
return_value='formatted delay')
def test_call_basic(self, mock_format_delay, mock_recheck_limits,
mock_info, mock_ControlDaemon):
app = mock.Mock(return_value='app response')
midware = middleware.TurnstileMiddleware(app, {})
midware.mapper = mock.Mock()
environ = {}
result = midware(environ, 'start_response')
self.assertEqual(result, 'app response')
mock_recheck_limits.assert_called_once_with()
midware.mapper.routematch.assert_called_once_with(environ=environ)
self.assertFalse(mock_format_delay.called)
app.assert_called_once_with(environ, 'start_response')
self.assertEqual(environ, {
'turnstile.conf': midware.conf,
})
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware.TurnstileMiddleware, 'recheck_limits')
@mock.patch.object(middleware.TurnstileMiddleware, 'format_delay',
return_value='formatted delay')
def test_call_processors(self, mock_format_delay, mock_recheck_limits,
mock_info, mock_ControlDaemon):
app = mock.Mock(return_value='app response')
midware = middleware.TurnstileMiddleware(app, {})
midware.mapper = mock.Mock()
midware.preprocessors = [mock.Mock(), mock.Mock()]
midware.postprocessors = [mock.Mock(), mock.Mock()]
environ = {}
result = midware(environ, 'start_response')
self.assertEqual(result, 'app response')
mock_recheck_limits.assert_called_once_with()
for proc in midware.preprocessors:
proc.assert_called_once_with(midware, environ)
midware.mapper.routematch.assert_called_once_with(environ=environ)
self.assertFalse(mock_format_delay.called)
for proc in midware.postprocessors:
proc.assert_called_once_with(midware, environ)
app.assert_called_once_with(environ, 'start_response')
self.assertEqual(environ, {
'turnstile.conf': midware.conf,
})
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware.TurnstileMiddleware, 'recheck_limits')
@mock.patch.object(middleware.TurnstileMiddleware, 'format_delay',
return_value='formatted delay')
def test_call_delay(self, mock_format_delay, mock_recheck_limits,
mock_info, mock_ControlDaemon):
app = mock.Mock(return_value='app response')
midware = middleware.TurnstileMiddleware(app, {})
midware.mapper = mock.Mock()
midware.preprocessors = [mock.Mock(), mock.Mock()]
midware.postprocessors = [mock.Mock(), mock.Mock()]
environ = {
'turnstile.delay': [
(30, 'limit1', 'bucket1'),
(20, 'limit2', 'bucket2'),
(60, 'limit3', 'bucket3'),
(10, 'limit4', 'bucket4'),
],
}
result = midware(environ, 'start_response')
self.assertEqual(result, 'formatted delay')
mock_recheck_limits.assert_called_once_with()
for proc in midware.preprocessors:
proc.assert_called_once_with(midware, environ)
midware.mapper.routematch.assert_called_once_with(environ=environ)
mock_format_delay.assert_called_once_with(60, 'limit3', 'bucket3',
environ, 'start_response')
for proc in midware.postprocessors:
self.assertFalse(proc.called)
self.assertFalse(app.called)
self.assertEqual(environ, {
'turnstile.delay': [
(30, 'limit1', 'bucket1'),
(20, 'limit2', 'bucket2'),
(60, 'limit3', 'bucket3'),
(10, 'limit4', 'bucket4'),
],
'turnstile.conf': midware.conf,
})
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware, 'HeadersDict', return_value=mock.Mock(**{
'items.return_value': 'header items',
}))
def test_format_delay(self, mock_HeadersDict, mock_info,
mock_ControlDaemon):
midware = middleware.TurnstileMiddleware('app', {})
limit = mock.Mock(**{
'format.return_value': ('limit status', 'limit entity'),
})
start_response = mock.Mock()
result = midware.format_delay(10.1, limit, 'bucket', 'environ',
start_response)
self.assertEqual(result, 'limit entity')
mock_HeadersDict.assert_called_once_with([('Retry-After', '11')])
limit.format.assert_called_once_with(
'413 Request Entity Too Large', mock_HeadersDict.return_value,
'environ', 'bucket', 10.1)
start_response.assert_called_once_with(
'limit status', 'header items')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(middleware, 'HeadersDict', return_value=mock.Mock(**{
'items.return_value': 'header items',
}))
def test_format_delay_altstatus(self, mock_HeadersDict, mock_info,
mock_ControlDaemon):
midware = middleware.TurnstileMiddleware('app', {
'status': 'some other status',
})
limit = mock.Mock(**{
'format.return_value': ('limit status', 'limit entity'),
})
start_response = mock.Mock()
result = midware.format_delay(10.1, limit, 'bucket', 'environ',
start_response)
self.assertEqual(result, 'limit entity')
mock_HeadersDict.assert_called_once_with([('Retry-After', '11')])
limit.format.assert_called_once_with(
'some other status', mock_HeadersDict.return_value,
'environ', 'bucket', 10.1)
start_response.assert_called_once_with(
'limit status', 'header items')
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(config.Config, 'get_database', return_value='database')
def test_db(self, mock_get_database, mock_info, mock_ControlDaemon):
midware = middleware.TurnstileMiddleware('app', {})
db = midware.db
self.assertEqual(db, 'database')
mock_get_database.assert_called_once_with()
@mock.patch.object(control, 'ControlDaemon')
@mock.patch.object(middleware.LOG, 'info')
@mock.patch.object(config.Config, 'get_database', return_value='database')
def test_db_cached(self, mock_get_database, mock_info, mock_ControlDaemon):
midware = middleware.TurnstileMiddleware('app', {})
midware._db = 'cached'
db = midware.db
self.assertEqual(db, 'cached')
self.assertFalse(mock_get_database.called)
| [
"[email protected]"
] | |
d16a62c88c77fdb893b4269bd3894ff2bf460ba0 | 02255565aff9ea18a4d566955cc53ca06090efa4 | /python_django.py | cf4625e4823034de98520ac80998d9c35978e234 | [] | no_license | BrainiacRawkib/Practical-Python-for-Begineers | 20a8a3697812bed78646c6af54a6dc195694109a | cb29ea1a38339fcf2fac005feb92b5a72ae98387 | refs/heads/master | 2020-12-01T09:10:06.802758 | 2019-12-28T15:27:40 | 2019-12-28T15:27:40 | 230,598,655 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 523 | py | from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
YEAR_IN_SCHOOL_CHOICES = (
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
)
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in (self.JUNIOR, self.SENIOR) | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.