blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 288 | content_id stringlengths 40 40 | detected_licenses listlengths 0 112 | license_type stringclasses 2 values | repo_name stringlengths 5 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 684 values | visit_date timestamp[us]date 2015-08-06 10:31:46 2023-09-06 10:44:38 | revision_date timestamp[us]date 1970-01-01 02:38:32 2037-05-03 13:00:00 | committer_date timestamp[us]date 1970-01-01 02:38:32 2023-09-06 01:08:06 | github_id int64 4.92k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-04 01:52:49 2023-09-14 21:59:50 ⌀ | gha_created_at timestamp[us]date 2008-05-22 07:58:19 2023-08-21 12:35:19 ⌀ | gha_language stringclasses 147 values | src_encoding stringclasses 25 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 128 12.7k | extension stringclasses 142 values | content stringlengths 128 8.19k | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
605d3e5caa7fa4db8866768bafaaf398a50fc019 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/CodeJamData/12/32/7.py | 1f66c1edf3d24d25821c6d77f5de8b98751e2cc1 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Python | false | false | 735 | py | import sys
input = sys.stdin
T = int(input.readline())
for t in range(1, T + 1):
print 'Case #{t}:'.format(t = t)
D, N, A = [i for i in input.readline().split(' ')]
D = float(D)
N = int(N)
A = int(A)
Ss = []
for i in range(N):
Ss.append([float(i) for i in input.readline().split(' ')])
As = [float(i) for i in input.readline().split(' ')]
for i in range(A):
a = As[i]
ss = [0]
for j in range(len(Ss)):
s = Ss[j]
if s[1] < D:
ss.append(s[0] - (2 * s[1] / a) ** .5)
elif j > 0 and Ss[j-1][1] < D:
t0 = Ss[j-1][0]
t1 = s[0]
p0 = Ss[j-1][1]
p1 = s[1]
v = (p1 - p0) / (t1 - t0)
tt = t0 + (D - p0) / v
ss.append(tt - (2 * D / a) ** .5)
t = max(ss) + (2 * D / a) ** .5
print t
| [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
d831223448974d37278e556ab69903d9e1e0c238 | 32c44b66ec20651893aaa83da355740784c85d94 | /python/rsyscall/tests/trio_test_case.py | 710cbe0e9a9599658a763eda318cce0855ad7992 | [] | no_license | LongJohnCoder/rsyscall | 1dbbba3aa7dcae3b018c159f409f3c56a1c5f896 | 1b4c0f51f92c0a1b91e1b45389fcecb1f0cc29bf | refs/heads/master | 2023-06-10T02:45:35.711203 | 2021-07-03T18:52:00 | 2021-07-03T19:42:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,696 | py | "A trio-enabled variant of unittest.TestCase"
import trio
import unittest
import functools
import types
from trio._core._run import Nursery
class TrioTestCase(unittest.TestCase):
"A trio-enabled variant of unittest.TestCase"
nursery: Nursery
async def asyncSetUp(self) -> None:
"Asynchronously set up resources for tests in this TestCase"
pass
async def asyncTearDown(self) -> None:
"Asynchronously clean up resources for tests in this TestCase"
pass
def __init__(self, methodName='runTest') -> None:
test = getattr(type(self), methodName)
@functools.wraps(test)
async def test_with_setup() -> None:
async with trio.open_nursery() as nursery:
self.nursery = nursery
await self.asyncSetUp()
try:
await test(self)
except BaseException as exn:
try:
await self.asyncTearDown()
except BaseException as teardown_exn:
# have to merge the exceptions if they both throw;
# might as well do this with trio.MultiError since we have it
raise trio.MultiError([exn, teardown_exn])
else:
raise
else:
await self.asyncTearDown()
nursery.cancel_scope.cancel()
@functools.wraps(test_with_setup)
def sync_test_with_setup(self) -> None:
trio.run(test_with_setup)
setattr(self, methodName, types.MethodType(sync_test_with_setup, self))
super().__init__(methodName)
| [
"sbaugh@catern.com"
] | sbaugh@catern.com |
b6ac65bd1ad0a81210f12320b3bd5ec52a2559f6 | 1a7b243e9288b00cf8ece60022f2e1c0a0c4a244 | /atcoder/mayokon/20221122/B.py | d7445027afb90b60da8531d53a08db43a9e6a266 | [] | no_license | hitochan777/kata | 4714bf4ec4e4083a9817b09c11820a1cc52aa33e | dda49e2dc6ae1d9a6e1d91f765762b53deb5b490 | refs/heads/main | 2023-08-31T12:48:21.688282 | 2023-08-27T14:47:09 | 2023-08-27T14:47:09 | 132,759,036 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 218 | py | A = int(input())
B = int(input())
C = int(input())
X = int(input())
cnt = 0
for a in range(0,A+1):
for b in range(0,B+1):
for c in range(0,C+1):
if 500*a + 100*b + 50*c == X:
cnt += 1
print(cnt) | [
"hitochan777@gmail.com"
] | hitochan777@gmail.com |
ec44d6396f5633a199cf5e79464a01e6c09bdf72 | c88420c9abf96c73139da0769f6eddbe6cf732dd | /tests_oval_graph/test_tools.py | fabae5074228d119de205a12df5246bf614b6cd0 | [
"Apache-2.0"
] | permissive | pombredanne/OVAL-visualization-as-graph | 0dcf077c6254e95f3f66ba00a805b5f09d1f21c3 | 64dcb9e14f58e3708022eda55ea3c4d3ec2b7b89 | refs/heads/master | 2023-01-20T09:21:31.215607 | 2022-01-31T17:08:56 | 2022-01-31T17:08:56 | 238,423,157 | 0 | 0 | Apache-2.0 | 2020-02-05T10:25:14 | 2020-02-05T10:25:13 | null | UTF-8 | Python | false | false | 3,530 | py | import json
import os
import re
import tempfile
import uuid
from pathlib import Path
import pytest
TOP_PATH = Path(__file__).parent
class TestTools():
@staticmethod
def find_files(file_name, search_path):
result = []
# root, directory, files
for root, _, files in os.walk(search_path):
for filename in files:
if file_name in filename:
result.append(os.path.abspath(os.path.join(root, filename)))
return result
@staticmethod
def get_text_file(src):
path = TOP_PATH / src
with open(path, 'r', encoding="utf-8") as data:
return data.readlines()
@staticmethod
def get_random_path_in_tmp():
return Path(tempfile.gettempdir()) / str(uuid.uuid4())
@staticmethod
def compare_results_html(result):
result_ = TestTools.get_text_file(result)
reference_pattern = TestTools.get_text_file(
'test_commands/test_data/referenc_pattern_html_report.txt')
prefix_start = '<script>var data_of_tree = '
prefix_end = ';</script><div>\n'
data_in_html = ""
matched = False
for row in result_:
if prefix_start in row and prefix_end in row:
matched = True
data_in_html = row
break
assert matched
tmp_json_str = data_in_html.replace(prefix_start, '').replace(prefix_end, '')
tmp_json = json.loads(tmp_json_str)
data_in_html = prefix_start + json.dumps(tmp_json, indent=4, sort_keys=False) + prefix_end
count_row = 0
rule_name = 'xccdforgssgprojectcontentrulepackageabrtremoved'
for row in reference_pattern:
if row in data_in_html or rule_name in row:
count_row += 1
assert count_row == len(reference_pattern)
@staticmethod
def get_data_json(src):
path = TOP_PATH / src
with open(path, 'r', encoding="utf-8") as data:
return json.load(data)
@staticmethod
def compare_results_json(result):
result = TestTools.get_data_json(result)
reference_result = TestTools.get_data_json(
'test_commands/test_data/referenc_result_data_json.json')
rule_name = "xccdf_org.ssgproject.content_rule_package_abrt_removed"
result_rule_name = [
x for x in result.keys() if re.search(
rule_name, x)]
assert result[result_rule_name[0]] == reference_result[rule_name]
@staticmethod
def find_all_in_string(regex, count, string):
assert len(re.findall(regex, string)) == count
@staticmethod
def get_questions_not_selected(capsys, client, result):
out = client.get_questions()[0].choices
assert out == result
captured = capsys.readouterr()
regex = r'rule_package_\w+_removed +\(Not selected\)'
TestTools.find_all_in_string(regex, 6, captured.out)
@staticmethod
def get_questions_with_option_show_failed_rules(client):
out = client.get_questions()[0].choices
rule1 = 'xccdf_org.ssgproject.content_rule_package_abrt_removed'
assert out[0] == rule1
with pytest.raises(Exception, match="list index out of range"):
assert out[2] is None
@staticmethod
def prepare_tree_test(client, rule):
rules = {'rules': [rule]}
results_src = client.prepare_data(rules)
TestTools.compare_results_html(results_src[0])
client.kill_web_browsers()
| [
"hony.com@seznam.cz"
] | hony.com@seznam.cz |
50da00dda33ee4c2a14d43488ca4da002f47d368 | f962e5082eee76c127fd76731df4ff4c93f0df79 | /src/zojax/newsletter/vocabulary.py | bc1998b45912841c80c85e96661648fc3b89fad1 | [
"ZPL-2.1"
] | permissive | Zojax/zojax.newsletter | b6ff222433fddf3f2411f619d95cb9b6580dd174 | 8275d1e9e65b34e6a59345be2cadc070272bac30 | refs/heads/master | 2021-01-01T16:12:35.312230 | 2011-08-09T22:33:14 | 2011-08-09T22:33:14 | 2,037,918 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,304 | py | ##############################################################################
#
# Copyright (c) 2008 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
$Id$
"""
from zope import interface
from zope.component import getUtility
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary
from interfaces import INewsletterProduct
class NewslettersVocabulary(object):
interface.implements(IVocabularyFactory)
def __call__(self, context):
product = getUtility(INewsletterProduct)
terms = []
for name, newsletter in product.items():
terms.append(
(newsletter.title, SimpleTerm(name, name, newsletter.title)))
terms.sort()
return SimpleVocabulary([term for title, term in terms])
| [
"andrey.fedoseev@gmail.com"
] | andrey.fedoseev@gmail.com |
6dfe1a4a4b9481dc683f14bdb2304fd439392e45 | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_199/2066.py | 6da9b64945c6b5b3a256889ce3f2e62be992b0de | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,020 | py | import numpy as np
import queue
def vectorize(s):
vector = np.zeros(len(s), dtype=np.bool)
for i in range(len(s)):
if s[i] == '+':
vector[i] = 0
else:
vector[i] = 1
return vector
def hash(arr):
s = list()
for e in arr:
if e:
s.append('-')
else:
s.append('+')
return ''.join(s)
def flip(arr, s, e):
arr[s:e] = np.ones(e-s) - arr[s:e]
def neighbors(arr, k):
for i in range(0 ,arr.shape[0] - k+1):
n = np.array(arr, copy=True)
flip(n, i, i+k)
yield n
def intersect(a, b):
return not set(map(tuple, a)).isdisjoint(map(tuple, b))
def double_bfs(a, b, k):
layerA = [a]
layerB = [b]
visitedA = set()
visitedB = set()
visitedA.add(hash(a))
visitedB.add(hash(b))
counta = 0
countb = 0
i = 0
while layerA and layerB and not intersect(layerA, layerB):
if i % 2:
tmpLayer = list()
for e in layerA:
for n in neighbors(e, k):
h = hash(n)
if h not in visitedA:
tmpLayer.append(n)
visitedA.add(h)
layerA = list()
layerA += tmpLayer
counta += 1
else:
tmpLayer = list()
for e in layerB:
for n in neighbors(e, k):
h = hash(n)
if h not in visitedB:
tmpLayer.append(n)
visitedB.add(h)
layerB = list()
layerB += tmpLayer
countb += 1
i += 1
if layerA and layerB:
return counta + countb
else:
return -1
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
s, k = tuple(input().split(" "))
k = int(k)
r = double_bfs(vectorize(s), np.zeros(len(s)), k)
if r == -1:
r = 'IMPOSSIBLE'
print("Case #{}: {} ".format(i, r))
| [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
83db0f6e8b3fec051b0592ba75b6a9710d03e8fe | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02411/s620883244.py | db7b1d2c327f09d76502a44758ef180738377b44 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 430 | py | a=[]
w=""
while(w!="-1 -1 -1"):
w=input()
a.append(w)
a.pop()
for st in a:
s=st.split()
m=int(s[0])
f=int(s[1])
r=int(s[2])
if (m==-1 or f==-1):
print("F")
elif (m+f>=80):
print("A")
elif(m+f>=65):
print("B")
elif(m+f>=50):
print("C")
elif(m+f>=30 and r>=50):
print("C")
elif(m+f>=30 and r<50):
print("D")
else:
print("F") | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
f6aae21a1d1ba38683187e0fe2deaf430c3544e5 | d5df07e8c505ce2d19994fa7e85e442b92f5d9fa | /list-test.py | 169cd9f059a05b10d78e4596557ebe031d76e69b | [] | no_license | ietuday/python-notes | 7c618413abea2bb51929ca162cc06763f3a41787 | 3c18f344cfc2c030fd9de26d9b763099bcd0683d | refs/heads/master | 2020-07-11T09:07:54.840245 | 2019-10-24T10:23:11 | 2019-10-24T10:23:11 | 204,498,941 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 408 | py | # my_list = [1, 2, 3]
# my_list1 = ['UDAY', 100, 23.2]
# my_list2 = ['Test', 55, 25.89]
# print(len(my_list))
# print(my_list1[0])
# print(my_list1[1:])
# print(my_list1 + my_list2)
# my_list1[0] = "uday"
# my_list1.append(6)
# my_list1.pop()
# my_list1.pop(0)
# print(my_list1)
new_list = ['a', 'e', 'x', 'b', 'c']
num_list = [4, 1, 8, 3]
new_list.sort()
num_list.reverse()
print(new_list)
print(num_list)
| [
"udayaditya.singh@gmail.com"
] | udayaditya.singh@gmail.com |
a9c00e769cbc58a04c1ecad8fd09e8afc0771992 | 8316b326d035266d41875a72defdf7e958717d0a | /SVM/__init__.py | 0f824238730fd5109d7c28e1c01f9bdaea17f273 | [] | no_license | MrFiona/MachineLearning | 617387592b51f38e59de64c090f943ecee48bf1a | 7cb49b8d86abfda3bd8b4b187ce03faa69e6302d | refs/heads/master | 2021-05-06T17:18:49.864855 | 2018-01-24T15:29:36 | 2018-01-24T15:29:36 | 111,804,323 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 159 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time : 2017-12-06 19:49
# Author : MrFiona
# File : __init__.py.py
# Software: PyCharm Community Edition | [
"1160177283@qq.com"
] | 1160177283@qq.com |
f9e83508d8e83fcc4f437a2cdfe467f30dc9a06e | 4e29395020ce78f435e75e0b3f1e09b227f6f4d8 | /ataraxia/inference/terror/python/terror-mixup/detect_infe.py | 14a21f3c149092acb9600535816e0740c435a594 | [] | no_license | luoyangustc/argus | 8b332d94af331a2594f5b1715ef74a4dd98041ad | 2ad0df5d7355c3b81484f6625b82530b38b248f3 | refs/heads/master | 2020-05-25T21:57:37.815370 | 2019-05-22T09:42:40 | 2019-05-22T09:42:40 | 188,005,059 | 5 | 3 | null | null | null | null | UTF-8 | Python | false | false | 4,674 | py | # -*- coding: utf-8 -*-
import traceback
import caffe
import cv2
import numpy as np
from evals.utils.error import *
from util_infe import *
def det_create_net(configs):
det_model = dict()
det_code = 0
det_message = ""
deploy = str(configs['model_files']["det_deploy.prototxt"])
weight = str(configs['model_files']["det_weight.caffemodel"])
labelfile = str(configs['model_files']["det_labels.csv"])
batch_size = 1
if "batch_size" in configs:
batch_size = configs['batch_size']
try:
change_deploy(deploy_file=deploy, input_data_batch_size=batch_size)
net = caffe.Net(deploy, weight, caffe.TEST)
label_dict = parse_label_file(labelfile)
det_model['net'] = net
det_model['label'] = label_dict
except Exception as e:
det_code = 400
det_message = "create model error"
det_model = {}
return det_model, det_code, det_message
def det_net_inference(det_model, images):
try:
resized_images, images_h_w = det_pre_eval(images)
output = det_eval(det_model['net'], resized_images)
ret = det_post_eval(images_h_w, output, det_model['label'])
except ErrorBase as e:
return [], e.code, str(e)
except Exception as e:
CTX.logger.error("inference error: %s", traceback.format_exc())
return [], 599, str(e)
return ret, 0, ''
def det_pre_eval(images):
resized_images = []
images_h_w = []
for index, i_data in enumerate(images):
height, width, _ = i_data.shape
images_h_w.append([height, width])
resized_images.append(det_preProcessImage(oriImage=i_data))
return resized_images, images_h_w
def det_post_eval(images_h_w, output, label_dict):
resps = []
_t1 = time.time()
# output_bbox_list : bbox_count * 7
output_bbox_list = output['detection_out'][0][0]
image_result_dict = dict() # image_id : bbox_list
for i_bbox in output_bbox_list:
# i_bbox : length == 7 ; 0==image_id,1==class_index,2==score,3==bbox_xmin,4==bbox_ymin,5==bbox_xmax,6==bbox_ymax
image_id = int(i_bbox[0])
if image_id >= len(images_h_w):
break
h = images_h_w[image_id][0]
w = images_h_w[image_id][1]
class_index = int(i_bbox[1])
if class_index < 1: # background index == 0 , refinedet not output background info ,so the line not used
continue
score = float(i_bbox[2])
if score < float(label_dict['threshold'][class_index]):
continue
name = label_dict['class'][class_index]
bbox_dict = dict()
bbox_dict['index'] = class_index
bbox_dict['score'] = score
bbox_dict['class'] = name
bbox = i_bbox[3:7] * np.array([w, h, w, h])
bbox_dict['pts'] = []
xmin = int(bbox[0]) if int(bbox[0]) > 0 else 0
ymin = int(bbox[1]) if int(bbox[1]) > 0 else 0
xmax = int(bbox[2]) if int(bbox[2]) < w else w
ymax = int(bbox[3]) if int(bbox[3]) < h else h
bbox_dict['pts'].append([xmin, ymin])
bbox_dict['pts'].append([xmax, ymin])
bbox_dict['pts'].append([xmax, ymax])
bbox_dict['pts'].append([xmin, ymax])
if image_id not in image_result_dict:
image_result_dict[image_id] = []
image_result_dict.get(image_id).append(bbox_dict)
for image_id in range(len(images_h_w)):
if image_id in image_result_dict:
resps.append(image_result_dict[image_id])
else:
resps.append([]) # the image_id output zero bbox info
return resps
def det_preProcessImage(oriImage=None):
img = cv2.resize(oriImage, (320, 320))
img = img.astype(np.float32, copy=False)
img = img - np.array([[[103.52, 116.28, 123.675]]])
img = img * 0.017
img = img.transpose((2, 0, 1))
return img
def det_eval(net, images):
'''
eval forward inference
Return
---------
output: network numpy.mdarray
'''
for index, i_data in enumerate(images):
net.blobs['data'].data[index] = i_data
output = net.forward()
if 'detection_out' not in output or len(output['detection_out']) < 1:
raise ErrorForwardInference()
return output
def det_checkSendToDetectOrNot(det_result, det_label_clsNeed):
# det_model_need_index = []
# for key in det_model['label']['clsNeed']:
# if int(det_model['label']['clsNeed'][key]) == 0:
# det_model_need_index.append(int(key))
retFlag = 0 # not send to detect model
for bbox in det_result:
if bbox['index'] in det_label_clsNeed:
retFlag = 1
return retFlag
| [
"luoyang@qiniu.com"
] | luoyang@qiniu.com |
af5e4461e66a2137c033c27dc911ef1b32dfb7e5 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_350/ch28_2019_08_26_19_23_44_756656.py | 136eecc3a1a9ad5a3ae059340d4ec3dcf72d8c70 | [] | 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 | 141 | py | x = float(input("qual velocidade?"))
if x> 80:
b= 5*(x-80)
print("pagar [0:.2f]".format(b))
else:
print( "Não multado")
| [
"you@example.com"
] | you@example.com |
0fc8a59904407fc02f5ff638fdf9ab119906cfdd | db1dcf7cf7218e0de8eb7fa0da709effa507c3bf | /matplotlib Plotting Cookbook/SF_MPC/Chapter2/_vti_cnf/11.py | d18fda36661c5ae2d2c0845bf8cb4673f0fd013e | [] | no_license | AaronCHH/B_PYTHON_matplotlib | a65da48771ce8248d51ee054eab91eeb3ce50e74 | 84c809800b3b797a09a5abfc76860ca7f7df8b80 | refs/heads/master | 2021-01-19T10:17:05.132372 | 2017-04-10T19:29:54 | 2017-04-10T19:29:54 | 87,849,667 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 192 | py | vti_encoding:SR|utf8-nl
vti_timelastmodified:TR|29 Jun 2013 08:03:58 -0000
vti_extenderversion:SR|12.0.0.0
vti_cacheddtm:TX|29 Jun 2013 08:03:58 -0000
vti_filesize:IR|432
vti_backlinkinfo:VX|
| [
"aaronhsu219@gmail.com"
] | aaronhsu219@gmail.com |
0414c312b0adc043e78392e1586e975937711833 | ed37c6acf35ad8dfa7064c7d304f046c3657cb7a | /leetcode/56_merge_intervals/solution_210429.py | c37c2065690797b4a019a10a0f897a3e3b549713 | [] | no_license | etture/algorithms_practice | 7b73753f5d579b7007ddd79f9a73165433d79b13 | ba398a040d2551b34f504ae1ce795e8cd5937dcc | refs/heads/master | 2021-11-18T20:37:11.730912 | 2021-10-03T23:25:24 | 2021-10-03T23:25:24 | 190,863,957 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,952 | py | # Basic imports --------------------------------------------
from __future__ import annotations
import sys
# 파이썬 기본 재귀 limit이 1000이라고 함 --> 10^6으로 manual하게 설정
sys.setrecursionlimit(10**6)
from os.path import dirname, abspath, basename, normpath
root = abspath(__file__)
while basename(normpath(root)) != 'algo_practice':
root = dirname(root)
sys.path.append(root)
from utils.Tester import Tester, Logger
logger = Logger(verbose=False)
# ----------------------------------------------------------
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
cur_intv = []
answer = list()
for intv in sorted(intervals, key=lambda x: (x[0], x[1])):
if len(cur_intv) == 0:
cur_intv = intv
elif intv[0] <= cur_intv[1]:
start = min(intv[0], cur_intv[0])
end = max(intv[1], cur_intv[1])
cur_intv = [start, end]
else:
answer.append(cur_intv)
cur_intv = intv
answer.append(cur_intv)
return answer
test_cases = [
([[[1,3],[2,6],[8,10],[15,18]]], [[1,6],[8,10],[15,18]]),
([[[1,4],[4,5]]], [[1,5]]),
([[[2,5],[6,10],[7,10],[8,12],[13,16],[15,16],[16,20],[21,25],[26,30],[27,31]]], [[2,5],[6,12],[13,20],[21,25],[26,31]]),
([[[1,2]]], [[1,2]]),
([[[1,4],[0,4]]], [[0,4]]),
([[[1,4],[2,3]]], [[1,4]]),
([[[2,4],[1,9]]], [[1,9]]),
([[[2,4],[3,4],[5,7],[7,8],[7,8],[7,9],[1,8],[3,8],[1,9]]], [[1,9]]),
]
if __name__ == '__main__':
sol = Solution()
Tester.factory(test_cases, func=lambda input: sol.merge(*input)).run(unordered_output=False)
| [
"etture@gmail.com"
] | etture@gmail.com |
90239e4ccaf243ab11b90610f1c6f3cacc2e01c2 | 7d2f933ed3c54e128ecaec3a771817c4260a8458 | /venv/Lib/site-packages/sklearn/utils/random.py | 415adab2197e6f4f24a35ebd361f44a12b118bd8 | [] | no_license | danielmoreira12/BAProject | c61dfb1d0521eb5a28eef9531a00e744bfb0e26a | 859f588305d826a35cc8f7d64c432f54a0a2e031 | refs/heads/master | 2021-01-02T07:17:39.267278 | 2020-02-25T22:27:43 | 2020-02-25T22:27:43 | 239,541,177 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,369 | py | # Author: Hamzeh Alsalhi <ha258@cornell.edu>
#
# License: BSD 3 clause
import array
import numpy as np
import scipy.sparse as sp
from . import check_random_state
from . import deprecated
from ._random import sample_without_replacement
__all__ = ['sample_without_replacement']
@deprecated("random_choice_csc is deprecated in version "
"0.22 and will be removed in version 0.24.")
def random_choice_csc(n_samples, classes, class_probability=None,
random_state=None):
return _random_choice_csc(n_samples, classes, class_probability,
random_state)
def _random_choice_csc(n_samples, classes, class_probability=None,
random_state=None):
"""Generate a sparse random matrix given column class distributions
Parameters
----------
n_samples : int,
Number of samples to draw in each column.
classes : list of size n_outputs of arrays of size (n_classes,)
List of classes for each column.
class_probability : list of size n_outputs of arrays of size (n_classes,)
Optional (default=None). Class distribution of each column. If None the
uniform distribution is assumed.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Returns
-------
random_matrix : sparse csc matrix of size (n_samples, n_outputs)
"""
data = array.array('i')
indices = array.array('i')
indptr = array.array('i', [0])
for j in range(len(classes)):
classes[j] = np.asarray(classes[j])
if classes[j].dtype.kind != 'i':
raise ValueError("class dtype %s is not supported" %
classes[j].dtype)
classes[j] = classes[j].astype(np.int64, copy=False)
# use uniform distribution if no class_probability is given
if class_probability is None:
class_prob_j = np.empty(shape=classes[j].shape[0])
class_prob_j.fill(1 / classes[j].shape[0])
else:
class_prob_j = np.asarray(class_probability[j])
if not np.isclose(np.sum(class_prob_j), 1.0):
raise ValueError("Probability array at index {0} does not sum to "
"one".format(j))
if class_prob_j.shape[0] != classes[j].shape[0]:
raise ValueError("classes[{0}] (length {1}) and "
"class_probability[{0}] (length {2}) have "
"different length.".format(j,
classes[j].shape[0],
class_prob_j.shape[0]))
# If 0 is not present in the classes insert it with a probability 0.0
if 0 not in classes[j]:
classes[j] = np.insert(classes[j], 0, 0)
class_prob_j = np.insert(class_prob_j, 0, 0.0)
# If there are nonzero classes choose randomly using class_probability
rng = check_random_state(random_state)
if classes[j].shape[0] > 1:
p_nonzero = 1 - class_prob_j[classes[j] == 0]
nnz = int(n_samples * p_nonzero)
ind_sample = sample_without_replacement(n_population=n_samples,
n_samples=nnz,
random_state=random_state)
indices.extend(ind_sample)
# Normalize probabilities for the nonzero elements
classes_j_nonzero = classes[j] != 0
class_probability_nz = class_prob_j[classes_j_nonzero]
class_probability_nz_norm = (class_probability_nz /
np.sum(class_probability_nz))
classes_ind = np.searchsorted(class_probability_nz_norm.cumsum(),
rng.rand(nnz))
data.extend(classes[j][classes_j_nonzero][classes_ind])
indptr.append(len(indices))
return sp.csc_matrix((data, indices, indptr),
(n_samples, len(classes)),
dtype=int)
| [
"danielmoreira12@github.com"
] | danielmoreira12@github.com |
be0c7c9847c375566f6bdcba686ff45f5a1ba5a3 | e40def3bc96af0847983ea3b7eafb711dfd8a349 | /pandas/plot.py | 48b82d14a29e8f4de64215972de9787f2358f852 | [] | no_license | dagangge/myPythonCode | c4c84529a6ea65851972ecdf730b61da1ae6c7d1 | d9ec6691acfca3634f175274025dad6532353363 | refs/heads/master | 2023-04-01T04:39:16.379663 | 2021-04-14T14:11:31 | 2021-04-14T14:11:31 | 298,705,491 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 198 | py | import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib
import matplotlib.pyplot as plt
s=Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
s.plot() | [
"865580807@qq.com"
] | 865580807@qq.com |
54dbad31362f52c4ea7f27268e7bacc584d53a40 | 903d03d6c69080fb798b51fa081edd973431f442 | /test.py | e3a63ded76781894dcb2a94e604d291c299cb673 | [] | no_license | possager/weiboAPI | 72e9c274f287e90c5bbe6d52bc8f6a08174fa5bd | 22736bfabd6aafef3cb5f6062b949813cf4af9c8 | refs/heads/master | 2021-01-19T09:25:11.697153 | 2017-05-27T09:40:11 | 2017-05-27T09:40:11 | 87,757,780 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,889 | py | from weibo import APIClient
import dataEncode
import webbrowser
import urllib2
import requests
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
import json
import ssl
APP_KEY='922763770'
APP_SECRET='0ee74c72b699d61d2f7062ec8034496c'
CALLBACK='http://www.baidu.com'
client=APIClient(app_key=APP_KEY,app_secret=APP_SECRET,redirect_uri=CALLBACK)
url=client.get_authorize_url()
print url
aaa=time.time()
# a=webbrowser.open(url)
# request=client.request_access_token('de7a0d762b801f6160ce6007987ceb85'
# )
# access_token=request.access_token
# expires_in=request.expiress_in
# client.set_access_token(access_token,expires_in)
# client.statuses.updata.post(statues=u'Test OAuth 2.0 Send a Weibo!')
chrome=webdriver.Chrome()
chrome.get(url)
chrome.find_element_by_id('userId').send_keys('passager@163.com')
chrome.find_element_by_id('passwd').send_keys('ll13715325265')
time.sleep(0.6)
chrome.find_element_by_css_selector('#outer > div > div.WB_panel.oauth_main > form > div > div.oauth_login_box01.clearfix > div > p > a.WB_btn_login.formbtn_01').click()
time.sleep(2)
print chrome.current_url
url2=chrome.current_url
chrome.close()
bbb=time.time()
print bbb-aaa
code=url2.split('code=')[1]
r=client.request_access_token(code)
# print help(r)
accesstoken=r.get('access_token')
print r.keys()
expiresin= r.get('expires_in')
# print r.get('uid')
# print r.get('expires')
# client.set_access_token(access_token=accesstoken,expires=expiresin)
#
# print client.statuses.user_timeline.get()
# print client.user.show.get()
data={
'access_token':accesstoken
}
print accesstoken
url3='https://api.weibo.com/2/statuses/user_timeline/ids.json?access_token='+accesstoken
# request1=urllib2.urlopen(url3,data=data,context=ssl._create_default_https_context)
request1=requests.get(url3,verify=False).content
print request1 | [
"passager@163.com"
] | passager@163.com |
1d61846901aede39d970d9d42c1de5c0d0d2caf7 | 825f2018da6c27f0260078d299a1e1e8cac59c98 | /_setupares.py | d89d6562da731efc56edd9ecf1f1b0388190039d | [
"Python-2.0",
"MIT"
] | permissive | dropkitchen/gevent | 9c99db94bb58e17ce814425f80c0b67772e1cfb2 | 785b7b5546fcd0a184ea954f5d358539c530d95f | refs/heads/master | 2020-12-10T16:37:12.861841 | 2020-01-13T14:20:26 | 2020-01-13T14:20:26 | 233,649,088 | 0 | 0 | NOASSERTION | 2020-01-13T17:07:31 | 2020-01-13T17:07:30 | null | UTF-8 | Python | false | false | 4,037 | py | # -*- coding: utf-8 -*-
"""
setup helpers for c-ares.
"""
from __future__ import print_function, absolute_import, division
import os
import os.path
import shutil
import sys
from _setuputils import Extension
import distutils.sysconfig # to get CFLAGS to pass into c-ares configure script pylint:disable=import-error
from _setuputils import WIN
from _setuputils import quoted_dep_abspath
from _setuputils import system
from _setuputils import make_universal_header
from _setuputils import should_embed
from _setuputils import LIBRARIES
from _setuputils import DEFINE_MACROS
from _setuputils import glob_many
from _setuputils import dep_abspath
from _setuputils import RUNNING_ON_CI
from _setuputils import RUNNING_FROM_CHECKOUT
from _setuputils import cythonize1
CARES_EMBED = should_embed('c-ares')
# See #616, trouble building for a 32-bit python against a 64-bit platform
_config_vars = distutils.sysconfig.get_config_var("CFLAGS")
if _config_vars and "m32" in _config_vars:
_m32 = 'CFLAGS="' + os.getenv('CFLAGS', '') + ' -m32" '
else:
_m32 = ''
# Use -r, not -e, for support of old solaris. See
# https://github.com/gevent/gevent/issues/777
ares_configure_command = ' '.join([
"(cd ", quoted_dep_abspath('c-ares'),
" && if [ -r ares_build.h ]; then cp ares_build.h ares_build.h.orig; fi ",
" && sh ./configure --disable-dependency-tracking -C " + _m32 + "CONFIG_COMMANDS= ",
" && cp ares_config.h ares_build.h \"$OLDPWD\" ",
" && cat ares_build.h ",
" && if [ -r ares_build.h.orig ]; then mv ares_build.h.orig ares_build.h; fi)",
"> configure-output.txt"])
def configure_ares(bext, ext):
print("Embedding c-ares", bext, ext)
bdir = os.path.join(bext.build_temp, 'c-ares')
ext.include_dirs.insert(0, bdir)
print("Inserted ", bdir, "in include dirs", ext.include_dirs)
if not os.path.isdir(bdir):
os.makedirs(bdir)
if WIN:
src = "deps\\c-ares\\ares_build.h.dist"
dest = os.path.join(bdir, "ares_build.h")
print("Copying %r to %r" % (src, dest))
shutil.copy(src, dest)
return
cwd = os.getcwd()
os.chdir(bdir)
try:
if os.path.exists('ares_config.h') and os.path.exists('ares_build.h'):
return
try:
system(ares_configure_command)
except:
with open('configure-output.txt', 'r') as t:
print(t.read(), file=sys.stderr)
raise
if sys.platform == 'darwin':
make_universal_header('ares_build.h', 'CARES_SIZEOF_LONG')
make_universal_header('ares_config.h', 'SIZEOF_LONG', 'SIZEOF_SIZE_T', 'SIZEOF_TIME_T')
finally:
os.chdir(cwd)
ARES = Extension(name='gevent.resolver.cares',
sources=['src/gevent/resolver/cares.pyx'],
include_dirs=['src/gevent/resolver'] + [dep_abspath('c-ares')] if CARES_EMBED else [],
libraries=list(LIBRARIES),
define_macros=list(DEFINE_MACROS),
depends=glob_many('src/gevent/resolver/dnshelper.c',
'src/gevent/resolver/cares_*.[ch]'))
ares_required = RUNNING_ON_CI and RUNNING_FROM_CHECKOUT
ARES.optional = not ares_required
if CARES_EMBED:
ARES.sources += glob_many('deps/c-ares/*.c')
# Strip the standalone binaries that would otherwise
# cause linking issues
for bin_c in ('acountry', 'adig', 'ahost'):
ARES.sources.remove('deps/c-ares' + os.sep + bin_c + '.c')
ARES.configure = configure_ares
if WIN:
ARES.libraries += ['advapi32']
ARES.define_macros += [('CARES_STATICLIB', '')]
else:
ARES.define_macros += [('HAVE_CONFIG_H', '')]
if sys.platform != 'darwin':
ARES.libraries += ['rt']
ARES.define_macros += [('CARES_EMBED', '1')]
else:
ARES.libraries.append('cares')
ARES.define_macros += [('HAVE_NETDB_H', '')]
ARES.configure = lambda bext, ext: print("c-ares not embedded, not configuring", bext, ext)
ARES = cythonize1(ARES)
| [
"jamadden@gmail.com"
] | jamadden@gmail.com |
9c7acc99003214db1aeb7c8fd53410f903cd0bbd | 7a11b6d4063685cb08b074ac8d08ab6e1d045ff5 | /repeat_from_book/checker.py | 95f7070c10dfc1dc4b2da7b88ba417880a7d04c2 | [] | no_license | slavaider/python | 8a9f5769bd519e0e270c5814ef46ec5c653ab7c1 | f98896b8e9dd93fe7d2b4a495b67704ef5f08373 | refs/heads/master | 2023-03-02T15:12:56.218871 | 2021-02-07T16:20:08 | 2021-02-07T16:20:32 | 301,493,207 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 277 | py | from functools import wraps
from flask import session
def check_logged_in(func):
@wraps(func)
def wrapper(*args, **kwargs):
if 'logged_in' in session:
return func(*args, **kwargs)
return 'You are currently logged out'
return wrapper
| [
"slavaider1@gmail.com"
] | slavaider1@gmail.com |
caee573049550a60b14c325eae47beb72ed3dcf2 | a149044762566830b4356343c062ee84c8056471 | /healthid/tests/products/test_batch_info.py | 27d0d43cae787809178d65b62d884feda6c67ec4 | [] | no_license | malep2007/healtid-web-api | 23fbe8b34a3c5256cbb60cf15205f65cc035df13 | d9e88b4d8fe1dbc297b61bb007d4182928e515d4 | refs/heads/dev | 2022-12-12T03:24:37.537569 | 2019-12-17T16:26:59 | 2019-12-17T16:26:59 | 228,655,076 | 0 | 1 | null | 2022-12-08T05:25:00 | 2019-12-17T16:17:27 | Python | UTF-8 | Python | false | false | 4,036 | py | from healthid.tests.base_config import BaseConfiguration
from healthid.tests.test_fixtures.batch_info \
import batch_info_query, update_batch_info, \
query_product_batch_info, single_batch_info, \
all_batch_info, delete_batch_info, near_expired_batches
from healthid.utils.messages.products_responses import PRODUCTS_ERROR_RESPONSES
class TestBatchInfo(BaseConfiguration):
"""
Testing Adding user by the Master Admin
"""
def setUp(self):
super().setUp()
self.batch_data = {
'product_id': self.product.id,
'supplier_id': self.supplier.id,
'expiry_date': '2020-02-10'
}
def test_add_batch_info(self):
"""
test batch info creation
"""
resp = self.query_with_token(
self.access_token, batch_info_query.format(**self.batch_data))
self.assertIn('data', resp)
self.assertEqual(
resp['data']['createBatchInfo']['batchInfo']['supplier']['name'],
self.supplier.name)
def test_update_batch(self):
"""
Test if batch can be updated.
"""
self.batch_data['batch_id'] = self.batch_info.id
resp = self.query_with_token(
self.access_token_master,
update_batch_info.format(**self.batch_data))
self.assertIn('data', resp)
self.assertEqual(
resp['data']['updateBatchInfo']['batchInfo']['supplier']['name'],
self.supplier.name)
self.assertEqual(
resp['data']['updateBatchInfo']['batchInfo']['batchNo'],
self.batch_info.batch_no)
def test_product_batches(self):
product_data = {'product_id': self.product.id}
resp = self.query_with_token(
self.access_token, query_product_batch_info.format(**product_data))
self.assertIn('data', resp)
self.assertEqual(resp['data']['productBatchInfo'][0]['batchNo'],
self.batch_info.batch_no)
def test_single_batch_info(self):
product_data = {'batch_id': self.batch_info.id}
resp = self.query_with_token(self.access_token,
single_batch_info.format(**product_data))
self.assertIn('data', resp)
self.assertEqual(resp['data']['batchInfo']['batchNo'],
self.batch_info.batch_no)
def test_all_batch_info(self):
resp = self.query_with_token(self.access_token, all_batch_info)
self.assertIn('data', resp)
self.assertEqual(resp['data']['allBatchInfo'][0]['batchNo'],
self.batch_info.batch_no)
def test_invalid_date_format(self):
"""
test wrong date format
"""
date_field = 'expiry_date'
self.batch_data['expiry_date'] = date_field
resp = self.query_with_token(
self.access_token, batch_info_query.format(**self.batch_data))
self.assertIn(
'invalid literal',
resp['errors'][0]['message'])
def test_invalid_batch_info_id(self):
"""
test wrong batch info id
"""
batch_info_id = '12121212121'
self.batch_data['batch_id'] = batch_info_id
resp = self.query_with_token(
self.access_token_master,
update_batch_info.format(**self.batch_data))
self.assertIn('data', resp)
self.assertIn(PRODUCTS_ERROR_RESPONSES[
"inexistent_batchinfo"].format(batch_info_id),
resp['errors'][0]['message'])
def test_delete_batch_info(self):
batch_info = {'batch_id': self.batch_info.id}
resp = self.query_with_token(self.access_token_master,
delete_batch_info.format(**batch_info))
self.assertIn('data', resp)
def test_near_expired_batches(self):
response = self.query_with_token(
self.access_token, near_expired_batches)
self.assertIn('nearExpiredBatches', response['data'])
| [
"ephraim.malinga@gmail.com"
] | ephraim.malinga@gmail.com |
b42a0e6d37ee2a5fa993caa522af78285fec971f | 64cbac4b5381d9692da08ff42d958d1149afa47d | /rooms/default/usual/troll_bridge.py | d75506a799df9a1128a4d16c7a1c327e2ec65c4b | [] | no_license | kolobok001/Uirs | 3c4c78c255849a66da88a35263f7d18d1bf31c0c | b9ab1e672f3f60c62cef3d6879f3d8ceefa091b2 | refs/heads/master | 2020-04-10T05:50:56.215016 | 2019-06-19T16:39:41 | 2019-06-19T16:39:41 | 160,838,488 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,135 | py | from constants import *
import random
name = 'Мост'
c_PRICE = 75 # Стоимость прохода
c_MIN_ROOM_COUNT = 200 # Мин комнат
c_MIN_STRENGTH_ANSW = 100 # Мин силы для нападения
c_MIN_INTELL_ANSW = 100 # Мин интелекта для ответа
c_TROLL_R1 = 'Вы видите огромного тролля. Часть его лица покрыта мхом, остальную украшают множество шрамов. На голове у него советская каска со звездой.\n\n — Через этот мост просто так не ходят! Плати {} или обед!'.format(c_PRICE)
c_TROLL_R2 = ' — О привет боец. Не узнал сразу. Ты давай иди... Иди.'
GO = 'Пройти через мост'
LEAVE = 'Пройти мимо'
ESCAPE = 'Попытаться вырваться и убежать'
GUP = 'Сдаться'
PAY = 'Заплатить 75 золотых'
EAT = 'Обед?!'
FIGHT = 'Напасть!'
CHEAT = 'Служу Советскому Союзу!'
def enter(user, reply):
msg = (
'Обычный такой мост. Через самую обычную реку.'
)
reply(msg, photo='BQADAgAD2wgAAmrZzgdIlwyFp4vXPwI')
user.set_room_temp('question', 'first')
def dice(user, reply, result, subject=None):
if subject == ESCAPE:
if result > (DICE_MAX / 4) * 3:
reply('Вы сумели вырвать свою лодыжку из на секунду ослабшей хватки. Нога побаливает, но вы на свободе!')
user.make_damage(10,15,reply)
user.leave(reply)
elif result < DICE_MAX / 4:
reply('Удача отвернулась от Вас. В попытке вырваться Вы умудрились удариться головой об мост и умереть.')
user.death(reply, reason=name)
else:
reply('Попытка вырваться была бесполезной. Вы под мостом.')
if user.has_item('sunion_helmet'):
reply(c_TROLL_R2)
user.leave(reply)
else:
reply(c_TROLL_R1)
user.set_room_temp('question','underbridge')
elif subject == FIGHT:
if result > (DICE_MAX / 5) * 4:
reply('Ловким ударом вы сбили каску троллю на глаза. Второй окончательно отправил монстра в мир снов.')
reply('Вы нашли немного денег и забрали каску.')
user.add_item('loot','sunion_helmet')
user.give_gold(random.randrange(5,100,5))
user.leave(reply)
else:
reply('Зря вы так поверили в свои силы. Драться с троллем — та еще затея.')
user.death(reply, reason=name)
def action(user, reply, text):
question = user.get_room_temp('question',def_val='first')
if question == 'first':
if text == GO:
if user.rooms_count < c_MIN_ROOM_COUNT:
reply('Проходя по мосту вы нашли золотую монетку.')
user.add_item('neutral','coin')
user.leave(reply)
else:
reply('Огромная лапа схватила вас за ногу и тянет под мост.')
user.set_room_temp('question','scarryhand')
elif text == LEAVE:
reply('Вы прошли мимо.')
user.leave(reply)
elif question == 'scarryhand':
if text == GUP:
reply('Вы под мостом.')
if user.has_item('sunion_helmet'):
reply(c_TROLL_R2)
user.leave(reply)
else:
reply(c_TROLL_R1)
user.set_room_temp('question','underbridge')
elif text == ESCAPE:
user.throw_dice(reply, ESCAPE)
elif question == 'underbridge':
if text == FIGHT:
user.throw_dice(reply, FIGHT)
elif text == PAY:
if user.paid(c_PRICE):
reply('Тролль отпустил вас.')
else:
reply('Ввиду отсутвия у вас необходимой суммы, Тролль хорошенько намял Вам бока, перед тем как отпустить.')
user.make_damage(40,70,reply,name=name)
user.leave(reply)
elif text == EAT:
reply('Тролль был очень рад, что Вы решили его накормить. Жаль только пообедал он вами.')
user.death(reply, reason=name)
elif text == CHEAT:
reply(' — Молодец боец. Аккуратней ходить нужно. Вот держи каску, береги голову.')
user.add_item('loot','sunion_helmet')
user.leave(reply)
def get_actions(user):
question = user.get_room_temp('question',def_val='first')
answers = []
if question == 'first':
answers = [ GO, LEAVE ]
if question == 'scarryhand':
answers = [ GUP, ESCAPE ]
if question == 'underbridge':
answers = [ PAY, EAT ]
if user.damage >= c_MIN_STRENGTH_ANSW:
answers += [ FIGHT ]
if user.mana_damage >= c_MIN_INTELL_ANSW:
answers += [ CHEAT ]
random.shuffle(answers)
return answers
| [
"ang14@tpu.ru"
] | ang14@tpu.ru |
b44784ea4cd012dae3fbd9559a9c116273a2f562 | 26f5cf8b9a5f264489eeed963f33f367b63846a5 | /books/urls.py | 7560d84530053653cf89891da5551ae34df5266b | [] | no_license | ondrejsika/django-and-rest-framework-example | 0d789fb3d72b104ac6a0f0c44778647d5c38f80b | 2f7252204091a7a7df6af28ed0dad9178a5bfc29 | refs/heads/master | 2020-03-31T07:25:41.474003 | 2018-10-08T07:10:34 | 2018-10-08T07:10:34 | 152,021,376 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 515 | py | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
path('authors/', views.AuthorList.as_view()),
path('authors/<int:pk>/', views.AuthorDetail.as_view()),
path('books/', views.BookList.as_view()),
path('books/<int:pk>/', views.BookDetail.as_view()),
path('books-full/', views.BookFullList.as_view()),
path('books-full/<int:pk>/', views.BookFullDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns) | [
"ondrej@ondrejsika.com"
] | ondrej@ondrejsika.com |
24911df90b31620520ed626ab5dfd9a7d3c31978 | 27ce4fe663d6f9e6a02b1a2ac455b28625817bbe | /project_name/apps/module/models.py | f18ce09d112d807293363c151d3621a5ff4a1789 | [] | no_license | jonaqp/restaurant | e7da25bba0f6ccae2be65a6da3ece11026f196c7 | 749e2f9e9e3b7417b483e0f6897925172ecbac82 | refs/heads/master | 2021-07-19T10:49:21.293986 | 2017-10-23T23:03:17 | 2017-10-23T23:03:18 | 108,049,029 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,819 | py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from project_name.apps.core import constants as core_constants
from project_name.apps.core.models import Role, Permission
from project_name.apps.core.utils.fields import BaseModel
class Module(BaseModel):
band_choice = core_constants.TYPE_BAND_OPTIONS
name = models.CharField(
_('name'), max_length=200, null=True, blank=True)
icon = models.CharField(
_('icon'), max_length=200, null=True, blank=True)
match = models.CharField(
_('match'), default="#", max_length=200, null=False, blank=False)
urlName = models.CharField(
_('urlName'), max_length=200, null=True, blank=True)
reference = models.CharField(
_('reference'), unique=True, max_length=100, null=False, blank=False)
order = models.IntegerField(
_('order'), default=0, null=False, blank=False)
bandType = models.CharField(
_('band type'), choices=band_choice,
max_length=80, default=core_constants.CODE_BAND_ONE)
class Meta:
ordering = ['order']
unique_together = ['name']
verbose_name = _('01. module')
verbose_name_plural = _('01. modules')
def __str__(self):
return self.name
class ModuleItem(BaseModel):
name = models.CharField(
_('name'), max_length=200, null=True, blank=True)
icon = models.CharField(
_('icon'), max_length=200, null=True, blank=True)
match = models.CharField(
_('match'), default="#", max_length=200, null=False, blank=False)
urlName = models.CharField(
_('urlName'), max_length=200, null=True, blank=True)
reference = models.CharField(
_('reference'), unique=True, max_length=100, null=False, blank=False)
order = models.IntegerField(
_('order'), null=False, blank=False, default=0)
moduleId = models.ForeignKey(
Module, verbose_name=_('module'),
related_name="%(app_label)s_%(class)s_moduleId",
)
def module_text(self):
return "{0}".format(self.moduleId)
class Meta:
ordering = ['moduleId']
verbose_name = _('02. module item')
verbose_name_plural = _("02. module items")
def __str__(self):
return "{0}-{1}".format(self.moduleId, self.name)
class RoleModule(BaseModel):
roleId = models.ForeignKey(
Role, verbose_name=_('role'),
related_name="%(app_label)s_%(class)s_roleId",
on_delete=models.SET_NULL, blank=True, null=True)
moduleId = models.ForeignKey(
Module, verbose_name=_('module'),
related_name="%(app_label)s_%(class)s_moduleId",
on_delete=models.SET_NULL, blank=True, null=True)
class Meta:
unique_together = ["roleId", "moduleId"]
verbose_name = _('03. module team')
verbose_name_plural = _('03. module teams')
def get_moduleitem_list(self):
module_item = RoleModuleItem.objects.filter(roleModuleId=self)
return ", ".join([p.moduleItemId.name for p in module_item])
def get_module_order(self):
return self.moduleId.order
def __str__(self):
return "{0}".format(self.moduleId)
class RoleModuleItem(BaseModel):
roleModuleId = models.ForeignKey(
RoleModule, verbose_name=_('role module'),
related_name="%(app_label)s_%(class)s_roleModuleId",
)
moduleItemId = models.ForeignKey(
ModuleItem, verbose_name=_('module item'),
related_name="%(app_label)s_%(class)s_moduleItemId",
)
class Meta:
unique_together = ['roleModuleId', 'moduleItemId']
verbose_name = _('04. module item team')
verbose_name_plural = _('04. module item teams')
def __str__(self):
return "{0} | {1}".format(self.roleModuleId, self.moduleItemId.name)
| [
"jony327@gmail.com"
] | jony327@gmail.com |
a16c8f741256dc75de021a3213e8e222b279ca0b | cf62f7a7f9e13205fe83957fb7bfcf1b097bf481 | /src/demo/mygene_info_demo_tornado.py | 30251600990815c04ad9abefc0bc4e7cd5f0f9f2 | [
"Apache-2.0"
] | permissive | biothings/mygene.info | 09bf19f481c066789a4ad02a0d2880f31dae28f6 | fe1bbdd81bc29b412ca4288d3af38e47c0602ab7 | refs/heads/master | 2023-08-22T21:34:43.540840 | 2023-08-08T23:25:15 | 2023-08-08T23:25:18 | 54,933,630 | 89 | 20 | NOASSERTION | 2023-07-18T23:53:49 | 2016-03-29T00:36:49 | Python | UTF-8 | Python | false | false | 3,292 | py | # Copyright [2013-2014] [Chunlei Wu]
#
# 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
if sys.version > '3':
PY3 = True
else:
PY3 = False
if PY3:
import urllib.request, urllib.parse, urllib.error
import http.client
else:
import urllib
import httplib
import types
import json
import tornado.httpserver
import tornado.ioloop
import tornado.web
def call_service(url):
if PY3:
h = http.client.HTTPConnection('mygene.info')
else:
h = httplib.HTTPConnection('mygene.info')
h.request('GET', url)
res = h.getresponse()
con = res.read()
if res.status == 200:
out = json.loads(con)
return out
class MainHandler(tornado.web.RequestHandler):
def get(self):
d = {'gene_list': None, 'ps_list': None, 'error': None}
query = self.get_argument('q', '')
if query:
if PY3:
out = call_service('/v2/query?' + urllib.parse.urlencode(dict(q=query, species='mouse', limit=1000)))
else:
out = call_service('/v2/query?' + urllib.urlencode(dict(q=query, species='mouse', limit=1000)))
if 'total' in out:
gene_list = []
for gene in out['hits']:
gene_list.append({'id': gene['_id'],
'symbol': gene.get('symbol', 'None'),
'name': gene.get('name', '')})
d['gene_list']=gene_list
else:
d['error'] = out.get('error', out.get('reason', 'Invalid query!'))
else:
geneid = self.get_argument('showgene', '')
if geneid:
#show gene page
gene = call_service('/v2/gene/%s?fields=reporter' % geneid)
ps_list = []
if gene and 'reporter' in gene:
ps_list = gene['reporter'].get('Mouse430_2',[])
if PY3:
if type(ps_list) is not list:
# if only one probeset available, it's returned as a string, so we need to convert it to a list
ps_list = [ps_list]
else:
if type(ps_list) is not types.ListType:
# if only one probeset available, it's returned as a string, so we need to convert it to a list
ps_list = [ps_list]
d['ps_list'] = ps_list
self.render('templates/demo_form.html', **d)
def main():
application = tornado.web.Application([(r"/", MainHandler)])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8000, address='127.0.0.1')
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
| [
"devnull@localhost"
] | devnull@localhost |
781eb5722fec078b29ed808af679ab9a0b5b8f0e | d2e8ad203a37b534a113d4f0d4dd51d9aeae382a | /django_graphene_authentication/django_graphene_authentication/relay.py | 9d2f1c2163c056870935260c72b97ce76640a60c | [
"MIT"
] | permissive | Koldar/django-koldar-common-apps | 40e24a7aae78973fa28ca411e2a32cb4b2f4dbbf | 06e6bb103d22f1f6522e97c05ff8931413c69f19 | refs/heads/main | 2023-08-17T11:44:34.631914 | 2021-10-08T12:40:40 | 2021-10-08T12:40:40 | 372,714,560 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 579 | py | import graphene
from django_graphene_authentication.refresh_token import mixins
class Revoke(mixins.RevokeMixin, graphene.ClientIDMutation):
class Input:
refresh_token = graphene.String()
@classmethod
def mutate_and_get_payload(cls, *args, **kwargs):
return cls.revoke(*args, **kwargs)
class DeleteRefreshTokenCookie(
mixins.DeleteRefreshTokenCookieMixin,
graphene.ClientIDMutation):
@classmethod
def mutate_and_get_payload(cls, *args, **kwargs):
return cls.delete_cookie(*args, **kwargs)
| [
"massimobono1@gmail.com"
] | massimobono1@gmail.com |
ffe5cd63811f205748b69cb9a622c880e614a86d | a34e3d435f48ef87477d3ae13ca8a43015e5052c | /testcl;.py | c218f4f1968829da715a9b944993ec581fa8467a | [] | no_license | haehn/sandbox | 636069372fc7bb7fd72b5fde302f42b815e8e9b0 | e49a0a30a1811adb73577ff697d81db16ca82808 | refs/heads/master | 2021-01-22T03:39:03.415863 | 2015-02-11T23:16:22 | 2015-02-11T23:16:22 | 26,128,048 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 839 | py | import numpy as np
import pyopencl as cl
import cv2
import time
import sys
img = cv2.imread(sys.argv[1], cv2.CV_LOAD_IMAGE_GRAYSCALE)
width, height = (img.shape[0], img.shape[1])
img_s = img.ravel()
ctx = cl.create_some_context()
start_t = time.clock()
queue = cl.CommandQueue(ctx)
mf = cl.mem_flags
a_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=img_s)
# b_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b_np)
prg = cl.Program(ctx, """
__kernel void sum(__global const uchar *a_g, __global uchar *res_g) {
int gid = get_global_id(0);
res_g[gid] = a_g[gid];
}
""").build()
res_g = cl.Buffer(ctx, mf.WRITE_ONLY, img_s.nbytes)
prg.sum(queue, img_s.shape, None, a_g, res_g)
res_np = np.empty_like(img_s)
cl.enqueue_copy(queue, res_np, res_g)
# Check on CPU with Numpy:
print time.clock() - start_t | [
"haehn@seas.harvard.edu"
] | haehn@seas.harvard.edu |
79b8e52abe81a012cea985b58ba90198dbb33399 | a4e0ececd5e55d67af59fd262ab4673b55998912 | /mantisshrimp/models/rcnn/loss_fn.py | c9b09348d89138e97dadb43b20c7e9004e85c45a | [
"Apache-2.0"
] | permissive | JCustin/mantisshrimp | 4f7d76eaf412c9b3a2ab3c8e726010c889ee366e | af24828515258e068da22d2e95412081385af710 | refs/heads/master | 2022-11-21T08:13:53.370185 | 2020-07-27T14:55:45 | 2020-07-27T14:55:45 | 283,005,733 | 0 | 0 | null | 2020-07-27T20:14:02 | 2020-07-27T20:14:01 | null | UTF-8 | Python | false | false | 130 | py | __all__ = ["loss_fn"]
from mantisshrimp.imports import *
def loss_fn(preds, targets) -> Tensor:
return sum(preds.values())
| [
"lucasgouvaz@gmail.com"
] | lucasgouvaz@gmail.com |
9f38bf6c3538159ed9420272c258efc56153ac61 | d554b1aa8b70fddf81da8988b4aaa43788fede88 | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4123/codes/1836_2602.py | 375ed4a876dddcca1a85349d57566605fb884002 | [] | no_license | JosephLevinthal/Research-projects | a3bc3ca3b09faad16f5cce5949a2279cf14742ba | 60d5fd6eb864a5181f4321e7a992812f3c2139f9 | refs/heads/master | 2022-07-31T06:43:02.686109 | 2020-05-23T00:24:26 | 2020-05-23T00:24:26 | 266,199,309 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 354 | py | from numpy import*
from numpy.linalg import*
vet = array(eval(input()))
bac = array([[2,1,4],[1,2,0],[2,3,2]])
tot = dot(inv(bac),vet.T)
print("estafilococo:",round(tot[0],1))
print("salmonela:",round(tot[1],1))
print("coli:",round(tot[2],1))
if tot[0] == min(tot):
print("estafilococo")
elif tot[1] == min(tot):
print("salmonela")
else:
print("coli") | [
"jvlo@icomp.ufam.edu.br"
] | jvlo@icomp.ufam.edu.br |
912e06fc01774d8e264451b8bdbcc9eb27fbddb4 | 26f6313772161851b3b28b32a4f8d255499b3974 | /Python/1796_SecondLargestDigitinaString.py | da88296810ceba5b1f0af5e196c98189a9449b32 | [] | no_license | here0009/LeetCode | 693e634a3096d929e5c842c5c5b989fa388e0fcd | f96a2273c6831a8035e1adacfa452f73c599ae16 | refs/heads/master | 2023-06-30T19:07:23.645941 | 2021-07-31T03:38:51 | 2021-07-31T03:38:51 | 266,287,834 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 936 | py | """
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
Example 1:
Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Example 2:
Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit.
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters and/or digits.
"""
class Solution:
def secondHighest(self, string: str) -> int:
digits = list(set([int(s) for s in string if s.isdigit()]))
# print(digits)
digits.sort()
return -1 if len(digits) < 2 else digits[-2]
S = Solution()
string = "dfa12321afd"
print(S.secondHighest(string))
string = "abc1111"
print(S.secondHighest(string))
| [
"here0009@163.com"
] | here0009@163.com |
1b370635bc20855456c5ed1d1e3a001af1b670e6 | 74f902dedade999b9b6d9567c87f80d5975d6813 | /day3/intro/11_args.py | 84cde6d1acf1907496e2999462aa6af0eaf36208 | [
"MIT"
] | permissive | britneh/CS35_IntroPython_GP | ed315daad2b06eeef9ec7d1040e3c5a874dbaf0d | e0a3441766973a833341b3f1f16f33d6c9f5c0d3 | refs/heads/main | 2022-12-05T09:29:54.053705 | 2020-09-02T21:13:19 | 2020-09-02T21:13:19 | 291,771,959 | 0 | 0 | MIT | 2020-09-02T21:12:59 | 2020-08-31T16:48:36 | null | UTF-8 | Python | false | false | 1,863 | py | # Experiment with positional arguments, arbitrary arguments, and keyword
# arguments.
# Write a function f1 that takes two integer positional arguments and returns
# the sum. This is what you'd consider to be a regular, normal function.
def f1(a, b):
return a + b
print(f1(1, 2))
# Write a function f2 that takes any number of integer arguments and prints the
# sum. Google for "python arbitrary arguments" and look for "*args"
def f2(*args):
sum = 0
for i in args:
sum += i
return sum
print(f2(1)) # Should print 1
print(f2(1, 3)) # Should print 4
print(f2(1, 4, -12)) # Should print -7
print(f2(7, 9, 1, 3, 4, 9, 0)) # Should print 33
a = [7, 6, 5, 4]
# What thing do you have to add to make this work?
print(f2(*a)) # Should print 22
# Write a function f3 that accepts either one or two arguments. If one argument,
# it returns that value plus 1. If two arguments, it returns the sum of the
# arguments. Google "python default arguments" for a hint.
def f3(a, b=1):
return a + b
print(f3(1, 2)) # Should print 3
print(f3(8)) # Should print 9
# Write a function f4 that accepts an arbitrary number of keyword arguments and
# prints out the keys and values like so:
#
# key: foo, value: bar
# key: baz, value: 12
#
# Google "python keyword arguments".
def f4(**kwargs):
for k, v in kwargs.items():
print(f'key: {k}, value: {v}')
# Alternate:
# for k in kwargs:
# print(f'key: {k}, value: {kwargs[k]}')
# Should print
# key: a, value: 12
# key: b, value: 30
f4(a=12, b=30)
# Should print
# key: city, value: Berkeley
# key: population, value: 121240
# key: founded, value: "March 23, 1868"
f4(city="Berkeley", population=121240, founded="March 23, 1868")
d = {
"monster": "goblin",
"hp": 3
}
# What thing do you have to add to make this work?
f4(**d)
| [
"tomtarpeydev@gmail.com"
] | tomtarpeydev@gmail.com |
2c280713fe03766a6619977c13fdbbf4799148a2 | 36fea845f6b80e7b1e626af81b47c470cf22e21e | /819.最常见的单词.py | d3b49d242ae04cd175de6293c4b16b2b1a177277 | [] | no_license | nerutia/leetcode_new | d7e87911d06798e2c1ffaa3109731e05809d6a92 | be10290be530f3fa7f54f3ea4140265cdbce6964 | refs/heads/master | 2023-04-26T15:00:48.048616 | 2021-05-18T14:37:10 | 2021-05-18T14:37:10 | 355,743,019 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 992 | py | '''
Description:
Version: 1.0
Author: hqh
Date: 2021-05-18 13:28:20
LastEditors: hqh
LastEditTime: 2021-05-18 13:41:12
'''
#
# @lc app=leetcode.cn id=819 lang=python3
#
# [819] 最常见的单词
#
# @lc code=start
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph = paragraph.replace('!', ' ')
paragraph = paragraph.replace('?', ' ')
paragraph = paragraph.replace("'", ' ')
paragraph = paragraph.replace(';', ' ')
paragraph = paragraph.replace(".", ' ')
paragraph = paragraph.replace(',', ' ')
st = paragraph.split(" ")
d = {}
r = ""
c = 0
for s in st:
s = s.lower()
if s == ' ' or s == '' or s in banned:
continue
if s in d:
d[s] += 1
else:
d[s] = 1
if d[s] > c:
c = d[s]
r = s
return r
# @lc code=end
| [
"765126614@163.com"
] | 765126614@163.com |
3300c16d54eae8bee5450656a6d8dfcdb013833b | 9b64f0f04707a3a18968fd8f8a3ace718cd597bc | /huaweicloud-sdk-bms/huaweicloudsdkbms/v1/model/security_groups_list.py | 91d2a2bd6050972034ff800f8ac2c4f8db0aea47 | [
"Apache-2.0"
] | permissive | jaminGH/huaweicloud-sdk-python-v3 | eeecb3fb0f3396a475995df36d17095038615fba | 83ee0e4543c6b74eb0898079c3d8dd1c52c3e16b | refs/heads/master | 2023-06-18T11:49:13.958677 | 2021-07-16T07:57:47 | 2021-07-16T07:57:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,225 | py | # coding: utf-8
import re
import six
class SecurityGroupsList:
"""
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 = {
'name': 'str',
'id': 'str'
}
attribute_map = {
'name': 'name',
'id': 'id'
}
def __init__(self, name=None, id=None):
"""SecurityGroupsList - a model defined in huaweicloud sdk"""
self._name = None
self._id = None
self.discriminator = None
if name is not None:
self.name = name
if id is not None:
self.id = id
@property
def name(self):
"""Gets the name of this SecurityGroupsList.
安全组名称或者UUID
:return: The name of this SecurityGroupsList.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this SecurityGroupsList.
安全组名称或者UUID
:param name: The name of this SecurityGroupsList.
:type: str
"""
self._name = name
@property
def id(self):
"""Gets the id of this SecurityGroupsList.
安全组ID。
:return: The id of this SecurityGroupsList.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this SecurityGroupsList.
安全组ID。
:param id: The id of this SecurityGroupsList.
:type: str
"""
self._id = id
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):
import simplejson as json
return json.dumps(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, SecurityGroupsList):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
8ac2d25a23231e9360e19467332fad8ea801f94e | 245ba2bf9aabba09ae4642a8e5baf26131b37834 | /00_startcamp/03_day/list_prob_05.py | 6b6541bb126a092affc72b81b3296d9e1dc1289f | [] | no_license | toohong5/TIL | 3c441db905bf53025f6f6e0942336bdc3a959297 | cb22fe0003405861c80203b02a396b7374db356b | refs/heads/master | 2023-01-13T12:56:09.260384 | 2019-11-27T08:31:01 | 2019-11-27T08:31:01 | 195,918,089 | 0 | 0 | null | 2023-01-07T18:11:17 | 2019-07-09T02:30:56 | Jupyter Notebook | UTF-8 | Python | false | false | 885 | py | '''
문제 5.
표준 입력으로 물품 가격 여러 개가 문자열 한 줄로 입력되고, 각 가격은 ;(세미콜론)으로 구분되어 있습니다.
입력된 가격을 높은 가격순으로 출력하는 프로그램을 만드세요.
# 입력 예시: 300000;20000;10000
'''
prices = input('물품 가격을 입력하세요: ')
# 아래에 코드를 작성해 주세요.
list_prices=prices.split(';')
for i in list_prices:
i=int[i]
list_prices.sort(reverse=True)
for i in list_prices:
print(int(i))
"""
문자열 <=> 리스트 형변환이 포인트!!
makes = prices.split(';') # split(): 공백기준으로 나눔
숫자형 형변환 필요!
boxes = [] #빈 리스트 만들기
for make in makes:
boxes.append(int(make)) #list.append() : list에 요소를 추가함.
boxes.sort(reverse=True) #내림차순 정렬
for boc in boxes:
print(box)
"""
| [
"toohong5@gmail.com"
] | toohong5@gmail.com |
55f51f0c9e4ba597d9ea1fc708d00385517cc3d2 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_189/ch84_2019_06_06_12_01_40_398784.py | 12b9f5b979b2321e96b097121293dd3f3c00dcd6 | [] | 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 | 198 | py | def inverte_dicionario():
dict.keys()=dk
dict.values()=dv
for a in dk:
dv.append(a)
for b in dv:
dk.append(b)
dv=dict.keys()
dk=dict.values()
return (dk,dv) | [
"you@example.com"
] | you@example.com |
f2d159fc07d28468032264b1bff2539285a8b8ef | 7188c98e04cd9c48942195b7f0f22e4717efb674 | /build/fuchsia/emu_target.py | e6ef52d0b356d76dc347c274cfb6906ca62c3e37 | [
"BSD-3-Clause"
] | permissive | tornodo/chromium | 1aa8fda7e9f506ddf26d69cd74fcf0e9e6595e39 | 1d748d142bde525249a816b1d9179cd9b9fa6419 | refs/heads/master | 2022-11-30T12:17:02.909786 | 2020-08-01T03:40:02 | 2020-08-01T03:40:02 | 197,871,448 | 0 | 0 | BSD-3-Clause | 2020-08-01T03:40:03 | 2019-07-20T02:53:57 | null | UTF-8 | Python | false | false | 4,886 | py | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Implements commands for running/interacting with Fuchsia on an emulator."""
import amber_repo
import boot_data
import logging
import os
import runner_logs
import subprocess
import sys
import target
import tempfile
class EmuTarget(target.Target):
def __init__(self, output_dir, target_cpu, system_log_file):
"""output_dir: The directory which will contain the files that are
generated to support the emulator deployment.
target_cpu: The emulated target CPU architecture.
Can be 'x64' or 'arm64'."""
super(EmuTarget, self).__init__(output_dir, target_cpu)
self._emu_process = None
self._system_log_file = system_log_file
self._amber_repo = None
def __enter__(self):
return self
def _GetEmulatorName(self):
pass
def _BuildCommand(self):
"""Build the command that will be run to start Fuchsia in the emulator."""
pass
def _SetEnv(self):
return os.environ.copy()
# Used by the context manager to ensure that the emulator is killed when
# the Python process exits.
def __exit__(self, exc_type, exc_val, exc_tb):
self.Shutdown();
def Start(self):
emu_command = self._BuildCommand()
# We pass a separate stdin stream. Sharing stdin across processes
# leads to flakiness due to the OS prematurely killing the stream and the
# Python script panicking and aborting.
# The precise root cause is still nebulous, but this fix works.
# See crbug.com/741194.
logging.debug('Launching %s.' % (self._GetEmulatorName()))
logging.debug(' '.join(emu_command))
# Zircon sends debug logs to serial port (see kernel.serial=legacy flag
# above). Serial port is redirected to a file through emulator stdout.
# If runner_logs are not enabled, we output the kernel serial log
# to a temporary file, and print that out if we are unable to connect to
# the emulator guest, to make it easier to diagnose connectivity issues.
temporary_log_file = None
if runner_logs.IsEnabled():
stdout = runner_logs.FileStreamFor('serial_log')
else:
temporary_log_file = tempfile.NamedTemporaryFile('w')
stdout = temporary_log_file
# TODO(crbug.com/1100402): Delete when no longer needed for debug info.
# Log system statistics at the start of the emulator run.
_LogSystemStatistics('system_start_statistics_log')
self._emu_process = subprocess.Popen(emu_command,
stdin=open(os.devnull),
stdout=stdout,
stderr=subprocess.STDOUT,
env=self._SetEnv())
try:
self._WaitUntilReady()
except target.FuchsiaTargetException:
if temporary_log_file:
logging.info('Kernel logs:\n' +
open(temporary_log_file.name, 'r').read())
raise
def GetAmberRepo(self):
if not self._amber_repo:
self._amber_repo = amber_repo.ManagedAmberRepo(self)
return self._amber_repo
def Shutdown(self):
if not self._emu_process:
logging.error('%s did not start' % (self._GetEmulatorName()))
return
returncode = self._emu_process.poll()
if returncode == None:
logging.info('Shutting down %s' % (self._GetEmulatorName()))
self._emu_process.kill()
elif returncode == 0:
logging.info('%s quit unexpectedly without errors' %
self._GetEmulatorName())
elif returncode < 0:
logging.error('%s was terminated by signal %d' %
(self._GetEmulatorName(), -returncode))
else:
logging.error('%s quit unexpectedly with exit code %d' %
(self._GetEmulatorName(), returncode))
# TODO(crbug.com/1100402): Delete when no longer needed for debug info.
# Log system statistics at the end of the emulator run.
_LogSystemStatistics('system_end_statistics_log')
def _IsEmuStillRunning(self):
if not self._emu_process:
return False
return os.waitpid(self._emu_process.pid, os.WNOHANG)[0] == 0
def _GetEndpoint(self):
if not self._IsEmuStillRunning():
raise Exception('%s quit unexpectedly.' % (self._GetEmulatorName()))
return ('localhost', self._host_ssh_port)
def _GetSshConfigPath(self):
return boot_data.GetSSHConfigPath(self._output_dir)
# TODO(crbug.com/1100402): Delete when no longer needed for debug info.
def _LogSystemStatistics(log_file_name):
# Log the cpu load and process information.
subprocess.call(['top', '-b', '-n', '1'],
stdin=open(os.devnull),
stdout=runner_logs.FileStreamFor(log_file_name),
stderr=subprocess.STDOUT)
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
1573ae9cc0de70115451009b23056acaede86ffb | e03e59d67c96c1afa0a1c76e62235a3e3f639976 | /py_hypo_tensor/pack/ten25kmeans.py | c5a6bc14a03be2f8114a57ad9d9dc4a4a5948392 | [] | no_license | kangmihee/EX_python | 10a63484802e6ff5454f12f7ade7e277dbf3df97 | 0a8dafe667f188cd89ef7f021823f6b4a9033dc0 | refs/heads/master | 2020-07-02T00:23:05.465127 | 2019-09-03T07:49:46 | 2019-09-03T07:49:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,424 | py | # clustering
import tensorflow as tf
from tensorflow.contrib.factorization import KMeans
k = 3
# num_feature = 1
# arr = [[1],[2],[2],[4],[2]]
num_feature = 2
arr = [[1,2],[2,3],[3,4],[5,5],[5,10],[15,5]]
x = tf.placeholder(tf.float32, shape=[None, num_feature])
kmodel = KMeans(inputs=x, num_clusters=k, \
distance_metric='squared_euclidean', use_mini_batch=True)
#print(kmodel)
(all_scores, cluster_idx, scores, cluster_centers_initialized, init_op, train_op)=\
kmodel.training_graph()
cluster_idx = cluster_idx[0]
avg_distance = tf.reduce_mean(scores) # 요소값 거리의 평균
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(init_op, feed_dict = {x:arr}))
print(sess.run(train_op, feed_dict = {x:arr}))
print(sess.run(all_scores, feed_dict = {x:arr}))
print(sess.run(cluster_idx, feed_dict = {x:arr}))
print(sess.run(scores, feed_dict = {x:arr}))
print(sess.run(cluster_centers_initialized, feed_dict = {x:arr}))
# 학습
for i in range(1, 100):
_,d,idx = sess.run([train_op, avg_distance, cluster_idx], feed_dict = {x:arr})
#print(i, idx)
if i % 10 == 0:
print(i, ' ', 'distance :', d)
print(d, idx)
print()
for i in range(0, k):
result = []
for j in range(0, idx.size, 1):
if idx[j] == i:
result.append(arr[j])
print(i, '에 속한 데이터:', result)
| [
"acorn@acorn-PC"
] | acorn@acorn-PC |
adf93adbbb84bc9ab04bec37a232eafa6cf2b456 | bf397eb8e8a1543ec283b7a4536dc7cd08b6a3bf | /cct/processinggui/project/samplenamecomboboxdelegate.py | 1e18e3f472a59cabc70fde07836aae677ec39a12 | [
"BSD-3-Clause"
] | permissive | chrisgauthier9/cct | 0c152a72b61baa43b99719d60c6ad26b41d50c91 | 62da7149b15c0d39e9303e0cbe0cffa13bac55ba | refs/heads/master | 2021-02-17T00:01:22.190527 | 2020-01-23T11:26:38 | 2020-01-23T11:26:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,291 | py | from PyQt5 import QtCore, QtWidgets
class SampleNameComboBoxDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent: QtWidgets.QWidget = None):
super().__init__(parent)
def createEditor(self, parent: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
index: QtCore.QModelIndex) -> QtWidgets.QWidget:
editor = QtWidgets.QComboBox(parent)
editor.addItem('-- None --')
editor.addItems(index.model().samplenames())
editor.setCurrentIndex(0)
editor.setFrame(False)
return editor
def setEditorData(self, editor: QtWidgets.QWidget, index: QtCore.QModelIndex) -> None:
editor.setCurrentIndex(editor.findText(index.data(QtCore.Qt.EditRole)))
if editor.currentIndex() < 0:
editor.setCurrentIndex(0)
def setModelData(self, editor: QtWidgets.QWidget, model: QtCore.QAbstractItemModel,
index: QtCore.QModelIndex) -> None:
model.setData(index, editor.currentText() if editor.currentIndex()>0 else None, QtCore.Qt.EditRole)
def updateEditorGeometry(self, editor: QtWidgets.QWidget, option: QtWidgets.QStyleOptionViewItem,
index: QtCore.QModelIndex) -> None:
editor.setGeometry(option.rect)
| [
"awacha@gmail.com"
] | awacha@gmail.com |
19c2031bdaaa1ef32237a1cd4a8c95656227cb4a | ebdb9e08fa1366588c1de13520a3f827b62f33a2 | /tests/algorithms/test_augmentations_functional.py | 81d0d72203cc0cf8d8ce22e412db87486766e103 | [
"Apache-2.0"
] | permissive | sarvex/composer | a10261aeb1f2e73a5c946bdfde2793f59b56e011 | 3dafa6fefd7f405394a98e88ed4a79bde36ae3e5 | refs/heads/dev | 2023-07-31T13:58:48.886476 | 2023-07-09T03:42:50 | 2023-07-09T03:42:50 | 659,656,450 | 0 | 0 | Apache-2.0 | 2023-07-09T03:42:51 | 2023-06-28T09:31:09 | Python | UTF-8 | Python | false | false | 2,733 | py | # Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from typing import Callable, Tuple, Union, cast
import numpy as np
import pytest
import torch
from PIL.Image import Image as PillowImage
from PIL.Image import fromarray
from composer.algorithms.utils.augmentation_common import image_as_type
from composer.functional import augmix_image, colout_batch, cutout_batch, randaugment_image
AnyImage = Union[torch.Tensor, PillowImage]
InputAugFunction = Callable[[AnyImage], AnyImage]
def _input_image(img_type: str, dtype: torch.dtype) -> AnyImage:
rng = np.random.default_rng(123)
torch.manual_seed(123)
N, H, W, C = 4, 6, 5, 3
if img_type == 'pillow':
ints = rng.integers(256, size=(H, W, C)).astype(np.uint8)
return fromarray(ints, mode='RGB')
elif dtype == torch.uint8:
if img_type == 'single_tensor':
return torch.randint(256, size=(C, H, W)).to(dtype=torch.uint8)
return torch.randint(256, size=(N, C, H, W)).to(dtype=torch.uint8)
elif dtype in (torch.float16, torch.float, torch.float64):
if img_type == 'single_tensor':
return torch.rand(size=(C, H, W)).to(dtype=dtype)
return torch.rand(size=(N, C, H, W)).to(dtype=dtype)
else:
raise ValueError(f'Invalid dtype: {dtype}')
def _input_output_pair(img_type: str, img_dtype: torch.dtype, f_aug: InputAugFunction) -> Tuple[AnyImage, AnyImage]:
img = _input_image(img_type, dtype=img_dtype)
return img, f_aug(img)
@pytest.fixture(params=(torch.uint8, torch.float16, torch.float, torch.float64))
def img_dtype(request) -> torch.dtype:
return request.param
@pytest.mark.parametrize('img_type', ['pillow', 'single_tensor', 'batch_tensor'])
@pytest.mark.parametrize('f_aug', [colout_batch, cutout_batch, augmix_image, randaugment_image])
def test_batch_augmentation_funcs_preserve_type(img_type: str, img_dtype: torch.dtype, f_aug: InputAugFunction):
img, out = _input_output_pair(img_type, img_dtype, f_aug)
assert type(out) == type(img)
@pytest.mark.parametrize('img_type', ['pillow', 'single_tensor', 'batch_tensor'])
@pytest.mark.parametrize('f_aug', [cutout_batch, augmix_image, randaugment_image]) # colout changes shape
def test_batch_augmentation_funcs_preserve_shape(img_type: str, img_dtype: torch.dtype, f_aug: InputAugFunction):
img, out = _input_output_pair(img_type, img_dtype, f_aug)
if img_type == 'pillow':
img = cast(PillowImage, img)
out = cast(PillowImage, out)
img = image_as_type(img, torch.Tensor)
out = image_as_type(out, torch.Tensor)
assert isinstance(img, torch.Tensor)
assert isinstance(out, torch.Tensor)
assert out.shape == img.shape
| [
"noreply@github.com"
] | sarvex.noreply@github.com |
c8033f11875e0540fede783230f0f058cb96b7be | e081eebc37aef48084fa62a1b36443f03b9e2abe | /ATcdvta.py | 676a486d77ecfd11286069f8b492baf6b7bf1952 | [] | no_license | S-C-U-B-E/CodeChef-Practise-Beginner-Python | 93fa202eede83cf4f58177bffb4ecc4ddb7f19bc | 78a02303b3cdd7eb7b0c45be59a1c282234f8719 | refs/heads/master | 2021-03-24T01:10:43.913150 | 2020-03-16T12:49:12 | 2020-03-16T12:49:12 | 247,501,633 | 16 | 8 | null | null | null | null | UTF-8 | Python | false | false | 1,605 | py | n=int(input())
w=int(input())
h=int(input())
th=int(input())
fh=int(input())
thsnd=int(input())
fin,ini=0,0
nthsnd = int(w/1000)
nfh = int((w-nthsnd*1000)/500)
nth = int((w-nthsnd*1000-nfh*500)/200)
nh = int((w-nthsnd*1000-nfh*500-nth*200)/100)
'print(nthsnd+nfh+nth+nh,nthsnd,nfh,nth,nh)'
'i=0'
if w>(h*100+th*200+fh*500+thsnd*1000):
print(0)
elif n<(nthsnd+nfh+nth+nh) or h<nh or th<nth or fh<nfh or thsnd<nthsnd:
print(0)
elif n==(nthsnd+nfh+nth+nh) and (nh<=h and nth<=th and nfh<=fh and nthsnd<=thsnd):
print(n)
else:
while True:
'i+=1'
ini = nthsnd+nfh+nth+nh
while 10+nh<=h and nthsnd>0 and (nthsnd-1)+nfh+nth+(nh+10)<=n:
nthsnd=nthsnd-1
nh=nh+10
while 5+nh<=h and nfh>0 and nthsnd+(nfh-1)+nth+(5+nh)<=n:
nfh=nfh-1
nh=nh+5
while 2+nh<=h and nth>0 and nthsnd+nfh+nth-1+nh+2<=n:
nth=nth-1
nh=nh+2
'print("i=" + str(i), nthsnd, nfh, nth, nh)'
while 5+nth<=th and nthsnd>0 and nthsnd-1+nfh+nth+5+nh<=n:
nthsnd=nthsnd-1
nth=nth+5
while 2+nth<=th and 1+nh<=h and nfh>0 and nthsnd+nfh-1+nth+2+nh+1<=n:
nfh=nfh-1
nh=nh+1
nth=nth+2
'print("i=" + str(i), nthsnd, nfh, nth, nh)'
while 2+nfh<=fh and nthsnd>0 and nthsnd-1+nfh+2+nth+nh<=n:
nthsnd=nthsnd-1
nfh=nfh+2
'print("i="+str(i),nthsnd,nfh,nth,nh)'
fin = nthsnd+nfh+nth+nh
if fin==ini:
break
if fin<=n:
print(fin)
else:
print(0)
| [
"sssanyal10@gmail.com"
] | sssanyal10@gmail.com |
c202b12baf8f83ee6d761d904307a8dc2cf7a64a | 7f3596e5fe2f483019895a3a3f1ee9820f1cbbf5 | /ws/search/tests/test_impute_values.py | 517d5300f7f2e4454a8e170c7b63f7ea4b907b49 | [
"MIT"
] | permissive | adityasundaram/mydig-webservice | 898d95597d432d0b6a70b24170c8d32d93fad0cf | bbd978b78524100819c2f0c6b8cc2533a1ea1783 | refs/heads/master | 2021-09-11T12:28:10.014399 | 2018-04-05T19:01:53 | 2018-04-05T19:01:53 | 114,708,579 | 0 | 0 | null | 2017-12-19T02:15:37 | 2017-12-19T02:15:37 | null | UTF-8 | Python | false | false | 1,236 | py | import unittest
import sys
import json
sys.path.append('../')
from response_converter import TimeSeries
class TestImputeTSValues(unittest.TestCase):
def setUp(self):
str_ts1 = """[["2012-08-01T00:00:00.000Z",1,null],["2012-09-01T00:00:00.000Z",1,416.1],
["2012-10-01T00:00:00.000Z",1,426.4],["2012-11-01T00:00:00.000Z",1,450],
["2012-12-01T00:00:00.000Z",1,472.5],["2013-01-01T00:00:00.000Z",1,121.6],
["2013-02-01T00:00:00.000Z",null],["2013-03-01T00:00:00.000Z",1,129.9],
["2013-04-01T00:00:00.000Z",1,127.2],["2013-05-01T00:00:00.000Z",1,127],["2013-06-01T00:00:00.000Z",1,122.3],
["2013-07-01T00:00:00.000Z",1,119.8],["2013-08-01T00:00:00.000Z",1,119.1]]"""
self.ts_obj1 = TimeSeries(json.loads(str_ts1), None, None, impute_method='previous')
self.ts_obj2 = TimeSeries(json.loads(str_ts1), None, None, impute_method='average')
def test_impute_values_previous(self):
ts = self.ts_obj1.ts
self.assertTrue(len(ts) == 12)
self.assertEqual(ts[5][len(ts[5]) - 1], 121.6)
def test_impute_values_average(self):
ts = self.ts_obj2.ts
self.assertEqual(len(ts), 12)
self.assertEqual(ts[5][len(ts[5]) - 1], 125.75)
| [
"amandeep.s.saggu@gmail.com"
] | amandeep.s.saggu@gmail.com |
2e089f91f92fe252ea3c9c24a0355e35cf4d3c10 | c14cd11d8b4e6e7ee4b83a5abec586efadd48f74 | /spk1/urls.py | bffdbfec0a48007bd988920ceeee5b26615cb44f | [] | no_license | RafeaAlmejrab22/DECISION-SUPPORT-SYSTEM | 619a8c67a8f718f08ed53637857477f657b8b900 | 5f4d2bdd6656bc4a25b5691dc66c4b915a5e19b7 | refs/heads/master | 2023-06-14T06:13:03.544880 | 2021-07-12T05:19:40 | 2021-07-12T05:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,004 | py | """spk1 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name="index"),
path('alternatif/',include(('alternatif.urls', 'alternatif'), namespace="alternatif")),
path('perhitungan/',include(('perhitungan.urls', 'perhitungan'), namespace="perhitungan")),
]
| [
"dim.dim10032000@gmail.com"
] | dim.dim10032000@gmail.com |
f8ed63e0f1d48af4394e5b1a5bebc6492a5dd59c | df3853b41ed05d86f5bcd992fcc265f637c67784 | /1sem/lab5/Z13.py | 21248cb0d965367a3e7ea0bd9480cdeb1fadd5e7 | [] | no_license | KseniaMIPT/Adamasta | 6ab0121519581dbbbf6ae788d1da85f545f718d1 | e91c34c80834c3f4bf176bc4bf6bf790f9f72ca3 | refs/heads/master | 2021-01-10T16:48:31.141709 | 2016-11-23T21:02:25 | 2016-11-23T21:02:25 | 43,350,507 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 203 | py | rating = list(map(int, str(input()).split()))
rating_sort = [rating[i] for i in range(len(rating) - 1) if rating[i] !=2 and rating[i + 1] != 5] + [rating[-1]]
print(sum(rating_sort)/len(rating_sort)//1)
| [
"ksenia22.11@yandex.ru"
] | ksenia22.11@yandex.ru |
0c5288f57dc30e77375ce4169aac74fb5d40ae1d | 8afb5afd38548c631f6f9536846039ef6cb297b9 | /GIT-USERS/TOM-Lambda/CSEUFLEX_Intro_Python_GP/intro/13_file_io.py | 3b3f718794e8a0d9400e51fe893366db7c1230c9 | [
"MIT"
] | permissive | bgoonz/UsefulResourceRepo2.0 | d87588ffd668bb498f7787b896cc7b20d83ce0ad | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | refs/heads/master | 2023-03-17T01:22:05.254751 | 2022-08-11T03:18:22 | 2022-08-11T03:18:22 | 382,628,698 | 10 | 12 | MIT | 2022-10-10T14:13:54 | 2021-07-03T13:58:52 | null | UTF-8 | Python | false | false | 1,090 | py | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
with open("foo.txt") as fp:
<<<<<<< HEAD
for line in fp:
print(line)
=======
for line in fp:
print(line)
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
# Open up a file called "bar.txt" (which doesn't exist yet) for
# writing. Write three lines of arbitrary content to that file,
<<<<<<< HEAD
# then close the file. Open up "bar.txt" and inspect it to make
=======
# then close the file. Open up "bar.txt" and inspect it to make
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
# sure that it contains what you expect it to contain
fp = open("bar.txt", "w")
<<<<<<< HEAD
fp.write("""Line 1
Line 2
Line 3""")
=======
fp.write(
"""Line 1
Line 2
Line 3"""
)
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
| [
"bryan.guner@gmail.com"
] | bryan.guner@gmail.com |
22e9d46602d08ad7c7ea4017987a7ce1c55782aa | c438d26f6f2822bb883f7bfa21e4cd04eb157f29 | /problem2.py | e543c05a572e85ee941e0394f7baf2ca4b6a14e6 | [] | no_license | GLAU-TND/python_assignment2-Ankitwww99 | d2ff88376ca4292ff7f1255099a47860202d29bd | 0e93f178b78e9c980ef9d4584a2f8e4cacfee0a8 | refs/heads/master | 2020-08-04T17:04:13.921535 | 2019-10-02T15:55:23 | 2019-10-02T15:55:23 | 212,213,553 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 462 | py | def cntlsta(lst,k):
sum=0
l=[]
s=0
i=0
if k==0:
return 0
while i < (len(lst)):
sum=sum+lst[i]
l.append(lst[i])
i=i+1
if sum==k:
return l
if sum>k:
sum=0
s=s+1
i=s
l=[]
return None
print(cntlsta([1,2,3,4,15],9))
print(cntlsta([1,2,3,4,115],115))
print(cntlsta([5,8,1,7,4,15],9))
print(cntlsta([],1))
| [
"noreply@github.com"
] | GLAU-TND.noreply@github.com |
7c7fa2770e8caabefb30691dcd3a75745641a5a2 | b4aaa26889f1c7e33a0de48848e30c0119284f14 | /app/tasks/generate_report.py | f1d3cda2218846ae4dbdc706fed3970d5e41c836 | [] | no_license | paulosjd/btk2 | 1d727f360c9767add5135988c75df63e5d8ada8e | dc63b90a796750e6b26018443d2256fcc1339afb | refs/heads/master | 2022-07-05T13:57:07.071734 | 2020-05-19T08:23:14 | 2020-05-19T08:23:14 | 188,910,952 | 0 | 0 | null | 2022-06-21T23:23:37 | 2019-05-27T21:26:02 | Python | UTF-8 | Python | false | false | 6,076 | py | import base64
import datetime
import io
import os
from operator import itemgetter
from tempfile import NamedTemporaryFile
from typing import List, NamedTuple, Optional, Sequence
import matplotlib.pyplot as plt
import pandas as pd
from celery.utils.log import get_task_logger
from django.template.loader import get_template
from matplotlib.ticker import FormatStrFormatter
from xhtml2pdf import pisa
from app.models import Profile, ProfileParamUnitOption
from app.utils import get_monthly_means, get_rolling_mean
from btk2.celery import celery_app
log = get_task_logger(__name__)
@celery_app.task
def profile_report_pdf(profile_id, date_str='',
param_ids: List[int] = None,
removed_stats: List[str] = None) -> Optional[str]:
removed_stats = removed_stats or []
current_file = os.path.abspath(os.path.dirname(__file__))
tmp_folder = os.path.join(current_file, 'report_temp')
profile = Profile.objects.filter(id=profile_id).first()
if not profile or not param_ids:
return
today = None
try:
today = datetime.datetime.strptime(date_str, '%b %d %Y')
except ValueError:
pass
report_data = {
'items_list': get_items_list(
profile.all_datapoints().filter(parameter_id__in=param_ids),
profile,
removed_stats=removed_stats
),
'date': today or datetime.date.today()
}
pdf = render_to_pdf('profile_report.html', report_data)
file = NamedTemporaryFile(
suffix='report.pdf', dir=tmp_folder, delete=False
)
with open(file.name, 'wb') as f:
f.write(pdf)
return file.name
def render_to_pdf(template_src, context_dct) -> Optional[bytes]:
template = get_template(template_src)
html = template.render(context_dct)
result = io.BytesIO()
pdf = pisa.pisaDocument(io.BytesIO(html.encode("utf-8")), result)
if not pdf.err:
return result.getvalue()
log.error(pdf.error)
def get_items_list(all_dps: List[object], profile: object,
removed_stats: List[str]) -> List[dict]:
prm_fiels = 'unit_symbol', 'has_val2', 'val2_label_1', 'val2_label_2'
param_info = get_param_info(all_dps, profile)
items_list = [{
'name': name,
'unit_symbol': param_info.symbols[ind],
'val2_label_1': lab1,
'val2_label_2': lab2,
'has_val2': has_val2,
'records': [{k: getattr(obj, k) for k in ['date', 'value', 'value2']}
for obj in all_dps if obj.parameter.name == name]
} for ind, (name, has_val2, lab1, lab2, _) in enumerate(param_info.names)]
for ind, item in enumerate(items_list):
dps, extra = [{k: dct[k] for k in ['date', 'value', 'value2']}
for dct in item['records']], {'param_name': item['name']}
plot_items = [(item['records'], 'records')]
for k, fn in [('rolling', get_rolling_mean),
('monthly', get_monthly_means)]:
if k not in removed_stats:
plot_items.append(
(fn(dps, extra=extra), f'{k}_means')
)
plots = {}
for data_set, stat_key in plot_items:
if len(data_set) > 3:
plot_bio = make_chart_from_data(
data_set, stat=stat_key,
**{k: item[k] for k in prm_fiels}
)
if plot_bio:
plots[stat_key] = base64.b64encode(plot_bio.getvalue()
).decode('ascii')
items_list[ind].update(
{f'{k}_plot': plots.get(k) for k in
['records', 'rolling_means', 'monthly_means']}
)
return items_list
def make_chart_from_data(means_data, stat='', **kwargs) -> Optional[io.BytesIO]:
title_map = {'rolling_means': 'Moving averages',
'monthly_means': 'Monthly averages (12 months)'}
fig, ax = plt.subplots(figsize=(7, 2.5))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
plt.title(title_map.get(stat, ''), fontsize=11, fontname='Arial',
loc='left', pad=6)
plt.ylabel(kwargs.get('unit_symbol', ''), fontname='Arial', fontsize=11)
dtf, key = ('%Y-%m-%d', 'date') if stat != 'monthly' else ('%Y-%b', 'month')
df = pd.DataFrame(
{pd.datetime.strptime(d[key], dtf)
if stat != 'records' else pd.to_datetime(datetime.datetime.combine(
d[key], datetime.time())):
[d.get(f'value{i}', '') for i in ['', 2]]
for d in means_data[::-1] if d.get(key)},
index=[kwargs.get(f'val2_label_{a}', f'value {a}') for a in [1, 2]]
)
ss = df.iloc[0, :]
try:
ss.plot(color="#8a3b78")
except TypeError:
return
if kwargs.get('has_val2'):
ss2 = df.iloc[1, :]
try:
ss2.plot(color="#c25476")
except TypeError:
return
plt.legend(loc='upper right', fontsize='small')
bio = io.BytesIO()
fig.savefig(bio, format="png", bbox_inches='tight')
plt.close(fig)
return bio
ParamInfo = NamedTuple('p_info', [('names', Sequence), ('symbols', list)])
def get_param_info(all_dps: List[object], profile: object) -> ParamInfo:
param_names = sorted(
set([(obj.parameter.name,
obj.parameter.num_values == 2,
obj.parameter.value2_short_label_1,
obj.parameter.value2_short_label_2,
obj.parameter.custom_symbol)
for obj in all_dps]),
key=itemgetter(0)
)
unit_symbols = []
for tpl in param_names:
symbol = tpl[4]
if not symbol:
try:
symbol = ProfileParamUnitOption.objects.get(
parameter__name=tpl[0], profile=profile
).unit_option.symbol
except ProfileParamUnitOption.DoesNotExist as e:
log.error(e)
symbol = 'n/a'
unit_symbols.append(symbol)
return ParamInfo(param_names, unit_symbols)
| [
"pjdavis@gmx.com"
] | pjdavis@gmx.com |
f2fae73edc4327adef147650ed73fbc0786589a0 | 6f1ae6561d63f3d081807c1cd3eda79035c6cd5f | /第六周/8-27/selenium的使用.py | d5bce611356efbf44919d5ea8f95946fee1086cb | [] | no_license | qq1295334725/zheng | 3ee0d70fdbaf42e86d5a9a65772209fd24d8c10a | 0d884b69feb4c9c4babec6c467697697337c4ca3 | refs/heads/master | 2020-03-25T11:27:28.952808 | 2018-08-28T11:10:08 | 2018-08-28T11:10:08 | 143,733,196 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,025 | py | """
座右铭:将来的你一定会感激现在拼命的自己
@project:正课
@author:Mr.Chen
@file:selenium.PY
@ide:PyCharm
@time:2018-08-27 10:04:30
"""
# selenium是一个网页自动化测试的一个工具,使用它可以操作浏览器来模拟人操作浏览器的行为。
# selenium:在爬虫中的使用。
# 1.获取动态的网页数据,一些动态的数据在网页的源代码中并没有显示,这时候可以考虑用selenium获取。
# 2.用于模拟登陆,对于一些需要登陆才能获取到数据的网页,一般如果采用分析参数破解的话,需要耗费大量的时间和精力进行网站的登录的破解,而如果使用selenium的话,就可以完全模拟人的登录行为来进行网站登录,就不需要分析参数进行网站的破解。
# selenium的特点:
# 1.它是通过驱动浏览器来进行网页的登录,或者是获取网页的信息。
# 2.由于selenium是驱动浏览器进行数据的爬取,而浏览器的打开,对网页发起请求,渲染页面都需要耗费大量的时间,所有一般不使用selenium进行网站数据的爬取,除非无法通过分析请求的方式进行网站登录,或者网站是动态网站,页面源代码中获取不到数据的这种情况下,才考虑使用selenium来进行爬取。
# 3.selenium提供的一些元素定位和查找的方法都是用纯python实现的,效率比较低。
# 4.selenium是免费开源的,支持很多的主流浏览器,IE,Chrome,Opera,FireFox,Safari等
# 1.安装selenium
# 2.安装浏览器驱动
from selenium import webdriver
# 第一步:创建一个浏览器对象
browser = webdriver.Chrome()
# browser = webdriver.Firefox()
# 第二步:使用浏览器对象对网址发起请求
browser.get("https://www.baidu.com")
# 获取网页的源代码
print(browser.page_source)
# 获取此次请求的地址
print(browser.current_url)
# 获取此次请求的cookies信息
print(browser.get_cookies())
# 退出浏览器
browser.quit()
| [
"1295334725@qq.com"
] | 1295334725@qq.com |
0a3803a0b8bb637190a11c8455b5785170c61562 | 37ba62db61fc4ec62634638763a984cbfbe40fe3 | /day15/05 map.py | e8ae93acbcabda0a8d34c5ea0dc6235cf2a2dead | [] | no_license | lt910702lt/python | ca2768aee91882c893a9bc6c1bdd1b455ebd511f | c6f13a1a9461b18df17205fccdc28f89854f316c | refs/heads/master | 2020-05-09T22:54:22.587206 | 2019-09-17T09:02:53 | 2019-09-17T09:02:53 | 181,485,866 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 269 | py | # 语法:map(function.iterable)
# lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 23, 23, 4, 52, 35, 234, 234, 234, 234, 234, 23, 4]
# it = map(lambda i: i * i, lst)
# print(list(it))
lst1 = [1, 2, 3, 4, 5]
lst2 = [2, 4, 6, 8]
print(list(map(lambda x, y: x + y, lst1, lst2)))
| [
"1103631738@qq.com"
] | 1103631738@qq.com |
4d840bfbdd66e558edf5897c9913312b0a8348af | b8955839739995b73e449609554983dd96e4665f | /apps/goods/serializers.py | 97c51ddf06768db9c5b3c9e109dd4e11f7ec75dd | [] | no_license | weixx11/HXshop | 17a11e237de407aa0d9f9114bc68987160977619 | 69a55b92a1e45c97f5a6c9de2738f7c16165d2b8 | refs/heads/master | 2022-12-10T18:12:00.282064 | 2018-05-14T20:01:05 | 2018-05-14T20:01:05 | 133,414,244 | 0 | 0 | null | 2022-12-08T00:58:35 | 2018-05-14T19:56:17 | JavaScript | UTF-8 | Python | false | false | 3,472 | py | #!/usr/bin/env python
#coding=utf-8
from rest_framework import serializers
from .models import Goods,GoodsCategory,GoodsImage,HotSearchWords,Banner,GoodsCategoryBrand,IndexAd
from django.db.models import Q
class CategorySerializer3(serializers.ModelSerializer):
'''三级分类'''
class Meta:
model = GoodsCategory
fields = "__all__"
class CategorySerializer2(serializers.ModelSerializer):
'''
二级分类
'''
#在parent_category字段中定义的related_name="sub_cat"
sub_cat = CategorySerializer3(many=True)
class Meta:
model = GoodsCategory
fields = "__all__"
#商品分类
class CategorySerializer(serializers.ModelSerializer):
"""
商品一级类别序列化
"""
sub_cat = CategorySerializer2(many=True)
class Meta:
model = GoodsCategory
fields = "__all__"
class GoodsImageSerializer(serializers.ModelSerializer):
class Meta:
model=GoodsImage
fields=["image"]
class GoodsSerializer(serializers.ModelSerializer):
category = CategorySerializer()
#images是数据库中设置的related_name="images"
images = GoodsImageSerializer(many=True)
class Meta:
model = Goods
fields = "__all__"
# fields=['name','click_num','market_price','add_time']
# depth=3
class HotWordsSerializer(serializers.ModelSerializer):
'''热搜'''
class Meta:
model = HotSearchWords
fields = "__all__"
class BannerSerializer(serializers.ModelSerializer):
"""
轮播图
"""
class Meta:
model=Banner
fields = "__all__"
class BrandSerializer(serializers.ModelSerializer):
class Meta:
model=GoodsCategoryBrand
fields = "__all__"
class IndexCategorySerializer(serializers.ModelSerializer):
#某个大类的商标,可以有多个商标,一对多的关系
brands = BrandSerializer(many=True)
# good有一个外键category,但这个外键指向的是三级类,直接反向通过外键category(三级类),取某个大类下面的商品是取不出来的
goods = serializers.SerializerMethodField()
# 在parent_category字段中定义的related_name="sub_cat"
# 取二级商品分类
sub_cat = CategorySerializer2(many=True)
# 广告商品
ad_goods = serializers.SerializerMethodField()
def get_ad_goods(self, obj):
goods_json = {}
ad_goods = IndexAd.objects.filter(category_id=obj.id, )
if ad_goods:
#取到这个商品Queryset[0]
good_ins = ad_goods[0].goods
#在serializer里面调用serializer的话,就要添加一个参数context(上下文request),嵌套serializer必须加
# serializer返回的时候一定要加 “.data” ,这样才是json数据
goods_json = GoodsSerializer(good_ins, many=False, context={'request': self.context['request']}).data
return goods_json
#自定义获取方法
def get_goods(self,obj):
# 将这个商品相关父类子类等都可以进行匹配
all_goods=Goods.objects.filter(Q(category_id=obj.id) | Q(category__parent_category_id=obj.id) | Q(
category__parent_category__parent_category_id=obj.id))
goods_serializer = GoodsSerializer(all_goods, many=True, context={'request': self.context['request']})
return goods_serializer.data
class Meta:
model=GoodsCategory
fields="__all__"
| [
"you@example.com"
] | you@example.com |
df7ec9f18af15fead55a4bfec1206e9c767b8107 | 2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8 | /pardus/tags/2007.3/system/base/kbd/actions.py | db6a125cbd9e3313359806cb87f044198566a9ca | [] | no_license | aligulle1/kuller | bda0d59ce8400aa3c7ba9c7e19589f27313492f7 | 7f98de19be27d7a517fe19a37c814748f7e18ba6 | refs/heads/master | 2021-01-20T02:22:09.451356 | 2013-07-23T17:57:58 | 2013-07-23T17:57:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 849 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright © 2005-2007 TUBITAK/UEKAE
# Licensed under the GNU General Public License, version 2.
# See the file http://www.gnu.org/copyleft/gpl.txt.
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import get
def setup():
pisitools.dosed("src/Makefile.in", "-O2", get.CFLAGS())
pisitools.dosed("src/Makefile.in", "install -s", "install")
autotools.rawConfigure("--prefix=/usr --mandir=/usr/share/man --datadir=/usr/share")
def build():
autotools.make("CC=%s" % get.CC())
def install():
autotools.rawInstall("DESTDIR=%s" % get.installDIR())
pisitools.domove("/usr/bin/setfont", "/bin")
pisitools.dosym("/bin/setfont", "/usr/bin/setfont")
pisitools.dodoc("CHANGES", "CREDITS", "README")
pisitools.dohtml("doc/*")
| [
"yusuf.aydemir@istanbul.com"
] | yusuf.aydemir@istanbul.com |
65e4a19d4a976e17ecc9559ce0980489a3e5c844 | 4912cbd47c19c58d142e6833911d70f5ea037357 | /question_bank/edit-distance/edit-distance.py | 007e929578c79ade9eea1b50284fc9767178145f | [
"Apache-2.0"
] | permissive | yatengLG/leetcode-python | a09a17cd9e60cafd9ff8ca9c068f5b70719c436f | 5d48aecb578c86d69835368fad3d9cc21961c226 | refs/heads/master | 2023-07-13T16:10:01.920716 | 2021-09-06T02:51:46 | 2021-09-06T02:51:46 | 286,969,109 | 13 | 6 | null | 2021-02-16T10:19:44 | 2020-08-12T09:13:02 | Python | UTF-8 | Python | false | false | 1,370 | py | # -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:216 ms, 在所有 Python3 提交中击败了47.71% 的用户
内存消耗:31.7 MB, 在所有 Python3 提交中击败了5.07% 的用户
解题思路:
动态规划
例:
'' h o r s e
'' 0 1 2 3 4 5
r 1 1 2 2 3 4
o 2 2 1 2 3 4
s 3 3 2 2 2 3
当 world2[i] == world1[j]时, dp[i][j] = dp[i-1][j-1]
当 world2[i] != world1[j]时,
1. dp[i][j] = dp[i-1][j]+1 可通过world2[i-1] 删除一个元素得到 world1[j]
2. dp[i][j] = dp[i-1][j-1]+1 可通过world2[i], world1[j] 替换最后一个元素得到
3. dp[i][j] = dp[i][j-1]+1 可通过world2[i] 插入一个元素得到 world1[j-1],
"""
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m = len(word1)
n = len(word2)
dp = [[[] for _ in range(m+1)] for _ in range(n+1)]
for i in range(n+1):
dp[i][0] = i
dp[0] = list(range(m+1))
for i in range(n):
for j in range(m):
if word2[i] == word1[j]:
dp[i+1][j+1] = dp[i][j]
else:
dp[i+1][j+1] = min(dp[i][j+1], dp[i+1][j], dp[i][j]) + 1
return dp[-1][-1] | [
"767624851@qq.com"
] | 767624851@qq.com |
cecc50718a1f0a5c7f2461ce5cd216a3f49a63bd | 4ea356a72330a3a494ab02647400284be575c52a | /acrofestival/winteracro/admin.py | b18bd20618036501e407e663d14eb7063a7a45c3 | [
"MIT"
] | permissive | adux/acrofestival | 5f6f69be758148793ea790f3c1ef39111f608a7f | 9bd3deeb222c82908ebea12de7e30c745094cb6e | refs/heads/master | 2021-11-18T11:56:51.245646 | 2020-03-03T15:24:09 | 2020-03-03T15:24:09 | 134,270,377 | 0 | 1 | MIT | 2021-09-08T01:43:18 | 2018-05-21T13:06:44 | CSS | UTF-8 | Python | false | false | 473 | py | from django.contrib import admin
# Register your models here.
from .models import Workshop, Entrie, Day
class WorkshopAdmin(admin.ModelAdmin):
list_display = ("date", "teachers", "time")
class DayEntrieInline(admin.StackedInline):
model = Entrie
extra = 1
can_delete = True
show_can_change = True
class DayAdmin(admin.ModelAdmin):
inlines = [DayEntrieInline]
admin.site.register(Day, DayAdmin)
admin.site.register(Workshop, WorkshopAdmin)
| [
"adriangarate@protonmail.com"
] | adriangarate@protonmail.com |
55d004bd940f98aac541a3d9617860d1ccb2c2aa | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02996/s018177603.py | 0fea81775a69808c845e20d650a52b897ab59fdb | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 190 | py | n = int(input())
ab = sorted([list(map(int, input().split())) for _ in range(n)], key = lambda i: i[1])
t = 0
for i in ab:
t += i[0]
if t > i[1]:
print("No")
exit()
print("Yes") | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
f0c4c96924b77be589057746ff28aa4ac23293d4 | b9a23d1947f5f6328ca13c7e652499173f64da47 | /s_194/target/s_194.py | 33abd4a33238685750b175cd3b3e564ff7e1abd6 | [] | no_license | berinhard/sketches | 96414a14ec40ca1281dcd8b2fec2c50db1d76e9a | f0e4be211397f205bcc6bd2c8b053b920a26bb62 | refs/heads/master | 2021-06-09T07:49:59.220785 | 2020-12-08T04:14:55 | 2020-12-08T04:23:43 | 137,092,663 | 41 | 15 | null | 2021-03-20T00:41:39 | 2018-06-12T15:34:49 | JavaScript | UTF-8 | Python | false | false | 1,350 | py | from pytop5js import *
square_size = 40
squares_map = {}
class Square:
def __init__(self, x, y, size):
self.x = x
self.y = y
self.size = size
self._alpha = 1
self.color = (random(255), random(255), random(255), self.alpha)
def display(self):
if self.alpha == 1:
fill(27)
else:
fill(*self.color)
stroke(27, 27, 27, 30)
rect(self.x, self.y, self.size, self.size)
@property
def alpha(self):
return self._alpha
@alpha.setter
def alpha(self, value):
if self._alpha + value < 255:
self._alpha += value
def update(self):
self.alpha += 2
self.color = self.color[0], self.color[1], self.color[2], self.alpha
def setup():
pixelDensity(displayDensity())
w, h = window.innerWidth, window.innerHeight
createCanvas(w, h)
for x in range(0, w, square_size):
for y in range(0, h, square_size):
squares_map[(x, y)] = Square(x, y, square_size)
background(27)
def clean_coord(x, y):
x = x // square_size * square_size
y = y // square_size * square_size
return x, y
def draw():
background(27)
for square in squares_map.values():
square.display()
x, y = clean_coord(mouseX, mouseY)
squares_map[(x, y)].update()
| [
"bernardoxhc@gmail.com"
] | bernardoxhc@gmail.com |
a5ac9e938afc8d218465dd6ec2f2b9c92d1d217a | 8b4b2e2a0efd50ecba15b1929691166f2ebf4be7 | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/Classes/coing_argument.py | 64450b9e74861af64358d9c9a8a5ffbd785d63a2 | [] | no_license | Hackman9912/PythonCourse | c2881958f622eb9e0aa18c5e36ca79fd4a6b1968 | dc445cd8183a07bc223d11fad86bbc112a8696c2 | refs/heads/master | 2020-11-26T13:25:36.405573 | 2019-12-19T17:04:39 | 2019-12-19T17:04:39 | 229,085,020 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 531 | py | # This program passes a Coin object as an argument to a function
import coin
def main():
# create a Coin object
my_coin = coin.Coin()
# This will display 'Heads'
print('Here is the coin before the flip', my_coin.get_sideup())
# Pass the object to the flip function
print('Tossing the coin....')
flip(my_coin)
# Display the coin
print('Here is the toss: ', my_coin.get_sideup())
# The flip function flips a coin
def flip(coin_obj):
coin_obj.toss()
# Call main
main() | [
"noreply@github.com"
] | Hackman9912.noreply@github.com |
e2ded31da46b881892f63cf08d086db6c0b39642 | 0ad7f553df6b210b5ac004fbf490ed651a21d55e | /algos/pole_zero_placement_02.py | b2bdb0ccca8cd80aa3c69f45bd3e75b2574e7290 | [] | no_license | MarianoDel/spyder_python | fa00987eb9aa1ef61d7224679a84c05a217c6c35 | 5f5896df68f95eb860bc08c21ae2b19516432cdc | refs/heads/master | 2020-05-23T06:14:57.329478 | 2020-04-23T14:58:16 | 2020-04-23T14:58:16 | 84,753,428 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,334 | py | #DIGITAL FILTER BY
#POLE ZERO PLACEMENT
#IIR_filters_pole_zero_placement.pdf
import sympy
from scipy import signal
from sympy import *
from pylab import *
import matplotlib.pyplot as plt
z = Symbol('z')
#Zeros
fs = 1000.
freqz1 = 25.
freqz2 = 185.
num = (z - e**(1.0j*freqz1/fs*2*pi)) * (z - e**(1.0j*-freqz1/fs*2*pi)) * (z - e**(1.0j*freqz2/fs*2*pi)) * (z - e**(1.0j*-freqz2/fs*2*pi))
#Poles recordar complejo conjugado y oscilacion en 1 (circulo)
freqp1 = fs
den = (z - freqp1/fs)
D = num / den
print (D)
bdig = num.expand()
print (bdig)
adig = den.expand()
print (adig)
bdig = [1.0, - 2.76967246245984, + 3.5690333642877, - 2.76967246245984, + 1.0]
#adig = [1.0, -2., 1.]
adig = [1.0, -1.]
w, h = signal.freqz(bdig, adig, worN = 1000)
figure(1)
clf()# clear the figure - "#" is the comment symbol in Python
subplot(311)
title('digital TF')
semilogx(w,20*log10(abs(h)))
ylabel('Mag. Ratio (dB)')
subplot(312)
semilogx(w,arctan2(imag(h),real(h))*180.0/pi)
ylabel('Phase (deg.)')
xlabel('Freq (Hz)')
subplot(313)
#plt.plot(w*fs/(2*pi),abs(h))
plt.plot(w,abs(h))
show() #may not be necessary depending on how your graphics thread is running.
figure(2)
clf()# clear the figure - "#" is the comment symbol in Python
plt.plot(w*fs/(2*pi),abs(h))
plt.show()
| [
"marianodeleu@yahoo.com.ar"
] | marianodeleu@yahoo.com.ar |
b270f021d57ff4f56e4435b593f65dd60ebb8d16 | 7889f7f0532db6a7f81e6f8630e399c90438b2b9 | /3.4.0/_downloads/5c12d4b66c26fc9c8cdfd42f3e8008a7/fancyarrow_demo.py | d7ee56c33566f48159b54dbca74ed26e4c821e2a | [] | no_license | matplotlib/matplotlib.github.com | ef5d23a5bf77cb5af675f1a8273d641e410b2560 | 2a60d39490941a524e5385670d488c86083a032c | refs/heads/main | 2023-08-16T18:46:58.934777 | 2023-08-10T05:07:57 | 2023-08-10T05:08:30 | 1,385,150 | 25 | 59 | null | 2023-08-30T15:59:50 | 2011-02-19T03:27:35 | null | UTF-8 | Python | false | false | 1,847 | py | """
================================
Annotation arrow style reference
================================
Overview of the arrow styles available in `~.Axes.annotate`.
"""
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
styles = mpatches.ArrowStyle.get_styles()
ncol = 2
nrow = (len(styles) + 1) // ncol
figheight = (nrow + 0.5)
fig = plt.figure(figsize=(4 * ncol / 1.5, figheight / 1.5))
fontsize = 0.2 * 70
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1.)
ax.set_xlim(0, 4 * ncol)
ax.set_ylim(0, figheight)
def to_texstring(s):
s = s.replace("<", r"$<$")
s = s.replace(">", r"$>$")
s = s.replace("|", r"$|$")
return s
for i, (stylename, styleclass) in enumerate(sorted(styles.items())):
x = 3.2 + (i // nrow) * 4
y = (figheight - 0.7 - i % nrow) # /figheight
p = mpatches.Circle((x, y), 0.2)
ax.add_patch(p)
ax.annotate(to_texstring(stylename), (x, y),
(x - 1.2, y),
ha="right", va="center",
size=fontsize,
arrowprops=dict(arrowstyle=stylename,
patchB=p,
shrinkA=5,
shrinkB=5,
fc="k", ec="k",
connectionstyle="arc3,rad=-0.05",
),
bbox=dict(boxstyle="square", fc="w"))
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.patches
matplotlib.patches.ArrowStyle
matplotlib.patches.ArrowStyle.get_styles
matplotlib.axes.Axes.annotate
| [
"quantum.analyst@gmail.com"
] | quantum.analyst@gmail.com |
3746a852c6bc0aebc5af92a3e4f2e7ff02091e05 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/arc082/A/4125923.py | f7db32956e3144952174fe45b7efd8127dcbc238 | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Python | false | false | 426 | py | #!/usr/bin/env python3
def main():
N = int(input())
a = list(map(int, input().split()))
a.sort()
r = 0
i, j = 0, 0
while i < N:
while j < N:
if a[j] - a[i] <= 2:
j += 1
else:
break
r = max(r, j - i)
if j == N:
break
i += 1
print(r)
if __name__ == '__main__':
main() | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
4778b23b3ab810d5e6fc6e46addab21026b8fb4b | 1c3f5f1bdf0e24f5d6db968572f13c860ac1c06e | /src/scs_analysis/cmd/cmd_aws_client_auth.py | 1049d56e5dd7fdaec3442eb54cc5560ee8d17247 | [
"MIT"
] | permissive | kbschulte/scs_analysis | 62a97dd2f719db59e295175759d9490a59cda011 | 5df0c6ba3d284993732eb60e4275ffaaf2f55b86 | refs/heads/master | 2023-08-29T06:48:44.813246 | 2021-11-05T08:59:17 | 2021-11-05T08:59:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,092 | py | """
Created on 2 Apr 2018
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
source repo: scs_analysis
example document:
{"org-id": "south-coast-science-test-user", "api-key": "9fdfb841-3433-45b8-b223-3f5a283ceb8e"}
"""
import optparse
# --------------------------------------------------------------------------------------------------------------------
class CmdAWSClientAuth(object):
"""unix command line handler"""
def __init__(self):
"""
Constructor
"""
self.__parser = optparse.OptionParser(usage="%prog [{ [-e ENDPOINT] [-c CLIENT_ID] [-I CERT_ID] | -d }] [-v]",
version="%prog 1.0")
# optional...
self.__parser.add_option("--endpoint", "-e", type="string", nargs=1, action="store", dest="endpoint",
help="set broker endpoint")
self.__parser.add_option("--client", "-c", type="string", nargs=1, action="store", dest="client_id",
help="set client ID")
self.__parser.add_option("--cert", "-i", type="string", nargs=1, action="store", dest="cert_id",
help="set certificate ID")
self.__parser.add_option("--delete", "-d", action="store_true", dest="delete", default=False,
help="delete the client authentication")
self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False,
help="report narrative to stderr")
self.__opts, self.__args = self.__parser.parse_args()
# ----------------------------------------------------------------------------------------------------------------
def is_valid(self):
if self.set() and self.delete:
return False
return True
def is_complete(self):
if self.endpoint is None or self.client_id is None or self.cert_id is None:
return False
return True
def set(self):
if self.endpoint is None and self.client_id is None and self.cert_id is None:
return False
return True
# ----------------------------------------------------------------------------------------------------------------
@property
def endpoint(self):
return self.__opts.endpoint
@property
def client_id(self):
return self.__opts.client_id
@property
def cert_id(self):
return self.__opts.cert_id
@property
def delete(self):
return self.__opts.delete
@property
def verbose(self):
return self.__opts.verbose
# ----------------------------------------------------------------------------------------------------------------
def print_help(self, file):
self.__parser.print_help(file)
def __str__(self, *args, **kwargs):
return "CmdAWSClientAuth:{endpoint:%s, client_id:%s, cert_id:%s, delete:%s, verbose:%s}" % \
(self.endpoint, self.client_id, self.cert_id, self.delete, self.verbose)
| [
"bruno.beloff@southcoastscience.com"
] | bruno.beloff@southcoastscience.com |
d92599eac4759e3998bc4c1a0dfe1e86c1f03efe | 1bb031d65889e53e531ae5e47156c817ce6235b4 | /IPython/kernel/ioloop/manager.py | a62445f3c7e65ac763e1401a7af9b61d6c5b2a8f | [
"BSD-3-Clause"
] | permissive | ptwobrussell/ipython | ba34209e88e8c2dae0e6fc13cc335d9dc7c3dea0 | 70362b811aced1ceb429433875ac0861c4d0729d | refs/heads/master | 2020-12-25T10:10:43.092703 | 2013-05-19T16:41:32 | 2013-05-19T16:41:32 | 10,165,966 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,159 | py | """A kernel manager with a tornado IOLoop"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import absolute_import
import zmq
from zmq.eventloop import ioloop
from zmq.eventloop.zmqstream import ZMQStream
from IPython.utils.traitlets import (
Instance
)
from IPython.kernel.manager import KernelManager
from .restarter import IOLoopKernelRestarter
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def as_zmqstream(f):
def wrapped(self, *args, **kwargs):
socket = f(self, *args, **kwargs)
return ZMQStream(socket, self.loop)
return wrapped
class IOLoopKernelManager(KernelManager):
loop = Instance('zmq.eventloop.ioloop.IOLoop', allow_none=False)
def _loop_default(self):
return ioloop.IOLoop.instance()
_restarter = Instance('IPython.kernel.ioloop.IOLoopKernelRestarter')
def start_restarter(self):
if self.autorestart and self.has_kernel:
if self._restarter is None:
self._restarter = IOLoopKernelRestarter(
kernel_manager=self, loop=self.loop,
config=self.config, log=self.log
)
self._restarter.start()
def stop_restarter(self):
if self.autorestart:
if self._restarter is not None:
self._restarter.stop()
connect_shell = as_zmqstream(KernelManager.connect_shell)
connect_iopub = as_zmqstream(KernelManager.connect_iopub)
connect_stdin = as_zmqstream(KernelManager.connect_stdin)
connect_hb = as_zmqstream(KernelManager.connect_hb)
| [
"benjaminrk@gmail.com"
] | benjaminrk@gmail.com |
2026ff5464305da3ae212d8bd4233db4498f3277 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03131/s519424569.py | ab12f1a4c837c6b35a7cc70da3a2b3be41e09e60 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 567 | py | import math
k,a,b = map(int,input().split())
t = k
cnt = 1
#ビスケットと1円を交換したほうがいい時
if a+1<b:
#1回1円と交換できるようになるまでビスケットを増やす
cnt += a-1
t -= a-1
#print(cnt)
#print(t)
#ビスケットと1円を交換→1円とビスケットを交換を限界まで繰り返す
cnt += b*math.floor(t/2)
cnt -= a*math.floor(t/2)
t -= 2 * math.floor(t/2)
#print(cnt)
#print(t)
#ビスケットをたたいて増やす
cnt += t
else:
cnt +=k
print(cnt) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
dbd0e39adbde158336207de5c8d35226107cf2b7 | 3a3c9e1e8e9c20f16c27943e655c5239c4c61f18 | /Python 3/lp3thw/ex40/ex40b.py | 415b7f7cbedca15aff14dcf3db16ebf8bec6117b | [] | no_license | jadeaxon/hello | bb3752faefcab2a61b54dd813835e88ce022b9c6 | c1902132f7f64b1c2668a07aee04ef3547899601 | refs/heads/master | 2023-01-27T13:55:49.415403 | 2020-10-04T01:03:42 | 2020-10-04T01:03:42 | 45,406,801 | 1 | 0 | null | 2023-01-11T22:20:50 | 2015-11-02T16:29:47 | HTML | UTF-8 | Python | false | false | 868 | py | #!/usr/bin/env python3
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
self.sing = self.sing_me_a_song # Alias
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
def reverse_sing(self):
r = list(self.lyrics)
r.reverse()
for line in r:
print(line)
happy_bday = Song([
"Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"
])
bulls_on_parade = Song([
"They rally around than family",
"With pockets full of shells"
])
lyrics = [
"Twinlke, twinkle little star",
"How I wonder what you are"
]
twinkle = Song(lyrics)
mary = Song([
"Mary had a little lamb",
"With mint sauce"
])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
twinkle.sing()
mary.sing()
mary.reverse_sing()
| [
"jeff.anderson@digecor.com"
] | jeff.anderson@digecor.com |
30a09246c1ad7d058070595ea37c3c60d45ce158 | 220dd5d666b85b716d5762097fb2d320bb8587fd | /hard/count_of_smaller_nums_after_self_315.py | 261cf929736ca02ab0fe95a5733128bfc9ca6adb | [] | no_license | bensenberner/ctci | 011946a335396def198acaa596d2b5902af7b993 | 1e1ba64580ee96392c92aa95904c4751e32d4e30 | refs/heads/master | 2021-01-10T14:09:01.698323 | 2020-09-06T04:17:53 | 2020-09-06T04:17:53 | 45,659,115 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,036 | py | """
You are given an integer array nums and you have to return a new counts array.
The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
----
Approach 1:
start from the right end. initialize a max heap.
for every element:
pop items off from the heap until either it is empty or the max is less than the current element
store the size of the heap in the result array
move to the left
hmmm but this is taking a while...maybe I can use better memoization?
But as I'm going through the output array...how would I know which previous result I could reuse?
They could be all different sizes
I'm going to try my approach first
wait a sec...I might have to pop out ALL the items...this is n^2logn!
no way this is the best answer
"""
import heapq
from collections import deque
class MaxHeap:
def __init__(self):
self.heap = []
def __bool__(self):
return bool(self.heap)
def push(self, val):
heapq.heappush(self.heap, -val)
def _pop(self):
return -heapq.heappop(self.heap)
def _peek(self):
return -self.heap[0]
def find_num_elements_greater_than(self, val):
position = 0
temp_stack = []
while self and val <= self._peek():
temp_stack.append(self._pop())
position += 1
while temp_stack:
self.push(temp_stack.pop())
return position
def countSmallerHeap(nums):
n = len(nums)
if n == 0:
return []
result = deque()
heap = MaxHeap()
for idx in range(n - 1, -1, -1):
num_elements_less_than = (
n - idx - 1 - heap.find_num_elements_greater_than(nums[idx])
)
result.appendleft(num_elements_less_than)
heap.push(nums[idx])
return list(result)
def countSmaller(nums):
n = len(nums)
counts = [0 for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
if nums[j] < nums[i]:
counts[i] += 1
return counts
| [
"benlerner95@gmail.com"
] | benlerner95@gmail.com |
873550b92b5310ad3dd76e9672067a40aae6a0dc | bda24355b0cd327c45bc0fc7deeffd8f010a69d7 | /plugins/keepercore/setup.py | eec28c9e20b5fa162a4a753568581e4c20c7f7e2 | [
"Apache-2.0"
] | permissive | TrendingTechnology/cloudkeeper | 41b01b3d7ed839cc8d3a13dff4ed4e65754bba64 | f1e292fa031af59ad634ae00c9167877deed92a0 | refs/heads/main | 2023-07-16T02:04:48.820156 | 2021-08-27T15:17:34 | 2021-08-27T15:17:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,363 | py | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="cloudkeeper-plugin-keepercore",
version="0.0.2",
description="Cloudkeeper Keepercore Plugin",
license="Apache 2.0",
packages=find_packages(),
long_description=read("README.md"),
entry_points={
"cloudkeeper.plugins": [
"keepercore = cloudkeeper_plugin_keepercore:KeepercorePlugin"
]
},
include_package_data=True,
zip_safe=False,
install_requires=["cloudkeeper"],
setup_requires=["pytest-runner"],
tests_require=["pytest"],
classifiers=[
# Current project status
"Development Status :: 4 - Beta",
# Audience
"Intended Audience :: System Administrators",
"Intended Audience :: Information Technology",
# License information
"License :: OSI Approved :: Apache Software License",
# Supported python versions
"Programming Language :: Python :: 3.8",
# Supported OS's
"Operating System :: POSIX :: Linux",
"Operating System :: Unix",
# Extra metadata
"Environment :: Console",
"Natural Language :: English",
"Topic :: Security",
"Topic :: Utilities",
],
keywords="cloud security",
)
| [
"noreply@github.com"
] | TrendingTechnology.noreply@github.com |
e9f3c160be47193869545f3bd9a4e9c4b4725470 | a814debee728e59a7a10d8c12b92c1f3ee97e19d | /Cadeias/Questao03.py | 34b21f4252426398efd21aaf4a7209289a604938 | [] | no_license | PedroVitor1995/Algoritmo-ADS-2016.1 | 0ee034d2f03b29d3c8177fb3402f7aeae08d07cf | 8e3b6dfb0db188b9f5d68dcb8619f6636883ab89 | refs/heads/master | 2021-01-01T15:51:56.636502 | 2017-07-19T13:47:36 | 2017-07-19T13:47:36 | 81,328,868 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 318 | py | #__*__ encoding:utf8 __*__
"""3. Leia uma frase e gere uma nova frase, retirando os espaços entre as palavras."""
def main():
frase = raw_input('Digite uma frase: ')
espaco = ' '
for letra in espaco:
if letra in frase:
frase = frase.replace(letra,'')
print frase
if __name__ == '__main__':
main() | [
"noreply@github.com"
] | PedroVitor1995.noreply@github.com |
c9ff2c8bf88605d0a7b76e8b6227f4d66df360f8 | fa60536fbc7c0d8a2a8f08f0a5b6351c77d08054 | /3]. Competitive Programming/03]. HackerRank/1]. Practice/08]. Problem Solving/Algorithms/04]. Sorting/Python/_58) Quicksort 1 - Partition.py | d21bac6d967ecd08251ed31010166f98336fdd0f | [
"MIT"
] | permissive | poojitha2002/The-Complete-FAANG-Preparation | 15cad1f9fb0371d15acc0fb541a79593e0605c4c | 7910c846252d3f1a66f92af3b7d9fb9ad1f86999 | refs/heads/master | 2023-07-17T20:24:19.161348 | 2021-08-28T11:39:48 | 2021-08-28T11:39:48 | 400,784,346 | 5 | 2 | MIT | 2021-08-28T12:14:35 | 2021-08-28T12:14:34 | null | UTF-8 | Python | false | false | 842 | py |
# Contributed by Paraj Shah
# https://github.com/parajshah
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'quickSort' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def quickSort(arr):
p = arr[0]
left = [arr[i] for i in range(len(arr)) if arr[i] < p]
equal = [arr[i] for i in range(len(arr)) if arr[i] == p]
right = [arr[i] for i in range(len(arr)) if arr[i] > p]
answer = left + equal + right
return answer
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
result = quickSort(arr)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| [
"parajshah2000@gmail.com"
] | parajshah2000@gmail.com |
d12238ab83b8b534203b5147815628b85fe6c142 | 03e3138f99f275d15d41a5c5bfb212f85d64d02e | /source/res/scripts/client/HeroTank.py | 61353111f978cdcbbf67b039336d8df486992494 | [] | no_license | TrenSeP/WorldOfTanks-Decompiled | e428728e7901146d0b599d02c930d70532232a97 | 1faa748acec1b7e435b657fd054ecba23dd72778 | refs/heads/1.4.1 | 2020-04-27T08:07:49.813023 | 2019-03-05T17:37:06 | 2019-03-05T17:37:06 | 174,159,837 | 1 | 0 | null | 2019-03-06T14:33:33 | 2019-03-06T14:24:36 | Python | UTF-8 | Python | false | false | 4,154 | py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/HeroTank.py
import random
import BigWorld
from ClientSelectableCameraVehicle import ClientSelectableCameraVehicle
from gui.hangar_vehicle_appearance import HangarVehicleAppearance
from gui.shared import events, EVENT_BUS_SCOPE, g_eventBus
from gui.shared.gui_items import GUI_ITEM_TYPE
from helpers import dependency
from items.components.c11n_constants import SeasonType
from skeletons.gui.customization import ICustomizationService
from skeletons.gui.game_control import IHeroTankController
from skeletons.gui.shared.utils import IHangarSpace
from vehicle_systems.tankStructure import ModelStates
from items import vehicles
from constants import IS_DEVELOPMENT
class _HeroTankAppearance(HangarVehicleAppearance):
_heroTankCtrl = dependency.descriptor(IHeroTankController)
_c11nService = dependency.descriptor(ICustomizationService)
def __init__(self, spaceId, vEntity):
super(_HeroTankAppearance, self).__init__(spaceId, vEntity)
self.__season = random.choice(SeasonType.COMMON_SEASONS)
def _getActiveOutfit(self):
styleId = self._heroTankCtrl.getCurrentTankStyleId()
if styleId:
style = self._c11nService.getItemByID(GUI_ITEM_TYPE.STYLE, styleId)
return style.getOutfit(self.__season)
return self._c11nService.getEmptyOutfit()
class HeroTank(ClientSelectableCameraVehicle):
_heroTankCtrl = dependency.descriptor(IHeroTankController)
_hangarSpace = dependency.descriptor(IHangarSpace)
def __init__(self):
self.__heroTankCD = None
ClientSelectableCameraVehicle.__init__(self)
return
def onEnterWorld(self, prereqs):
super(HeroTank, self).onEnterWorld(prereqs)
self._hangarSpace.onHeroTankReady += self._updateHeroTank
self._heroTankCtrl.onUpdated += self._updateHeroTank
self._heroTankCtrl.onInteractive += self._updateInteractive
def onLeaveWorld(self):
self._hangarSpace.onHeroTankReady -= self._updateHeroTank
self._heroTankCtrl.onUpdated -= self._updateHeroTank
self._heroTankCtrl.onInteractive -= self._updateInteractive
super(HeroTank, self).onLeaveWorld()
def removeModelFromScene(self):
if self.isVehicleLoaded:
self._onVehicleDestroy()
BigWorld.destroyEntity(self.id)
def recreateVehicle(self, typeDescriptor=None, state=ModelStates.UNDAMAGED, callback=None):
if self.__heroTankCD:
self.typeDescriptor = HeroTank.__getVehicleDescriptorByIntCD(self.__heroTankCD)
super(HeroTank, self).recreateVehicle(typeDescriptor, state, callback)
def _createAppearance(self):
return _HeroTankAppearance(self.spaceID, self)
def _updateHeroTank(self):
self.__heroTankCD = self._heroTankCtrl.getRandomTankCD()
if self.__heroTankCD:
self.recreateVehicle()
else:
self.removeModelFromScene()
def _updateInteractive(self, interactive):
if self.enabled != interactive:
self.enable(interactive)
self._onVehicleDestroy()
self.recreateVehicle()
def _onVehicleLoaded(self):
super(HeroTank, self)._onVehicleLoaded()
if self.enabled:
g_eventBus.handleEvent(events.HangarVehicleEvent(events.HangarVehicleEvent.ON_HERO_TANK_LOADED, ctx={'entity': self}), scope=EVENT_BUS_SCOPE.LOBBY)
def _onVehicleDestroy(self):
g_eventBus.handleEvent(events.HangarVehicleEvent(events.HangarVehicleEvent.ON_HERO_TANK_DESTROY, ctx={'entity': self}), scope=EVENT_BUS_SCOPE.LOBBY)
@staticmethod
def __getVehicleDescriptorByIntCD(vehicleIntCD):
_, nationId, itemId = vehicles.parseIntCompactDescr(vehicleIntCD)
return vehicles.VehicleDescr(typeID=(nationId, itemId))
def debugReloadHero(heroName):
if not IS_DEVELOPMENT:
return
for e in BigWorld.entities.values():
if isinstance(e, HeroTank):
heroDescriptor = vehicles.VehicleDescr(typeName=heroName)
e.recreateVehicle(heroDescriptor)
return
| [
"StranikS_Scan@mail.ru"
] | StranikS_Scan@mail.ru |
f858c1fb7b0e61b45ede9ea4c4052278ae547ed5 | af84bfe86aca06fea647679f1aa2a5e3fafb98f6 | /postprocess.py | 2f9b46505795fd27f813ce862e0c58c22c6b3a0b | [] | no_license | TeeeJay/ldifdiff | b58fed14a015be72cf0eb41ae2125696dccb59e1 | 4bd46381bebecbd8f60853ec06706954cf8434a2 | refs/heads/master | 2020-12-11T09:31:02.673878 | 2016-06-15T13:26:42 | 2016-06-15T13:26:42 | 37,706,256 | 0 | 0 | null | 2015-06-19T06:43:49 | 2015-06-19T06:43:48 | null | UTF-8 | Python | false | false | 1,649 | py | #!/usr/bin/env python2
"""
ldiffsearch truncates and wraps lines that exceeds 78 characters from LDAP/AD, and proceeds on next line prefixed with a space " ".
This tool fixes lines back to how they should be, without truncation for correct parsing by ldiff afterwards.
"""
import argparse
def postprocess(ldif_file):
with open(ldif_file+".postprocessed", 'w') as output:
write_previous = False
previous_line = ""
with open(ldif_file, 'r') as ldif:
for line in ldif:
line = line.strip("\n")
# between each entity there is an empty line
if (line.strip() == ""):
previous_line += "\n"
write_previous = True
elif line.startswith(" "):
line = line[1:]
write_previous = False
else:
write_previous = True
if previous_line and write_previous:
output.write(previous_line + "\n")
previous_line = ""
write_previous = False
previous_line += line
output.write(previous_line + "\n")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Post process LDIF-files that has been capped at 78 chars. Takes one input and creates a postprocessed file with .postprocessed file extension")
parser.add_argument('-i', '--input-file', default=None, dest='input_file', required=True, help="Will create a new file with postfix _postprocessed")
args = parser.parse_args()
postprocess(args.input_file)
| [
"teeejay@gmail.com"
] | teeejay@gmail.com |
5d8ef1b9215c2d6af2d47c0cc2f83c2c95504b3e | 8f43323e42495b766cae19a76a87d24c2ea2b086 | /compiler/tests/config_20_scn3me_subm.py | fefc8474cec8cb2d846aadf8a2e281e4b44620b0 | [
"BSD-3-Clause"
] | permissive | rowhit/OpenRAM | 7c78b3998044d8c30effd33c9176dc07491df949 | f98155fc0b6019dc61b73b59ca2a9d52245bb41c | refs/heads/master | 2021-05-05T22:32:43.177316 | 2017-12-19T15:39:43 | 2017-12-19T15:39:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 781 | py | word_size = 1
num_words = 16
num_banks = 1
tech_name = "scn3me_subm"
# Optional, will be over-ridden on command line.
output_path = "/tmp/scn3me_subm_mysram"
output_name = "sram_2_16_1_scn3me_subm"
decoder = "hierarchical_decoder"
ms_flop = "ms_flop"
ms_flop_array = "ms_flop_array"
control_logic = "control_logic"
bitcell_array = "bitcell_array"
sense_amp = "sense_amp"
sense_amp_array = "sense_amp_array"
precharge_array = "precharge_array"
column_mux_array = "single_level_column_mux_array"
write_driver = "write_driver"
write_driver_array = "write_driver_array"
tri_gate = "tri_gate"
tri_gate_array = "tri_gate_array"
wordline_driver = "wordline_driver"
replica_bitline = "replica_bitline"
replica_bitcell = "replica_bitcell"
bitcell = "bitcell"
delay_chain = "delay_chain"
| [
"mrg@ucsc.edu"
] | mrg@ucsc.edu |
ecbc41b30ba54303b78a059a1328552e34f4109f | 4c3e992678341ccaa1d4d14e97dac2e0682026d1 | /addons/survey/__manifest__.py | ef974c82ea37e77d0d5f0d2f2b34cc9dac0e9c29 | [] | no_license | gahan-corporation/wyatt | 3a6add8f8f815bd26643e1e7c81aea024945130d | 77e56da362bec56f13bf0abc9f8cf13e98461111 | refs/heads/master | 2021-09-03T18:56:15.726392 | 2018-01-08T02:54:47 | 2018-01-08T02:54:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,414 | py | # -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Survey',
'version': '2.0',
'category': 'Marketing',
'description': """
Create beautiful web surveys and visualize answers
==================================================
It depends on the answers or reviews of some questions by different users. A
survey may have multiple pages. Each page may contain multiple questions and
each question may have multiple answers. Different users may give different
answers of question and according to that survey is done. Partners are also
sent mails with personal token for the invitation of the survey.
""",
'summary': 'Create surveys, collect answers and print statistics',
'website': 'https://www.gerp.com/page/survey',
'depends': ['mail', 'website'],
'data': [
'security/survey_security.xml',
'security/ir.model.access.csv',
'views/survey_views.xml',
'views/survey_templates.xml',
'views/survey_result.xml',
'wizard/survey_email_compose_message.xml',
'data/survey_stages.xml',
],
'demo': ['data/survey_demo_user.xml',
'data/survey_demo_feedback.xml',
'data/survey.user_input.csv',
'data/survey.user_input_line.csv'],
'installable': True,
'auto_install': False,
'application': True,
'sequence': 105,
}
| [
"duchess@gahan-corporation.com"
] | duchess@gahan-corporation.com |
352e6c3406224898fe517bf8f1493a4d242124b9 | c79416e3f2bc1af3a5c3436282e5c6c95067f473 | /itp1/9_a.py | 6114b7444d81b87245db962dfa3bc7e8f57461de | [] | no_license | mollinaca/AOJ | c14149c265c3a6cc572617d381609ed624c68df3 | 3389c4060faa18934a02246a0c9e5e234a637514 | refs/heads/master | 2021-05-17T21:20:27.935501 | 2020-04-29T13:52:18 | 2020-04-29T13:52:18 | 250,957,993 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 294 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
w = input()
T = []
while True:
t = list(input().split())
if t == ['END_OF_TEXT']:
break
else:
t = [s.lower() for s in t]
T.append(t)
total = 0
for line in T:
total += line.count(w.lower())
print (total)
| [
"github@mail.watarinohibi.tokyo"
] | github@mail.watarinohibi.tokyo |
959594758724932556b4ff8aa9cbce0c27afd06b | 303c833c6fc31c76387d69aedd26ec01e2a52312 | /inscriptions/views.py | 5d26c106d68018ab230e83b009396e57588da31e | [] | no_license | excellencemichel/saintexupery | a9d9ead2c182705f2776d0e50a4f2b94a52a3384 | c109a03ad3dbacb6ee5bc4b20a40eb750afe0a53 | refs/heads/master | 2022-12-13T11:54:37.184139 | 2020-07-07T17:48:53 | 2020-07-07T17:48:53 | 151,463,288 | 1 | 0 | null | 2022-12-08T02:25:15 | 2018-10-03T18:48:52 | JavaScript | UTF-8 | Python | false | false | 3,330 | py |
from io import BytesIO
from email.mime.base import MIMEBase
from email import encoders
from time import strftime
from django.conf import settings
from django.core.mail import EmailMessage
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
#Local
from .models import Inscription, Information
from .forms import InscriptionModelForm
from pdfapp.utils import render_to_pdf
def inscriptions(request):
instance = Information.objects.last()
context = {
"instance": instance,
}
return render(request, "inscriptions/inscriptions.html", context)
def inscription(request):
form = InscriptionModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
human = True
instance = form.save(commit=False)
annee = strftime("%y")
mois = strftime("%m")
last_object = Inscription.objects.filter().last()
print("Voici le last_object : ", last_object)
if last_object == None:
last_id = 1
else:
last_id = last_object.id
print("Voici le last_id : ", last_id)
if last_id == 1:
object_id = last_id
print("Voici le object_id: ", object_id)
else:
object_id = last_id + 1
print("Voici le object_id: ", object_id)
matricule = "{annee}{mois}{id}".format(annee=annee, mois=mois, id=object_id)
instance.matricule = matricule
context = {"models_instance": instance}
context["route_fichier"] = settings.BASE_DIR
pdf_inscription = render_to_pdf("inscriptions/inscription_email_pdf.html", context)
filename = "mypdf_{}.pdf".format(matricule)
instance.pdf_inscription.save(filename, BytesIO(pdf_inscription.content))
subject = """"Confirmation de l'accusé de reception de l'inscription de {nom} {prenom}""".format(nom=instance.nom, prenom=instance.prenom)
subject_direction = """Une incription vient d'être faite depuis le site internet"""
with open(settings.BASE_DIR + "/inscriptions/templates/inscriptions/inscription_email_message_to_direction.txt") as f_to_direction:
inscription_message_to_direction = f_to_direction.read()
with open(settings.BASE_DIR + "/inscriptions/templates/inscriptions/inscription_email_message.txt") as f:
inscription_message = f.read()
from_email = settings.EMAIL_HOST_USER
to_email = [instance.email, instance.email_parent_un, instance.email_parent_deux]
to_email_direction = ["contact@ecf-saintex.com"]
email_pdf = EmailMessage(
subject = subject,
body =inscription_message,
from_email = from_email,
to=to_email,
)
email_to_direction = EmailMessage(
subject = subject_direction,
body = inscription_message_to_direction,
from_email= from_email,
to= to_email_direction,
)
# instance_attach = instance.pdf_inscription.read()
instance_attach = MIMEBase('application', "octet-stream")
instance_attach.set_payload(instance.pdf_inscription.read())
encoders.encode_base64(instance_attach)
instance_attach.add_header('Content-Disposition', 'attachment', filename="{matricule}.pdf".format(matricule=matricule))
# print(instance.pdf.name, instance.pdf.size)
email_pdf.attach(instance_attach)
email_to_direction.attach(instance_attach)
email_pdf.send()
email_to_direction.send()
return redirect(reverse("home"))
return render(request, "inscriptions/inscriptionform.html", {"form": form})
| [
"bnvnmmnl@gmail.com"
] | bnvnmmnl@gmail.com |
eb2741a086cdbc48c6df9cdb8b8c82eaca859692 | fa4f9854a42f5add3d0bb84efe66b3a0fd003dc0 | /minHeightTrees.py | abe1dfecfaf7a1b6e1192c251f12c03b11d7d9f5 | [] | no_license | NYCGithub/LC | dbf73326588272457f6421a712d12e6db87b9146 | 16b4c0987deecd14f3fef8636ac1f98177506768 | refs/heads/master | 2022-02-20T19:08:07.877950 | 2019-10-09T05:04:33 | 2019-10-09T05:04:33 | 120,974,104 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,719 | py | from collections import defaultdict
import collections
# from collections import defaultdict, deque
class Solution:
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
Time: O(N)
Space: O(N)
BFS: Start with all leaves (with only 1 neighbor), and keeping cutting off the leaves, and moving onto the next
set of leaves, until there are at most 2 nodes remaining. Those 2 nodes (or 1 node) are the results.
Intuition is that you want to use the most middle-located nodes, which can be one node or 2 nodes
depending on parity of total nodes
"""
if n == 1:
return [0]
graph = collections.defaultdict(set)
for u, v in edges:
graph[u].add(v)
graph[v].add(u)
leaves = collections.deque([node for node in range(n) if len(graph[node]) == 1]) # Only a single connection means it's a leaf.
while n > 2:
size = len(leaves)
n -= size
for _ in range(size):
l = leaves.pop()
neighbor = graph[l].pop()
graph[neighbor].remove(l) # Prune the leaf
if len(graph[neighbor]) == 1: # If after pruning its leave, the neighbor is now also leaf
leaves.appendleft(neighbor) #Work on this new generation of leaves in the next iteration.
return list(leaves)
class Solution_N_Squared:
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
minDepth = float('inf')
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
result = []
for node in range(n):
depth = self.bfsMaxDepth(node, None, graph)
if depth < minDepth:
result = [node]
minDepth = depth
elif depth == minDepth:
result.append(node)
return result
def bfsMaxDepth(self, node, prevNode, graph):
if graph[node] == [prevNode]:
return 0 # Reaches leaf.
maxDepth = float('-inf')
for child in graph[node]:
if child != prevNode:
depth = 1 + self.bfsMaxDepth(child, node, graph)
maxDepth = max(depth, maxDepth)
return maxDepth
sol = Solution()
print (sol.findMinHeightTrees(4,([1, 0], [1, 2], [1, 3])))
print (sol.findMinHeightTrees(6,([[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]])))
print (sol.findMinHeightTrees(6,([[0, 1], [0, 2], [0, 3], [3, 4], [4, 5]]))) | [
"joe.zhang@gmail.com"
] | joe.zhang@gmail.com |
25dda00aebd4cc10a8d217937dd78fbbbd95b211 | 340bf2f4560e368de8c3c58a8d1063a06394545d | /src/raveutils/body.py | a6eaf85e23d6c4c505331a9c47fdc0ce3b84fd0b | [
"BSD-3-Clause"
] | permissive | yourouguaduan/raveutils | 5ad17c9d6ad88b4ab767ceed41e302ba3c4b4a77 | b4f355249926ada87d863d8f25f2f6ae5d0c0a53 | refs/heads/master | 2020-09-15T18:58:20.796405 | 2019-05-29T01:52:10 | 2019-05-29T01:53:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,057 | py | #!/usr/bin/env python
import itertools
import numpy as np
import baldor as br
import openravepy as orpy
# Local modules
import raveutils as ru
def enable_body(body, enable):
"""
Enables all the links of a body.
Parameters
----------
body: orpy.KinBody
The OpenRAVE body
enable: bool
If true, will enable all the links.
"""
env = body.GetEnv()
with env:
for link in body.GetLinks():
link.Enable(enable)
def get_bounding_box_corners(body, transform=None, scale=1.):
"""
Get the bounding box corners (8 corners) for the given body.
If ``transform`` is given the corners are transformed properly.
The ``scale`` parameters is a factor used to scale the extents of the
bounding box.
Parameters
----------
body: orpy.KinBody
The OpenRAVE body
transform: array_like
Homogeneous transformation of the body. If ``None``, the corners are given
using the current pose of the body in OpenRAVE.
scale: float
The scale factor to modify the extents of the bounding box.
Returns
-------
corners: list
List containing the 8 box corners. Each corner is a XYZ ``np.array``
"""
if transform is not None:
Tinv = br.transform.inverse(body.GetTransform())
aabb = body.ComputeAABB()
corners = []
for k in itertools.product([-1,1],[-1,1],[-1,1]):
position = aabb.pos() + np.array(k)*aabb.extents()*scale
if transform is not None:
homposition = np.hstack((position,1))
homposition = np.dot(Tinv, homposition)
position = np.dot(transform, homposition)[:3]
corners.append(position)
return corners
def set_body_color(body, diffuse, ambient=None):
"""
Override diffuse and ambient color of the body
Parameters
----------
body: orpy.KinBody
The OpenRAVE body
diffuse: array_like
The input diffuse color in RGB format (3 elements array)
ambient: array_like
The input ambient color in RGB format (3 elements array)
Notes
-----
The value of each color channel (R, G and B) must be between :math:`[0, 1]`
"""
env = body.GetEnv()
is_ambient_available = ambient is not None
with env:
for link in body.GetLinks():
for geom in link.GetGeometries():
geom.SetDiffuseColor(diffuse)
if is_ambient_available:
geom.SetAmbientColor(ambient)
def set_body_transparency(body, transparency=0.0, links=None):
"""
Set the transparency value of all the body's geometries
Parameters
----------
body: orpy.KinBody
The OpenRAVE body
transparency: float
The transparency value. If it's out of range [0.0, 1.0], it'll be clipped.
links: list
List of links to be modified. By default all the links are.
"""
if links is None:
links_to_modify = [link.GetName() for link in body.GetLinks()]
else:
links_to_modify = links
transparency = np.clip(transparency, 0.0, 1.0)
env = body.GetEnv()
with env:
for link in body.GetLinks():
if link.GetName() in links_to_modify:
for geom in link.GetGeometries():
geom.SetTransparency(transparency)
| [
"fsuarez6@gmail.com"
] | fsuarez6@gmail.com |
c772160f77cd351a76bc81ec5c8e3205b930afd4 | 2f68b5577757e55dc7ae24655c4e262a1e78173d | /harisekhon/nagiosplugin/rest_nagiosplugin.py | 72c4d2bd3ec64262d133a223ab6ffb4248f90414 | [] | no_license | dwintergruen/pylib | 6785442029534b4b33811ec4dd0bf8cd6bf23338 | 8271ea9ce3c6c559295401dc42a3a1d139382d9e | refs/heads/master | 2020-03-23T19:31:34.395151 | 2018-07-02T22:18:29 | 2018-07-02T22:18:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,381 | py | #!/usr/bin/env python
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2016-12-19 17:42:51 +0000 (Mon, 19 Dec 2016)
#
# https://github.com/harisekhon/pylib
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn
# and optionally send me feedback to help steer this or other code I publish
#
# https://www.linkedin.com/in/harisekhon
#
"""
Rest API Check Specialization of NagiosPlugin
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from __future__ import unicode_literals
import logging
import json
import os
import sys
import time
import traceback
# Python 2.6+ only
from abc import ABCMeta #, abstractmethod
srcdir = os.path.abspath(os.path.dirname(__file__))
libdir = os.path.join(srcdir, 'pylib')
sys.path.append(libdir)
try:
# pylint: disable=wrong-import-position
from harisekhon.utils import log, log_option, UnknownError, support_msg_api, jsonpp
from harisekhon.utils import validate_host, validate_port, validate_user, validate_password
from harisekhon.nagiosplugin import NagiosPlugin
from harisekhon import RequestHandler
except ImportError as _:
print(traceback.format_exc(), end='')
sys.exit(4)
__author__ = 'Hari Sekhon'
__version__ = '0.5.2'
class RestNagiosPlugin(NagiosPlugin):
__version__ = __version__
# abstract class
__metaclass__ = ABCMeta
def __init__(self):
# Python 2.x
super(RestNagiosPlugin, self).__init__()
# Python 3.x
# super().__init__()
self.name = None
self.default_host = 'localhost'
self.default_port = 80
self.default_user = None
self.default_password = None
self.host = None
self.port = None
self.user = None
self.password = None
self.protocol = 'http'
self.msg = 'rest msg not defined yet'
self.request = RequestHandler()
self.request_method = 'get'
self.req = None
self.json_data = None
self.path = None
self.json = False
self.headers = {}
self.auth = True
self.ok()
def add_options(self):
self.add_hostoption(name=self.name,
default_host=self.default_host,
default_port=self.default_port)
if self.auth:
self.add_useroption(name=self.name,
default_user=self.default_user,
default_password=self.default_password)
self.add_ssl_option()
def process_options(self):
self.no_args()
self.host = self.get_opt('host')
self.port = self.get_opt('port')
validate_host(self.host)
validate_port(self.port)
if self.auth:
self.user = self.get_opt('user')
self.password = self.get_opt('password')
if self.auth == 'optional':
if self.user and self.password:
validate_user(self.user)
validate_password(self.password)
else:
validate_user(self.user)
validate_password(self.password)
ssl = self.get_opt('ssl')
log_option('ssl', ssl)
if ssl and self.protocol == 'http':
self.protocol = 'https'
if self.json:
# recommended for many systems like CouchDB
# but breaks Ambari API calls
#self.headers['Accept'] = 'application/json'
self.headers['Content-Type'] = 'application/json'
def run(self):
start_time = time.time()
self.req = self.query()
query_time = time.time() - start_time
if self.json:
log.info('parsing json response')
self.process_json(self.req.content)
else:
log.info('parsing response')
self.parse(self.req)
if '|' not in self.msg:
self.msg += ' |'
if ' query_time=' not in self.msg:
self.msg += ' query_time={0:.4f}s'.format(query_time)
def query(self):
url = '{proto}://{host}:{port}/'.format(proto=self.protocol,
host=self.host,
port=self.port)
if self.path:
url += self.path.lstrip('/')
auth = None
if self.user and self.password:
log.info('authenticating to Rest API')
auth = (self.user, self.password)
req = self.request.req(self.request_method, url, auth=auth, headers=self.headers)
return req
#@abstractmethod
def parse(self, req):
pass
#@abstractmethod
def parse_json(self, json_data):
pass
def process_json(self, content):
try:
self.json_data = json.loads(content)
if log.isEnabledFor(logging.DEBUG):
log.debug('JSON prettified:\n\n%s\n%s', jsonpp(self.json_data), '='*80)
return self.parse_json(self.json_data)
#except (KeyError, ValueError) as _:
#raise UnknownError('{0}: {1}. {2}'.format(type(_).__name__, _, support_msg_api()))
except (KeyError, ValueError):
raise UnknownError('{0}. {1}'.format(self.exception_msg(), support_msg_api()))
| [
"harisekhon@gmail.com"
] | harisekhon@gmail.com |
84e37796204678250e593e157001e537c5439c00 | 58cd392c642ac9408349f03dc72927db6abcce55 | /team2/src/Without_Doubt_Project/venv/lib/python3.6/site-packages/jsonrpcclient/aiohttp_client.py | 4bd5d88023f87a6fff951ef3df4538914bd2036b | [] | no_license | icon-hackathons/201902-dapp-competition-bu | 161226eb792425078351c790b8795a0fe5550735 | f3898d31a20f0a85637f150d6187285514528d53 | refs/heads/master | 2020-04-24T07:48:18.891646 | 2019-04-18T01:47:21 | 2019-04-18T01:47:21 | 171,809,810 | 3 | 11 | null | 2019-04-18T01:47:23 | 2019-02-21T06:01:04 | Python | UTF-8 | Python | false | false | 605 | py | """
aiohttp client.
http://aiohttp.readthedocs.io/
"""
import async_timeout
from .async_client import AsyncClient
class aiohttpClient(AsyncClient):
"""TODO: rename aiohttpClient to AiohttpClient"""
def __init__(self, session, endpoint):
super(aiohttpClient, self).__init__(endpoint)
self.session = session
async def send_message(self, request):
with async_timeout.timeout(10):
async with self.session.post(self.endpoint, data=request) as response:
response = await response.text()
return self.process_response(response)
| [
"41354736+sojinkim-icon@users.noreply.github.com"
] | 41354736+sojinkim-icon@users.noreply.github.com |
9802a6954af30e6d371395351f15844dbc16ee3d | d48dfa622e07d346a91be3aa8e8657e409faf552 | /Funkcje/15_funkcion_arguments_lab.py | 5746ff4fe552c9a37fa4f2ac3c2d7efaa5544308 | [] | no_license | sineczek/PythonSrednioZaawansowany | 71c8c94f7cdc193482a50b94315b86e1f0ab0039 | 75823b36de99ef9ac487672cf131a0b84ce23d2b | refs/heads/main | 2023-03-14T04:33:26.853500 | 2021-03-06T18:13:02 | 2021-03-06T18:13:02 | 332,524,333 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 830 | py | '''Napisz funkcję show_progress, która będzie wyświetlać linię tekstu powstałą wskutek powtórzenia zadaną ilość razy określonego znaku. Funkcja:
przyjmuje argument character, który określa jaki znak ma być powtarzany
przyjmuje argument how_many, który określa ile razy znak ma być powtórzony
wartość domyślna dla character to gwiazdka
Przetestuj działanie funkcji wywołując ją na różne sposoby np.:
show_progress(10)
show_progress(15)
show_progress(30)
show_progress(10, '-')
show_progress(15, '+')'''
def show_progress(how_many, character='*'):
print(character*how_many)
'''z rozwiązania
def show_progress(how_many, character='*'):
line = character * how_many
print(line)'''
show_progress(10)
show_progress(15)
show_progress(30)
show_progress(10, '-')
show_progress(15, '+') | [
"michalzaitz@gmail.com"
] | michalzaitz@gmail.com |
dc47554d104694d0430eeffc4c0eec3a12fa075f | 82fce9aae9e855a73f4e92d750e6a8df2ef877a5 | /Lab/venv/lib/python3.8/site-packages/OpenGL/GL/EXT/polygon_offset_clamp.py | e2a1cbb13ebb9879bacbb931b2614d8f23356d71 | [] | no_license | BartoszRudnik/GK | 1294f7708902e867dacd7da591b9f2e741bfe9e5 | 6dc09184a3af07143b9729e42a6f62f13da50128 | refs/heads/main | 2023-02-20T19:02:12.408974 | 2021-01-22T10:51:14 | 2021-01-22T10:51:14 | 307,847,589 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,196 | py | '''OpenGL extension EXT.polygon_offset_clamp
This module customises the behaviour of the
OpenGL.raw.GL.EXT.polygon_offset_clamp to provide a more
Python-friendly API
Overview (from the spec)
This extension adds a new parameter to the polygon offset function
that clamps the calculated offset to a minimum or maximum value.
The clamping functionality is useful when polygons are nearly
parallel to the view direction because their high slopes can result
in arbitrarily large polygon offsets. In the particular case of
shadow mapping, the lack of clamping can produce the appearance of
unwanted holes when the shadow casting polygons are offset beyond
the shadow receiving polygons, and this problem can be alleviated by
enforcing a maximum offset value.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/EXT/polygon_offset_clamp.txt
'''
from OpenGL.raw.GL.EXT.polygon_offset_clamp import _EXTENSION_NAME
def glInitPolygonOffsetClampEXT():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME )
### END AUTOGENERATED SECTION | [
"rudnik49@gmail.com"
] | rudnik49@gmail.com |
45854a5d6b2e7664c74356e9c67ba030022c07e7 | f2ddb6c0233709b72b592b62a8d913a48bb9e9e4 | /python/plot_fig_copy_compdecomp_voxels_sm.py | 9031db3a61f0f0d31fc47d9fd12d15c344d2caa7 | [
"MIT"
] | permissive | other3000/HashDAG | 4d97d83c997c776eef22d2623ed9ec939edb4f02 | 09bddd0dd19cb4eb326336aa5cbc558b74372b99 | refs/heads/master | 2023-09-05T12:58:29.266954 | 2021-07-19T08:07:22 | 2021-07-19T08:07:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,322 | py | import matplotlib.pyplot as plt
import re
import tools
from tools import get_array, dags, defines, names, indices
path = tools.results_prompt("copy_compdecomp_sm")
# Styling
plt.style.use("seaborn")
#plt.rc("font", family="serif", size=56)
#plt.rc("axes", labelsize=18)
#plt.rc("legend", fontsize=12)
plt.rc("font", family="serif", size=14)
plt.rc("axes", labelsize=32)
plt.rc("xtick", labelsize=20)
plt.rc("ytick", labelsize=20)
plt.rc("legend", fontsize=24)
# Setup
fig = plt.figure(dpi=100, figsize=(6, 6))
ax = fig.add_subplot(111)
# Do stuff
for i in range(len(dags)):
data = dags[i]
label_index = 0
time = get_array(data, "copied voxels")
num_voxels = get_array(data, "num voxels")
#label = "(MISSING LABEL)"
#if -1 != names[i].find("nothread"):
# label = "Single-threaded"
#else:
# threadCount = re.search(r"_thread(\d+)", names[i]).group(1)
# label = "{} threads".format(threadCount)
kwargs = {"linestyle": "None", "marker": "o", "markersize": 5}
ax.set_xlabel("template voxels")
ax.set_ylabel("changed voxels")
ax.plot(num_voxels, time, **kwargs)
ax.ticklabel_format( axis='both', style='sci', scilimits=(0,0) );
leg = ax.legend()
plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0)
plt.savefig(path + "plot.pdf", format="pdf")
plt.show()
| [
"phyronnaz@gmail.com"
] | phyronnaz@gmail.com |
90380fb9ae5ea96be27fa60de9f33eba60782874 | 2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8 | /pardus/playground/kaan.aksit/2011/science/misc/eigen/actions.py | 8e3c67b3898c90ead30d41622db22090d6e8cc40 | [] | no_license | aligulle1/kuller | bda0d59ce8400aa3c7ba9c7e19589f27313492f7 | 7f98de19be27d7a517fe19a37c814748f7e18ba6 | refs/heads/master | 2021-01-20T02:22:09.451356 | 2013-07-23T17:57:58 | 2013-07-23T17:57:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 762 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 2.
# See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
from pisi.actionsapi import cmaketools
from pisi.actionsapi import shelltools
from pisi.actionsapi import get
from pisi.actionsapi import pisitools
WorkDir = "eigen-eigen-6e7488e20373"
def setup():
shelltools.makedirs("%s/%s/build_dir" % (get.workDIR(),WorkDir))
shelltools.cd("%s/%s/build_dir" % (get.workDIR(),WorkDir))
cmaketools.configure(sourceDir = "..")
def install():
shelltools.cd("%s/%s/build_dir" % (get.workDIR(),WorkDir))
cmaketools.rawInstall("DESTDIR=%s" % get.installDIR())
pisitools.remove("/usr/include/eigen3/Eigen/src/Sparse/SparseAssign.h")
| [
"yusuf.aydemir@istanbul.com"
] | yusuf.aydemir@istanbul.com |
168a5715a8f443afbb27634ed7ba5bf81bc06c05 | 5c8139f1e57e06c7eaf603bd8fe74d9f22620513 | /PartB/py数字能组成的时间的最大的值2.py | 41a6a7dbc3d9a0c1a806795e35cd18baac6a5189 | [] | no_license | madeibao/PythonAlgorithm | c8a11d298617d1abb12a72461665583c6a44f9d2 | b4c8a75e724a674812b8a38c0202485776445d89 | refs/heads/master | 2023-04-03T07:18:49.842063 | 2021-04-11T12:02:40 | 2021-04-11T12:02:40 | 325,269,130 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 457 | py |
from typing import List
from itertools import permutations
class Solution:
def largestTimeFromDigits(self, A: List[int]) -> str:
A.sort(reverse=True)
for a, b, c, d, e, f in permutations(A):
if a*10+b <24 and c*10+d<60 and e*10+f<60:
return f"{a}{b}:{c}{d}:{e}{f}"
return ''
if __name__ == '__main__':
s = Solution()
list2 = [1, 2, 3, 4, 8, 9]
print(s.largestTimeFromDigits(list2))
| [
"2901429479@qq.com"
] | 2901429479@qq.com |
cc15e377f188cd0f76c707d649e69e12ea451d22 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/adjectives/_deep.py | 62008e31e6c16e7107fac9348ef229ddfa09d28a | [
"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 | 857 | py |
#calss header
class _DEEP():
def __init__(self,):
self.name = "DEEP"
self.definitions = [u'going or being a long way down from the top or surface, or being of a particular distance from the top to the bottom: ', u'very strongly felt or experienced and usually lasting a long time: ', u'(of a sound) low: ', u'showing or needing serious thought, or not easy to understand: ', u'If something is deep, it has a large distance between its edges, especially between its front and back edges: ', u'near the middle of something, and a long distance from its edges: ', u'(of a colour) strong and dark: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'adjectives'
def run(self, obj1, obj2):
self.jsondata[obj2] = {}
self.jsondata[obj2]['properties'] = self.name.lower()
return self.jsondata
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
95b66a589aaab9da93ad93693dde5f1a16916845 | 938c55df0653b377318cd434f0fedb97036cfe7d | /day20/func_hello.py | 69090887e8d4debd54f2c2b0d41b794431adeedb | [] | no_license | elliajen/pyworks | 6f754d0caaa4d110549f7704ade72f0002e63adb | a24a7c02f338fa8d7cfdab5a0d8bc005532dfa99 | refs/heads/master | 2023-08-26T17:27:11.893396 | 2021-10-22T04:28:43 | 2021-10-22T04:28:43 | 402,286,435 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 269 | py | # 함수 정의하고 사용하기
# 매개변수가 없는 함수
def hello(): # def 함수이름()
print("Hello~ Python!!")
# 매개변수가 있는 함수
def hello2(name):
print("Hello~", name)
hello() # 함수 호출
hello2("콩쥐")
hello2("흥부")
| [
"dmstndhk123@naver.com"
] | dmstndhk123@naver.com |
8faf8b17e0c96fe8cfb2baa07c6026757f0b9560 | e7b7505c084e2c2608cbda472bc193d4a0153248 | /LeetcodeNew/LinkedIn/LC_256.py | 8d7be595d1ec13084e3a6d6b1f26b8ff956d9361 | [] | no_license | Taoge123/OptimizedLeetcode | 8e5c1cd07904dfce1248bc3e3f960d2f48057a5d | 3e50f6a936b98ad75c47d7c1719e69163c648235 | refs/heads/master | 2023-02-27T21:13:40.450089 | 2023-02-07T04:11:09 | 2023-02-07T04:11:09 | 170,044,224 | 9 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,394 | py |
# O(n*3) space
def minCost1(self, costs):
if not costs:
return 0
r, c = len(costs), len(costs[0])
dp = [[0 for _ in xrange(c)] for _ in xrange(r)]
dp[0] = costs[0]
for i in xrange(1, r):
dp[i][0] = costs[i][0] + min(dp[ i -1][1:3])
dp[i][1] = costs[i][1] + min(dp[ i -1][0], dp[ i -1][2])
dp[i][2] = costs[i][2] + min(dp[ i -1][:2])
return min(dp[-1])
# change original matrix
def minCost2(self, costs):
if not costs:
return 0
for i in xrange(1, len(costs)):
costs[i][0] += min(costs[ i -1][1:3])
costs[i][1] += min(costs[ i -1][0], costs[ i -1][2])
costs[i][2] += min(costs[ i -1][:2])
return min(costs[-1])
# O(1) space
def minCost3(self, costs):
if not costs:
return 0
dp = costs[0]
for i in xrange(1, len(costs)):
pre = dp[:] # here should take care
dp[0] = costs[i][0] + min(pre[1:3])
dp[1] = costs[i][1] + min(pre[0], pre[2])
dp[2] = costs[i][2] + min(pre[:2])
return min(dp)
# O(1) space, shorter version, can be applied
# for more than 3 colors
def minCost(self, costs):
if not costs:
return 0
dp = costs[0]
for i in xrange(1, len(costs)):
pre = dp[:] # here should take care
for j in xrange(len(costs[0])):
dp[j] = costs[i][j] + min(pre[:j ] +pre[ j +1:])
return min(dp)
| [
"taocheng984@gmail.com"
] | taocheng984@gmail.com |
5eb901d996bc8176f0886ffdc7eceef8fff7534b | ad5a064d91e7055b7888030e6fb1e96355391fda | /circles.py | 93ccac506944553abc62cd172ae5e3a8097cd69e | [] | no_license | arsummers/pygame-tutorial | 914ecb335b6326751541cff883da0f4c73fd6e08 | d10cf65c51fc19cb08874b180f61e68d82b51d5e | refs/heads/master | 2020-09-01T02:34:05.770881 | 2019-12-05T02:32:19 | 2019-12-05T02:32:19 | 218,859,199 | 0 | 0 | null | 2019-12-05T02:32:20 | 2019-10-31T20:47:51 | Python | UTF-8 | Python | false | false | 539 | py | import pygame
pygame.init()
# drawing window
screen = pygame.display.set_mode([500, 500])
# runs until user tells it not to
running = True
while running:
# checks if user clicked close window button
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# makes the background white
screen.fill((255, 255, 255))
# draws a solid blue circle in center of screen
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
pygame.display.flip()
pygame.quit() | [
"aliyasummers1@gmail.com"
] | aliyasummers1@gmail.com |
fce3d5543845dda7bac7a6578133a769e422f51e | 200abee8ebb5fa255e594c8d901c8c68eb9c1a9c | /venv/02_Codesignal/02_The Core/089_arrayPreviousLess.py | fcad7a3c35a987d96fd0e08d4b9ad6ce19cbf901 | [] | no_license | Vestenar/PythonProjects | f083cbc07df57ea7a560c6b18efed2bb0dc42efb | f8fdf9faff013165f8d835b0ccb807f8bef6dac4 | refs/heads/master | 2021-07-20T14:14:15.739074 | 2019-03-12T18:05:38 | 2019-03-12T18:05:38 | 163,770,129 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 823 | py | def arrayPreviousLess(items):
ans = []
for i in range(len(items)):
temp = -1
for j in range(i-1, -1, -1):
if items[i] > items[j]:
temp = items[j]
break
ans.append(temp)
return ans
items = [2, 2, 1, 3, 4, 5, 5, 3]
print(arrayPreviousLess(items))
'''
# нужно вставить самое правое из чисел слева, которое меньше, чем текущее!
Given array of integers, for each position i, search among the previous positions
for the last (from the left) position that contains a smaller value.
Store this value at position i in the answer. If no such value can be found, store -1 instead.
Example
For items = [3, 5, 2, 4, 5], the output should be
arrayPreviousLess(items) = [-1, 3, -1, 2, 4].
''' | [
"vestenar@gmail.com"
] | vestenar@gmail.com |
406376f5ad914a792ccac23f0bb01428697934c1 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2715/60618/290367.py | a9a32fbfa625a8d66dddf8e9631a22324ddcf795 | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 218 | py | n=eval(input())
if len(n)==1:
print(0)
else:
a = [i[0] for i in n]
b = [i[1] for i in n]
if len(set(a))+len(set(b))>len(n):
print(len(set(a))+len(set(b))-1)
else:
print(len(n))
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
b84bcbe6f6303caccff3b48a2e45201ff8a4528e | b1d92172726262fc89f9a0c4a9e4888ebc91009e | /leetcode/easy/Meeting_Rooms.py | 60d9dca6bd97258777757122427eded3660a51ea | [] | no_license | SuperMartinYang/learning_algorithm | 0c5807be26ef0b7a1fe4e09832f3ce640cd3172b | e16702d2b3ec4e5054baad56f4320bc3b31676ad | refs/heads/master | 2021-06-27T14:00:18.920903 | 2019-05-05T23:25:29 | 2019-05-05T23:25:29 | 109,798,522 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 345 | py | class Solution(object):
def meeting_rooms(self, intervals):
"""
[meet_time_slots]
check whether there's overlap
:return: bool
"""
intervals.sort()
for i in range(1, len(intervals)):
if intervals[i][0] < intervals[i - 1][1]:
return False
return True
| [
"shy58@pitt.edu"
] | shy58@pitt.edu |
15423585575c7bb6219fccd4320efdec14e1f0e7 | 7f446cbc9cfeff35ddca053e924612b6b8febb0d | /.pycharm_helpers/python_stubs/-533200126/_yaml/StreamStartToken.py | 4bc2caec2c311b7bc945641da91ce39d8ad82819 | [] | no_license | theskyareblue/testdemo | 2832f9d643a0b2905b8fb38f78f02f60959f34a2 | 833afe4ea8dd92ebaed5fd40f1ad6ce4a1206604 | refs/heads/master | 2023-04-09T07:40:27.638892 | 2019-06-21T03:34:32 | 2019-06-21T03:34:32 | 192,511,828 | 1 | 0 | null | 2023-03-16T16:19:55 | 2019-06-18T09:46:52 | Python | UTF-8 | Python | false | false | 579 | py | # encoding: utf-8
# module _yaml
# from /usr/lib64/python2.7/site-packages/_yaml.so
# by generator 1.145
# no doc
# imports
import yaml as yaml # /usr/lib64/python2.7/site-packages/yaml/__init__.pyc
import __builtin__ as __builtins__ # <module '__builtin__' (built-in)>
import yaml.error as __yaml_error
import yaml.events as __yaml_events
import yaml.nodes as __yaml_nodes
import yaml.tokens as __yaml_tokens
class StreamStartToken(__yaml_tokens.Token):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
id = '<stream start>'
| [
"234315653@qq.com"
] | 234315653@qq.com |
7ab4e4ef4b55c54e28b904270dc8b9b90f39a137 | c37923008aab6d948bae9aeec77c763ddb222132 | /baekjoon/07_문자열/10_1316_그룹 단어 체커.py.py | d1d01b4210d16d13dbb9134194aedd1ea64ef590 | [] | no_license | JunyongPark2/daily_algorithm | feb7c0034ae00e56a92f81154de0fdc115cbd08c | f0c32bfc675f982ef5e4c81089b8c26cdcf2bea7 | refs/heads/master | 2023-04-15T07:46:58.019073 | 2021-04-29T14:15:34 | 2021-04-29T14:15:34 | 333,362,903 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 219 | py | N = int(input())
answer = 0
for i in range(N):
T = input()
temp = [T[0]]
for j in T:
if j != temp[-1]:
temp.append(j)
if len(set(temp)) == len(temp):
answer +=1
print(answer)
| [
"shewco3@gmail.com"
] | shewco3@gmail.com |
a9ec8ea5988e444dca3d757f8b9c21b088dfca19 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/CodeJamData/08/32/19.py | d403270b5ab392e016ae79fa730b5788d241862d | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Python | false | false | 1,582 | py | def is_ugly(n):
return n % 2 == 0 or n % 3 == 0 or n % 5 == 0 or n % 7 == 0
def add_expr(expr_dict, expr, n_e):
n = expr_dict.get(expr, 0)
expr_dict[expr] = n + n_e
def solve(digits):
# expressions = set([(None, digits[0])])
expressions = {}
expressions[(None, digits[0])] = 1
if len(digits) > 1:
for d in digits[1:]:
# new_expressions = set()
new_expressions = {}
for e, n_e in expressions.items():
# new_expressions.add(e[0], e[1] + d))
add_expr(new_expressions, (e[0], e[1] + d), n_e)
i = int(e[1])
if e[0] != None:
# new_expressions.add((e[0] + i, d))
add_expr(new_expressions, (e[0] + i, d), n_e)
# new_expressions.add((e[0] - i, d))
add_expr(new_expressions, (e[0] - i, d), n_e)
else:
# new_expressions.add((i, d))
add_expr(new_expressions, (i, d), n_e)
expressions = new_expressions
n_ugly = 0
for e, n_e in expressions.items():
i = int(e[1])
if e[0] != None:
if is_ugly(e[0] + i):
n_ugly += n_e
if is_ugly(e[0] - i):
n_ugly += n_e
else:
if is_ugly(i):
assert(n_e == 1)
n_ugly += n_e
return n_ugly
if __name__ == '__main__':
N = input()
for i in xrange(N):
digits = raw_input()
print 'Case #%d: %d' % (i + 1, solve(digits))
| [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
17fbdf1ad440e7e84077b0f663f3ed57526ed194 | 583fdb9f37dea28ada24e335f1e44ba6cf587770 | /动态规划/313 超级丑数.py | 1705630173f43c4c166bb4f5538c3e88b35868d8 | [] | no_license | Ford-z/LeetCode | 8c4c30eeaa3d8f02b24c8d0058c60f09c3a6debe | 88eeca3780b4dc77efce4f14d317ed1c872cf650 | refs/heads/master | 2021-11-21T00:51:05.314084 | 2021-09-16T15:45:18 | 2021-09-16T15:45:18 | 194,425,542 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 714 | py | #编写一段程序来查找第 n 个超级丑数。
#超级丑数是指其所有质因数都是长度为 k 的质数列表 primes 中的正整数。
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
dp=[0 for _ in range(n)]
dp[0]=1
j=1
Dict={}
for i in range(len(primes)):
Dict[primes[i]]=0
while j<n:
a=[]
for i in range(len(primes)):
a.append(dp[Dict[primes[i]]]*primes[i])
dp[j]=min(a)
for i in range(len(primes)):
if (dp[j]/dp[Dict[primes[i]]]==primes[i]):
Dict[primes[i]]+=1
j+=1
return dp[-1]
| [
"noreply@github.com"
] | Ford-z.noreply@github.com |
3d61c35293016f2d82a7f3191eafacbf9a4c49c8 | 47128c6ff1277eedf851670d33f7a288fdfe2246 | /variable/check_global_with_variable.py | 29942a346b779e5c2e19d8c8ae23330d4eb1c0bd | [] | no_license | chati757/python-learning-space | 5de7f11a931cf95bc076473da543331b773c07fb | bc33749254d12a47523007fa9a32668b8dc12a24 | refs/heads/master | 2023-08-13T19:19:52.271788 | 2023-07-26T14:09:58 | 2023-07-26T14:09:58 | 83,208,590 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,213 | py | import pandas as pd
def check_global(var):
result=None
try:
if(isinstance(var,pd.DataFrame)==True):
result = [key for key,val in globals().items() if(id(val)==id(var))][0]
else:
result = [key for key,val in globals().items() if(val==var)][0]
except IndexError:
pass
return result!=None
if __name__=="__main__":
print('checking global variable')
global global_x
global_x = 2
'''
ไม่สามารถตรวจว่าเป็น global variable หรือไม่จาก value ไม่ได้
'''
print(check_global(global_x))#global_x
global_x2 = 2
print(check_global(global_x2))#global_x
'''
สามารถตรวจว่าเป็น global variable หรือไม่จาก value ได้
'''
print('checking global_df')
global global_df
global_df = pd.DataFrame({'a':[2,3,4]})
print(check_global(global_df))#global_df
print('checking global_dict')
global global_dict
global_dict = {'testkey':'testval'}
print(check_global(global_dict))
print('checking global_list')
global global_list
global_list = ['test'] | [
"chati757@users.noreply.github.com"
] | chati757@users.noreply.github.com |
e10bf6b1d1b9bbd1d0daf309ecc48fc0e14e621d | 01645d084b5b8ee807e71892db3c49ae14ef70e4 | /SOL_start_end_OP.py | 1d5e32b6a8ac473fb22ae3bd2406c6bf530707e8 | [] | no_license | kardelen-karatas/rinf_to_geojson | 7cd0e334cf7efae85015076ac45f361c63c1f1fb | e1cdb956e7d046ce6c26825e93f2217e578af75f | refs/heads/master | 2021-08-07T19:11:27.324024 | 2017-11-08T19:57:09 | 2017-11-08T19:57:09 | 110,024,036 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,567 | py | from collections import namedtuple
import xml.etree.ElementTree as ET
import json
import geojson
from geojson import LineString, GeometryCollection
tree = ET.parse('RINFsol_lux_mal_nor.xml')
section_of_lines = tree.findall('.//SectionOfLine')
operational_points = tree.findall('.//OperationalPoint')
SectionOfLine = namedtuple('SectionOfLine', ['start', 'end'])
section_of_lines_aggr = {}
line_strings = []
for section in section_of_lines:
sol = SectionOfLine(
start={'id': section.find('SOLOPStart').get('Value')},
end={'id': section.find('SOLOPEnd').get('Value')}
)
start_op_point = tree.find('.//OperationalPoint/UniqueOPID[@Value="%s"]/...' % sol.start['id'])
end_op_point = tree.find('.//OperationalPoint/UniqueOPID[@Value="%s"]/...' % sol.end['id'])
if start_op_point == None or end_op_point == None:
print('no start or end op point for section of line: %s' % sol)
continue
start_op_point_coords = start_op_point.find('OPGeographicLocation')
end_op_point_coords = start_op_point.find('OPGeographicLocation')
sol.start['coords'] = (float(start_op_point_coords.get('Longitude').replace(',', '.')), float(start_op_point_coords.get('Latitude').replace(',', '.')))
sol.end['coords'] = (float(end_op_point_coords.get('Longitude').replace(',', '.')), float(end_op_point_coords.get('Latitude').replace(',', '.')))
line_strings.append(LineString([sol.start['coords'], sol.end['coords']]))
geometry_collection = GeometryCollection(line_strings)
print(geojson.dumps(geometry_collection))
| [
"kardelen.karatas@gmail.com"
] | kardelen.karatas@gmail.com |
2a06f6d42ef7654a6491eeee42242d003283ae42 | c41a14d4c709e9102bf31bbe2fe0f9a9d83dec8e | /main/filemapper/datastructure/FileFlags.py | 19a4e1223f5abf75efb51f0b6c4948d92c614105 | [] | no_license | AsiganTheSunk/galung-project | bbeba2eb950a545f521b9e2f58f2fbf6860d24f7 | 0b561fe17f4df733be7b9352e6d05db2fdde12ba | refs/heads/master | 2021-05-02T13:45:44.263497 | 2017-07-28T18:04:19 | 2017-07-28T18:04:19 | 72,658,706 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 545 | py | from enum import Enum
class FileFlags(Enum):
LIBRARY_FLAG = '0'
MAIN_SHOW_DIRECTORY_FLAG = '1'
SEASON_DIRECTORY_FLAG = '2'
SUBTITLE_DIRECTORY_SHOW_FLAG = '3'
SUBTITLE_SHOW_FLAG = '4'
SHOW_DIRECTORY_FLAG = '5'
SHOW_FLAG = '6'
SUBTITLE_DIRECTORY_FILM_FLAG = '7'
SUBTITLE_FILM_FLAG = '8'
FILM_DIRECTORY_FLAG = '9'
FILM_FLAG = '10'
SUBTITLE_DIRECTORY_ANIME_FLAG = '11'
SUBTITLE_ANIME_FLAG = '12'
ANIME_DIRECTORY_FLAG = '13'
ANIME_FLAG = '14'
IGNORE_FLAG = '15'
UNKOWN_FLAG = '30'
| [
"asiganthesunk@gmail.com"
] | asiganthesunk@gmail.com |
0dbd85686d5cb38abb763cb3d66038c28a99d88d | afbae26b958b5ef20548402a65002dcc8e55b66a | /release/stubs.min/Autodesk/Revit/DB/Structure/__init___parts/RebarConstraintTargetHostFaceType.py | 4676b8b854f9cb664310c709a52c23ccd30acfdb | [
"MIT"
] | permissive | gtalarico/ironpython-stubs | d875cb8932c7644f807dc6fde9dd513d159e4f5c | c7f6a6cb197e3949e40a4880a0b2a44e72d0a940 | refs/heads/master | 2023-07-12T01:43:47.295560 | 2022-05-23T18:12:06 | 2022-05-23T18:12:06 | 95,340,553 | 235 | 88 | NOASSERTION | 2023-07-05T06:36:28 | 2017-06-25T05:30:46 | Python | UTF-8 | Python | false | false | 1,166 | py | class RebarConstraintTargetHostFaceType(Enum,IComparable,IFormattable,IConvertible):
"""
A type to help identify the individual face on a host element to which a Rebar handle
is constrained.
enum RebarConstraintTargetHostFaceType,values: Bottom (2),End0 (3),End1 (4),FaceWithTagId (0),Side0 (5),Side1 (6),Top (1)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Bottom=None
End0=None
End1=None
FaceWithTagId=None
Side0=None
Side1=None
Top=None
value__=None
| [
"gtalarico@gmail.com"
] | gtalarico@gmail.com |
a5812e9a7e0183548687e3bdf57a315f6ad84171 | d6e97eb0746f2878b046446be3b040e698dfb6cc | /bigml/centroid.py | 5c29eba9023d3ef17130a1c0775e756894c06d9a | [
"Apache-2.0"
] | permissive | msabramo/python | 301fd7f3e2331691c656c26a020729fab783991d | cd5418c2424ea154b4f2e590aba43707a3fb934d | refs/heads/next | 2023-06-09T15:59:37.078547 | 2015-01-16T01:56:10 | 2015-01-16T01:56:10 | 29,335,448 | 0 | 0 | null | 2015-01-16T06:13:33 | 2015-01-16T06:13:33 | null | UTF-8 | Python | false | false | 3,309 | py | # -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2014 BigML
#
# 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.
"""Centroid structure for the BigML local Cluster
This module defines an auxiliary Centroid predicate structure that is used
in the cluster.
"""
import math
import sys
STATISTIC_MEASURES = [
'Minimum', 'Mean', 'Median', 'Maximum', 'Standard deviation']
def cosine_distance2(terms, centroid_terms, scale):
"""Returns the distance defined by cosine similarity
"""
# Centroid values for the field can be an empty list.
# Then the distance for an empty input is 1
# (before applying the scale factor).
if not terms and not centroid_terms:
return 0
if not terms or not centroid_terms:
return scale ** 2
input_count = 0
for term in centroid_terms:
if term in terms:
input_count += 1
cosine_similarity = input_count / math.sqrt(
len(terms) * len(centroid_terms))
similarity_distance = scale * (1 - cosine_similarity)
return similarity_distance ** 2
class Centroid(object):
"""A Centroid.
"""
def __init__(self, centroid_info):
self.center = centroid_info.get('center', {})
self.count = centroid_info.get('count', 0)
self.centroid_id = centroid_info.get('id', None)
self.name = centroid_info.get('name', None)
self.distance = centroid_info.get('distance', {})
def distance2(self, input_data, term_sets, scales, stop_distance2=None):
"""Squared Distance from the given input data to the centroid
"""
distance2 = 0.0
for field_id, value in self.center.items():
if isinstance(value, list):
# text field
terms = ([] if not field_id in term_sets else
term_sets[field_id])
distance2 += cosine_distance2(terms, value, scales[field_id])
elif isinstance(value, basestring):
if not field_id in input_data or input_data[field_id] != value:
distance2 += 1 * scales[field_id] ** 2
else:
distance2 += ((input_data[field_id] - value) *
scales[field_id]) ** 2
if stop_distance2 is not None and distance2 >= stop_distance2:
return None
return distance2
def print_statistics(self, out=sys.stdout):
"""Print the statistics for the training data clustered around the
centroid
"""
out.write(u"%s:\n" % self.name)
literal = u" %s: %s\n"
for measure_title in STATISTIC_MEASURES:
measure = measure_title.lower().replace(" ", "_")
out.write(literal % (measure_title, self.distance[measure]))
out.write("\n")
| [
"merce@bigml.com"
] | merce@bigml.com |
a8b5e581ff619f5b175c22c5887d590551cf6cd6 | 67f9452cc0511c3d5ed501b65c31d6e8a5e7576b | /seetpro14thau.py | 0f10032631962372f9fb6bde66c5b1a3260e4a2a | [] | no_license | thasleem-banu/python | 621bdc73722bcaa336bcbd95cd27d9aabfe7dd97 | 1003c3f32776d4ccf3ab1a1d98256c1158ca5670 | refs/heads/master | 2020-06-07T17:02:11.887671 | 2019-07-28T15:16:26 | 2019-07-28T15:16:26 | 193,060,927 | 2 | 3 | null | null | null | null | UTF-8 | Python | false | false | 246 | py | vs12,vit112=map(str,input().split())
was12=0
if len(vs12)>len(vit112):
vs12,vit112=vit112,dbj12
i=0
while i<len(vs12):
was12+=(ord(vit112[i])-ord(vs12[i]))
i+=1
for i in range(i,len(vit112)):
was12+=ord(vit112[i])-ord('a')+1
print(was12)
| [
"noreply@github.com"
] | thasleem-banu.noreply@github.com |
d814e5653725c10c49639622d7055ae9fda237e8 | 8a15c7b8a0586ad736de1d89ff4dc9e0a03b8db5 | /aws_batch/s3_utilities.py | 9b064099a1daf548b501fcd9405a3c208328b8a5 | [
"MIT"
] | permissive | elangovana/PPI-typed-relation-extractor | faa1a584c46bc71b7287012eb7a9fb2a5f8a68cd | 08e9a28199bb4454e2e1a09c5d833f243f6f5768 | refs/heads/master | 2022-12-01T10:50:28.052986 | 2021-05-31T21:35:25 | 2021-05-31T21:35:25 | 133,225,295 | 12 | 3 | MIT | 2022-11-28T18:52:53 | 2018-05-13T10:05:22 | Jupyter Notebook | UTF-8 | Python | false | false | 728 | py | import boto3
def get_bucketname_key(uripath):
assert uripath.startswith("s3://")
path_without_scheme = uripath[5:]
bucket_end_index = path_without_scheme.find("/")
bucket_name = path_without_scheme
key = "/"
if bucket_end_index > -1:
bucket_name = path_without_scheme[0:bucket_end_index]
key = path_without_scheme[bucket_end_index + 1:]
return bucket_name, key
def list_files(s3path_prefix):
assert s3path_prefix.startswith("s3://")
assert s3path_prefix.endswith("/")
bucket, key = get_bucketname_key(s3path_prefix)
s3 = boto3.resource('s3')
bucket = s3.Bucket(name=bucket)
return ((o.bucket_name, o.key) for o in bucket.objects.filter(Prefix=key))
| [
"aeg@amazon.com"
] | aeg@amazon.com |
5250e027100f74327932c57c3d5a701fd9b58639 | 3411ad233c411c06765f4b07f8670c12025178b6 | /201-300/201-210/206-reverseLinkedList/reverseLinkedList.py | 0c63d29f84b9386f3dde6b05728c773064896082 | [
"MIT"
] | permissive | xuychen/Leetcode | 7d9d31fed898ce58440f5ae6665d2ccaf1a4b256 | c8bf33af30569177c5276ffcd72a8d93ba4c402a | refs/heads/master | 2021-11-19T20:39:43.741589 | 2021-10-24T16:26:52 | 2021-10-24T16:26:52 | 140,212,398 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 429 | py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head, prev=None):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return prev
root = self.reverseList(head.next, head)
head.next = prev
return root | [
"xuychen@ucdavis.edu"
] | xuychen@ucdavis.edu |
e97ad2138ce5ac82edd0ef9354f26beb26a0f46d | d7663e323e2b48ad094e0ab7454ab0bed73aafd1 | /pychzrm course/journey_one/project_month01/2048/game_2048/main.py | eef4cfa05fbf55c14965a1fa967abe9f8fd08c33 | [] | no_license | Jack-HFK/hfklswn | f9b775567d5cdbea099ec81e135a86915ab13a90 | f125671a6c07e35f67b49013c492d76c31e3219f | refs/heads/master | 2021-06-19T05:58:54.699104 | 2019-08-09T10:12:22 | 2019-08-09T10:12:22 | 201,442,926 | 7 | 0 | null | 2021-04-20T18:26:03 | 2019-08-09T10:07:20 | HTML | UTF-8 | Python | false | false | 150 | py | """
游戏入口
"""
from ui import GameConsoleView
if __name__ == "__main__":
view = GameConsoleView()
view.start()
view.update()
| [
"88888888@qq.com"
] | 88888888@qq.com |
38e22ee27b056c715786b3e493e69cf40f501d48 | 3aa31edaed8ea4326984cabd48204bb69cb9acc2 | /backend/yuvicraft_app_25910/urls.py | e9fb7f674801b4c37c1d9798e3646fa03267c9f0 | [] | no_license | crowdbotics-apps/yuvicraft-app-25910 | 1f2c97f1b38400d6007f1b99592cffb9ea6335a7 | 637991691aaddd2d73dbac2f9486c96d63a341d8 | refs/heads/master | 2023-04-01T17:16:16.041312 | 2021-04-24T14:02:05 | 2021-04-24T14:02:05 | 361,176,682 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,241 | py | """yuvicraft_app_25910 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic.base import TemplateView
from allauth.account.views import confirm_email
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
urlpatterns = [
path("", include("home.urls")),
path("accounts/", include("allauth.urls")),
path("modules/", include("modules.urls")),
path("api/v1/", include("home.api.v1.urls")),
path("admin/", admin.site.urls),
path("users/", include("users.urls", namespace="users")),
path("rest-auth/", include("rest_auth.urls")),
# Override email confirm to use allauth's HTML view instead of rest_auth's API view
path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email),
path("rest-auth/registration/", include("rest_auth.registration.urls")),
]
admin.site.site_header = "Yuvicraft app"
admin.site.site_title = "Yuvicraft app Admin Portal"
admin.site.index_title = "Yuvicraft app Admin"
# swagger
api_info = openapi.Info(
title="Yuvicraft app API",
default_version="v1",
description="API documentation for Yuvicraft app App",
)
schema_view = get_schema_view(
api_info,
public=True,
permission_classes=(permissions.IsAuthenticated,),
)
urlpatterns += [
path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs")
]
urlpatterns += [path("", TemplateView.as_view(template_name='index.html'))]
urlpatterns += [re_path(r"^(?:.*)/?$",
TemplateView.as_view(template_name='index.html'))]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.