repo_name
stringlengths
7
111
__id__
int64
16.6k
19,705B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
151
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_url
stringlengths
26
130
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
14.6k
687M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
12 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
10.2M
gha_stargazers_count
int32
0
178k
gha_forks_count
int32
0
88.9k
gha_open_issues_count
int32
0
2.72k
gha_language
stringlengths
1
16
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
10
2.95M
src_encoding
stringclasses
5 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
10
2.95M
extension
stringclasses
19 values
num_repo_files
int64
1
202k
filename
stringlengths
4
112
num_lang_files
int64
1
202k
alphanum_fraction
float64
0.26
0.89
alpha_fraction
float64
0.2
0.89
hex_fraction
float64
0
0.09
num_lines
int32
1
93.6k
avg_line_length
float64
4.57
103
max_line_length
int64
7
931
realyuyangyang/Python3Michigan
13,623,636,290,131
1c82ed6fb1b4dba47f89c4b66a7cbccb592bcdce
8aac5a3085d4a7fb1c61bb5ef80984e5bdd2bbef
/CheckMyUnderstanding/ListWithComplexItems17_1_1/ac17_1_5.py
ba4a8c5fd0c58c34389a57006db25e7f34fe5e14
[]
no_license
https://github.com/realyuyangyang/Python3Michigan
a932d3d237526f84fdbcdcc7b92412086f9c807f
088244e7cc0e5d0270ab98fb7b5b10197d9f2d98
refs/heads/master
2023-08-29T22:47:10.947155
2021-11-12T13:22:08
2021-11-12T13:22:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Below, we have provided a list of lists. Use indexing to assign the element ‘horse’ to the variable name idx1 animals = [['cat', 'dog', 'mouse'], [ 'horse', 'cow', 'goat'], ['cheetah', 'giraffe', 'rhino']] idx1 = animals[1][0] print(idx1)
UTF-8
Python
false
false
253
py
70
ac17_1_5.py
69
0.630522
0.610442
0
9
26.666667
111
chenwil/API_stuff
13,563,506,742,919
2430842095dc8242fc5350bf83ee09419885fe8e
c35975087b0f5be43f7924e7d219f336df209b9a
/API_lecture.py
2ba8e5942fedf8ee228792c27614e158d359fbd3
[]
no_license
https://github.com/chenwil/API_stuff
849e79b53bd2cf741491818e9df057129e5abe64
b774bac6dc6528680402fef13c0f221c3abc7bdb
refs/heads/master
2021-05-04T20:52:09.940727
2018-02-01T14:57:58
2018-02-01T14:57:58
119,848,678
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests import secrets def get_stories(section): baseurl = "https://api.nytimes.com/svc/topstories/v2/" extended_url = baseurl + section + '.json' params = {'api-key' : secrets.nyt_key} return requests.get(extended_url, params).json() section = 'science' stories = get_stories(section) print(stories)
UTF-8
Python
false
false
329
py
1
API_lecture.py
1
0.696049
0.693009
0
14
22.5
58
spacearound404/Dudoser
9,680,856,295,210
2b9a3ee08867ced1227ec1533be87ad7f69cd0c3
ff7315a75d73eb5390f793a8a1d1c4f6f22f352e
/src/print_color.py
d3cf1ae5d5831e92fb6e10d514135394d3acccb5
[]
no_license
https://github.com/spacearound404/Dudoser
f3b0a39617aadd327b1015d32072f6195d770de7
b9010568ee94f502210e1b9441cfd140201f863a
refs/heads/master
2023-03-10T17:30:01.230455
2020-08-24T06:29:46
2020-08-24T06:29:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import ctypes import random import string import colorama from colorama import Fore, Back, Style kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) colorama.init() rand = 0 color = "" def buildblock(size): return ''.join(random.choice(string.ascii_letters) for _ in range(size)) for i in range(0,200): for k in range(0,500): rand = random.random() rand *= 10 rand = round(rand) if rand == 1: print(Fore.RED + buildblock(1), sep='', end='') if rand == 2: print(Fore.GREEN + buildblock(1), sep='', end='') if rand == 3: print(Fore.YELLOW + buildblock(1), sep='', end='') if rand == 4: print(Fore.BLUE + buildblock(1), sep='', end='') if rand == 5: print(Fore.MAGENTA + buildblock(1), sep='', end='') if rand == 6: print(Fore.CYAN + buildblock(1), sep='', end='') if rand >= 7: print(Fore.WHITE + buildblock(1), sep='', end='')
UTF-8
Python
false
false
1,039
py
14
print_color.py
6
0.555342
0.520693
0
35
28.685714
76
duvernea/Computer_Networks
10,333,691,336,672
60b89ba62e1ab322ddcf0d076cb985a8bb09d171
28ba38203472d0c533892dba6dfc8d28df49415c
/Project2/test_them_all.py
94bac191af23b389bbd0685c03c64df10e9624ef
[]
no_license
https://github.com/duvernea/Computer_Networks
982db25a33e914f364fdee379ace9aef0fd85dfd
7e947663f3f4f85735c6e55c8d65e11327335f44
refs/heads/master
2021-03-27T08:44:59.020177
2017-12-03T03:55:21
2017-12-03T03:55:21
111,327,134
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os for f in os.listdir("."): if f.endswith(".txt") and f != "out.txt": fn = f.split(".txt")[0] print "========= Running test: {} =========".format(fn) os.system("python run_spanning_tree.py {} out.txt".format(fn)) print "diff: ", os.system("diff -ur out.txt {}.txt".format(fn)) print '================== done ======================'
UTF-8
Python
false
false
385
py
313
test_them_all.py
31
0.45974
0.457143
0
9
41.777778
71
BCHoagland/Decipher
14,680,198,266,107
45ed482010f197e32aa2231ae8b13e1dd3f4b10e
04f1398e928c0aaecbaa6e15455d2abbce1eed71
/PPO/main.py
2dbbfcb72af5d94066f5f39da195562c2bf7c55d
[]
no_license
https://github.com/BCHoagland/Decipher
fbd3da8172b6fcd520e612318877556c3d9a0bc9
8f9cd0a54e1c38a6a03582274920cbb2db4cb562
refs/heads/master
2018-10-14T02:53:30.533585
2018-08-16T21:06:29
2018-08-16T21:06:29
139,516,804
0
0
null
false
2018-08-13T20:59:52
2018-07-03T02:14:57
2018-07-31T14:15:10
2018-08-13T20:59:52
7,212
0
0
0
Python
false
null
import os import gym from gym.spaces.box import Box from visdom import Visdom import numpy as np from copy import deepcopy import torch import torch.nn as nn import torch.optim as optim from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv from baselines.common.atari_wrappers import make_atari, wrap_deepmind from model import * from storage import RolloutStorage from visualize import update_viz gamma = 0.99 tau = 0.95 eps = 1e-5 num_mb = 4 num_stack = 4 N = 8 T = 128 total_steps = 1e7 iters = int(total_steps) // N // T epochs = 4 lr = 2.5e-4 value_loss_coef = 1 entropy_coef = 0.01 max_grad_norm = 0.5 clip = 0.1 viz = Visdom() xs, medians, first_quartiles, third_quartiles, mins, maxes = [], [], [], [], [], [] graph_colors = ['rgba(249, 166, 2, 0.2)', 'rgba(249, 166, 2, 0.4)', 'rgb(249, 166, 2)'] win_name = 'pong attempt 2' episode_rewards = torch.zeros([N, 1]) final_rewards = torch.zeros([N, 1]) class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) obs_shape = self.observation_space.shape self.observation_space = Box( self.observation_space.low[0, 0, 0], self.observation_space.high[0, 0, 0], [obs_shape[2], obs_shape[1], obs_shape[0]], dtype=self.observation_space.dtype) def observation(self, observation): return observation.transpose(2, 0, 1) def make_env(name, seed, rank): def _env(): # env = gym.make(name) env = make_atari(name) env.seed(seed + rank) env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _env env_name = "PongNoFrameskip-v4" envs = [make_env(env_name, 42, n) for n in range(N)] envs = SubprocVecEnv(envs) obs_shape = envs.observation_space.shape policy = CNN(obs_shape[0] * num_stack, envs.action_space.n) rollouts = RolloutStorage() optimizer = optim.Adam(policy.parameters(), lr=lr, eps=eps) stacked_s = torch.zeros(N, num_stack * obs_shape[0], *obs_shape[1:]) def update_stacked_s(obs): obs = torch.from_numpy(obs).float() dim_shape = obs_shape[0] stacked_s[:, :-dim_shape] = stacked_s[:, dim_shape:] stacked_s[:, -dim_shape:] = obs s = envs.reset() update_stacked_s(s) filename = "saved_params/pongMain_params.pkl" if os.path.isfile(filename): policy.load_state_dict(torch.load(filename)) for iter in range(iters): for step in range(T): with torch.no_grad(): a, log_p, v = policy(stacked_s) a_np = a.squeeze(1).cpu().numpy() s2, r, done, _ = envs.step(a_np) r = torch.from_numpy(r).view(-1, 1).float() episode_rewards += r mask = torch.FloatTensor([[0.0] if d else [1.0] for d in done]) if num_stack > 1: # stacked_s *= mask stacked_s *= mask.unsqueeze(2).unsqueeze(2) final_rewards *= mask final_rewards += (1 - mask) * episode_rewards episode_rewards *= mask rollouts.add(deepcopy(stacked_s), log_p, v, a, r, mask) s = s2 update_stacked_s(s) with torch.no_grad(): next_v = policy.get_value(stacked_s) rollouts.compute_adv_and_returns(next_v, gamma, tau, eps) for epoch in range(epochs): data = rollouts.get_mb(num_mb, N, T) for sample in data: s_mb, log_p_old_mb, a_mb, returns_mb, adv_mb = sample log_p_mb, v_mb, entropy = policy.eval(s_mb, a_mb) ratio = torch.exp(log_p_mb - log_p_old_mb) f1 = ratio * adv_mb f2 = torch.clamp(ratio, 1 - clip, 1 + clip) * adv_mb policy_loss = -torch.min(f1, f2).mean() value_loss = torch.pow(returns_mb - v_mb, 2).mean() loss = policy_loss + (value_loss * value_loss_coef) - (entropy * entropy_coef) optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(policy.parameters(), max_grad_norm) optimizer.step() rollouts.reset() total_num_steps = (iter + 1) * N * T xs.append(total_num_steps) graph_rewards = final_rewards.view(1, -1) mean_r = graph_rewards.mean().item() median_r = graph_rewards.median().item() min_r = torch.min(graph_rewards).item() max_r = torch.max(graph_rewards).item() medians.append(median_r) first_quartiles.append(np.percentile(graph_rewards.numpy(), 25)) third_quartiles.append(np.percentile(graph_rewards.numpy(), 75)) mins.append(min_r) maxes.append(max_r) update_viz(xs, medians, first_quartiles, third_quartiles, mins, maxes, graph_colors, env_name, win_name) print("iter", iter, "-> mean:", mean_r, "/ median:", median_r, "/ min:", min_r, "/ max:", max_r) if iter % 200 == 199: torch.save(policy.state_dict(), filename)
UTF-8
Python
false
false
4,816
py
37
main.py
33
0.611711
0.589286
0
161
28.913043
108
Xyntax/checkio
12,111,807,814,292
4a34150b97d1fdc07a5276342d5978c37c474b92
913b1b3aad5ccabd1e38418414010552c00a056b
/Home/Golden_Pyramid.py
d82ce11ec05d21e2948c8a9deb9909bb4674d228
[]
no_license
https://github.com/Xyntax/checkio
67b266597acc37e221ffca6a573e90d1e79a78b3
ca90bc70589d50f393eac131d76442f495a7f755
refs/heads/master
2016-09-11T03:03:49.089944
2015-06-25T03:13:27
2015-06-25T03:13:27
37,975,677
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
''' edit by xy ''' # -*- coding: utf-8 -*- # #blog ans1 # def golden_pyramid_d(triangle): # tr = [row[:] for row in triangle] # copy # for i in range(len(tr) - 2, -1, -1): # for j in range(i + 1): # tr[i][j] += max(tr[i + 1][j], tr[i + 1][j + 1]) # return tr[0][0] def count_gold(pyramid): """ Return max possible sum in a path from top to bottom """ tr = [list(x) for x in pyramid] i = len(tr) - 2 while i >= 0: for j in range(i + 1): tr[i][j] += max(tr[i + 1][j], tr[i + 1][j + 1]) i -= 1 return tr[0][0] # print count_gold(( # (1,), # (2, 1), # (1, 2, 1), # (1, 2, 1, 1), # (1, 2, 1, 1, 1), # (1, 2, 1, 1, 1, 1), # (1, 2, 1, 1, 1, 1, 9) # )) '''c1 =============== Golden Pyramid =============== Approach -------- This algorithm is a greedy approach to solving the problem. Instead of working forward through the pyramid, we will work backwards. The idea is to start in the second to bottom row and select maxium of the the next two possible values from the current node and add that value to the current node. After that we continue to roll up the rows and repeat the process for each node in that row. When we reach the starting node we will have the sum of the maximum path. *Note*: we are not finding the best path; we are only finding the maxium sum from that path. ​ Code ---- I want a mutable copy of the pyramid to work with. Get the number of rows from the **len** function. The last row is not in play to start hence **rows-1** Also we're working backwards so use the **reversed** function. Need to itertate over each item in the row. Note the plus 1, range(0) returns an empty list. The possible nodes to examine are 1) the on directly below i+1,j and the one below and to the right i+1, j+1. We use the **max** function to select the largest one and then add it to the current node. ''' ''' py = [list(i) for i in pyramid] for i in reversed(range(len(py)-1)): for j in range(i+1): py[i][j] +=(max(py[i+1][j], py[i+1][j+1])) ​ return py[0][0] '''
UTF-8
Python
false
false
2,312
py
19
Golden_Pyramid.py
19
0.541161
0.513865
0
123
17.772358
80
cschwede/keystone-customauth-sample
2,937,757,672,517
ca93f1bb5d51d7bde9aa8e8e1ac2b027ca36760b
c87bd45215f45e73e4ef7d4d5e991e544ce85d55
/tests/test_customauth.py
d05bc3cc960464c40118431a32f1e3e610d597b6
[ "Apache-2.0" ]
permissive
https://github.com/cschwede/keystone-customauth-sample
8e4670a0df7ff2e2fd4dbc308adcf5d9d10124e4
da68c2cce89c5763229d055c46075d2650555043
refs/heads/master
2021-01-19T07:13:11.589890
2014-12-31T13:24:33
2014-12-31T13:24:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 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. """Unit tests for customauth identity behavior.""" import time import unittest import mock from customauth.middleware import HappyHourIdentity class TestCustomAuth(unittest.TestCase): class DummyUser(object): def __init__(self): self.name = "Username" self.password = "secret" @mock.patch('time.localtime') @mock.patch('keystone.common.utils.check_password') def test_check_password(self, mock_checkpassword, mock_localtime): user_ref = self.DummyUser() cls = HappyHourIdentity() # Grant access when hour == 22 mock_localtime.return_value = time.strptime("22", "%H") self.assertTrue(cls._check_password('token', user_ref)) # Fallback to parent check_password otherwise mock_localtime.return_value = time.strptime("23", "%H") cls._check_password('token', user_ref) mock_checkpassword.assert_called_once_with('token', 'secret')
UTF-8
Python
false
false
1,499
py
5
test_customauth.py
3
0.698466
0.691795
0
41
35.560976
75
rafaelcardoso31101995/treinamento_git
13,030,930,795,065
4874bee67c5b9c6b735ff28dd09ea1c88e7493bc
2ce4c1a6a90cb07e406a143a11d453fcfd64b9a1
/aula07-desafio11.py
9638a71426597cb506908772e3b3e9042786dbd7
[]
no_license
https://github.com/rafaelcardoso31101995/treinamento_git
0892fdc4ee2de5baeac5bf05c32d113268928572
b191a0ec139527423de1af6aba129872dd13fe6b
refs/heads/master
2020-04-22T13:25:03.430478
2019-02-19T22:22:06
2019-02-19T22:22:06
170,408,592
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
width = float(input('Digite a largura: ')) height = float(input('Digite a altura: ')) area = width * height liters = area/2 print('A quantidade de tinta para pintar uma area de {} metros quadrados é {} litros'.format(area, liters))
UTF-8
Python
false
false
237
py
41
aula07-desafio11.py
39
0.694915
0.690678
0
7
32.428571
107
luke-limpert/Programming_Challenges
6,038,724,023,792
4790035bbdcfa33b9a1f414462ee7cdf228c4c51
f157610f9adb2b4fadc3ed3ab5cf0126f07e9793
/3Sum.py
a917178ff75048341ec07b6e84a4323a47d2f37a
[]
no_license
https://github.com/luke-limpert/Programming_Challenges
e48536403910414b98c1831838d758a7b8e47eb3
1357173da14bc57a1eb7e6e9c01b8e78c340858a
refs/heads/main
2023-02-04T19:28:40.935889
2020-12-18T21:28:58
2020-12-18T21:28:58
317,714,661
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? #Find all unique triplets in the array which gives the sum of zero. class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ #will allow us to skip duplicate solutions nums.sort() length, result = len(nums), [] for i in range(length): if i > 0 and nums[i] == nums[i-1]: continue #multiply by negative one #this allows for the sum of the other two numbers #to negate the value of the target target = nums[i] * -1 #indexer start, end = i + 1, length - 1 while start < end: #append list if the numbers negate to 0 if nums[start] + nums[end] == target: result.append([nums[i], nums[start], nums[end]]) start = start + 1 #skip similar elements to make sure we do not duplicate #this is why we .sort() in the beginning while start < end and nums[start] == nums[start - 1]: start = start + 1 #numbers did not negate - continue elif nums[start] + nums[end] < target: start = start + 1 else: end = end - 1 return result
UTF-8
Python
false
false
1,492
py
25
3Sum.py
24
0.491287
0.483244
0
41
35.414634
96
temp9999gi/projectautomation
4,501,125,755,864
92cdd030bf7f3299fb491ba8a93fc4054554baea
e6e5141787917abdb07308f832a36a467cc664f6
/source/codegen/codeGenCompFromDb/script/KlassInfoList.py
08c281b5a84a5468940159fdc3dfcf9eadc63e0f
[]
no_license
https://github.com/temp9999gi/projectautomation
a34ef13dc371c018bbb5808e0d8dec285e396dc9
4e1f3eed5fb481956d045019034d5fb4bd5828dd
refs/heads/master
2020-05-17T10:58:45.758691
2007-08-21T14:36:14
2007-08-21T14:36:14
33,873,113
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- '''애는 뭐하는 얘나? 음 뭐냐면 ''' # start class KlassInfoList: def __init__(self): self.klassList = [] def setKlassList(self, klassList): self.klassList = klassList def getKlassList(self): return self.klassList def setDaoXmlFileName(self, daoXmlFileName): self.daoXmlFileName = daoXmlFileName def setPackagePath(self, packagePath): self.packagePath = packagePath def getPackagePath(self): return self.packagePath
UTF-8
Python
false
false
493
py
246
KlassInfoList.py
150
0.695096
0.692964
0
19
22.684211
45
ArnabBasak/PythonRepository
12,017,318,512,400
bf5ba66fa3aad619f2ecbe78dd8ef896c76ec140
838d23e9590bc855926628d0f7b4ffe73e108565
/python programs/RegularExpress on corpus.py
29c1e6dae2c6f923bf2394dc9d4b17837ce40c5a
[]
no_license
https://github.com/ArnabBasak/PythonRepository
ca475b1bc728ede1e033c54f40392f5b4c3494d4
388478fd33c4ed654eb6b1cba5e0cbdcfb90cf0e
refs/heads/master
2021-07-15T17:05:47.435677
2020-07-17T09:09:56
2020-07-17T09:09:56
84,456,349
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re import os CorpusCheck = os.path.isfile('E:\python programs\progrms nltk\corpus.txt') if CorpusCheck == False: print('file does not exist sorry we cannot proceed') else: FileOpen = open('E:\python programs\progrms nltk\corpus.txt','r') FileRead = FileOpen.read() numbers = re.findall(r'\d{1,9}',FileRead) names = re.findall(r'[A-Z][a-z]*',FileRead) print(numbers) print(names) print('total number of names found in the corpus is',len(names))
UTF-8
Python
false
false
484
py
333
RegularExpress on corpus.py
205
0.683884
0.679752
0
14
33.571429
74
Fortyseven/ExercismWork
8,469,675,539,821
e27cf6075facefa086515efaf33a0b1991f10b26
a57e23980fefdf8b7a93b37d2cca5ed17739d166
/python/gigasecond/gigasecond.py
bdd11c831a250c4d8e30f785694890995b80d4f1
[]
no_license
https://github.com/Fortyseven/ExercismWork
9ff8baab87735957df5a5fffea2e7401853522b9
eb0b7680a8eee4029f2619c94353939143aa6e2a
refs/heads/master
2020-04-02T05:30:36.749103
2016-08-12T19:27:58
2016-08-12T19:27:58
60,718,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from datetime import datetime import sys import time def add_gigasecond(start_date): return start_date.timetuple() def main(): print add_gigasecond(datetime(2011, 4, 25)) if __name__ == '__main__': sys.exit(int(main() or 0))
UTF-8
Python
false
false
254
py
33
gigasecond.py
5
0.633858
0.602362
0
13
18.615385
48
shadansari/voltha-lite
6,786,048,359,969
f041622806fc3865fe37cd641cd5416776a6c29f
76eaa1a386d8d62c4e18c02c6705a9f3eb86bd6c
/voltha/adapters/tellabs_openomci_onu/tellabs_openomci_onu.py
0506606122976da2e7fb8b3180c5ccfc4b85c716
[ "Apache-2.0" ]
permissive
https://github.com/shadansari/voltha-lite
5abfd6959927c6d5d40a5379e4775fb95d095e4d
a4501bb7a2c1ae26a792799d8fb966f6230f708c
refs/heads/master
2020-05-19T15:07:21.018671
2019-05-05T20:04:21
2019-05-05T20:04:21
185,076,787
1
1
Apache-2.0
false
2019-10-21T18:46:22
2019-05-05T20:03:52
2019-05-05T20:06:46
2019-10-21T18:46:18
8,141
1
1
1
Python
false
false
# # Copyright 2017-present Tellabs, Inc. # # 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. # """ Tellabs OpenOMCI OLT/ONU adapter. """ from twisted.internet import reactor, task from zope.interface import implementer from voltha.adapters.brcm_openomci_onu.brcm_openomci_onu import BrcmOpenomciOnuAdapter from voltha.adapters.brcm_openomci_onu.brcm_openomci_onu_handler import BrcmOpenomciOnuHandler from voltha.adapters.interface import IAdapterInterface from voltha.protos import third_party from voltha.protos.adapter_pb2 import Adapter from voltha.protos.adapter_pb2 import AdapterConfig from voltha.protos.common_pb2 import LogLevel from voltha.protos.device_pb2 import DeviceType, DeviceTypes, Port, Image from voltha.protos.health_pb2 import HealthStatus from common.frameio.frameio import hexify from voltha.extensions.omci.openomci_agent import OpenOMCIAgent, OpenOmciAgentDefaults from voltha.extensions.omci.omci_me import * from voltha.extensions.omci.database.mib_db_dict import MibDbVolatileDict from voltha.adapters.brcm_openomci_onu.omci.brcm_capabilities_task import BrcmCapabilitiesTask from voltha.adapters.brcm_openomci_onu.omci.brcm_get_mds_task import BrcmGetMdsTask from voltha.adapters.brcm_openomci_onu.omci.brcm_mib_sync import BrcmMibSynchronizer from copy import deepcopy from omci.omci_entities import onu_custom_me_entities from voltha.extensions.omci.database.mib_db_ext import MibDbExternal _ = third_party log = structlog.get_logger() @implementer(IAdapterInterface) class TellabsOpenomciOnuAdapter(BrcmOpenomciOnuAdapter): name = 'tellabs_openomci_onu' supported_device_types = [ DeviceType( id=name, vendor_ids=['BFWS', 'TSLS', 'IPHO', 'SHGJ'], adapter=name, accepts_bulk_flow_update=True ) ] def __init__(self, adapter_agent, config): super(TellabsOpenomciOnuAdapter, self).__init__(adapter_agent, config) self.descriptor = Adapter( id=self.name, vendor='Tellabs Inc.', version='0.1', config=AdapterConfig(log_level=LogLevel.INFO) ) log.info('tellabs_openomci_onu.__init__', adapter=self.descriptor) self.broadcom_omci['mib-synchronizer']['state-machine'] = BrcmMibSynchronizer #self.broadcom_omci['mib-synchronizer']['database'] = MibDbVolatileDict self.broadcom_omci['mib-synchronizer']['database'] = MibDbExternal def device_types(self): return DeviceTypes(items=self.supported_device_types) def custom_me_entities(self): return onu_custom_me_entities()
UTF-8
Python
false
false
3,122
py
655
tellabs_openomci_onu.py
387
0.743113
0.738309
0
84
36.154762
94
cleemputc/python-algorithms
523,986,060,218
9a0831e73febaffc2ceadd3ddfdb0f7fdd024b3c
b73ef6e785b7f411548bc174a96539b55e146df2
/binarySearchAndInsert.py
81b881d3425e0c41f7b45721fdaa436289ca62d2
[]
no_license
https://github.com/cleemputc/python-algorithms
ead17f1465dd37764a333e2c0865fd218ada01d8
47043e5819faae718000fcf0514000afa04c95f8
refs/heads/master
2020-02-27T18:13:03.785988
2015-06-01T14:33:04
2015-06-01T14:33:04
35,211,001
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# binary search def bs_contains(ordered, target): low = 0 high = len(ordered)-1 while low <= high: mid = (low + high)/2 if target == ordered[mid]: return True elif target < ordered[mid]: high = mid - 1 else: low = mid + 1 return False # binary search combined with binary insert: def bs_contains(ordered, target): low = 0 high = len(ordered)-1 while low <= high: mid = (low + high)/2 if target == ordered[mid]: return mid elif target < ordered[mid]: high = mid - 1 else: low = mid + 1 return -(low + 1) def insertInPlace (ordered, target): idx = bs_contains(ordered, target) if idx < 0: ordered.insert(-(idx + 1), target) return ordered.insert(idx, target)
UTF-8
Python
false
false
728
py
13
binarySearchAndInsert.py
12
0.618132
0.600275
0
38
17.763158
44
paulyc/rpi-ramdisk
9,912,784,557,016
a24704329a12e1bc8e1d38c0d327499c1e5efc4d
6949e557531dfa2dbbeadcf1226e751fd07dc30c
/configs/infodisplay.config.py
70e45a6dd33f5fbc8950d3072bfce47fde96a20e
[]
no_license
https://github.com/paulyc/rpi-ramdisk
36cac144040491603cb1cd36838d50768dc3f0e8
d9e560f8f371158c24e683183ebb1d610e7237cc
refs/heads/master
2020-06-17T08:55:13.574912
2019-07-06T20:10:24
2019-07-06T20:13:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
hostname = 'infodisplay' packages = ['net', 'qmlrss', 'rygel']
UTF-8
Python
false
false
63
py
5
infodisplay.config.py
5
0.650794
0.650794
0
2
30.5
37
silva-thiago/python-3
10,685,878,650,077
b10a6b2a899db0e8833b5e6bdabfa129a3c0532c
e4778882d202ee81d437f0b853662985d78c2c03
/mundo-1-fundamentos/4-condicoes-python-if-else/ex034-aumentos-multiplos.py
0fef3049d329678385c5e1f86c541ee9bc1ae486
[ "MIT" ]
permissive
https://github.com/silva-thiago/python-3
5fe36644567319957b0f14c235bf9a8ae21d8710
be7b4b7c4370064f47936499d08fb86806dcf93a
refs/heads/master
2020-03-28T19:13:16.618949
2019-10-10T03:03:10
2019-10-10T03:03:10
148,955,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
salario = float(input('Quanto você ganha? ')) if salario < 1250: # aumento = salario + ((15 * salario) / 100) aumento = salario + ((((1.5 / 10) * 100) * salario) / 100) print('Parabéns, você acabou de ganhar um aumento! Seu novo salário será R${:.2f}!'.format(aumento)) else: # aumento = salario + ((10 * salario) / 100) aumento = salario + ((((1.0 / 10) * 100) * salario) / 100) print('Parabéns, você acabou de ganhar um aumento! Seu novo salário será R${:.2f}!'.format(aumento))
UTF-8
Python
false
false
496
py
39
ex034-aumentos-multiplos.py
38
0.638604
0.564682
0
9
53.111111
101
abhishekmano/Lung-Sound-Classification
2,516,850,851,917
d497f07d99e403107f6dca8bd4206126315e714b
eed90b812d9c858e23a7da78b099a24878397546
/upload code/loadmodel_2gan.py
6231cd183143de5db1258389016009a5e30e6376
[]
no_license
https://github.com/abhishekmano/Lung-Sound-Classification
7d0806cc90bfc28f208a4663a0f4b1963f95641d
fc371d3d43a3254efc5a6d81d8e4a4f0ecfd1fe4
refs/heads/main
2023-05-14T10:42:41.703126
2021-06-09T10:07:04
2021-06-09T10:07:04
317,948,189
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse from re import X import torch from torch.serialization import load import torchaudio import joblib import numpy as np import librosa import csv import torch.nn as nn import torch.nn.functional as F def loadmodel_2gan(filename): torch.backends.cudnn.benchmark = True def feature_extract(audio, sr): audio = audio.squeeze() y = audio.numpy() stft = librosa.stft(y) stft = np.abs(stft) mfcc = librosa.feature.mfcc(y, sr, n_mfcc=40) mfcc = np.mean(mfcc, axis=1) chroma = librosa.feature.chroma_stft(S=stft, sr=sr) chroma = np.mean(chroma, axis=1) # 12 features mel = librosa.feature.melspectrogram(y, sr) mel = np.mean(mel, axis=1) # 128 contrast = librosa.feature.spectral_contrast(y, sr) contrast = np.mean(contrast, axis=1) # 7 tonnetz = librosa.feature.tonnetz(y=librosa.effects.harmonic(y), sr=sr) tonnetz = np.mean(tonnetz, axis=1) # 6 features = np.hstack([mfcc, chroma, mel, contrast, tonnetz]) features = features.reshape((1, 193)) features = torch.from_numpy(features) features = features.float() return features class Discriminator(nn.Module): def __init__(self, num_dec_features, num_channels): super(Discriminator, self).__init__() #torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros') self.main = nn.Sequential( nn.utils.spectral_norm( nn.Conv1d(num_channels, 128, 3, bias=False) ), nn.LeakyReLU(0.2, inplace=True), nn.MaxPool1d(3), nn.utils.spectral_norm( nn.Conv1d(128, 128, 3, bias=False) ), nn.LeakyReLU(0.2, inplace=True), nn.MaxPool1d(3), nn.utils.spectral_norm( nn.Conv1d( 128, 128, 3, bias=False ) ), nn.LeakyReLU(0.2, inplace=True), nn.MaxPool1d(3), nn.utils.spectral_norm( nn.Conv1d( 128, 128, 3, bias=False ) ), nn.LeakyReLU(0.2, inplace=True), nn.MaxPool1d(3), ) self.true_fake = nn.Linear(128, 1) # output(1,3088,158) self.classifier = nn.Linear(128, 2) self.sigmoid = nn.Sigmoid() self.softmax = nn.Softmax(dim=2) def forward(self, features, case): hidden = self.main(features) # print("Hidden-size:",hidden.size()) reshaped_hidden = hidden.view(-1, 1, hidden.size(1)*hidden.size(2)) #print("Reshaped hidden-size:",reshaped_hidden.size()) if(case == 1): # sigmoid linear = self.true_fake(reshaped_hidden) # print(linear.size()) out = self.sigmoid(linear) # print(out.shape) return out else: # softmax linear = self.classifier(reshaped_hidden) # print(linear.size()) out = F.log_softmax(linear, dim=2) #out = self.softmax(linear) # print(out.shape) return out def consistency(value): if(value < 0.65): return "Moderate" elif(value < 0.85): return "High" else: return "Very High" def predict_out(): # model_path = 'savedmodels/cnn_2class.pt' #initial model model_path = 'savedmodels/GAN_2class_best_discriminator.pt' discriminator = Discriminator(193, 1) discriminator.load_state_dict(torch.load( model_path, map_location=torch.device('cpu'))) path = "./static/uploads/" + filename print("Going to Process: ", filename) try: audio_tensor, sample_rate = torchaudio.load( path, normalize=True) # [ 1 , 193 ] except RuntimeError: print("Couldnt open file") return "101", "Error", 0 feature = feature_extract(audio_tensor, sample_rate) with torch.no_grad(): audio_tensor = feature # [1 , 193] audio_tensor = torch.unsqueeze(audio_tensor, 0) # [1,1,193] output = discriminator(audio_tensor, 2) # [1,1,2] output = output.permute(1, 0, 2)[0] # [1,2] # print(output) softmax = nn.Softmax(dim=1) res = softmax(output) # print(res) z = res.squeeze(0).numpy() z = [round(elem, 2)for elem in z] pred = output.max(1, keepdim=True)[1] pred = pred.squeeze(0).squeeze(0).item() x_group = ["Abnormal", "Normal"] x = x_group[pred] y = consistency(res[0][pred]) z = round(res[0][pred].item()*100, 2) #print("predicted:", pred) return x, y, z x, y, z = predict_out() print(x, y, z) return x, y, z # for running only comment out when on web # loadmodel_2gan("crack_1.wav") # loadmodel_2gan("crack_2.wav") # loadmodel_2gan("crack_3.wav") # loadmodel_2gan("crack_4.wav") # loadmodel_2gan("crack_5.wav") # loadmodel_2gan("crack_6.wav") # loadmodel_2gan("crack_7.wav") # loadmodel_2gan("crack_8.wav") # loadmodel_2gan("crack_9.wav") # loadmodel_2gan("crack_10.wav") # loadmodel_2gan("wheeze1.wav") # loadmodel_2gan("wheeze2.wav") # loadmodel_2gan("wheeze3.wav") # loadmodel_2gan("wheeze4.wav") # loadmodel_2gan("wheeze5.wav")
UTF-8
Python
false
false
5,764
py
28
loadmodel_2gan.py
21
0.535045
0.504511
0
177
31.564972
144
travisbrodt/CW-Learning
4,037,269,286,418
621d32155ebc80b413ac8b1a96f3fe437291c38a
bea3ad1802ffd30da22ec391a4f3671840a10070
/Python/Solution_2_2.py
4228d09c41f5e6fabcc0c95ddd31d6e5b1d951a1
[]
no_license
https://github.com/travisbrodt/CW-Learning
6204359f2f33c452cc7fc52061d82aa242ac161b
3ff0407261da9cef2dd571e59942c13fc4b18a65
refs/heads/master
2020-04-16T16:24:25.054151
2019-01-14T22:39:56
2019-01-14T22:39:56
165,735,550
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import win32clipboard # get clipboard data win32clipboard.OpenClipboard() data = win32clipboard.GetClipboardData().split('\r\n') data = filter(None,data) data = ','.join(data) win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(data) win32clipboard.CloseClipboard()
UTF-8
Python
false
false
296
py
55
Solution_2_2.py
41
0.756757
0.716216
0
11
24.545455
54
gnanadeeppallela/220-Assignments
4,956,392,285,573
43ba0099da83f51e83228894b85f92f3f87f2d78
ac4587e176a01864b160c9171cdbb89ac84612ea
/First Assignment/firstproject_web_django/firstapp/views.py
963a6d7b71c240485d2a7cc70744e53b2aa30c0d
[]
no_license
https://github.com/gnanadeeppallela/220-Assignments
64b79025a1eb40653f7c6d67cda3aad18d70c0eb
375c4cf633a9c84529c313bc4e0a32eb43facdb4
refs/heads/master
2020-03-10T03:40:19.087672
2018-10-05T08:04:20
2018-10-05T08:04:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.shortcuts import render,render_to_response from pylab import * import timeit import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, svm import pandas as pd from sklearn.model_selection import train_test_split import psutil import os from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from django.http import HttpResponse # Create your views here. def loic(request): return render(request, 'firstapp/LOIC-download-Detection.html', context=None) def postsubmit(request): if request.method == 'POST': df = pd.read_csv(request.FILES['loicfile'], sep=",", error_bad_lines=False, index_col=False, dtype='float64') start = timeit.default_timer() X_data = np.array(df.ix[0:150, 1:3]) Y_target = np.array(df.ix[0:150, 5:]) validation_size = 0.20 seed = 7 X_train, X_test, Y_train, Y_test = train_test_split(X_data, Y_target, test_size=validation_size, random_state=seed) # clf=svm.SVR(kernel='rbf', gamma=1,C=1) clf = svm.SVC(kernel='linear', verbose=True, gamma='auto', C=1.0) m = clf.fit(X_train, Y_train.ravel()) predictions = clf.predict(X_test) # print(clf.score(X_test, Y_test)) np.mean((clf.predict(X_test) - Y_test) ** 2) x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1 y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1 h = (x_max / x_min) / 100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) plt.subplot(1,1,1) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, color='red', alpha=0.8) plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train, cmap=plt.cm.Paired) plt.ylabel('sepal-width') stop = timeit.default_timer() pid = os.getpid() py = psutil.Process(pid) memoryUse = py.memory_info()[0] / 2. ** 30 print("CPU Utilization: ") print(psutil.cpu_percent()) process = psutil.Process(os.getpid()) mem = process.memory_percent() print("Memory Utilization for this process: ") print(mem) print("Running time: ") print(stop - start) s0="sepal-length" n='\n' sd=psutil.cpu_percent() s1="CPU Utilization: " s2=str(sd) s3="Memory Utilization: " s4=str(mem) s5="Running time: " s6=str(stop - start) s=s1+s2+n+s3+s4+","+s5+s6 plt.xlabel('sepal-length') plt.title(s) #plt.figure(figsize=(20, 10)) canvas = FigureCanvas(plt.figure(1)) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response #return HttpResponse(buffer.getvalue(), mimetype="image/png") #return render(request, 'firstapp/result.html', buffer.getvalue(), mimetype="image/png") #return render(request, 'Home/result.html', context={'sourceaddress': sourceaddress})
UTF-8
Python
false
false
3,216
py
7
views.py
4
0.585821
0.566542
0
102
30.529412
117
rcarino/Kata
10,539,849,792,107
c3006f89859782148e9f9f2f49d9838f34fb7f79
ff8e0fdf537efd696d9db774c01355fad43f0779
/by_day/8_1_15/8_1_15_stocks.py
f27127b81526463cbe6626ff5c77a2e84231b52b
[]
no_license
https://github.com/rcarino/Kata
62fa7df730d9b8847d0042d2ad3a0f40a6897474
cc5753cbe31ca79e718343b6d59cbf7ad3e8a56b
refs/heads/master
2016-09-07T04:25:02.355569
2016-01-24T08:38:51
2016-01-24T08:38:51
5,977,285
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__author__ = 'rcarino' def max_profit(a): min_so_far = a[0] if len(a) else 0 max_profit = 0 for i in a: max_profit = max(max_profit, i - min_so_far) min_so_far = min(i, min_so_far) return max_profit assert max_profit([3, 2, 1]) == 0 assert max_profit([2, 4, 5, 1]) == 3
UTF-8
Python
false
false
304
py
113
8_1_15_stocks.py
111
0.552632
0.513158
0
12
24.333333
52
Andrii-Ishchenko-dp/stepik-auto-tests-course
5,695,126,654,559
64a3b9285e6e63b6d7720ff6619927dff6c679f7
597094dd3abadbe0f7f8ed3739049355c1fa80f4
/les2.4.0.py
9192b0926fc91a39558c5d08df539d674898f987
[]
no_license
https://github.com/Andrii-Ishchenko-dp/stepik-auto-tests-course
05ea5e7c8e7a2ec8c76d9256f9d8c06f224ea363
50b448a9e9d9778df68625cb3f205e4dc387f9e9
refs/heads/main
2023-02-11T10:19:08.427838
2020-12-28T08:12:39
2020-12-28T08:12:39
324,941,060
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver import time # импортируем время, чтобы использовать time.sleep(n) для остановки работы программы на n секунд import math def mat(x): return str(math.log(abs(12*math.sin(x)))) try: #блок в котором мы указываем прямую ссылку на тестируемую страницу browser = webdriver.Chrome() browser.get("http://suninjuly.github.io/explicit_wait2.html") # говорим Selenium проверять в течение 5 секунд, пока кнопка не станет кликабельной button = WebDriverWait(browser, 12).until( EC.text_to_be_present_in_element((By.ID, "price"), "100")) submit=browser.find_element_by_css_selector ("#book") submit.click() num=browser.find_element_by_css_selector ("#input_value") x=int(num.text) ans=browser.find_element_by_css_selector ("#answer") ans.send_keys(mat(x)) sub=browser.find_element_by_css_selector ("#solve") sub.click() finally: time.sleep(10) # ставим выполнене команды на паузу 10 секунд browser.quit()
UTF-8
Python
false
false
1,544
py
9
les2.4.0.py
9
0.64
0.630189
0
31
40.741935
136
verdog/advent_of_code
12,910,671,699,206
5d5bebb7ff99c336d9f59bda7f8f15542898a294
e4ce27c95c88826f1e4cf29332e8b16ac6f62a04
/2018/6/6b.py
bd87c6348385f11836e5e25d74dfddcdf43860de
[]
no_license
https://github.com/verdog/advent_of_code
f9ded80c33bf6ae0948bdfa2bb9b83a8f3a471fc
cccb19880034aadab0f2235e8283ab6f8a3ba40e
refs/heads/master
2020-04-09T20:03:38.331452
2018-12-08T06:48:31
2018-12-08T06:48:31
160,562,432
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 import sys from collections import defaultdict def mandist(a, b): return(abs(b[0] - a[0]) + abs(b[1] - a[1])) with open(sys.argv[1], "r") as f: data = f.read().split('\n')[:-1] minx = None miny = None maxx = None maxy = None points = [] for coords in data: points.append((int(coords.split(",")[0]), int(coords.split(",")[1]))) for point in points: if (minx == None or point[0] < minx): minx = point[0] if (maxx == None or point[0] > maxx): maxx = point[0] if (miny == None or point[1] < miny): miny = point[1] if (maxy == None or point[1] > maxy): maxy = point[1] bound = int(sys.argv[2]) cap = int(sys.argv[3]) minx -= bound miny -= bound maxx += bound maxy += bound totalarea = 0 for y in range(miny-1, maxy+2): for x in range(minx-1, maxx+2): total = 0 for point in points: dist = mandist((x, y), point) total += dist if total < cap: totalarea += 1 print(totalarea)
UTF-8
Python
false
false
1,046
py
17
6b.py
16
0.537285
0.512428
0
49
20.346939
73
khou22/khou22.github.io
10,582,799,461,142
bc9c599dd7d05e0493b0b919acb480faed8fb97b
509fade8744c59b64d92ec3389efde291ce6fd20
/photography/imageManager.py
fc37f2174b2c2c71c4a762cf4698331674e96495
[]
no_license
https://github.com/khou22/khou22.github.io
06c5a85fb1c7174b3c783dbabd5b9fba16342b72
c1df6a8a56ab49b0adc016a5c85936b582366dbd
refs/heads/master
2023-04-27T01:39:54.957427
2023-01-25T07:39:08
2023-01-25T07:39:08
39,487,529
5
3
null
false
2023-04-12T05:44:08
2015-07-22T05:31:50
2021-11-09T18:25:09
2023-04-12T05:44:04
3,210,926
4
2
4
HTML
false
false
# An image manager for a local cache of small images # Can check whether the image exists already before creating import glob import os from io import BytesIO import requests from PIL import Image ''' Pinned to bottom right corner ''' def watermark_with_transparency(base_image: Image, watermark: Image, size: float, offset: float) -> Image: width, height = base_image.size watermark_width, watermark_height = watermark.size # Configure watermark positioning based on base image watermarkFinalWidth = int(round(size * width)) watermarkFinalHeight = int( round((watermarkFinalWidth / watermark_width) * watermark_height)) watermarkX = width - watermarkFinalWidth - int(round(offset * width)) watermarkY = height - watermarkFinalHeight - int(round(offset * height)) watermark_resized = watermark.resize( (watermarkFinalWidth, watermarkFinalHeight), resample=Image.NEAREST) watermark_box = (watermarkX, watermarkY, watermarkX + watermarkFinalWidth, watermarkY + watermarkFinalHeight) print("Width: %d | Height: %d" % (watermarkFinalWidth, watermarkFinalHeight)) transparent = Image.new('RGBA', (width, height), (0, 0, 0, 0)) transparent.paste(base_image, (0, 0)) transparent.paste(watermark_resized, watermark_box, mask=watermark_resized) transparent = transparent.convert("RGB") return transparent class ImageManager: def __init__(self, directory): if not os.path.exists(directory): os.makedirs(directory) self.directory = directory self.images = {} self.placeholderImages = {} self.allFileNames = [] imageList = glob.glob('%s/*.jpg' % directory) # TODO: only jpeg images right now imagePlaceholderList = glob.glob('%s/*placeholder.jpg' % directory) for imagePlaceholder in imagePlaceholderList: if imagePlaceholder in imageList: imageList.remove(imagePlaceholder) # Prevent duplicates fileName = self.fileNameWithoutExt(imagePlaceholder) self.placeholderImages[fileName] = imagePlaceholder # print("Found placeholder %s" % fileName) for imagePath in imageList: fileName = os.path.basename(imagePath) self.images[fileName] = imagePath self.allFileNames.append(fileName) def getAllNames(self): return self.allFileNames; def fileNameWithoutExt(self, fileName): splitFileName = os.path.splitext(os.path.basename(fileName)) if 'Angelo' in fileName: print(fileName) print(splitFileName) return splitFileName[0] def fileNamePlaceholder(self, fileName): return "%s.placeholder.jpg" % self.fileNameWithoutExt(fileName) def exists(self, image): imageExists = image in self.images.keys() placeholderImageName = self.fileNameWithoutExt(self.fileNamePlaceholder(image)) placeholderImageExists = placeholderImageName in self.placeholderImages.keys() return imageExists and placeholderImageExists def getSrc(self, image): filePath = self.images[image] placeholderFileName = self.fileNamePlaceholder(filePath) img = Image.open(filePath) return filePath, placeholderFileName, img.width, img.height # Download the file into the image store using the imageName def create(self, imageName, src, resizeWidth, placeholderWidth): imageFileName = self.fileNameWithoutExt(imageName) imagePath = "%s/%s.jpg" % (self.directory, imageFileName) imagePlaceholderPath = "%s/%s.placeholder.jpg" % (self.directory, imageFileName) # Download image print("Downloading source: %s" % src) response = requests.get(src) img = Image.open(BytesIO(response.content)) ## Large Image # Resize to width width = resizeWidth widthPercent = (width/float(img.size[0])) height = int(float(img.size[1]) * float(widthPercent)) if width > height: # If landscape height = width heightPercentage = height/float(img.size[1]) width = int(float(img.size[0] * float(heightPercentage))) # Apply resize imgResize = img.resize((width, height), Image.ANTIALIAS) # Watermark the image watermark = Image.open('watermark.png') imgResize = watermark_with_transparency(imgResize, watermark, size=0.13, offset=0.01) # Save the resized image imgResize.save(imagePath, 'JPEG', quality=100) # Placeholder image widthPlaceholder = placeholderWidth widthPercentPlaceholder = (placeholderWidth/float(imgResize.size[0])) heightPlaceholder = int(float(imgResize.size[1]) * float(widthPercentPlaceholder)) if widthPlaceholder > heightPlaceholder: # If landscape heightPlaceholder = widthPlaceholder heightPlaceholderPercentage = heightPlaceholder/float(img.size[1]) widthPlaceholder = int(float(img.size[0] * float(heightPlaceholderPercentage))) imgResize = imgResize.resize((widthPlaceholder, heightPlaceholder), Image.ANTIALIAS) imgResize.save(imagePlaceholderPath, 'JPEG', quality=90) # Save local mapping self.images[imageName] = imagePath self.placeholderImages[self.fileNameWithoutExt(imagePlaceholderPath)] = imagePlaceholderPath # On success, retrun the local path return imagePath, imagePlaceholderPath, width, height
UTF-8
Python
false
false
5,642
py
1,525
imageManager.py
47
0.667671
0.663063
0
145
37.910345
100
jarkynashyrova/pythoProject
695,784,704,221
560b3d175fd62a6a6e507dc7f8484228cc636e4d
74345f6521e4a9be6f1540333d37ce7d2fcb58cc
/if_condition2.py
ea31fdb32acd3ee640dea8e2d761093df0bfe0fb
[]
no_license
https://github.com/jarkynashyrova/pythoProject
c42d44e9c25db4e65538201600417122aa51530c
27ce31384da611b93f322437228de7ee77e48376
refs/heads/master
2023-04-09T17:32:43.298049
2021-04-23T02:54:41
2021-04-23T02:54:41
360,694,085
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#3/14/2021 if ststament continues chapter 5 num = 20 if num >= 1 and num <= 10: print(f"number is equal or greater than 1 and less than 10") else: print(f"number is less than 1 or greater than 10.") ''' #expression AND/OR expression AND/OR expression OR: # anything with true is true True OR True = True True OR False = True False OR True = True False or False = False AND: # in and case anything with False is false True OR True = True True OR False = False False OR True = False False or False = False ''' #expression OR expression = True or False = True #where country= 'UK or country='USA >> True or False # The if-elif-else (we going to use alot) #age =int(input('enter the visitors:')) age = 3 if 0 <= age <=4: print("uour admission cost is $0.") # just did unit testing by going each code elif 4 < age < 18: print("your admisson cost is $5.") elif 18 <= age <140: print("your admisson cost is $10.") else: print("invalid age was entered, bye.") #if I enter string like one I will have a error becouse I converted int #age = int(input('enter the visitors:')) #elif checks the condition #age = int(input('enter the visitors age:')) price = 0 if age < 4: price =0 elif age <18: price = 5 elif age < 140: price = 10 else: price =10 print("invalid age was entered, bye.") print(f"your admission cost is ${price}.") #n , 0 < n < 2000000 print("---5-3----Aliena colors -------------") #alien_color = input ('enter the elien color (green/yellow/red): ') #if alien_color == 'green': #print(f"You just earned 5 points!!") #elif alien_color == 'yellow': #print(f"you just earned 2 points, whee!") #elif alien_color == 'red': #print(f" you just earned 10 points, you are killing it, man!!") #else: #print("no points, sorry, take a rest, meditate.") print("--------------------------") friends = () # ifata structurelidt or tuples is emty the result will be true case if friends: print("good for you, can I be your friend.") else: print(f"Go out make some friends, only good friends.") print('--------------Using Multiple list ------------') # class home work # // floor division -division ignoring the remainder # % modulus -gives the remainder print("Famouse interview question fuzzbzzz------------") num = int(input("enter the number > 0:")) #if (num % 3 == 0) and (num % 5 == 0): #print("Fuzzbuzz") #elif num % 3 == 0: #print("fuzz") #elif num % 5 == 0: #print("Buzz")
UTF-8
Python
false
false
2,468
py
32
if_condition2.py
29
0.636548
0.608185
0
88
27.011364
84
karthikpappu/pyc_source
3,143,916,074,267
fbc2f4a4a25a4c51204541ec10d87219164e24b5
91fa095f423a3bf47eba7178a355aab3ca22cf7f
/pycfiles/dez-0.10.9.32-py2.7/get_url.py
8cd1173f6db3a8ceb29b15a9fbe9596960102acc
[]
no_license
https://github.com/karthikpappu/pyc_source
0ff4d03e6d7f88c1aca7263cc294d3fa17145c9f
739e7e73180f2c3da5fd25bd1304a3fecfff8d6e
refs/heads/master
2023-02-04T11:27:19.098827
2020-12-27T04:51:17
2020-12-27T04:51:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# uncompyle6 version 3.7.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) # [GCC 8.4.0] # Embedded file name: build/bdist.linux-x86_64/egg/dez/samples/get_url.py # Compiled at: 2020-04-19 19:55:58 from dez.http.client import HTTPClient import event def main(**kwargs): url = 'http://%s:%s/' % (kwargs['domain'], kwargs['port']) c = HTTPClient() c.get_url(url, cb=req_cb, timeout=1) event.signal(2, event.abort) event.dispatch() def req_cb(response): print response.status_line
UTF-8
Python
false
false
552
py
114,545
get_url.py
111,506
0.672101
0.583333
0
19
28.105263
73
GabrielRojas74/Talleres-AyP
8,495,445,319,679
d4eae1ffeb0d3502902624760daa0bec2ce92629
d97be2b7b171f12d4a4b7992893f39f8a97d2b90
/Taller funciones/punto#6.py
26e64b5ebcd3b406912e65922c270e294bfc7ee7
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
https://github.com/GabrielRojas74/Talleres-AyP
68032d202bd6b3722c9e115a3811914d76fb3744
346b87ddc118b4c8f45fe083f63b4bacb5d01d19
refs/heads/main
2023-08-11T20:11:04.325288
2021-09-19T18:05:16
2021-09-19T18:05:16
392,033,005
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""6.Retorna una lista con las palabras iniciales con la letra que pasa por parametro """ """ Entradas lista-list-->lista elemento-->str-->elemento Salidas lista-list-->lista """ frutas = open('frutas.txt', 'r') lista_frutas = [] for i in frutas: lista_frutas.append(i) def eliminar_un_caracter(lista, elemento): auxilar = [] for i in lista: a = i.replace(elemento, "") auxilar.append(a) return auxilar def letra(lista, elemento): auxiliar = [] for x in lista: if(x[0] == "P"): print(x) auxiliar.append(x) return auxiliar if __name__ == "__main__": nueva = eliminar_un_caracter(lista_frutas, "\n") nueva_fin = letra(nueva, "") print(nueva_fin)
UTF-8
Python
false
false
688
py
58
punto#6.py
48
0.643895
0.640988
0
29
22.724138
89
niranjanh/RegExp
4,458,176,071,653
e3fbdc27cdd74ce29545e954b78d8a95c8a82ccb
fb4bbb223e92b7c1777ddde6f3bc70edf133f3b7
/regexp_08.py
746c613308349b906fbccab7ebabd95103335e3a
[]
no_license
https://github.com/niranjanh/RegExp
2b926672970fae47205f6b07e6fcf6deec532b34
66cd09c6845e171a94195e67a872e6f25399477a
refs/heads/master
2022-11-18T20:01:31.402937
2020-07-16T06:08:38
2020-07-16T06:08:38
280,067,084
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Quantifiers Description Check that the pattern ‘ab+’ will not match the string ‘ac’. You can also play around with the '+' quantifier by using it to match different types of strings. Execution Time Limit 15 seconds */ import re # input string string = "ac" # regex pattern pattern = "ab+" # check whether pattern is present in string or not result = re.search(pattern, string) # print result if result != None: print(True) else: print(False)
UTF-8
Python
false
false
475
py
17
regexp_08.py
16
0.708779
0.704497
0
33
13.151515
97
monkey-hjy/LeetCode
11,141,145,187,306
aa85cd57e46008d5dfa501ff72192334455c07ad
0cda467f9295bcc47c316f949479572c0f056f61
/9-回文数/回文数.py
ebb27756a4508cabad21a219b2a3a7fda2def8c6
[ "MIT" ]
permissive
https://github.com/monkey-hjy/LeetCode
8985eba7b9d75205d9265e1c9380ed5083a3ff0c
a7aefcd2a7462bdf60dcc2cea887f37d30d2fb46
refs/heads/main
2021-05-19T05:01:07.560728
2020-12-24T03:37:36
2020-12-24T03:37:36
251,538,763
0
0
MIT
false
2020-12-23T03:50:11
2020-03-31T08:07:39
2020-12-22T09:22:29
2020-12-23T03:44:09
43
0
0
0
Python
false
false
# -*- coding: utf-8 -*- # @Time : 2020/3/14 21:24 # @Author : Monkey # @File : ClassCreate.py # @Software: PyCharm # @Demand : ''' 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 '''
UTF-8
Python
false
false
278
py
46
回文数.py
25
0.594737
0.531579
0
9
20
44
Sebbl0508/notqickestsort
8,151,847,937,207
872258c4c3eef2c8b719e88ee2154f2aa09b55eb
7f0647103612ca769656806cebbfaf30395dc895
/numberdumper.py
4903d5bd74a9ad9bbb2550da646868f0df060f9f
[]
no_license
https://github.com/Sebbl0508/notqickestsort
a5becd66833d034017b9e7e2dd5dd586cb38fb6f
513927fece9ad0dbf9c613e0bd0d5f1427b046f0
refs/heads/master
2022-11-25T00:50:03.502468
2020-07-10T10:07:12
2020-07-10T10:07:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import sys import random def main(): n = int(input("Highest number: ")) b = int(input("How many numbers: ")) f = open('numbers.txt', 'w').close() f = open('numbers.txt', 'w') for i in range(b): f.write(str(random.randrange(0, n)) + ",") f.close() f = open("numbers.txt", "r") k = remove_lastchar("numbers.txt") f.close() f = open("numbers.txt", "w") f.write(''.join(k)) f.close() def remove_lastchar(f): fl = open(f).readlines() return [s.rstrip(",") for s in fl] main()
UTF-8
Python
false
false
551
py
3
numberdumper.py
2
0.546279
0.544465
0
27
19.407407
50
gombru/LearnFromWebData
1,537,598,314,684
941bdc310f1bcb14786fa476a7932848fdd14a0f
16f0171b1aecb8d104a208df4953884a9ab97b26
/googlenet_regression/train.py
f66c8f0ad5c33f229d804b4bfb514d9487470d7a
[]
no_license
https://github.com/gombru/LearnFromWebData
97538dd91822a0e2a7d12084cde0d9dbf64f3c70
163447027c856004836abe40d9f653ec03da0702
refs/heads/master
2020-03-24T23:12:43.819864
2018-08-01T12:25:10
2018-08-01T12:25:10
143,123,717
13
7
null
null
null
null
null
null
null
null
null
null
null
null
null
caffe_root = '../../caffe-master/' # this file should be run from {caffe_root}/examples (otherwise change this line) import sys sys.path.insert(0, caffe_root + 'python') import caffe from create_solver import create_solver from do_solve import do_solve import os caffe.set_device(0) caffe.set_mode_gpu() weights = '../../../datasets/SocialMedia/models/pretrained/bvlc_googlenet.caffemodel' assert os.path.exists(weights) niter = 10001111 base_lr = 0.001 #Starting from 0.01 (from quick solver) -- Working 0.001 display_interval = 200 #200 #number of validating images is test_iters * batchSize test_interval = 1000 #1000 test_iters = 100 #80 #Name for training plot and snapshots training_id = 'SM_Inception_frozen_word2vec_tfidf' #Set solver configuration solver_filename = create_solver('prototxt/train_frozen_word2vec_tfidf_SM.prototxt', 'prototxt/val_frozen_word2vec_tfidf_SM.prototxt', training_id, base_lr=base_lr) #Load solver solver = caffe.get_solver(solver_filename) #Copy init weights solver.net.copy_from(weights) print 'Running solvers for %d iterations...' % niter solvers = [('my_solver', solver)] _, _, _ = do_solve(niter, solvers, display_interval, test_interval, test_iters, training_id) print 'Done.'
UTF-8
Python
false
false
1,234
py
3
train.py
2
0.745543
0.710697
0
39
30.615385
163
MikiLauLu/aliexpress-refund-bot
7,593,502,205,292
51c3beb9bf605cde0965d80d495c2f96bd17de11
337e5f56827c0e370d96a4cdc231eca2634f6d4e
/bot.py
7bf0b3f8bbb74ad82cf7725c67df5cf3a9f37d3b
[]
no_license
https://github.com/MikiLauLu/aliexpress-refund-bot
b8f6ce0ac00b1de901a207ce34c121457a198ab1
cb4f4f08ed638e236f2f2105638160d81f0216f4
refs/heads/master
2022-04-25T03:57:11.693990
2020-04-21T11:06:58
2020-04-21T11:06:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
token = "YOURBOTTOKEN" import telegram import logging from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackQueryHandler from telegram.ext.dispatcher import run_async import threading, queue import AliExpress import sys import os import datetime import sqlite3 import epn_parse CHAT_LINK = 'https://t.me/ChatAliexpressRefunderBot' WELCOME_TEXT = 'Дорогие друзья! 👋 Число вопрос по поводу бота растет 📈, и я вижу что не всем хочется писать в личку ✍️, поэтому я хочу предложить вам новый способ задать вопросы по боту 📞, товарам 🛒, поиску 🔍, рефанду 💰 и другим темам! Присоединяйтесь к чату 📝 бота @AliexpressRefunderBot! Здесь я отвечу на ваши вопросы ❓, услышу ваши пожелания 💬 и улучшу бота 🛠, получу ваш фидбек ♥️ и многое другое! Жду вас в чате!\n\n [Зайти в чат!](' + CHAT_LINK + ')\n\nВведите модель товара для поиска (например "клавиатура Motospeed"):' TIMEOUT = 400 CASHBACK_LINK = 'https://givingassistant.org/?rid=1vT1QGCSmU' MY_ID = 275413429 vape_filters = 'vs <бренд>,for <бренд>,atomiz,part,case,cover,replac,pcs' phone_filters = 'case,cover,glass,for <бренд>,vs <бренд>,pcs,replac,motherboard,part' laptop_filters = 'case,cover,part,replac,motherboard,assembl,glass,bag,pcs' #conn = sqlite3.connect("mydatabase.db") #cursor = conn.cursor() #cursor.execute("""CREATE TABLE users # (user_id text primary key, user_name text, last_login text, # total_logins text) # """) #conn.commit() #conn.close() updater = Updater(token=token, workers=50) PRODUCT_CHOOSE, BRAND_CHOOSE, PRICE_RANGE_CHOOSE, FILTER_WORDS_CHOOSE, SEARCH_NEXT = range(5) GET_MESSAGE_TO_POST = range(1) GET_MESSAGE_TO_PRINT = range(1) CHOOSE_FILTERS = range(1) condition_result_ready_dict = {} condition_user_ready_dict = {} link_dict = {} cookie_list = [] reply_keyboard = [['/find', '/test'], ['/start', '/help'], ['/filters', '/cancel']] markup = telegram.ReplyKeyboardMarkup(reply_keyboard) def update_db(update): user_id = str(update.message.chat_id) user_name = update.message.from_user.username last_login = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") total_logins = str(1) if not os.path.exists("mydatabase.db"): conn = sqlite3.connect("mydatabase.db") cursor = conn.cursor() cursor.execute("""CREATE TABLE users (user_id text primary key, user_name text, last_login text, total_logins text) """) conn.commit() conn.close() conn = sqlite3.connect("mydatabase.db") cursor = conn.cursor() count = cursor.execute("SELECT * FROM users WHERE user_id=?", (user_id,)).fetchall() if len(count) > 0: total_logins = str(int(count[0][3]) + 1) conn.execute("INSERT OR REPLACE INTO users values (?, ?, ?, ?)", (user_id, user_name, last_login, total_logins)) conn.commit() cursor.close() conn.close() def get_all_users_from_db(): conn = sqlite3.connect("mydatabase.db") cursor = conn.cursor() all_users = cursor.execute("SELECT * FROM users").fetchall() cursor.close() conn.close() return all_users def delete_user_from_db(user_id): conn = sqlite3.connect("mydatabase.db") cursor = conn.cursor() cursor.execute("DELETE FROM users WHERE user_id=?", (user_id,)) conn.commit() cursor.close() conn.close() def start(bot, update): update_db(update) bot.send_message(chat_id=update.message.chat_id, reply_markup=markup, text='Бот ищет товары с неправильным брендом, который можно перевести в подделку и получить 100% рефанд!' 'Чтобы искать товар, введите поиск, как вы искали бы его на Aliexpress. ' 'Например, вводить просто "телефон" бессмысленно, нужно вводить, например ' '"телефон Ulefone S7". Искать самые популярные бренды вроде "телефон Xiaomi" ' 'так же бессмысленно, так как их продавцов мало, они авторизованные, ' 'и заполняют поле "бренд" в описании правильно. Идеальный поиск - ' 'ввести что-то содержащее имя бренда, имя модели и тип товара, например ' '"Meizu EP51 Wireless Bluetooth Earphone".' ' По всем вопросам обращайтесь к @simonvorobyov (https://t.me/simonvorobyov)') def help(bot, update): update_db(update) bot.send_message(chat_id=update.message.chat_id, reply_markup=markup, text='Бот ищет товары с неправильным брендом, который можно перевести в подделку и получить 100% рефанд!' 'Чтобы искать товар, введите поиск, как вы искали бы его на Aliexpress. ' 'Например, вводить просто "телефон" бессмысленно, нужно вводить, например ' '"телефон Ulefone S7". Искать самые популярные бренды вроде "телефон Xiaomi" ' 'так же бессмысленно, так как их продавцов мало, они авторизованные, ' 'и заполняют поле "бренд" в описании правильно. Идеальный поиск - ' 'ввести что-то содержащее имя бренда, имя модели и тип товара, например ' '"Meizu EP51 Wireless Bluetooth Earphone".' ' По всем вопросам обращайтесь к @simonvorobyov (https://t.me/simonvorobyov)') @run_async def iddqd(bot, update): bot.send_message(chat_id=update.message.chat_id, text="Secret found! Stopping server!") global updater updater.stop() sys.exit(0) @run_async def idfa(bot, update): bot.send_message(chat_id=update.message.chat_id, text="Secret found! Restarting server!") global updater updater.stop() os.execl(sys.executable, 'python3', 'bot.py', *sys.argv[1:]) def text_reply(bot, update, user_data): bot.send_message(chat_id=update.message.chat_id, text="Введите /find чтобы начать поиск товара для refund'а." " По всем вопросам обращайтесь к @simonvorobyov (https://t.me/simonvorobyov)") @run_async def test_search(bot, update, user_data): user_data['product'] = 'test' user_data['min_price'] = '' user_data['max_price'] = '' user_data['filter_words'] = [] user_data['brand'] = ['test'] update.message.reply_text('Выполняем тестовый запрос!') link_dict[update.message.chat_id] = [] condition_result_ready_dict[update.message.chat_id] = threading.Condition() condition_user_ready_dict[update.message.chat_id] = threading.Condition() threading.Thread(name='refund_thread', target=AliExpress.find_refund, args=( user_data, link_dict[update.message.chat_id], condition_result_ready_dict[update.message.chat_id], condition_user_ready_dict[update.message.chat_id])).start() with condition_result_ready_dict[update.message.chat_id]: if not condition_result_ready_dict[update.message.chat_id].wait(TIMEOUT): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Поиск завершен по таймауту. /find чтобы начать новый поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END if link_dict[update.message.chat_id][0] is None: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Больше ничего не найдено, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END elif link_dict[update.message.chat_id][0][0] == -1: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Не получилось обойти капчу, попробуйте повторить запрос еще раз позже.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END else: link = epn_parse.get_cashback_link(cookie_list, link_dict[update.message.chat_id][0][0]) if link: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[!](" + link_dict[update.message.chat_id][ 0][0] + ")[Нажми на ссылку чтобы заказать!](" + link + ")") else: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[Нажми на ссылку чтобы заказать!](" + link_dict[update.message.chat_id][0][ 0] + ")") keyboard = [[telegram.InlineKeyboardButton("Да", callback_data='да'), telegram.InlineKeyboardButton("Нет", callback_data='нет')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Искать дальше? Да/Нет (д/н либо /yes или /no)', reply_markup=reply_markup) return SEARCH_NEXT @run_async def repeat(bot, update, user_data): if ('product' not in user_data) or ('brand' not in user_data): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('В предыдущем поиске не задан бренд или поиск. /find чтобы начать новый поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END update.message.reply_text('Повторяем предыдущий поиск!') link_dict[update.message.chat_id] = [] condition_result_ready_dict[update.message.chat_id] = threading.Condition() condition_user_ready_dict[update.message.chat_id] = threading.Condition() threading.Thread(name='refund_thread', target=AliExpress.find_refund, args=( user_data, link_dict[update.message.chat_id], condition_result_ready_dict[update.message.chat_id], condition_user_ready_dict[update.message.chat_id])).start() with condition_result_ready_dict[update.message.chat_id]: if not condition_result_ready_dict[update.message.chat_id].wait(TIMEOUT): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Поиск завершен по таймауту. /find чтобы начать новый поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END if link_dict[update.message.chat_id][0] is None: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Больше ничего не найдено, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END elif link_dict[update.message.chat_id][0][0] == -1: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Не получилось обойти капчу, попробуйте повторить запрос еще раз позже.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END else: link = epn_parse.get_cashback_link(cookie_list, link_dict[update.message.chat_id][0][0]) if link: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[!](" + link_dict[update.message.chat_id][ 0][0] + ")[Нажми на ссылку чтобы заказать!](" + link + ")") else: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[Нажми на ссылку чтобы заказать!](" + link_dict[update.message.chat_id][0][ 0] + ")") keyboard = [[telegram.InlineKeyboardButton("Да", callback_data='да'), telegram.InlineKeyboardButton("Нет", callback_data='нет')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Искать дальше? Да/Нет (д/н либо /yes или /no)', reply_markup=reply_markup) return SEARCH_NEXT @run_async def begin(bot, update, user_data): if update.callback_query: query = update.callback_query update = query else: query = '' if query and query.data == 'repeat': if ('product' not in user_data) or ('brand' not in user_data): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('В предыдущем поиске не задан бренд или поиск. /find чтобы начать новый поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END update.message.reply_text('Повторяем предыдущий поиск!') link_dict[update.message.chat_id] = [] condition_result_ready_dict[update.message.chat_id] = threading.Condition() condition_user_ready_dict[update.message.chat_id] = threading.Condition() threading.Thread(name='refund_thread', target=AliExpress.find_refund, args=( user_data, link_dict[update.message.chat_id], condition_result_ready_dict[update.message.chat_id], condition_user_ready_dict[update.message.chat_id])).start() with condition_result_ready_dict[update.message.chat_id]: if not condition_result_ready_dict[update.message.chat_id].wait(TIMEOUT): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Поиск завершен по таймауту. /find чтобы начать новый поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END if link_dict[update.message.chat_id][0] is None: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Больше ничего не найдено, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END elif link_dict[update.message.chat_id][0][0] == -1: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Не получилось обойти капчу, попробуйте повторить запрос еще раз позже.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END else: link = epn_parse.get_cashback_link(cookie_list, link_dict[update.message.chat_id][0][0]) if link: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[!](" + link_dict[update.message.chat_id][ 0][0] + ")[Нажми на ссылку чтобы заказать!](" + link + ")") else: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[Нажми на ссылку чтобы заказать!](" + link_dict[update.message.chat_id][0][ 0] + ")") keyboard = [[telegram.InlineKeyboardButton("Да", callback_data='да'), telegram.InlineKeyboardButton("Нет", callback_data='нет')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Искать дальше? Да/Нет (д/н либо /yes или /no)', reply_markup=reply_markup) return SEARCH_NEXT else: update_db(update) keyboard = [[telegram.InlineKeyboardButton("Cancel", callback_data='cancel')], [telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup, chat_id=update.message.chat_id, text= WELCOME_TEXT) return PRODUCT_CHOOSE def product_reply(bot, update, user_data): if update.callback_query: if update.callback_query.data == 'cancel': return cancel(bot, update, user_data) elif update.callback_query.data == 'repeat_last': query = update.callback_query update = query if 'product' not in user_data: update.message.reply_text( 'Продукт в прошлом поиске не был задан!') return cancel(bot, update, user_data) keyboard = [[telegram.InlineKeyboardButton("Skip", callback_data='skip')], [telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Поиск ' + user_data['product'] + '! Введите диапазон цен в формате 10-30 (в долларах) (/skip чтобы пропустить ввод цен):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return PRICE_RANGE_CHOOSE text = update.message.text user_data['product'] = text keyboard = [[telegram.InlineKeyboardButton("Skip", callback_data='skip')], [telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Поиск сохранен! Введите диапазон цен в формате 10-30 (в долларах) (/skip чтобы пропустить ввод цен):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return PRICE_RANGE_CHOOSE def price_range_reply(bot, update, user_data): if update.callback_query: if update.callback_query.data == 'cancel': return cancel(bot, update, user_data) elif update.callback_query.data == 'repeat_last': query = update.callback_query update = query if 'min_price' not in user_data or 'max_price' not in user_data: update.message.reply_text( 'Максимальная или минимальная цена не были заданы в прошлом поиске!') return cancel(bot, update, user_data) keyboard = [[telegram.InlineKeyboardButton("Skip", callback_data='skip')], [telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Диапазон цен ' + user_data['min_price'] + '-' + user_data['max_price'] + '! Введите слова для фильтрации, которые надо исключить из поиска, через запятую (например case,for,glass) (/skip чтобы пропустить ввод фильтров):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return FILTER_WORDS_CHOOSE text = update.message.text prices = text.split('-') if len(prices) < 2: update.message.reply_text( 'Вы ввели диапазон цен неправильно, диапазон не сохранен. ' 'Введите слова для фильтрации, которые надо исключить из поиска, через запятую (например case,for,glass) (/skip чтобы пропустить ввод фильтров):') user_data['min_price'] = '' user_data['max_price'] = '' return FILTER_WORDS_CHOOSE min_price = prices[0] if not min_price: min_price = '' max_price = prices[1] if not max_price: max_price = '' user_data['min_price'] = min_price user_data['max_price'] = max_price keyboard = [[telegram.InlineKeyboardButton("Skip", callback_data='skip')], [telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Диапазон цен сохранен! Введите слова для фильтрации, которые надо исключить из поиска, через запятую (например case,for,glass) (/skip чтобы пропустить ввод фильтров):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return FILTER_WORDS_CHOOSE def skip_price_range_reply(bot, update, user_data): if update.callback_query: query = update.callback_query update = query if query.data == 'cancel': return cancel(bot, update, user_data) elif query.data == 'repeat_last': if 'min_price' not in user_data or 'max_price' not in user_data: update.message.reply_text( 'Максимальная или минимальная цена не были заданы в прошлом поиске!') return cancel(bot, update, user_data) keyboard = [[telegram.InlineKeyboardButton("Skip", callback_data='skip')], [telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Диапазон цен ' + user_data['min_price'] + '-' + user_data[ 'max_price'] + '! Введите слова для фильтрации, которые надо исключить из поиска, через запятую (например case,for,glass) (/skip чтобы пропустить ввод фильтров):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return FILTER_WORDS_CHOOSE user_data['min_price'] = '' user_data['max_price'] = '' keyboard = [[telegram.InlineKeyboardButton("Skip", callback_data='skip')], [telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Диапазон не задан. Введите слова для фильтрации через запятую (например case,for,glass) (/skip чтобы пропустить ввод фильтров):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return FILTER_WORDS_CHOOSE def filter_reply(bot, update, user_data): if update.callback_query: if update.callback_query.data == 'cancel': return cancel(bot, update, user_data) elif update.callback_query.data == 'repeat_last': query = update.callback_query update = query if 'filter_words' not in user_data: update.message.reply_text( 'Фильтры не были заданы в прошлом поиске!') return cancel(bot, update, user_data) keyboard = [[telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Фильтры ' + str(user_data['filter_words']) + '! Введите бренд (можно несколько, через запятую) ' '(например "Xiaomi,Amazfit"):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return BRAND_CHOOSE text = update.message.text filter_words = text.split(',') if not filter_words: filter_words = [] user_data['filter_words'] = filter_words keyboard = [[telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Фильтры сохранены! Введите бренд (можно несколько, через запятую) ' '(например "Xiaomi,Amazfit"):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return BRAND_CHOOSE def skip_filter_reply(bot, update, user_data): if update.callback_query: query = update.callback_query update = query if query.data == 'cancel': return cancel(bot, update, user_data) elif query.data == 'repeat_last': if 'filter_words' not in user_data: update.message.reply_text( 'Фильтры не были заданы в прошлом поиске!') return cancel(bot, update, user_data) keyboard = [[telegram.InlineKeyboardButton("Repeat last", callback_data='repeat_last')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Фильтры ' + str(user_data['filter_words']) + '! Введите бренд (можно несколько, через запятую) ' '(например "Xiaomi,Amazfit"):', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return BRAND_CHOOSE user_data['filter_words'] = [] keyboard = [[telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Фильтры не заданы. Введите бренд (можно несколько, через запятую) ' '(например "Xiaomi,Amazfit"):', reply_markup=reply_markup) return BRAND_CHOOSE @run_async def brand_reply(bot, update, user_data): if update.callback_query: if update.callback_query.data == 'cancel': return cancel(bot, update, user_data) elif update.callback_query.data == 'repeat_last': query = update.callback_query update = query if 'brand' not in user_data: update.message.reply_text( 'Бренды в прошлом поиске не были заданы!') return cancel(bot, update, user_data) update.message.reply_text('Бренды ' + str(user_data['brand']) + '! Начинаем поиск!') else: text = update.message.text brand_words = text.lower().split(',') if not brand_words: brand_words = [] user_data['brand'] = brand_words update.message.reply_text('Бренд сохранен! Начинаем поиск!') link_dict[update.message.chat_id] = [] condition_result_ready_dict[update.message.chat_id] = threading.Condition() condition_user_ready_dict[update.message.chat_id] = threading.Condition() threading.Thread(name='refund_thread', target=AliExpress.find_refund, args=(user_data, link_dict[update.message.chat_id], condition_result_ready_dict[update.message.chat_id], condition_user_ready_dict[update.message.chat_id])).start() with condition_result_ready_dict[update.message.chat_id]: if not condition_result_ready_dict[update.message.chat_id].wait(TIMEOUT): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Поиск завершен по таймауту. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END if link_dict[update.message.chat_id][0] is None: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Больше ничего не найдено, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END elif link_dict[update.message.chat_id][0][0] == -1: bot.send_message(chat_id=MY_ID, text='Seems like bot stopped to work, fix me!', parse_mode=telegram.ParseMode.MARKDOWN) keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Кажется, Алиэкспресс заблокировал поиск каптчой, к сожалению проблема пока неразрешима, попробуйте повторить поиск позже.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END else: link = epn_parse.get_cashback_link(cookie_list, link_dict[update.message.chat_id][0][0]) if link: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[!](" + link_dict[update.message.chat_id][ 0][0] + ")[Нажми на ссылку чтобы заказать!](" + link + ")") else: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[Нажми на ссылку чтобы заказать!](" + link_dict[update.message.chat_id][0][0] + ")") keyboard = [[telegram.InlineKeyboardButton("Да", callback_data='да'), telegram.InlineKeyboardButton("Нет", callback_data='нет')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Искать дальше? Да/Нет (д/н либо /yes или /no)', reply_markup=reply_markup) return SEARCH_NEXT @run_async def answer_yes(bot, update, user_data): with condition_user_ready_dict[update.message.chat_id]: condition_user_ready_dict[update.message.chat_id].notifyAll() with condition_result_ready_dict[update.message.chat_id]: if not condition_result_ready_dict[update.message.chat_id].wait(TIMEOUT): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Поиск завершен по таймауту. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END if link_dict[update.message.chat_id][0] is None: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Больше ничего не найдено, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END elif link_dict[update.message.chat_id][0][0] == -1: bot.send_message(chat_id=MY_ID, text='Seems like bot stopped to work, fix me!', parse_mode=telegram.ParseMode.MARKDOWN) keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Кажется, Алиэкспресс заблокировал поиск каптчой, к сожалению проблема пока неразрешима, попробуйте повторить поиск позже.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END else: link = epn_parse.get_cashback_link(cookie_list, link_dict[update.message.chat_id][0][0]) if link: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[!](" + link_dict[update.message.chat_id][ 0][0] + ")[Нажми на ссылку чтобы заказать!](" + link + ")") else: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[Нажми на ссылку чтобы заказать!](" + link_dict[update.message.chat_id][0][0] + ")") keyboard = [[telegram.InlineKeyboardButton("Да", callback_data='да'), telegram.InlineKeyboardButton("Нет", callback_data='нет')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Искать дальше? Да/Нет (д/н либо /yes или /no)', reply_markup=reply_markup) return SEARCH_NEXT @run_async def answer_no(bot, update, user_data): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Хорошо, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END @run_async def search_next(bot, update, user_data): if update.message: text = update.message.text else: text = '' if update.callback_query: query = update.callback_query update = query else: query = '' if text.lower() == 'да' or text.lower() == 'д' or (query and query.data == 'да'): with condition_user_ready_dict[update.message.chat_id]: condition_user_ready_dict[update.message.chat_id].notifyAll() with condition_result_ready_dict[update.message.chat_id]: if not condition_result_ready_dict[update.message.chat_id].wait(TIMEOUT): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Поиск завершен по таймауту. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END if link_dict[update.message.chat_id][0] is None: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Больше ничего не найдено, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END else: link = epn_parse.get_cashback_link(cookie_list, link_dict[update.message.chat_id][0][0]) if link: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[!](" + link_dict[update.message.chat_id][ 0][0] + ")[Нажми на ссылку чтобы заказать!](" + link + ")") else: bot.send_message(parse_mode=telegram.ParseMode.MARKDOWN, chat_id=update.message.chat_id, text="Неправильный бренд, бренд товара " + link_dict[update.message.chat_id][0][1] + " не совпадает с брендами " + str(user_data['brand']) + "\n[Нажми на ссылку чтобы заказать!](" + link_dict[update.message.chat_id][0][0] + ")") keyboard = [[telegram.InlineKeyboardButton("Да", callback_data='да'), telegram.InlineKeyboardButton("Нет", callback_data='нет')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Искать дальше? Да/Нет (д/н либо /yes или /no)', reply_markup=reply_markup) return SEARCH_NEXT else: keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Хорошо, поиск завершен. /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END def cancel(bot, update, user_data): if hasattr(update, 'callback_query'): if update.callback_query: query = update.callback_query update = query keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Пока! Продолжим в следующий раз! /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END def conversation_timeout(bot, update, user_data): keyboard = [[telegram.InlineKeyboardButton("Find", callback_data='find')], [telegram.InlineKeyboardButton("Repeat", callback_data='repeat')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Ты думаешь слишком долго! Продолжим в следующий раз! /find чтобы начать новый поиск, /repeat чтобы повторить последний поиск.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END def post_message(bot, update): users = get_all_users_from_db() for user in users: try: bot.forward_message(int(user[0]), update.message.chat_id, update.message.message_id) except: delete_user_from_db(user[0]) #bot.send_message(chat_id=int(user[0]), text=update.message.text, parse_mode=ParseMode.MARKDOWN) update.message.reply_text('Готово! Пост опубликован!') return ConversationHandler.END def print_message(bot, update): bot.send_message(chat_id=update.message.chat_id, text=update.message.text, parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END def count_users(bot, update): users = get_all_users_from_db() bot.send_message(chat_id=update.message.chat_id, text=('Количество юзеров в базе: ' + str(len(users)))) def begin_post(bot, update): bot.send_message(chat_id=update.message.chat_id, text='Форвардни мне сообщение которое нужно опубликовать. /cancel для отмены.') return GET_MESSAGE_TO_POST def begin_print(bot, update): bot.send_message(chat_id=update.message.chat_id, text='Напиши мне сообщение которое нужно написать от моего имени. /cancel для отмены.') return GET_MESSAGE_TO_PRINT def filters(bot, update): if update.callback_query: query = update.callback_query update = query keyboard = [[telegram.InlineKeyboardButton("Телефоны", callback_data='телефоны')], [telegram.InlineKeyboardButton("Вейпы", callback_data='вейпы')], [telegram.InlineKeyboardButton("Ноутбуки", callback_data='ноутбуки')], [telegram.InlineKeyboardButton("Cancel", callback_data='cancel')]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Выберите категорию, для которой вы хотите посмотреть фильтры.', reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) return CHOOSE_FILTERS def choose_filters(bot, update, user_data): if update.callback_query: query = update.callback_query if query.data == 'cancel': return cancel(bot, update, user_data) elif query.data == 'вейпы': query.message.reply_text('Фильтры для вейпов:', parse_mode=telegram.ParseMode.MARKDOWN) query.message.reply_text('*' + vape_filters + '*', parse_mode=telegram.ParseMode.MARKDOWN) query.message.reply_text('*Замените <бренд> на название бренда вейпа.*', parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END elif query.data == 'телефоны': query.message.reply_text('Фильтры для телефонов:', parse_mode=telegram.ParseMode.MARKDOWN) query.message.reply_text('*' + phone_filters + '*', parse_mode=telegram.ParseMode.MARKDOWN) query.message.reply_text('*Замените <бренд> на название бренда телефона.*', parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END elif query.data == 'ноутбуки': query.message.reply_text('Фильтры для ноутбуков:', parse_mode=telegram.ParseMode.MARKDOWN) query.message.reply_text('*' + laptop_filters + '*', parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END return ConversationHandler.END else: update.message.reply_text('Вы не нажали кнопку.', parse_mode=telegram.ParseMode.MARKDOWN) return ConversationHandler.END def main(): logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) global updater global cookie_list dispatcher = updater.dispatcher start_handler = CommandHandler('start', start) help_handler = CommandHandler('help', help) iddqd_handler = CommandHandler('iddqd', iddqd) idfa_handler = CommandHandler('idfa', idfa) count_users_handler = CommandHandler('count', count_users) filters_handler = ConversationHandler( entry_points=[CommandHandler('filters', filters)], states={ CHOOSE_FILTERS: [CallbackQueryHandler(choose_filters, pass_user_data=True) ], ConversationHandler.TIMEOUT: [MessageHandler(Filters.text, conversation_timeout, pass_user_data=True), ] }, fallbacks=[CommandHandler('cancel', cancel, pass_user_data=True)], conversation_timeout=TIMEOUT + 5 ) conv_handler = ConversationHandler( entry_points=[CommandHandler('find', begin, pass_user_data=True), CallbackQueryHandler(begin, pass_user_data=True), CommandHandler('repeat', repeat, pass_user_data=True), CommandHandler('test', test_search, pass_user_data=True)], states={ PRODUCT_CHOOSE: [MessageHandler(Filters.text, product_reply, pass_user_data=True), CommandHandler('yes', answer_yes, pass_user_data=True), CommandHandler('no', answer_no, pass_user_data=True), CallbackQueryHandler(product_reply, pass_user_data=True) ], BRAND_CHOOSE: [MessageHandler(Filters.text, brand_reply, pass_user_data=True), CallbackQueryHandler(brand_reply, pass_user_data=True) ], PRICE_RANGE_CHOOSE: [MessageHandler(Filters.text, price_range_reply, pass_user_data=True), CommandHandler('skip', skip_price_range_reply, pass_user_data=True), CallbackQueryHandler(skip_price_range_reply, pass_user_data=True) ], FILTER_WORDS_CHOOSE: [MessageHandler(Filters.text, filter_reply, pass_user_data=True), CommandHandler('skip', skip_filter_reply, pass_user_data=True), CallbackQueryHandler(skip_filter_reply, pass_user_data=True) ], SEARCH_NEXT: [MessageHandler(Filters.text, search_next, pass_user_data=True), CommandHandler('yes', answer_yes, pass_user_data=True), CommandHandler('no', answer_no, pass_user_data=True), CallbackQueryHandler(search_next, pass_user_data=True) ], ConversationHandler.TIMEOUT: [MessageHandler(Filters.text, conversation_timeout, pass_user_data=True), ] }, fallbacks = [CommandHandler('cancel', cancel, pass_user_data=True)], conversation_timeout = TIMEOUT+5 ) conv_post_handler = ConversationHandler( entry_points=[CommandHandler('post', begin_post)], states={ GET_MESSAGE_TO_POST: [MessageHandler(Filters.text, post_message), ], }, fallbacks=[CommandHandler('cancel', cancel, pass_user_data=True)], conversation_timeout=TIMEOUT+5 ) conv_print_handler = ConversationHandler( entry_points=[CommandHandler('print', begin_print)], states={ GET_MESSAGE_TO_PRINT: [MessageHandler(Filters.text, print_message), ], }, fallbacks=[CommandHandler('cancel', cancel, pass_user_data=True)], conversation_timeout=TIMEOUT+5 ) text_handler = MessageHandler(Filters.text, text_reply, pass_user_data=True) dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(iddqd_handler) dispatcher.add_handler(idfa_handler) dispatcher.add_handler(filters_handler) dispatcher.add_handler(conv_handler) dispatcher.add_handler(conv_post_handler) dispatcher.add_handler(count_users_handler) dispatcher.add_handler(conv_print_handler) dispatcher.add_handler(text_handler) #epn_parse.login_epn() updater.start_polling(poll_interval = 1.0, timeout=20) if __name__ == '__main__': try: main() except KeyboardInterrupt: exit()
UTF-8
Python
false
false
59,442
py
4
bot.py
4
0.592583
0.589808
0
918
57.482571
533
spinoza1791/pi3d_book
9,285,719,343,027
2f164ff9e46db5a6141f549e279d75e9f3af6d69
ea4d61f1b1e900e0b9d9ca70699eec464f06e9ee
/programs/sprites01.py
91b691ae60dbcf13c9f51b63807f06572ca209f2
[]
no_license
https://github.com/spinoza1791/pi3d_book
afe7edc790b40338acd70fefed35e94200c48049
c2a90ccdf0b39e95b5c416c7f98dd3c5750959b7
refs/heads/master
2020-05-03T11:27:12.570207
2015-11-13T12:54:22
2015-11-13T12:54:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals import demo import pi3d DISPLAY = pi3d.Display.create(x=150, y=150) shader = pi3d.Shader("uv_flat") CAMERA = pi3d.Camera(is_3d=False) tex1 = pi3d.Texture("techy1.jpg") #tex1 = pi3d.Texture("techy2.png") tex2 = pi3d.Texture("glassbuilding.jpg") #tex2 = pi3d.Texture("techy2.png") z1 = 5.0 # z value of sprite1 a1 = 1.0 # alpha value of sprite1 a2 = 1.0 # alpha value of sprite2 sprite1 = pi3d.Sprite(w=400.0, h=400.0, x=-100.0, y=100.0, z=z1) sprite1.set_draw_details(shader, [tex1]) sprite2 = pi3d.Sprite(w=400.0, h=400.0, x=100.0, y=-100.0, z=z1 + 0.2) sprite2.set_draw_details(shader, [tex2]) """ The two Sprites start off overlapping with sprite2 slightly further away. Both have default alpha value of 1.0 """ keys = pi3d.Keyboard() while DISPLAY.loop_running(): sprite1.draw() sprite2.draw() """ Keys w,s move sprite1 back,forward a,d decrease,increase sprite1 alpha and z,c decrease,increase sprite2 alpha NB sprite2 is drawn after sprite1 see what happens if sprite1 is in front of sprite2 as you reduce the alpha so you can see through it. Now put sprite2 in front and reduce its alpha. Try swapping tex1 and tex2 (one at a time) to techy2.png, move them back and forth and change their alpha values. """ k = keys.read() if k > -1: if k == 27: break elif k == ord('w'): # away z1 += 0.1 elif k == ord('s'): # nearer z1 -= 0.1 elif k == ord('a'): # less solid sprite1 a1 -= 0.05 elif k == ord('d'): # more solid sprite1 a1 += 0.05 elif k == ord('z'): # less solid sprite2 a2 -= 0.05 elif k == ord('c'): # more solid sprite2 a2 += 0.05 sprite1.positionZ(z1) sprite1.set_alpha(a1) sprite2.set_alpha(a2) keys.close() DISPLAY.destroy()
UTF-8
Python
false
false
1,855
py
56
sprites01.py
28
0.657143
0.587062
0
61
29.409836
82
matplotlib/matplotlib.github.com
5,540,507,862,821
0cb002454e031928749b0e11635fc987acd571eb
7889f7f0532db6a7f81e6f8630e399c90438b2b9
/_downloads/ac4f86bd93cba659ce07e61072e8ab4a/mathtext_wx_sgskip.py
a5fd58888656b4b91e822adbf2703eaa6425f39e
[]
no_license
https://github.com/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
false
2023-08-30T15:59:50
2011-02-19T03:27:35
2023-08-19T17:14:35
2023-08-30T15:59:49
5,051,744
22
58
3
null
false
false
../../3.1.3/_downloads/ac4f86bd93cba659ce07e61072e8ab4a/mathtext_wx_sgskip.py
UTF-8
Python
false
false
77
py
14,250
mathtext_wx_sgskip.py
4,420
0.805195
0.545455
0
1
77
77
glenMoutrie/PyCast
8,830,452,774,676
e1ae6c64603d76b951e0540e6d99faed5450d88c
39baaddf53bcdf884d85d5e0cf020f161863f250
/ARIMA/auto_arima.py
c0e28abf621f21d17f7f0b2af931e15f24705a6d
[]
no_license
https://github.com/glenMoutrie/PyCast
b2668c2e29477016352b694fbcb5b5aa7b807924
f7f57c4b6546653a8b07dd923c5f453d28a8d90e
refs/heads/master
2021-09-15T21:23:25.293787
2018-06-11T05:07:15
2018-06-11T05:07:15
108,550,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from enum import Enum from TimeSeriesOO.FrequencyEstimator import estimateFrequency class informationCriteria(Enum): AICC = 1 AIC = 2 BIC = 3 class testProcedure(Enum): KPSS = 1 ADF = 2 PP = 3 class seasonalTest(Enum): SEAS = 1 OCSB = 2 HEGY = 3 CH = 4 def approx(x): return len(x) > 150 or estimateFrequency(x) > 12 class autoArima: def __init__(self, x, d = None, D = None, max_p = 5, max_q = 5, max_P = 2, max_Q = 2, max_order = 5, max_d = 2, max_D = 1, start_p = 2, start_q = 2, start_P = 1, start_Q = 1, stationary = False, seasonal = True, ic = informationCriteria.AICC, stepwise = False, trace = False, approximation = approx, truncate = None, xreg = None, test = testProcedure.KPSS, seasonal_test = seasonalTest.SEAS, allowdrift = True, allowmean = True, lmbd = None, biasadj = False, parallel = False, num_cores = 2,): pass if __name__ == "__main__": pass
UTF-8
Python
false
false
1,069
py
15
auto_arima.py
10
0.549111
0.523854
0
39
26.435897
84
alejandro-robles7/CatsAndDogs
16,518,444,264,735
7d7a87db59ae1382ea352db96a13d008823ad3cf
4453b1776a2b0e0f503208f3f452aeb059635ebb
/code/classification_testing.py
14d06fd7ab0e10b327f8dbbcee074321d24c8eae
[]
no_license
https://github.com/alejandro-robles7/CatsAndDogs
fbcdecab8332b2453808e06e6f73577a959c07bc
e206a10090fd81a595e405600a615346bbfbc6e0
refs/heads/master
2020-05-17T18:17:27.936688
2019-05-06T03:20:32
2019-05-06T03:20:32
183,879,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This is code to load trained model and test it from keras.models import load_model from os import environ import matplotlib.pyplot as plt from keras.preprocessing.image import ImageDataGenerator def predict_and_plot(model, test_generator, columns=5): text_labels = [] plt.figure(figsize=(30, 20)) for i, batch in enumerate(test_generator): pred = model.predict(batch[0]) if pred > 0.5: text_labels.append('dog') else: text_labels.append('cat') plt.subplot(5 / columns + 1, columns, i + 1) plt.title('This is a ' + text_labels[i]) imgplot = plt.imshow(batch[0][0]) i += 1 if i % 10 == 0: break plt.show() return text_labels def load_my_model(modelpath, weightpath): model = load_model(modelpath) model.load_weights(weightpath) return model def get_generator(data_directory, target_size): return ImageDataGenerator(rescale=1. / 255).flow_from_directory( data_directory, target_size=target_size, batch_size=1, class_mode='binary') if __name__ == '__main__': # Needed to run model environ['KMP_DUPLICATE_LIB_OK'] = 'True' # dimensions of our images. img_width, img_height = 150, 150 # Path to data local_path = '/Users/alejandro.robles/PycharmProjects/CatsAndDogs/{}' test_data_dir = local_path.format('classification testing utility') # Validation and test set are the same here # Path to model and weights model_path, model_path_better = 'models/model_keras.h5', 'models/model_keras_full.h5' model_weights_path, model_weights_path_better = 'models/model_weights.h5', 'models/model_weights_full.h5' # Loading models model = load_my_model(model_path, model_weights_path) model_better = load_my_model(model_path_better, model_weights_path_better) # Test Generator test_generator = get_generator(test_data_dir, (img_width, img_height)) # Predictions predicted_labels = predict_and_plot(model, test_generator) predicted_labels_better_model = predict_and_plot(model, test_generator)
UTF-8
Python
false
false
2,136
py
3
classification_testing.py
2
0.659644
0.644663
0
63
32.809524
116
ttaylor14/PNation
6,743,098,686,659
1c9510bd6e0e1c23d71d92bbfcfcb01694eaa1bc
0744122cc12f0fba0929cffc59a8a6ddc90418e1
/data/YearPoints/Top50.py
f87745f12231cda005bd17c9ce8af69a99bead6c
[ "MIT" ]
permissive
https://github.com/ttaylor14/PNation
a1b60435cd77acfc6569dedd87d69e44fb806c0c
6c616bc95751ba77e85b22b14bb66e2c8e13142a
refs/heads/master
2020-05-19T07:38:16.186475
2020-01-04T15:54:29
2020-01-04T15:54:29
184,900,859
1
0
null
false
2019-10-04T15:04:04
2019-05-04T13:50:19
2019-09-30T01:19:10
2019-10-04T15:04:04
24,330
1
0
0
Python
false
false
# Creating Roto Rankings # last Update : 10.13.19 # Creating Chart to Visually Show how Points are distributed for the top 10 ranked players each year # libraries import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import parallel_coordinates import seaborn as sns currentYear = 2019 AllTeam = pd.DataFrame() yearRange = list(range(2000, currentYear + 1)) # print(yearRange) for x in yearRange: filename = "%s.csv" % x team = pd.read_csv(filename, sep=',', encoding='utf-8') team = team[:50] #print(team) AllTeam = pd.concat([AllTeam, team]) AllTeam = AllTeam[['Rank', 'Total_Points', 'Season_bat']] AllTeam.rename(columns={'Season_bat':'Season'}, inplace=True) AllTeam.rename(columns={'Rank':'Player_Ranking'}, inplace=True) pkmn_type_colors = ['#78C850', # Grass '#F08030', # Fire '#6890F0', # Water '#A8B820', # Bug '#A8A878', # Normal '#A040A0', # Poison '#F8D030', # Electric '#E0C068', # Ground '#EE99AC', # Fairy '#C03028', # Fighting '#F85888', # Psychic '#B8A038', # Rock '#705898', # Ghost '#98D8D8', # Ice '#7038F8', # Dragon '#78CA50', '#F08630', '#6896F0', '#A87820', '#A88878', '#AAA878' ] sns.lineplot(data= AllTeam, x="Player_Ranking", y="Total_Points", hue="Season", palette=pkmn_type_colors, markers=True, dashes=True, sort=False) plt.legend(bbox_to_anchor=(1, 1), loc=2) plt.title('Historical Points Scored by Top 50 Ranked Players Each Year') plt.show()
UTF-8
Python
false
false
1,874
py
113
Top50.py
22
0.519744
0.456777
0
72
25.027778
144
dwatow/MockKgsDataObjectGenerator
1,803,886,264,752
40c500614736886cadfb004cd7252450b0659ddb
9ded0c41fc626fbfc9b69d8fb21eb83f85778c4e
/xmlMain.py
12b833e57bc0d4d3b73c21cc0778d17b53346d37
[]
no_license
https://github.com/dwatow/MockKgsDataObjectGenerator
dbddfec55d8b3c0b4ccf55c2b30fb919cfcb2d78
b6b004627d2d4c416a5a472e7be1f8fcb3809448
refs/heads/master
2021-01-14T08:23:38.644041
2017-02-13T06:31:48
2017-02-13T06:31:48
41,518,984
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import xml.etree.ElementTree as ET import XmlObj as XmlTableObj import XmlKDoMock as XmlKDataObject from XmlKDoMock import xml2Class as xml2class from xml2.references import References as xml2ref from xml2.references import ExtendReferences as xml2extdref from xml2.references import ExternalReferences as xml2extlref tree = ET.ElementTree(file='DB.xml') root = tree.getroot() kdo_class_list = {} for class_element in root: kdo_class_obj = xml2class(class_element.attrib["Name"]) kdo_class_list[ class_element.attrib["Name"] ] = kdo_class_obj for class_element in root: #print(class_element.attrib["Name"]) curr_class_name = class_element.attrib["Name"] kdo_class_obj = kdo_class_list[curr_class_name] for class_chirld in class_element: if class_chirld.tag == 'ExternalReferences': for external_reference_element in class_chirld: extl_obj = xml2extlref(curr_class_name, external_reference_element.attrib['SourceName'], external_reference_element.attrib['TargetName'], external_reference_element.attrib['ClassName']) kdo_class_obj.AddBeforeClass(extl_obj.MyBeforeClass()) kdo_class_obj.AddReference(extl_obj.MyDotHCode()) kdo_class_obj.AddCollectionFunction(extl_obj.MyDotHCollectionFunction()) kdo_class_obj.AddRelListFunction(extl_obj.MyDotCppCollectionFunction()) kdo_class_obj.AddInitRef(extl_obj.MyInitDotCppCode()) rel_kdo_class_obj = kdo_class_list[extl_obj.RelClassName()] rel_kdo_class_obj.AddBeforeClass(extl_obj.RelBeforeClass()) rel_kdo_class_obj.AddReference(extl_obj.RelDotHCode()) rel_kdo_class_obj.AddCollectionFunction(extl_obj.RelDotHCollectionFunction()) rel_kdo_class_obj.AddRelListFunction(extl_obj.RelDotCppCollectionFunction()) rel_kdo_class_obj.AddInitRef(extl_obj.RelInitDotCppCode()) kdo_class_list[extl_obj.RelClassName()] = rel_kdo_class_obj if class_chirld.tag == 'ExtendReferences': for extend_reference_element in class_chirld: extd_obj = xml2extdref(curr_class_name, extend_reference_element.attrib['SourceName'], extend_reference_element.attrib['TargetName'], extend_reference_element.attrib['ClassName'], extend_reference_element.attrib['Relation']) kdo_class_obj.AddBeforeClass(extd_obj.MyBeforeClass()) kdo_class_obj.AddReference(extd_obj.MyDotHCode()) kdo_class_obj.AddRefField(extd_obj.RelDotHField_Syskey()) kdo_class_obj.AddInitRefField(extd_obj.RelDotCppField_Syskey()) kdo_class_obj.AddInitRef(extd_obj.MyInitDotCppCode()) rel_kdo_class_obj = kdo_class_list[extd_obj.RelClassName()] rel_kdo_class_obj.AddBeforeClass(extd_obj.RelBeforeClass()) rel_kdo_class_obj.AddReference(extd_obj.RelDotHCode()) rel_kdo_class_obj.AddCollectionFunction(extd_obj.RelDotHCollectionFunction()) rel_kdo_class_obj.AddRelListFunction(extd_obj.RelDotCppCollectionFunction()) kdo_class_list[extd_obj.RelClassName()] = rel_kdo_class_obj if class_chirld.tag == 'References': for reference_element in class_chirld: ref_obj = xml2ref(curr_class_name, reference_element.attrib['Name'], reference_element.attrib['Type'], reference_element.attrib['Relation']) kdo_class_obj.AddBeforeClass(ref_obj.MyBeforeClass()) kdo_class_obj.AddReference(ref_obj.MyDotHCode()) kdo_class_obj.AddInitRef(ref_obj.MyInitDotCppCode()) if curr_class_name == 'ManufactureProcess': print(ref_obj.my_class_name) kdo_class_obj.AddRefField(ref_obj.RelDotHField_Syskey()) kdo_class_obj.AddInitRefField(ref_obj.RelDotCppField_Syskey()) rel_kdo_class_obj = kdo_class_list[ref_obj.RelClassName()] rel_kdo_class_obj.AddBeforeClass(ref_obj.RelBeforeClass()) rel_kdo_class_obj.AddReference(ref_obj.RelDotHCode()) rel_kdo_class_obj.AddCollectionFunction(ref_obj.RelDotHCollectionFunction()) rel_kdo_class_obj.AddInitRef(ref_obj.RelInitDotCppCode()) rel_kdo_class_obj.AddRelListFunction(ref_obj.RelDotCppCollectionFunction()) kdo_class_list[ref_obj.RelClassName()] = rel_kdo_class_obj if class_chirld.tag == 'Properties': for property_element in class_chirld: #print(' ', property_element.attrib["Type"], property_element.attrib["Name"]) kdo_class_obj.AddMemberVariable(property_element.attrib["Type"], property_element.attrib["Name"]) kdo_class_list[curr_class_name] = kdo_class_obj print('--------------------------') for class_name, stub_obj in kdo_class_list.items(): #stub_obj.Write2File('KDataObject\\') stub_obj.Write2DotHFile('KDataObject\\') stub_obj.Write2DotCppFile('KDataObject\\') #stub_obj.Write2DotHFile('') #stub_obj.Write2DotCppFile('') print('----------生成TableObj----------') table_obj_list = [] for class_element in root: #print(class_element.attrib["Name"]) table_obj_class_obj = XmlTableObj.xml2Class(class_element.attrib["Name"]) for class_chirld in class_element: #if class_chirld.tag == 'References': #for reference_element in class_chirld: ##print(' ', reference_element.attrib['Name'], reference_element.attrib['Type'], reference_element.attrib['Relation']) #table_obj_class_obj.AddReference(reference_element.attrib['Name'], reference_element.attrib['Type'], reference_element.attrib['Relation']) if class_chirld.tag == 'Properties': for property_element in class_chirld: #print(' ', property_element.attrib["Type"], property_element.attrib["Name"]) table_obj_class_obj.AddMemberVariable(property_element.attrib["Type"].lower(), property_element.attrib["Name"]) table_obj_list.append(table_obj_class_obj); print('--------------------------') for obj in table_obj_list: #obj.Write2File('KDataObject') obj.Write2DotHFile('TableObj') obj.Write2DotCppFile('TableObj') report = '生成' + str(len(table_obj_list)) + '個KDataObject.h檔案\n' report += '生成' + str(len(table_obj_list)) + '個KDataObject.cpp檔案\n' report += '生成' + str(len(table_obj_list)) + '個TableObj.h檔案\n' report += '生成' + str(len(table_obj_list)) + '個TableObj.cpp檔案\n' print(report) '''檔案生成,資料夾要保留,才會順利生成。'''
UTF-8
Python
false
false
6,004
py
11
xmlMain.py
8
0.738771
0.735225
0
117
49.623932
228
snow-stone/python
12,446,815,253,754
7cd154d61911a52035f7b99c46559f622b3a8f45
bdadee64ca8c143a925ec84736e3966ef0183bce
/python_rsync/rsync.py
0aad571b18a334729c71e79ce19d9917d8215145
[]
no_license
https://github.com/snow-stone/python
fcb69950f5984d654f555ca591583c0a0763bef4
0e79a0fb265a22a409309b1c0f992f00ef588f95
refs/heads/master
2020-03-11T10:51:53.268373
2019-10-18T14:24:45
2019-10-18T14:24:45
129,953,986
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import commands, os import scipy.io as io def makeDirectory(directory): if not os.path.exists(directory): os.makedirs(directory) else: print directory, " exists" def runJob(cmd): print "running Job using bash command : %s" % cmd status, jobOutput = commands.getstatusoutput(cmd) if status == 0 : print "Job return value : 0" print "Job output :" print jobOutput else : print "Job failed" print "Job output :" print jobOutput return status, jobOutput def tryJob(sourceDir, targetDir): cmd = "rsync -av %s %s/" % (sourceDir, targetDir) return runJob(cmd) def create_write_database_NoSync(): # naming # begin by D1, D2, D3 : debit min, medium, max # then : dash # if NN then NN, if not, directly get into resolution : 1b, 1d, 1j, 1k... caseByAlias=[ #1b "D1-1b", #1d "D1-1d", #1d_lR2 "D1-1d_lR2_afterAugust", #1j "D2-NN-1j_test_from0", "D2-NN-1j_test_from0p3_forcingStep_St1_A_eq_0p05", "D2-NN-1j_test_from0p3_forcingSinus_St3p2_A_eq_0p05", "D1-1j_mapped", # test_from_0p45_of3 "D2-1j_mapped", # test_from_0p45_of3 "D3-1j_mapped", # test_from_0p45_of3 "D2-1j_syn", "D2-NN-1j_syn", #1k_4x4x4.pw : note that this is not "1k.pw" "D2-NN-1k_syn", "D2-NN-1k_syn_forcing", # t_r "t_r-2a_1_gradP0p703125" ] caseInfo=dict.fromkeys(caseByAlias) for case in caseByAlias: caseInfo[case]={ 'sourceDir':[], 'targetDir':[], 'name2plot':[], 'latestTime':[] } # IMPORTANT COMMENT HRER : # sourceDir need to include machie name like "newton:" # targetDir doesn't need to exit before running # dirName will be rsync-ed # IMPORTANT : no backslash at the end #dirName="/postProcessing" alias="D1-1b" caseInfo[alias]['sourceDir']="newton:/store/lmfa/fct/hluo/zaurak/caseByGeometry/T/new-mesh/pointwise/postProcessing/1b_mirrorMerge"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1b"+"/"+alias caseInfo[alias]['name2plot']=alias makeDirectory(caseInfo[alias]['targetDir']) alias="D1-1d" caseInfo[alias]['sourceDir']="newton:/store/lmfa/fct/hluo/zaurak/caseByGeometry/T/new-mesh/pointwise/postProcessing/1d_mapped_NearestFace"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1d"+"/"+alias caseInfo[alias]['name2plot']=alias makeDirectory(caseInfo[alias]['targetDir']) alias="D1-1d_lR2_afterAugust" caseInfo[alias]['sourceDir']="newton:/store/lmfa/fct/hluo/zaurak/caseByMachine/occigen/T/passiveScalar/Newtonian/mapped/flowRate/min/1d_lR2/afterAugust"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1d_lR2"+"/"+alias caseInfo[alias]['name2plot']="D1-1d_{lR2,afterAugust}" makeDirectory(caseInfo[alias]['targetDir']) base_1j="newton:/store/lmfa/fct/hluo/occigen/caseByGeometry/T/BirdCarreau/synthetic/flowRate/medium/fluctuation_off/1j" alias="D2-NN-1j_test_from0" caseInfo[alias]['sourceDir']=base_1j+"/"+"test_from0"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D2-NN-1j_{testFrom0}" caseInfo[alias]['latestTime']="0.3" makeDirectory(caseInfo[alias]['targetDir']) alias="D2-NN-1j_test_from0p3_forcingStep_St1_A_eq_0p05" caseInfo[alias]['sourceDir']=base_1j+"/"+"synthetic_phasedStepFrom_test_from_0/From0p3_3_of3"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D2-NN-1j_{testFrom0.3;Step,St=1,A=0.05}" makeDirectory(caseInfo[alias]['targetDir']) alias="D2-NN-1j_test_from0p3_forcingSinus_St3p2_A_eq_0p05" caseInfo[alias]['sourceDir']=base_1j+"/"+"synthetic_phasedSinusFrom_test_from_0/From0p3_2_of3"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D2-NN-1j_{testFrom0.3;Sinus,St=3.2,A=0.05}" caseInfo[alias]['latestTime']="0.6" makeDirectory(caseInfo[alias]['targetDir']) base_1jN="newton:/store/lmfa/fct/hluo/occigen/caseByGeometry/T/Newtonian/mapped/flowRate" alias="D1-1j_mapped" caseInfo[alias]['sourceDir']=base_1jN+"/"+"min/test_from_0p45_of3/syntheticMedium_FluctuationOff"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D1-1j_{mapped}" caseInfo[alias]['latestTime']="0.6" makeDirectory(caseInfo[alias]['targetDir']) alias="D2-1j_mapped" caseInfo[alias]['sourceDir']=base_1jN+"/"+"medium/test_from_0p45_of3/syntheticMedium_FluctuationOff"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D2-1j_{mapped}" caseInfo[alias]['latestTime']="0.9" makeDirectory(caseInfo[alias]['targetDir']) alias="D3-1j_mapped" caseInfo[alias]['sourceDir']=base_1jN+"/"+"max/test_from_0p45_of3/syntheticMedium_FluctuationOff"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D3-1j_{mapped}" caseInfo[alias]['latestTime']="0.6" makeDirectory(caseInfo[alias]['targetDir']) base_1jN="newton:/store/lmfa/fct/hluo/occigen/caseByGeometry/T/Newtonian/synthetic/flowRate/medium/fluctuation_off/1j" alias="D2-1j_syn" caseInfo[alias]['sourceDir']=base_1jN+"/"+"test_from_0"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D2-1j_{syn}" makeDirectory(caseInfo[alias]['targetDir']) alias="D2-NN-1j_syn" caseInfo[alias]['sourceDir']="newton:/store/lmfa/fct/hluo/occigen/caseByGeometry/T/BirdCarreau/synthetic/flowRate/medium/fluctuation_on/medium_cmptStream"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1j"+"/"+alias caseInfo[alias]['name2plot']="D2-NN-1j_{syn}" makeDirectory(caseInfo[alias]['targetDir']) alias="D2-NN-1k_syn" caseInfo[alias]['sourceDir']="newton:/store/lmfa/fct/hluo/occigen/caseByGeometry/testMesh/T/flux_medium/1k_4x4x4_BC_phasedOff"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1k"+"/"+alias caseInfo[alias]['name2plot']="D2-NN-1k_{syn}" caseInfo[alias]['latestTime']="0.3" makeDirectory(caseInfo[alias]['targetDir']) alias="D2-NN-1k_syn_forcing" caseInfo[alias]['sourceDir']="newton:/store/lmfa/fct/hluo/occigen/caseByGeometry/testMesh/T/flux_medium/1k_4x4x4_BC_phasedOn"#+dirName caseInfo[alias]['targetDir']="/store/T_c/1k"+"/"+alias caseInfo[alias]['name2plot']="D2-NN-1k_{syn,forcing}" caseInfo[alias]['latestTime']="0.6" makeDirectory(caseInfo[alias]['targetDir']) alias="t_r-2a_1_gradP0p703125" caseInfo[alias]['sourceDir']="newton:/store/lmfa/fct/hluo/occigen/caseByGeometry/pipes/shape_square/pw/2a_1/Newtonian/CASE_mapFields_From2b/gradP0_0p703125"#+dirName caseInfo[alias]['targetDir']="/store/t_r/2a_1"+"/"+alias caseInfo[alias]['name2plot']="2a\_1_{gradP0p703125}" makeDirectory(caseInfo[alias]['targetDir']) #for case in caseByAlias: # print "" # print "====================" # print "running Job for case with alias : %s" % case # stat, output = tryJob(caseInfo[case]['sourceDir'], caseInfo[case]['targetDir']) #print "--------------------" #print "print keys : ", caseInfo.keys() #print "writing database to dataBase.mat" #print "--------------------" #io.savemat("dataBase",caseInfo) import json print "--------------------" print "print keys : ", caseInfo.keys() print "writing database to json" print "--------------------" json.dump(caseInfo, open("database.txt",'w')) def read_database_and_rsync(database, case, dirName): print "" print "====================" print "running Job for case with alias : %s" % case print "sourceDir : " + database[case]['sourceDir'] stat, output = tryJob(database[case]['sourceDir']+'/'+dirName, database[case]['targetDir']) def main(): import json create_write_database_NoSync() database=json.load(open("/home/hluo/work/git/python/python_rsync/database.txt")) caseByAlias=[ "D1-1j_mapped", # test_from_0p45_of3 "D2-1j_mapped", # test_from_0p45_of3 "D3-1j_mapped", # test_from_0p45_of3 "D2-NN-1j_test_from0", "D2-NN-1j_test_from0p3_forcingSinus_St3p2_A_eq_0p05", "D2-NN-1k_syn", "D2-NN-1k_syn_forcing", ] for case in caseByAlias : read_database_and_rsync(database, case, 'postProcessing') read_database_and_rsync(database, case, '{'+database[case]['latestTime']+','+'constant,system}') main()
UTF-8
Python
false
false
8,706
py
161
rsync.py
134
0.644498
0.608316
0
223
38.040359
169
yuanying/remora
13,297,218,769,012
d947c3a096c2481b5d81d82c79617beabc2e56d3
393881678d95c52a54fdd0c06c32a56de0272cee
/remora/constants.py
f580f9de63879344d8b0be6f458c254068ae208c
[ "Apache-2.0" ]
permissive
https://github.com/yuanying/remora
a4211c8fa2fe6912bdb4408074a60cea73c70455
b61cfc7c5035d8dc9a887bbdd9da333b05c2f6d3
refs/heads/master
2020-03-27T12:29:00.016270
2019-12-03T06:44:35
2019-12-03T06:44:35
82,024,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import yaml __remora_root_dir = os.path.abspath(os.path.dirname(__file__)) DEFAULT_CONFIG_FILE_PATH = os.path.join(__remora_root_dir, 'default.yaml') DEFAULT_CONFIG = yaml.safe_load( open(DEFAULT_CONFIG_FILE_PATH).read() )
UTF-8
Python
false
false
815
py
92
constants.py
78
0.719018
0.71411
0
23
34.434783
78
rbawden/nematus
7,078,106,113,536
79394421161ca0681d023799ca1f67e552c73185
8d43e716cc9a7099baa2187d26a73c5feb94627f
/nematus/console.py
305c4d4a5df57e04f5b37653c71ded74ce2a01d0
[ "BSD-3-Clause" ]
permissive
https://github.com/rbawden/nematus
222f75495da65992b032dffa1903e2b392016a83
6929149aa297625a92d52215bc0d6ed9bea48d50
refs/heads/master
2021-01-01T06:41:06.727912
2019-05-10T19:02:29
2019-05-10T19:02:29
97,483,098
2
2
null
true
2017-07-17T14:03:34
2017-07-17T14:03:34
2017-07-16T08:22:36
2017-07-13T09:01:33
1,461
0
0
0
null
null
null
#!/usr/bin/env python """ Parses console arguments. """ import sys import argparse from abc import ABCMeta, abstractmethod from settings import DecoderSettings, TranslationSettings, ServerSettings class ConsoleInterface(object): """ All modes (abstract base class) """ __metaclass__ = ABCMeta def __init__(self): self._parser = argparse.ArgumentParser() self._add_shared_arguments() self._add_arguments() def _add_shared_arguments(self): """ Console arguments used in all modes """ self._parser.add_argument('--models', '-m', type=str, nargs = '+', required=True, metavar="MODEL", help="model to use. Provide multiple models (with same vocabulary) for ensemble decoding") self._parser.add_argument('-p', type=int, default=1, help="Number of processes (default: %(default)s))") self._parser.add_argument('--device-list', '-dl', type=str, nargs='*', required=False, metavar="DEVICE", help="User specified device list for multi-thread decoding (default: [])") self._parser.add_argument('-v', action="store_true", help="verbose mode.") @abstractmethod def _add_arguments(self): """ Console arguments used in specific mode """ pass # to be implemented in subclass def parse_args(self): """ Returns the parsed console arguments """ return self._parser.parse_args() def get_decoder_settings(self): """ Returns a `DecoderSettings` object based on the parsed console arguments. """ args = self.parse_args() return DecoderSettings(args) class ConsoleInterfaceDefault(ConsoleInterface): """ Console interface for default mode """ def _add_arguments(self): self._parser.add_argument('-k', type=int, default=5, help="Beam size (default: %(default)s))") self._parser.add_argument('-n', type=float, default=0.0, nargs="?", const=1.0, metavar="ALPHA", help="Normalize scores by sentence length (with argument, exponentiate lengths by ALPHA)") self._parser.add_argument('-c', action="store_true", help="Character-level") self._parser.add_argument('--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="Input file (default: standard input)") self._parser.add_argument('--output', '-o', type=argparse.FileType('w'), default=sys.stdout, metavar='PATH', help="Output file (default: standard output)") self._parser.add_argument('--output_alignment', '-a', type=argparse.FileType('w'), default=None, metavar='PATH', help="Output file for alignment weights (default: standard output)") self._parser.add_argument('--json_alignment', action="store_true", help="Output alignment in json format") self._parser.add_argument('--n-best', action="store_true", help="Write n-best list (of size k)") self._parser.add_argument('--suppress-unk', action="store_true", help="Suppress hypotheses containing UNK.") self._parser.add_argument('--print-word-probabilities', '-wp', action="store_true", help="Print probabilities of each word") self._parser.add_argument('--search_graph', '-sg', help="Output file for search graph rendered as PNG image") # added multisource arguments self._parser.add_argument('--aux_input', type=argparse.FileType('r'), default=[], metavar='PATH', help="Auxiliary input file", nargs='+') self._parser.add_argument('--predicted_trg', default=False, action='store_true', help='Use previous predicted target translation as additional input instead of auxiliary' 'input provided. Overrides any additional input specified on command line.') def get_translation_settings(self): """ Returns a `TranslationSettings` object based on the parsed console arguments. """ args = self.parse_args() return TranslationSettings(args) class ConsoleInterfaceServer(ConsoleInterface): """ Console interface for server mode Most parameters required in default mode are provided with each translation request to the server (see `nematus/server/request.py`). """ def _add_arguments(self): self._parser.add_argument('--style', default='Nematus', help='API style; see `README.md` (default: Nematus)') self._parser.add_argument('--host', default='localhost', help='Host address (default: localhost)') self._parser.add_argument('--port', type=int, default=8080, help='Host port (default: 8080)') def get_server_settings(self): """ Returns a `ServerSettings` object based on the parsed console arguments. """ args = self.parse_args() return ServerSettings(args)
UTF-8
Python
false
false
5,537
py
20
console.py
17
0.568358
0.56583
0
125
43.296
124
patriciamv/eDO_datathon
1,202,590,864,175
954c8d7f157a54b1f92d7697c0aae16dd6be16cd
0bbf66caa8787c634678754f01175e0a120d8b53
/code/03_train_keras_IMAGE.py
fa4423fe93505e815eed69abd5ce25ef2f8f4620
[]
no_license
https://github.com/patriciamv/eDO_datathon
5c1158f691c70b9336d5975aa32d7050d5f66159
5f0365234bed425848fe66ba7a4d7ef4e95fcd0a
refs/heads/master
2020-04-01T14:56:34.003550
2018-11-09T16:30:57
2018-11-09T16:30:57
153,314,539
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense, Conv2D, Flatten #one-hot encode target column y_train_clusters = to_categorical(y_train_clusters) #create model model = Sequential() #add model layers model.add(Conv2D(64, kernel_size=3, activation="relu", input_shape=(768,1024,1))) model.add(Conv2D(32, kernel_size=3, activation="relu")) model.add(Flatten()) model.add(Dense(3, activation="softmax")) #compile model using accuracy to measure model performance model.compile(optimizer='adam', loss='categorical_crossentropy') #train the model model.fit(x_train_gray[:3], y_train_clusters[:3], validation_data=(x_train_gray[:3], y_train_clusters[:3]), epochs=3) #predict first 3 images in the test set model.predict(x_train_gray[:3]) y_train_clusters
UTF-8
Python
false
false
813
py
13
03_train_keras_IMAGE.py
11
0.760148
0.729397
0
26
30.307692
117
feitianyiren/eums
7,653,631,765,040
c7fdb8486ff9ba23dba3d1a3f0007a095d498cd5
e08e0878ee9d85c7515b9fca89dba5a8b9f7417b
/eums/api/distribution_plan/distribution_plan_endpoint.py
b170e5b4f24a8d01ce06a7a24c197884e784e6e7
[ "MIT" ]
permissive
https://github.com/feitianyiren/eums
e61f0744e4c5e55e4cc98a273f7d8aa57bddb9e8
2b67cba8215d0fe67677d9177b252609ad74b0b4
refs/heads/master
2020-04-07T11:48:07.082880
2017-06-12T08:16:09
2017-06-12T08:16:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import logging from django.db import transaction from django.db.models import Q from rest_framework import serializers from rest_framework.decorators import detail_route from rest_framework.permissions import DjangoModelPermissions from rest_framework.response import Response from rest_framework.routers import DefaultRouter from rest_framework.viewsets import ModelViewSet from eums.api.filter.filter_mixin import RequestFilterMixin from eums.models import DistributionPlan, UserProfile, SystemSettings, ReleaseOrderItem, DistributionPlanNode, Runnable from eums.permissions.distribution_plan_permissions import DistributionPlanPermissions from eums.services.flow_scheduler import schedule_run_directly_for logger = logging.getLogger(__name__) class DistributionPlanSerializer(serializers.ModelSerializer): distributionplannode_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = DistributionPlan fields = ('id', 'programme', 'distributionplannode_set', 'location', 'consignee', 'delivery_date', 'track', 'contact_person_id', 'remark', 'total_value', 'is_received', 'type', 'number', 'number_of_items', 'confirmed', 'shipment_received', 'is_retriggered', 'time_limitation_on_distribution', 'tracked_date', 'is_auto_track_confirmed') class DistributionPlanViewSet(ModelViewSet, RequestFilterMixin): permission_classes = (DjangoModelPermissions, DistributionPlanPermissions) queryset = DistributionPlan.objects.all() serializer_class = DistributionPlanSerializer supported_filters = { 'programme': 'programme__name__icontains', 'from': 'delivery_date__gte', 'to': 'delivery_date__lte', 'consignee': 'consignee' } @transaction.atomic def perform_update(self, serializer): super(DistributionPlanViewSet, self).perform_update(serializer) distribution_plan_node_for_ip_filter = { 'distribution_plan': serializer.data['id'], 'tree_position': Runnable.IMPLEMENTING_PARTNER, 'location__isnull': True } DistributionPlanNode.objects.filter(**distribution_plan_node_for_ip_filter).update( location=serializer.data['location'], contact_person_id=serializer.data['contact_person_id']) @detail_route(['GET', ]) def answers(self, request, *args, **kwargs): delivery = DistributionPlan.objects.get(pk=(kwargs['pk'])) return Response(delivery.answers()) @detail_route(['GET', ]) def node_answers(self, request, *args, **kwargs): delivery = DistributionPlan.objects.get(pk=(kwargs['pk'])) return Response(delivery.node_answers()) @detail_route(['PATCH', ]) def retrigger_delivery(self, request, *args, **kwargs): delivery = DistributionPlan.objects.get(pk=(kwargs['pk'])) delivery.is_retriggered = True delivery.save() schedule_run_directly_for(delivery, 0) return Response() def list(self, request, *args, **kwargs): logged_in_user = request.user query = request.GET.get('query') user_profile, consignee = self.get_user_profile(logged_in_user) if user_profile and consignee: filtered_deliveries = self._deliveries_for_ip(request, consignee, query) return Response(self.get_serializer(filtered_deliveries, many=True).data) admin_deliveries = self._deliveries_for_admin(request, query) return Response(self.get_serializer(admin_deliveries, many=True).data) @staticmethod def get_user_profile(logged_in_user): try: user_profile = UserProfile.objects.get(user=logged_in_user) consignee = user_profile.consignee return user_profile, consignee except: return None, None def _deliveries_for_admin(self, request, query): return DistributionPlanViewSet.__filter_deliveries_by_query(query, DistributionPlan.objects.filter( **self.build_filters(request.query_params)).distinct()) def _deliveries_for_ip(self, request, consignee, query): filtered_distribution_plans = DistributionPlanViewSet.__filter_distribution_plans_depends_on_auto_track() filters = self.build_filters(request.query_params, **{'consignee': consignee}) deliveries = DistributionPlanViewSet.__filter_deliveries_by_query(query, filtered_distribution_plans.filter( **filters).distinct()) filtered_deliveries = filter( lambda x: x.is_partially_received() is None or x.is_partially_received() or x.is_retriggered, deliveries) return filtered_deliveries @staticmethod def __filter_distribution_plans_depends_on_auto_track(): if SystemSettings.objects.first().auto_track: return DistributionPlan.objects \ .filter(Q(distributionplannode__item__polymorphic_ctype=ReleaseOrderItem.TYPE_CODE) | Q(track=True)) \ .distinct() return DistributionPlan.objects.filter(Q(track=True) | (Q(track=False) & Q(is_auto_track_confirmed=True))) @staticmethod def __filter_deliveries_by_query(query, deliveries): return filter(lambda delivery: query in str(delivery.number()), deliveries) if query else deliveries distributionPlanRouter = DefaultRouter() distributionPlanRouter.register(r'distribution-plan', DistributionPlanViewSet)
UTF-8
Python
false
false
5,483
py
689
distribution_plan_endpoint.py
585
0.693234
0.693051
0
124
43.217742
119
Parthi3610/Learning_with_python3
11,089,605,602,396
452eb8a16992e67c75a839c9c2551ac317891fc8
aa39fedbaaad10e8ec69c54e9ebacac2a1473709
/src/chapter12/range1.py
2f3a2a5cacb73fae6c2a3d3608ef53880b8b5014
[]
no_license
https://github.com/Parthi3610/Learning_with_python3
1cd32e0fe29d784992e760e3ba2046f771a3010e
64fa9e7c519d4c164d65640bec7784e30bc7ff01
refs/heads/master
2022-12-27T17:13:18.284620
2020-10-13T03:12:19
2020-10-13T03:12:19
298,830,427
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random rng = random.Random() dice_throw = rng.randrange(1,7) print(dice_throw)
UTF-8
Python
false
false
89
py
24
range1.py
24
0.719101
0.696629
0
7
11.714286
31
Salekya/pythonScripts
12,910,671,692,549
780e434906965708410789ad8e247000a187a393
fde2a16b27cc93464a28769a2a0047a1bc728d8f
/Multiples.py
dc504c7fde5b3aa8b8dc52d612e80a454676a25e
[]
no_license
https://github.com/Salekya/pythonScripts
57d2868f914a17df42df3fd786a88cbf6673af61
fc299db658b5773682cd0f3f07f422944f0533af
refs/heads/master
2020-07-08T23:51:56.755945
2019-08-22T14:42:27
2019-08-22T14:42:27
203,815,058
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#s=("enter the numbers") def multiple(var): #var=range(1,101) ans = [] for j in range(1, var): tmp = "" if j%3==0: tmp = tmp + 'Fizz' if j%5==0: tmp += "Buzz" ans.append(tmp or j) return ans ans = multiple(50) print(ans)
UTF-8
Python
false
false
305
py
15
Multiples.py
15
0.442623
0.406557
0
20
13.95
30
Ascend/ModelZoo-PyTorch
3,985,729,689,533
f24b2658c830a1a4e766b940951ee4762ecbc938
2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02
/PyTorch/dev/cv/multimodality/st-gcn_ID2967_for_PyTorch/feeder/tools.py
69214786e59feaa6134c3e8a9f146a7b7e68b22b
[ "BSD-2-Clause", "Apache-2.0", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later" ]
permissive
https://github.com/Ascend/ModelZoo-PyTorch
4c89414b9e2582cef9926d4670108a090c839d2d
92acc188d3a0f634de58463b6676e70df83ef808
refs/heads/master
2023-07-19T12:40:00.512853
2023-07-17T02:48:18
2023-07-17T02:48:18
483,502,469
23
6
Apache-2.0
false
2022-10-15T09:29:12
2022-04-20T04:11:18
2022-10-10T08:03:54
2022-10-15T04:01:18
53,470
7
5
2
Python
false
false
# # BSD 3-Clause License # # Copyright (c) 2017 xxxx # All rights reserved. # Copyright 2021 Huawei Technologies Co., Ltd # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ============================================================================ # import numpy as np import random import os NPU_CALCULATE_DEVICE = 0 if os.getenv('NPU_CALCULATE_DEVICE') and str.isdigit(os.getenv('NPU_CALCULATE_DEVICE')): NPU_CALCULATE_DEVICE = int(os.getenv('NPU_CALCULATE_DEVICE')) def downsample(data_numpy, step, random_sample=True): # input: C,T,V,M begin = np.random.randint(step) if random_sample else 0 return data_numpy[:, begin::step, :, :] def temporal_slice(data_numpy, step): # input: C,T,V,M C, T, V, M = data_numpy.shape return data_numpy.reshape(C, T / step, step, V, M).transpose( (0, 1, 3, 2, 4)).reshape(C, T / step, V, step * M) def mean_subtractor(data_numpy, mean): # input: C,T,V,M # naive version if mean == 0: return C, T, V, M = data_numpy.shape valid_frame = (data_numpy != 0).sum(axis=3).sum(axis=2).sum(axis=0) > 0 begin = valid_frame.argmax() end = len(valid_frame) - valid_frame[::-1].argmax() data_numpy[:, :end, :, :] = data_numpy[:, :end, :, :] - mean return data_numpy def auto_pading(data_numpy, size, random_pad=False): C, T, V, M = data_numpy.shape if T < size: begin = random.randint(0, size - T) if random_pad else 0 data_numpy_paded = np.zeros((C, size, V, M)) data_numpy_paded[:, begin:begin + T, :, :] = data_numpy return data_numpy_paded else: return data_numpy def random_choose(data_numpy, size, auto_pad=True): # input: C,T,V,M C, T, V, M = data_numpy.shape if T == size: return data_numpy elif T < size: if auto_pad: return auto_pading(data_numpy, size, random_pad=True) else: return data_numpy else: begin = random.randint(0, T - size) return data_numpy[:, begin:begin + size, :, :] def random_move(data_numpy, angle_candidate=[-10., -5., 0., 5., 10.], scale_candidate=[0.9, 1.0, 1.1], transform_candidate=[-0.2, -0.1, 0.0, 0.1, 0.2], move_time_candidate=[1]): # input: C,T,V,M C, T, V, M = data_numpy.shape move_time = random.choice(move_time_candidate) node = np.arange(0, T, T * 1.0 / move_time).round().astype(int) node = np.append(node, T) num_node = len(node) A = np.random.choice(angle_candidate, num_node) S = np.random.choice(scale_candidate, num_node) T_x = np.random.choice(transform_candidate, num_node) T_y = np.random.choice(transform_candidate, num_node) a = np.zeros(T) s = np.zeros(T) t_x = np.zeros(T) t_y = np.zeros(T) # linspace for i in range(num_node - 1): a[node[i]:node[i + 1]] = np.linspace( A[i], A[i + 1], node[i + 1] - node[i]) * np.pi / 180 s[node[i]:node[i + 1]] = np.linspace(S[i], S[i + 1], node[i + 1] - node[i]) t_x[node[i]:node[i + 1]] = np.linspace(T_x[i], T_x[i + 1], node[i + 1] - node[i]) t_y[node[i]:node[i + 1]] = np.linspace(T_y[i], T_y[i + 1], node[i + 1] - node[i]) theta = np.array([[np.cos(a) * s, -np.sin(a) * s], [np.sin(a) * s, np.cos(a) * s]]) # perform transformation for i_frame in range(T): xy = data_numpy[0:2, i_frame, :, :] new_xy = np.dot(theta[:, :, i_frame], xy.reshape(2, -1)) new_xy[0] += t_x[i_frame] new_xy[1] += t_y[i_frame] data_numpy[0:2, i_frame, :, :] = new_xy.reshape(2, V, M) return data_numpy def random_shift(data_numpy): # input: C,T,V,M C, T, V, M = data_numpy.shape data_shift = np.zeros(data_numpy.shape) valid_frame = (data_numpy != 0).sum(axis=3).sum(axis=2).sum(axis=0) > 0 begin = valid_frame.argmax() end = len(valid_frame) - valid_frame[::-1].argmax() size = end - begin bias = random.randint(0, T - size) data_shift[:, bias:bias + size, :, :] = data_numpy[:, begin:end, :, :] return data_shift def openpose_match(data_numpy): C, T, V, M = data_numpy.shape assert (C == 3) score = data_numpy[2, :, :, :].sum(axis=1) # the rank of body confidence in each frame (shape: T-1, M) rank = (-score[0:T - 1]).argsort(axis=1).reshape(T - 1, M) # data of frame 1 xy1 = data_numpy[0:2, 0:T - 1, :, :].reshape(2, T - 1, V, M, 1) # data of frame 2 xy2 = data_numpy[0:2, 1:T, :, :].reshape(2, T - 1, V, 1, M) # square of distance between frame 1&2 (shape: T-1, M, M) distance = ((xy2 - xy1)**2).sum(axis=2).sum(axis=0) # match pose forward_map = np.zeros((T, M), dtype=int) - 1 forward_map[0] = range(M) for m in range(M): choose = (rank == m) forward = distance[choose].argmin(axis=1) for t in range(T - 1): distance[t, :, forward[t]] = np.inf forward_map[1:][choose] = forward assert (np.all(forward_map >= 0)) # string data for t in range(T - 1): forward_map[t + 1] = forward_map[t + 1][forward_map[t]] # generate data new_data_numpy = np.zeros(data_numpy.shape) for t in range(T): new_data_numpy[:, t, :, :] = data_numpy[:, t, :, forward_map[ t]].transpose(1, 2, 0) data_numpy = new_data_numpy # score sort trace_score = data_numpy[2, :, :, :].sum(axis=1).sum(axis=0) rank = (-trace_score).argsort() data_numpy = data_numpy[:, :, :, rank] return data_numpy def top_k_by_category(label, score, top_k): instance_num, class_num = score.shape rank = score.argsort() hit_top_k = [[] for i in range(class_num)] for i in range(instance_num): l = label[i] hit_top_k[l].append(l in rank[i, -top_k:]) accuracy_list = [] for hit_per_category in hit_top_k: if hit_per_category: accuracy_list.append(sum(hit_per_category) * 1.0 / len(hit_per_category)) else: accuracy_list.append(0.0) return accuracy_list def calculate_recall_precision(label, score): instance_num, class_num = score.shape rank = score.argsort() confusion_matrix = np.zeros([class_num, class_num]) for i in range(instance_num): true_l = label[i] pred_l = rank[i, -1] confusion_matrix[true_l][pred_l] += 1 precision = [] recall = [] for i in range(class_num): true_p = confusion_matrix[i][i] false_n = sum(confusion_matrix[i, :]) - true_p false_p = sum(confusion_matrix[:, i]) - true_p precision.append(true_p * 1.0 / (true_p + false_p)) recall.append(true_p * 1.0 / (true_p + false_n)) return precision, recall
UTF-8
Python
false
false
8,348
py
11,303
tools.py
8,028
0.585889
0.568759
0
237
34.227848
88
webclinic017/new_ant
4,398,046,517,376
b178edaee8197953fd42bd12dc415e7641fa9ce1
fe3de107d45887065fecddd2d7a2a55c603e888f
/ant/ergate/migrations/0004_simulation_count.py
0247a26bf09370560a89ad067569aef0b4263e47
[]
no_license
https://github.com/webclinic017/new_ant
9e3fe17d32b078d2fad99c1d07266dd057658019
11e7f180541367ea475c75f83239f0946b021765
refs/heads/master
2023-01-19T04:22:34.541074
2020-11-26T04:03:05
2020-11-26T04:03:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.1.2 on 2020-11-13 07:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ergate', '0003_auto_20201113_1546'), ] operations = [ migrations.AddField( model_name='simulation', name='count', field=models.IntegerField(blank=True, null=True), ), ]
UTF-8
Python
false
false
415
py
53
0004_simulation_count.py
25
0.566265
0.491566
0
18
21.055556
61
dahalbhawan/matific
19,542,101,200,493
de61c51943a6bbeb9879d8b64a4b08f642766112
8321fb5370726c144615cb94e6b2a322096c5ee6
/basketball/base/signals.py
3588d9d2f735894d649f8e9a82ae97cc78e6d16c
[]
no_license
https://github.com/dahalbhawan/matific
da1306f9eac7f34b98b43c6b9d191f9b4ce5d0e9
1ec15eccb1b7b9a9fa0a82e20b98f51210ed22a9
refs/heads/master
2023-07-03T06:49:53.544253
2021-07-28T05:46:31
2021-07-28T05:46:31
389,497,291
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.utils import timezone from django.db.models.signals import post_save from django.contrib.auth.signals import user_logged_in, user_logged_out from django.conf.global_settings import TIME_ZONE from django.contrib.auth import get_user_model from .models import Player, Coach, LeagueAdmin, Usage from rest_framework.authtoken.models import Token User = get_user_model() # Signal receiver to create Player, Coach or LeagueAdmin instance, whichever appropriate, as User instance is created is created def role_created(sender, instance, **kwargs): if instance.role == 1: Player.objects.get_or_create(user=instance) elif instance.role == 2: Coach.objects.get_or_create(user=instance) elif instance.role == 3: LeagueAdmin.objects.get_or_create(user=instance) else: pass post_save.connect(receiver=role_created, sender=User) # Signal to automatically trigger Token creation when User instance is created def create_auth_token(sender, instance, **kwargs): Token.objects.get_or_create(user=instance) post_save.connect(receiver=create_auth_token, sender=User) # Signal to update usage statistics (login_times) upon user login def update_login_times(sender, user, **kwargs): try: usage, created = Usage.objects.get_or_create(user=user) usage.login_times += 1 usage.save() except Usage.DoesNotExist: pass user_logged_in.connect(receiver=update_login_times) # Signal to update usage statictics (usage_time) upon user logout def update_usage_time(sender, user, **kwargs): try: usage, created = Usage.objects.get_or_create(user=user) user.last_logout = timezone.now() user.save() recent_usage = -(user.last_login - user.last_logout).total_seconds()/3600 #recent usage duration in hours print(user.last_logout) usage.usage_time += recent_usage usage.save() except Usage.DoesNotExist: pass user_logged_out.connect(receiver=update_usage_time)
UTF-8
Python
false
false
2,010
py
34
signals.py
21
0.719403
0.715423
0
56
34.910714
128
steadydoer/problem-solving
19,353,122,641,349
c93747ab7e08cf3f98657ab2d79fa73a65618de9
3488b7c4ed26ccb0c650711574e8308bc9eacf2e
/programmers/level3/12946/solution.py
9d519a1dd0d807b6e96211281216c5b144756e0d
[]
no_license
https://github.com/steadydoer/problem-solving
0d50109d990e82d5204f90e77e34d346cfd69926
e9f52acad5473afdab4990cb99cceeec3df91b08
refs/heads/master
2021-07-16T05:10:52.416451
2020-06-10T05:46:54
2020-06-10T05:46:54
174,530,297
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Programmers Coding Test Practice # Level 3 # # https://programmers.co.kr/learn/courses/30/lessons/12946 # # ============================================================================== def hanoi(start, layover, end, n, answer): if n == 1: answer.append([start, end]) return else: hanoi(start, end, layover, n-1, answer) answer.append([start, end]) hanoi(layover, start, end, n-1, answer) return def solution(n): answer = [] hanoi(1, 2, 3, n, answer) return answer if __name__ == "__main__": assert solution(2) == [[1, 2], [1, 3], [2, 3]]
UTF-8
Python
false
false
624
py
70
solution.py
62
0.485577
0.451923
0
27
22.111111
80
SySS-Research/Seth
2,954,937,542,390
ae60f27d36b7c8d46b9ae5bf587ffd57eb1c1efe
9c2fef12f06d7627ed264c97d23d971d8b14d4e6
/seth/consts.py
e3fe5e0abeb4cca8a716e1ff8a5e87d5dd7c4279
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
https://github.com/SySS-Research/Seth
96f2f52a7d6849a0616695c218580b72f0a564b2
8b6e36c8437db0a2e1300e2077d7ead41dcf8f9b
refs/heads/master
2023-02-21T01:06:52.562947
2023-02-09T14:27:53
2023-02-09T14:27:53
84,575,372
1,331
369
MIT
false
2022-11-11T12:24:17
2017-03-10T15:46:38
2022-11-11T05:29:33
2022-11-11T12:24:16
2,015
1,235
335
13
Python
false
false
from binascii import hexlify, unhexlify TERM_PRIV_KEY = { # little endian, from [MS-RDPBCGR].pdf "n": [ 0x3d, 0x3a, 0x5e, 0xbd, 0x72, 0x43, 0x3e, 0xc9, 0x4d, 0xbb, 0xc1, 0x1e, 0x4a, 0xba, 0x5f, 0xcb, 0x3e, 0x88, 0x20, 0x87, 0xef, 0xf5, 0xc1, 0xe2, 0xd7, 0xb7, 0x6b, 0x9a, 0xf2, 0x52, 0x45, 0x95, 0xce, 0x63, 0x65, 0x6b, 0x58, 0x3a, 0xfe, 0xef, 0x7c, 0xe7, 0xbf, 0xfe, 0x3d, 0xf6, 0x5c, 0x7d, 0x6c, 0x5e, 0x06, 0x09, 0x1a, 0xf5, 0x61, 0xbb, 0x20, 0x93, 0x09, 0x5f, 0x05, 0x6d, 0xea, 0x87 ], # modulus "d": [ 0x87, 0xa7, 0x19, 0x32, 0xda, 0x11, 0x87, 0x55, 0x58, 0x00, 0x16, 0x16, 0x25, 0x65, 0x68, 0xf8, 0x24, 0x3e, 0xe6, 0xfa, 0xe9, 0x67, 0x49, 0x94, 0xcf, 0x92, 0xcc, 0x33, 0x99, 0xe8, 0x08, 0x60, 0x17, 0x9a, 0x12, 0x9f, 0x24, 0xdd, 0xb1, 0x24, 0x99, 0xc7, 0x3a, 0xb8, 0x0a, 0x7b, 0x0d, 0xdd, 0x35, 0x07, 0x79, 0x17, 0x0b, 0x51, 0x9b, 0xb3, 0xc7, 0x10, 0x01, 0x13, 0xe7, 0x3f, 0xf3, 0x5f ], # private exponent "e": [ 0x5b, 0x7b, 0x88, 0xc0 ] # public exponent } # http://www.millisecond.com/support/docs/v5/html/language/scancodes.htm SCANCODE = { 0: None, 1: "ESC", 2: "1", 3: "2", 4: "3", 5: "4", 6: "5", 7: "6", 8: "7", 9: "8", 10: "9", 11: "0", 12: "-", 13: "=", 14: "Backspace", 15: "Tab", 16: "Q", 17: "W", 18: "E", 19: "R", 20: "T", 21: "Y", 22: "U", 23: "I", 24: "O", 25: "P", 26: "[", 27: "]", 28: "Enter", 29: "CTRL", 30: "A", 31: "S", 32: "D", 33: "F", 34: "G", 35: "H", 36: "J", 37: "K", 38: "L", 39: ";", 40: "'", 41: "`", 42: "LShift", 43: "\\", 44: "Z", 45: "X", 46: "C", 47: "V", 48: "B", 49: "N", 50: "M", 51: ",", 52: ".", 53: "/", 54: "RShift", 55: "PrtSc", 56: "Alt", 57: "Space", 58: "Caps", 59: "F1", 60: "F2", 61: "F3", 62: "F4", 63: "F5", 64: "F6", 65: "F7", 66: "F8", 67: "F9", 68: "F10", 69: "Num", 70: "Scroll", 71: "Home (7)", 72: "Up (8)", 73: "PgUp (9)", 74: "-", 75: "Left (4)", 76: "Center (5)", 77: "Right (6)", 78: "+", 79: "End (1)", 80: "Down (2)", 81: "PgDn (3)", 82: "Ins", 83: "Del", #91: "LMeta", 92: "RMeta", } REV_SCANCODE = dict([(v, k) for k, v in SCANCODE.items()]) REV_SCANCODE[" "] = REV_SCANCODE["Space"] REV_SCANCODE["LMeta"] = 91 # https://support.microsoft.com/de-de/help/324097/list-of-language-packs-and-their-codes-for-windows-2000-domain-control KBD_LAYOUT_CNTRY = { 0x436: b"Afrikaans", 0x041c: b"Albanian", 0x401: b"Arabic_Saudi_Arabia", 0x801: b"Arabic_Iraq", 0x0c01: b"Arabic_Egypt", 0x1001: b"Arabic_Libya", 0x1401: b"Arabic_Algeria", 0x1801: b"Arabic_Morocco", 0x1c01: b"Arabic_Tunisia", 0x2001: b"Arabic_Oman", 0x2401: b"Arabic_Yemen", 0x2801: b"Arabic_Syria", 0x2c01: b"Arabic_Jordan", 0x3001: b"Arabic_Lebanon", 0x3401: b"Arabic_Kuwait", 0x3801: b"Arabic_UAE", 0x3c01: b"Arabic_Bahrain", 0x4001: b"Arabic_Qatar", 0x042b: b"Armenian", 0x042c: b"Azeri_Latin", 0x082c: b"Azeri_Cyrillic", 0x042d: b"Basque", 0x423: b"Belarusian", 0x402: b"Bulgarian", 0x403: b"Catalan", 0x404: b"Chinese_Taiwan", 0x804: b"Chinese_PRC", 0x0c04: b"Chinese_Hong_Kong", 0x1004: b"Chinese_Singapore", 0x1404: b"Chinese_Macau", 0x041a: b"Croatian", 0x405: b"Czech", 0x406: b"Danish", 0x413: b"Dutch_Standard", 0x813: b"Dutch_Belgian", 0x409: b"English_United_States", 0x809: b"English_United_Kingdom", 0x0c09: b"English_Australian", 0x1009: b"English_Canadian", 0x1409: b"English_New_Zealand", 0x1809: b"English_Irish", 0x1c09: b"English_South_Africa", 0x2009: b"English_Jamaica", 0x2409: b"English_Caribbean", 0x2809: b"English_Belize", 0x2c09: b"English_Trinidad", 0x3009: b"English_Zimbabwe", 0x3409: b"English_Philippines", 0x425: b"Estonian", 0x438: b"Faeroese", 0x429: b"Farsi", 0x040b: b"Finnish", 0x040c: b"French_Standard", 0x080c: b"French_Belgian", 0x0c0c: b"French_Canadian", 0x100c: b"French_Swiss", 0x140c: b"French_Luxembourg", 0x180c: b"French_Monaco", 0x437: b"Georgian", 0x407: b"German_Standard", 0x807: b"German_Swiss", 0x0c07: b"German_Austrian", 0x1007: b"German_Luxembourg", 0x1407: b"German_Liechtenstein", 0x408: b"Greek", 0x040d: b"Hebrew", 0x439: b"Hindi", 0x040e: b"Hungarian", 0x040f: b"Icelandic", 0x421: b"Indonesian", 0x410: b"Italian_Standard", 0x810: b"Italian_Swiss", 0x411: b"Japanese", 0x043f: b"Kazakh", 0x457: b"Konkani", 0x412: b"Korean", 0x426: b"Latvian", 0x427: b"Lithuanian", 0x042f: b"FYRO Macedonian", 0x043e: b"Malay_Malaysia", 0x083e: b"Malay_Brunei_Darussalam", 0x044e: b"Marathi", 0x414: b"Norwegian_Bokmal", 0x814: b"Norwegian_Nynorsk", 0x415: b"Polish", 0x416: b"Portuguese_Brazilian", 0x816: b"Portuguese_Standard", 0x418: b"Romanian", 0x419: b"Russian", 0x044f: b"Sanskrit", 0x081a: b"Serbian_Latin", 0x0c1a: b"Serbian_Cyrillic", 0x041b: b"Slovak", 0x424: b"Slovenian", 0x040a: b"Spanish_Traditional_Sort", 0x080a: b"Spanish_Mexican", 0x0c0a: b"Spanish_Modern_Sort", 0x100a: b"Spanish_Guatemala", 0x140a: b"Spanish_Costa_Rica", 0x180a: b"Spanish_Panama", 0x1c0a: b"Spanish_Dominican_Republic", 0x200a: b"Spanish_Venezuela", 0x240a: b"Spanish_Colombia", 0x280a: b"Spanish_Peru", 0x2c0a: b"Spanish_Argentina", 0x300a: b"Spanish_Ecuador", 0x340a: b"Spanish_Chile", 0x380a: b"Spanish_Uruguay", 0x3c0a: b"Spanish_Paraguay", 0x400a: b"Spanish_Bolivia", 0x440a: b"Spanish_El_Salvador", 0x480a: b"Spanish_Honduras", 0x4c0a: b"Spanish_Nicaragua", 0x500a: b"Spanish_Puerto_Rico", 0x441: b"Swahili", 0x041d: b"Swedish", 0x081d: b"Swedish_Finland", 0x449: b"Tamil", 0x444: b"Tatar", 0x041e: b"Thai", 0x041f: b"Turkish", 0x422: b"Ukrainian", 0x420: b"Urdu", 0x443: b"Uzbek_Latin", 0x843: b"Uzbek_Cyrillic", 0x042a: b"Vietnamese", } RELAY_PORT=13389 SERVER_RESPONSES = [ "030000130ed00000123400020f080001000000", "0300007e02f0807f66740a0100020100301a020122020103020100020101020100020101020300fff80201020450000500147c00012a14760a01010001c0004d63446e3a010c1000040008000100000003000000030c1000eb030400ec03ed03ee03ef03020c0c000000000000000000040c0600f003080c080005030000", "0300000b02f0802e000008", "300da003020104a4060204c000005e", ] SERVER_RESPONSES = [unhexlify(x.encode()) for x in SERVER_RESPONSES]
UTF-8
Python
false
false
6,621
py
10
consts.py
8
0.60444
0.403715
0
183
35.180328
259
rikkouri/project-a
9,036,611,195,462
bfe85d95a4b83e3371eed8fe69536433e05c68ca
73c5b421321354bab94d2950220c66269bbbf14c
/Exercises/Arithmetic Operators Solution.py
2952db577926ff64d121fc8cf88b2614e922072d
[]
no_license
https://github.com/rikkouri/project-a
38554f50992da356c40021ba3f044661afca3505
95fe44a8c607ca3716997421645fe605d452ab5a
refs/heads/master
2021-01-10T05:10:51.374379
2016-03-07T11:44:07
2016-03-07T11:44:07
49,488,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Prompt the user to input two values operandOne = raw_input('Enter a value: ') operandTwo = raw_input('Enter another value: ') #Now perform the sums and output the result print( operandOne + ' + ' + operandTwo + ' = ' + str( int(operandOne) + int(operandTwo) ) ) print( operandOne + ' - ' + operandTwo + ' = ' + str( int(operandOne) - int(operandTwo) ) ) print( operandOne + ' * ' + operandTwo + ' = ' + str( int(operandOne) * int(operandTwo) ) ) print( operandOne + ' / ' + operandTwo + ' = ' + str( int(int(operandOne) / int(operandTwo)) ) ) print( operandOne + ' % ' + operandTwo + ' = ' + str( int(operandOne) % int(operandTwo) ) ) print( operandOne + ' ** ' + operandTwo + ' = ' + str( int(operandOne) ** int(operandTwo) ) )
UTF-8
Python
false
false
732
py
46
Arithmetic Operators Solution.py
29
0.621585
0.621585
0
11
65.454545
96
dwillis/nicar2019-scraping
15,659,450,768,360
e4286ae601dc5b4d69351f8da1d8b59213ca79f1
cb9841a060c8f487a76c0ec950d9c76fdcee6291
/scraping_site/form_with_post_request.py
b5f74f73e4a10a9f99f91af6e01661ad87075c57
[]
no_license
https://github.com/dwillis/nicar2019-scraping
4c00f17a9fcbb5747e392378de2ff89702294f26
0ee91d0f39bda2e979edb07949e4739d3a9f6a78
refs/heads/master
2023-03-26T09:37:15.264478
2021-03-20T13:47:24
2021-03-20T13:47:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask import Blueprint, render_template, request from .data_api import get_race_results, get_years_offices bp = Blueprint('form_with_post_request', __name__) @bp.route('/5', methods=['GET', 'POST']) def form_with_post_request(): year = request.values.get('year') office = request.values.get('office') if year is not None and office is not None: results = get_race_results(year, office) return render_template( 'simple-table-multistep.html', results=results, path=request.path ) years, offices = get_years_offices(year=year) return render_template( 'results-form-multistep.html', year=year, years=years, offices=offices, )
UTF-8
Python
false
false
751
py
44
form_with_post_request.py
25
0.624501
0.623169
0
29
24.896552
57
nikblack3/Machine-Learning
3,556,232,944,720
0274f9cb593143f8727877c6d8220d9b0aa78a50
0a63fb23f46f6d452514f6962b41bcbbca7172f7
/A1/Soln/faces.py
7d8a561d4be7fd6851d068eab32a9ee4b8073d86
[]
no_license
https://github.com/nikblack3/Machine-Learning
d145be0a94315db5dbce9faa95b947310e432a8f
039771df03db0a022d649ce2da54ded50e443356
refs/heads/master
2020-03-16T15:04:48.367525
2018-03-30T21:56:49
2018-03-30T21:56:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from util import * import get_data from pylab import * import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook import random import time from scipy.misc import * import matplotlib.image as mpimg import os from scipy.ndimage import filters import urllib import itertools # ----------- HELPER FUNCTIONS ----------- def process_image(im): """ Process the given image and output the data Args: im (str): path to the image Returns: the processed data """ data = imread("./cropped/" + im) / 225. data = reshape(data, 1024) data = np.insert(data, 0, 1) return data # noinspection PyTypeChecker def predict(im, theta): """ Predicts the image using trained theta. Args: im (str): the image file name theta (vector[float]): trained theta Returns: prediction based on the trained theta """ data = process_image(im) prediction = np.dot(theta.T, data) return prediction # ----------- Answers ----------- # Part 1 # See faces.pdf # Part 2 def divide_sets(actor, training_size = 0, path = "./cropped"): """ Given the downloaded data set and a selected actor, return three randomized list of training set, validation set and test set. Args: actor (str): The selected actor training_size (int): The size of the training set. return the full training set if set to 0 path (str): The path to the cropped files Returns: ([training set], [validation set], [test set]) where |training set| >= 70 |validation set| == 10 |test set| == 10 """ if actor not in actor_count.keys(): print "Error: actor [{1}] is not included in the data set".format(actor) raise ValueError("Actor not in the data set") if actor_count[actor] < 90: print "Warning: actor [{0}] only has [{1}] of images, which does not have " \ "enough photos to satisfy the training " \ "requirement".format(actor, actor_count[actor]) all_actor_image = [image for image in os.listdir(path) if actor in image] np.random.shuffle(all_actor_image) test_set = all_actor_image[0: 10] validation_set = all_actor_image[10:20] training_set = all_actor_image[20:] if training_size != 0: training_set = training_set[:min([training_size, len(training_set)])] return training_set, validation_set, test_set # Part 3 # noinspection PyTypeChecker def classify(actor1 = "baldwin", actor2 = "carell", training_size = 0, validate = True, test = True): """ Train a linear classifier on actors 1 and 2 Args: actor1 (str): name of the first actor. We label actor1 as 1 actor2 (str): name of the second actor. We label actor2 as 0 training_size (int): number of elements in the training set. train the full set if size given is 0. validate (bool): indicate if the function call validates the validation set test (bool): indicate if the function call tests on the test set Returns: The trained theta vector """ if actor1 not in actor_names or actor2 not in actor_names: print "Error: actor(s) given is not in the data set" raise ValueError # divide all sets actor1_training_set, actor1_validation_set, \ actor1_test_set = divide_sets(actor1, training_size) actor2_training_set, actor2_validation_set, \ actor2_test_set = divide_sets(actor2, training_size) training_set = actor1_training_set + actor2_training_set validation_set = actor1_validation_set + actor2_validation_set test_set = actor1_test_set + actor2_test_set print "\n----------- Training on {} data: -----------".format(len(training_set)) # initialize input, output and theta to zeros # Note: we are removing the bias term by adding a dummy term in x: x_0 # x: N * D matrix # y: N * 1 vector # theta: D * 1 vector x = np.zeros((len(training_set), 1025)) y = np.zeros((len(training_set), 1)) theta = np.zeros((1025, 1)) # fill the data with given data set i = 0 for image in actor1_training_set: data = process_image(image) x[i] = data y[i] = 1 i += 1 for image in actor2_training_set: data = process_image(image) x[i] = data y[i] = 0 i += 1 # use gradient descent to train theta if training_size >= 20: theta = grad_descent(loss, dlossdx, x, y, theta, 0.005) else: theta = grad_descent(loss, dlossdx, x, y, theta, 0.001) # validate on validation set if validate is True: print "----------- Validating -----------" total = len(validation_set) correct_count = 0 for im in validation_set: prediction = predict(im, theta) if im in actor1_validation_set and norm(prediction) > 0.5: correct_count += 1 elif im in actor2_validation_set and norm(prediction) <= 0.5: correct_count += 1 print "Result on [Validation Set]: {} / {}\n".format(correct_count, total) if test is True: # test on test set print "----------- Testing -----------" total = len(test_set) correct_count = 0 for im in test_set: prediction = predict(im, theta) if im in actor1_validation_set and norm(prediction) > 0.5: correct_count += 1 elif im in actor2_validation_set and norm(prediction) <= 0.5: correct_count += 1 print "Result on [Test Set]: {} / {}".format(correct_count, total) return theta # Part 4 # TODO: save RGB image # a) def plot_theta(actor1 = "baldwin", actor2 = "carell", compare_size = 2): """ compare the thetas of different number of training sets Args: actor1 (str): the first actor's name actor2 (str): the second actor's name compare_size (int): the comparing training set's size. train full set if 0. Returns: """ full_theta = classify(actor1, actor2, validate = False, test = False) # Note: theta contains a bias term as the first element so drop it full_theta = np.delete(full_theta, 0) full_theta = np.reshape(full_theta, (32, 32)) # ret = np.empty((full_theta.shape[0], full_theta.shape[1], 3), dtype=np.uint8) # ret[:, :, 0] = full_theta # ret[:, :, 1] = full_theta # ret[:, :, 2] = full_theta imsave("./Report/images/4/a_full_theta.jpg", full_theta) # plt.imsave("./Report/images/4/a_full_theta.jpg", ret, cmap = "RdBu") # toimage(full_theta).save("./Report/images/4/a_full_theta.jpg") two_theta = classify(actor1, actor2, compare_size, validate = False, test = False) # print two_theta.shape two_theta = np.delete(two_theta, 0) two_theta = np.resize(two_theta, (32, 32)) # ret = np.empty((two_theta.shape[0], two_theta.shape[1], 3), dtype=np.uint8) # ret[:, :, 0] = two_theta # ret[:, :, 1] = two_theta # ret[:, :, 2] = two_theta imsave("./Report/images/4/a_two_theta.jpg", two_theta) # plt.imsave("./Report/images/4/a_two_theta.jpg", ret, cmap = "RdBu") # toimage(two_theta).save("./Report/images/4/a_two_theta.jpg") # b) def visualize_gradient(): pass # Part 5 act = ['Lorraine Bracco', 'Peri Gilpin', 'Angie Harmon', 'Alec Baldwin', 'Bill Hader', 'Steve Carell'] def overfitting(): """ Overfit the data We denote male as 1 and female as 0 Returns: """ training_sizes = [5, 10, 20, 50, 100, 150] thetas = [np.zeros((1025, 1)) for i in range(6)] training_actor_names = [a.split()[1].lower() for a in act] actor_genders = {'bracco': 0, 'chenoweth': 0, 'drescher': 0, 'ferrera': 0, 'gilpin': 0, 'harmon': 0, 'baldwin': 1, 'butler': 1, 'carell': 1, 'hader': 1, 'radcliffe': 1, 'vartan': 1} # test_actor_names = [a for a in actor_names if a not in training_actor_names] training_result = dict() validation_result = dict() for i in range(len(training_sizes)): print "----------- Training on size {} -----------".format(training_sizes[i]) actor_training_set, actor_validation_set, \ actor_test_set = dict(), dict(), dict() for a in training_actor_names: actor_training_set[a], actor_validation_set[a], \ actor_test_set[a] = divide_sets(a, training_sizes[i]) print "[{}]: {}".format(a, len(actor_training_set[a])) # get all training data training_set = list( itertools.chain.from_iterable(actor_training_set.values())) validation_set = list( itertools.chain.from_iterable(actor_validation_set.values())) x = np.zeros((len(training_set), 1025)) y = np.zeros((len(training_set), 1)) # fill the data with given data set j = 0 for actor in actor_training_set.keys(): for image in actor_training_set[actor]: data = process_image(image) x[j] = data y[j] = actor_genders[actor] j += 1 thetas[i] = grad_descent(loss, dlossdx, x, y, thetas[i], 0.005) # test on training set total = sum( [len(actor_training_set[actor]) for actor in actor_training_set.keys()]) correct_count = 0 for actor in actor_training_set.keys(): for im in actor_training_set[actor]: prediction = predict(im, thetas[i]) if actor_genders[actor] == 1 and norm(prediction) > 0.5: correct_count += 1 elif actor_genders[actor] == 0 and norm(prediction) <= 0.5: correct_count += 1 correct_rate = 100. * correct_count / total training_result[training_sizes[i]] = correct_rate print "Result on [Training Set]: {} / {}\n".format(correct_count, total) # test on validation set total = sum( [len(actor_validation_set[actor]) for actor in actor_validation_set.keys()]) correct_count = 0 for actor in actor_validation_set.keys(): for im in actor_validation_set[actor]: prediction = predict(im, thetas[i]) if actor_genders[actor] == 1 and norm(prediction) > 0.5: correct_count += 1 elif actor_genders[actor] == 0 and norm(prediction) <= 0.5: correct_count += 1 correct_rate = 100. * correct_count / total validation_result[training_sizes[i]] = correct_rate print "Result on [Validation Set]: {} / {}\n".format(correct_count, total) plt.plot(training_sizes, [training_result[size] for size in training_sizes], color = "r", linewidth = 2, marker = "o", label = "Training Set") plt.plot(training_sizes, [validation_result[size] for size in training_sizes], color = "b", linewidth = 2, marker = "o", label = "Validation Set") plt.title("Training Set Size VS Performance") plt.xlabel("Training Set Size / images") plt.ylabel("Performance / %") plt.legend() plt.savefig("./Report/images/5/1.jpg") # Part 6 # see faces.pdf for calculations and util.py for implementations # Part 7 def multiclass_classification(test_training = True, validate = True): # initialize sets training_actor_names = [a.split()[1].lower() for a in act] training_set, validation_set, test_set = dict(), dict(), dict() for actor in training_actor_names: training_set[actor], validation_set[actor], \ test_set[actor] = divide_sets(actor) # get input data x = np.zeros((len(list(itertools.chain.from_iterable(training_set.values()))), 1025)) y = np.zeros((len(list(itertools.chain.from_iterable(training_set.values()))), len(training_actor_names))) k = 0 for i in range(len(training_actor_names)): for im in training_set[training_actor_names[i]]: x[k] = process_image(im) y[k][i] = 1 k += 1 # train theta theta = np.zeros((len(training_actor_names), 1025)) theta = grad_descent_m(loss_m, dlossdx_m, x, y, theta, 0.0000001).T # validate on training set if test_training is True: print "----------- Testing on Training Set -----------" total = len(list(itertools.chain.from_iterable(training_set.values()))) correct_count = 0 for i in range(len(training_actor_names)): for im in training_set[training_actor_names[i]]: prediction = predict(im, theta) prediction = np.argmax(prediction) if prediction == i: correct_count += 1 print "Result on [Training Set]: {} / {}\n".format(correct_count, total) # validate on validation set if validate is True: print "----------- Testing on Validation Set -----------" total = len(list(itertools.chain.from_iterable(validation_set.values()))) correct_count = 0 for i in range(len(training_actor_names)): for im in validation_set[training_actor_names[i]]: prediction = predict(im, theta) prediction = np.argmax(prediction) if prediction == i: correct_count += 1 print "Result on [Validation Set]: {} / {}\n".format(correct_count, total) return theta # Part 8 def plot_theta_multiclass(): training_actor_names = [a.split()[1].lower() for a in act] thetas = multiclass_classification(False, False).T for i in range(thetas.shape[0]): theta = np.delete(thetas[i], 0) theta = np.reshape(theta, (32, 32)) # ret = np.empty((theta.shape[0], theta.shape[1], 3), dtype=np.uint8) # ret[:, :, 0] = theta # ret[:, :, 1] = theta # ret[:, :, 2] = theta imsave("./Report/images/8/{}.jpg".format(training_actor_names[i]), theta) # imsave("./Report/images/8/{}.jpg".format(i), theta, cmap="RdBu") if __name__ == "__main__": # part 1 # part 2 actor = "baldwin" a, b, c = divide_sets(actor) print "{}\n{}\n{}".format(a, b, c) # part 3 classify() # part 4 # a) plot_theta() # b) # part 5 overfitting() # part 6 # part 7 multiclass_classification() # part 8 plot_theta_multiclass()
UTF-8
Python
false
false
14,804
py
26
faces.py
14
0.572953
0.554242
0
427
33.669789
85
Mrsilent501/req
15,693,810,513,997
7b261322163c43e5beb36406e40b17ba3ab3bec1
9a15ef181ea00c00ea24ca5a08dd2e1f56b59118
/s.py
1f700a5175c7b7893f0fad09feb5e65d2d8657e3
[]
no_license
https://github.com/Mrsilent501/req
7d9b2c63eeb9a6ac6f8aeedadcf247386790d14c
f600edcf2ed7e3022bfbda9331ce15d854f570f9
refs/heads/main
2023-07-31T10:36:10.132912
2021-09-29T23:39:35
2021-09-29T23:39:35
411,860,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests url = "http://www.ipinfo.io" print (requests.get(url).text)
UTF-8
Python
false
false
76
py
1
s.py
1
0.723684
0.723684
0
3
24.333333
30
itsolutionscorp/AutoStyle-Clustering
5,892,695,150,527
d2e685a7e9084ed75570bdd03fbc02c9c8620ba8
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/difference-of-squares/0e7b0b33e1e343e4a99d5701e2c13ebf.py
36bcec0e67ea1ccbead38be4f095a48dc86aa4c9
[]
no_license
https://github.com/itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
true
2016-05-23T05:40:56
2016-05-23T05:40:56
2016-05-19T22:14:37
2016-05-19T22:35:40
133,854
0
0
0
null
null
null
def square_of_sum(n): return ((n+1)*n/2)**2 def sum_of_squares(n): total =0 for p in range(1,n+1): total+=p**2 return total def difference(n): return abs(square_of_sum(n) - sum_of_squares(n))
UTF-8
Python
false
false
239
py
54,209
0e7b0b33e1e343e4a99d5701e2c13ebf.py
21,653
0.535565
0.506276
0
11
19.181818
52
luque/better-ways-of-thinking-about-software
4,904,852,688,275
6b3127a8fcc61a87839247dcc6950dc2343c91a4
a9e3f3ad54ade49c19973707d2beb49f64490efd
/Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/cms/djangoapps/export_course_metadata/toggles.py
9eca63c6ef19f335f9fdd107d011095d70cdec6f
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
permissive
https://github.com/luque/better-ways-of-thinking-about-software
8c3dda94e119f0f96edbfe5ba60ca6ec3f5f625d
5809eaca7079a15ee56b0b7fcfea425337046c97
refs/heads/master
2021-11-24T15:10:09.785252
2021-11-22T12:14:34
2021-11-22T12:14:34
163,850,454
3
1
MIT
false
2021-11-22T12:12:31
2019-01-02T14:21:30
2019-01-02T14:40:26
2021-11-22T12:12:30
6,548
0
2
0
JavaScript
false
false
""" Toggles for export_course_metadata app """ from edx_toggles.toggles import WaffleFlag # .. toggle_name: export_course_metadata # .. toggle_implementation: WaffleFlag # .. toggle_default: False # .. toggle_description: Export of course metadata (initially to s3 for use by braze) # .. toggle_use_cases: temporary # .. toggle_creation_date: 2021-03-01 # .. toggle_target_removal_date: None # .. toggle_tickets: AA-461 EXPORT_COURSE_METADATA_FLAG = WaffleFlag('cms.export_course_metadata', __name__) # lint-amnesty, pylint: disable=toggle-missing-annotation
UTF-8
Python
false
false
562
py
5,713
toggles.py
4,192
0.738434
0.717082
0
15
36.466667
139
handsomekiwi/Algorithms
18,932,215,871,377
cb45445bb0b8aeb5e58a18c61e05c88e3f9acf8d
b171d3fe11061d780e723438b5366a81ad93f076
/Algorithms4th/UnionFind/quick_union/quick_union_test.py
a31c3b3a0452473a9f4c59638032164ebadb0887
[]
no_license
https://github.com/handsomekiwi/Algorithms
bcb0e00591895f2d90f56aced8f83f8087697718
742b902b7abb56dd25e935333e32d4b5a708d365
refs/heads/master
2021-02-19T07:56:40.513519
2016-04-13T12:29:31
2016-04-13T12:29:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from quick_union import QuickUnion from union_find_test import UnionFindTest class QuickUnionTest(UnionFindTest, unittest.TestCase): """docstring for QuickUnionTest""" cls = QuickUnion if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
271
py
42
quick_union_test.py
37
0.697417
0.697417
0
11
22.909091
55
atretyak1985/erp_azon5_server
4,337,916,997,688
fa103428aca6bc5e56e99000d5a232c85207f2d9
3df8bbcba29779527c8da773dffc766e073f2b65
/parser/offer.py
1c393490bc6dc404652d45e9b3e9dd16003842ee
[]
no_license
https://github.com/atretyak1985/erp_azon5_server
32d7fbd1a4baf2cc7b00158074ddde25fb9e70ee
4470fe2aa6e57f4b73b01081bec71fc29283c06b
refs/heads/master
2020-03-20T00:47:57.664401
2018-10-31T16:16:00
2018-10-31T16:16:00
137,056,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import datetime as dt import json import logging import re from bs4 import BeautifulSoup from models.apartment import ApartamentModel from parser.utils import get_content_for_url try: from __builtin__ import unicode except ImportError: unicode = lambda x, *args: x log = logging.getLogger(__file__) def get_title(offer_markup): """ Searches for offer title on offer page :param offer_markup: Class "offerbody" from offer page markup :type offer_markup: str :return: Title of offer :rtype: str, None """ html_parser = BeautifulSoup(offer_markup, "html.parser") return html_parser.h1.text.strip() def get_poster_name(offer_markup): """ Searches for poster name :param offer_markup: Class "offerbody" from offer page markup :type offer_markup: str :return: Poster name or None if poster name was not found (offer is outdated) :rtype: str, None :except: Poster name not found """ poster_name_parser = BeautifulSoup(offer_markup, "html.parser").find(class_="offer-user__details") try: if poster_name_parser.a is not None: found_name = poster_name_parser.a.text.strip() else: found_name = poster_name_parser.h4.text.strip() except AttributeError: return return found_name def get_gps(offer_markup): """ Searches for gps coordinates (latitude and longitude) :param offer_markup: Class "offerbody" from offer page markup :type offer_markup: str :return: Tuple of gps coordinates :rtype: tuple """ html_parser = BeautifulSoup(offer_markup, "html.parser") if html_parser.find(class_="mapcontainer") is not None: gps_lat = html_parser.find(class_="mapcontainer").attrs['data-lat'] gps_lon = html_parser.find(class_="mapcontainer").attrs['data-lon'] else: gps_lat = 0 gps_lon = 0 return gps_lat, gps_lon def parse_description(offer_markup): """ Searches for description if offer markup :param offer_markup: Body from offer page markup :type offer_markup: str :return: Description of offer :rtype: str """ html_parser = BeautifulSoup(offer_markup, "html.parser") return html_parser.find(id="textContent").text.replace(" ", "").replace("\n", " ").replace("\r", "").strip() def get_month_num_for_string(value): value = value.lower()[:3] return { 'січ': 1, 'лют': 2, 'бер': 3, 'кві': 4, 'тра': 5, 'чер': 6, 'лип': 7, 'сер': 8, 'вер': 9, 'жов': 10, 'лис': 11, 'гру': 12, }.get(value) def get_img_url(offer_markup): """ Searches for images in offer markup :param offer_markup: Class "offerbody" from offer page markup :type offer_markup: str :return: Images of offer in list :rtype: list """ html_parser = BeautifulSoup(offer_markup, "html.parser") images = html_parser.find_all(class_="bigImage") output = [] for img in images: output.append(img.attrs["src"]) return output def get_date_added(offer_markup): """ Searches of date of adding offer :param offer_markup: Class "offerbody" from offer page markup :type offer_markup: str :return: Date of adding offer :rtype: str """ html_parser = BeautifulSoup(offer_markup, "html.parser") date = html_parser.find(class_="offer-titlebox__details").em.contents date = date[4] if len(date) > 4 else date[0] date = date.replace("Dodane", "").replace("\n", "").replace(" ", "").replace("o ", "").replace(", ", " ") # 'в 19:04 24 серпня 2018 ' # 10:09 04 września 2017 date_parts = date.split(' ') hour, minute = map(int, date_parts[1].split(':')) month = get_month_num_for_string(date_parts[3]) year = int(date_parts[4]) day = int(date_parts[2]) date_added = dt.datetime(year=year, hour=hour, minute=minute, day=day, month=month) return int((date_added - dt.datetime(1970, 1, 1)).total_seconds()) def parse_tracking_data(offer_markup): """ Parses price and add_id from OLX tracking data script :param offer_markup: Head from offer page :type offer_markup: str :return: Tuple of int price and it's currency or None if this offer page got deleted :rtype: dict :except: This offer page got deleted and has no tracking script. """ html_parser = BeautifulSoup(offer_markup, "html.parser") scripts = html_parser.find_all('script') for script in scripts: if script.string and "pageView" in script.string: data = script.string break try: split_data = re.split('"pageView":|;', data) data_dict = json.loads(split_data[3].replace('{', "{").replace("}}'", "}")) except json.JSONDecodeError as e: logging.info("JSON failed to parse pageView offer attributes. Error: {0}".format(e)) data_dict = {} return data_dict def parse_flat_data(offer_markup): """ Parses data from script of Google Tag Manager :param offer_markup: Body from offer page markup :type offer_markup: str :return: GPT dict data :rtype: dict """ html_parser = BeautifulSoup(offer_markup, "html.parser") scripts = html_parser.find_all('script') for script in scripts: if script.string and "GPT.targeting =" in script.string: data = script.string break try: split_data = re.split('GPT.targeting = |;', data) data_dict = json.loads(split_data[2].replace(";", "")) except json.JSONDecodeError as e: logging.info("JSON failed to parse GPT offer attributes. Error: {0}".format(e)) data_dict = {} return data_dict def parse_region(offer_markup): """ Parses region information :param offer_markup: Class "offerbody" from offer page markup :type offer_markup: str :return: Region of offer :rtype: list """ html_parser = BeautifulSoup(offer_markup, "html.parser") region = html_parser.find(class_="show-map-link").text return region.replace(", ", ",").split(",") def parse_offer(url): """ Parses data from offer page url :param url: Offer page markup :param url: Url of current offer page :type url: str :return: Dictionary with all offer details or None if offer is not available anymore :rtype: dict, None """ log.info(url) html_parser = BeautifulSoup(get_content_for_url(url).content, "html.parser") offer_content = str(html_parser.body) poster_name = get_poster_name(offer_content) data_track = parse_tracking_data(str(html_parser)) data_dict = parse_flat_data(offer_content) region = parse_region(offer_content) if len(region) == 3: city, area, district = region else: city, area = region district = None apartment = ApartamentModel() apartment.add_id = data_track.get("ad_id"), apartment.title = get_title(offer_content), apartment.price = data_dict.get("ad_price"), apartment.currency = data_dict.get("currency"), apartment.city = city, apartment.district = district, apartment.region = area, apartment.gps = get_gps(offer_content), apartment.description = parse_description(offer_content), apartment.poster_name = poster_name, apartment.url = url, apartment.date_added = get_date_added(offer_content), apartment.images = get_img_url(offer_content), apartment.private_business = data_dict.get("private_business"), apartment.total_area = data_dict.get("total_area"), apartment.number_of_rooms = data_dict.get("number_of_rooms"), return apartment
UTF-8
Python
false
false
7,736
py
8
offer.py
5
0.640406
0.632605
0
237
31.455696
113
serkyron/win-proxy
13,460,427,548,444
9e2a17de42ee628b5bcc6d84b4a7e29b03e66d0d
68b14d8d07323a01deae201d3f491aefb99f1ed3
/proxy.py
df2e40c7013c9a39ac67ddb842da428535b13899
[]
no_license
https://github.com/serkyron/win-proxy
88ff3f2332942d26764ceed0369789e2fb512e6b
0f05facf83bb8a4335d528e983c7946f0b9efd36
refs/heads/master
2022-12-03T04:25:11.170535
2020-08-20T09:57:46
2020-08-20T09:57:46
263,770,986
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import _winreg as winreg import ctypes import sys import platform system = platform.system() if system != "Windows": raise Exception("OS type not supported") INTERNET_SETTINGS = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Internet Settings', 0, winreg.KEY_ALL_ACCESS) def set_key(name, value, type): winreg.SetValueEx(INTERNET_SETTINGS, name, 0, type, value) if sys.argv[1] == "off": set_key('ProxyEnable', 0, winreg.REG_DWORD) else: set_key('ProxyEnable', 1, winreg.REG_DWORD) set_key('ProxyServer', sys.argv[2], winreg.REG_SZ) INTERNET_OPTION_REFRESH = 37 INTERNET_OPTION_SETTINGS_CHANGED = 39 internet_set_option = ctypes.windll.Wininet.InternetSetOptionW internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0) internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
UTF-8
Python
false
false
843
py
1
proxy.py
1
0.746145
0.727165
0
30
27.133333
67
sundw2014/Learning-Discrepancy
2,877,628,093,184
dd2db3e031d54fcab5a61c03b8f313004d4eae86
e002090450f25923b424ec1a6af79667bd85d3f9
/examples/quadrotor_LQR/quadrotor_LQR.py
169e79226c3c3f2f11b81c61b69e23b54082bc2a
[]
no_license
https://github.com/sundw2014/Learning-Discrepancy
1db20609cec98babcdbac1d4f05266163687c04a
0daf0344870c83e60a9cb685a8f6b97fb40f33a4
refs/heads/master
2023-09-03T23:46:05.502781
2021-01-12T04:35:50
2021-01-12T04:35:50
264,091,299
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 3D Control of Quadcopter # based on https://github.com/juanmed/quadrotor_sim/blob/master/3D_Quadrotor/3D_control_with_body_drag.py # The dynamics is from pp. 17, Eq. (2.22). https://www.kth.se/polopoly_fs/1.588039.1550155544!/Thesis%20KTH%20-%20Francesco%20Sabatino.pdf # The linearization is from Different Linearization Control Techniques for # a Quadrotor System (many typos) import numpy as np import scipy import scipy.linalg # from scipy.integrate import odeint import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from .nonlinear_dynamics import g, m, Ix, Iy, Iz, f import contextlib waypoints = [[1, 1, 1], [1, 1, 2], [0, 0, 0]] def odeint(f, x0, t, args=()): x = [np.array(x0),] for idx in range(len(t)-1): dot_x = f(x[-1], t[idx], *args) x.append(x[-1] + dot_x*(t[idx+1]-t[idx])) return np.array(x) @contextlib.contextmanager def temp_seed(seed): state = np.random.get_state() np.random.seed(seed) try: yield finally: np.random.set_state(state) def lqr(A, B, Q, R): """Solve the continuous time lqr controller. dx/dt = A x + B u cost = integral x.T*Q*x + u.T*R*u """ # http://www.mwm.im/lqr-controllers-with-python/ # ref Bertsekas, p.151 # first, try to solve the ricatti equation X = np.matrix(scipy.linalg.solve_continuous_are(A, B, Q, R)) # compute the LQR gain K = np.matrix(scipy.linalg.inv(R) * (B.T * X)) eigVals, eigVecs = scipy.linalg.eig(A - B * K) return np.asarray(K), np.asarray(X), np.asarray(eigVals) # The control can be done in a decentralized style # The linearized system is divided into four decoupled subsystems # X-subsystem # The state variables are x, dot_x, pitch, dot_pitch Ax = np.array( [[0.0, 1.0, 0.0, 0.0], [0.0, 0.0, g, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0]]) Bx = np.array( [[0.0], [0.0], [0.0], [1 / Ix]]) # Y-subsystem # The state variables are y, dot_y, roll, dot_roll Ay = np.array( [[0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -g, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0]]) By = np.array( [[0.0], [0.0], [0.0], [1 / Iy]]) # Z-subsystem # The state variables are z, dot_z Az = np.array( [[0.0, 1.0], [0.0, 0.0]]) Bz = np.array( [[0.0], [1 / m]]) # Yaw-subsystem # The state variables are yaw, dot_yaw Ayaw = np.array( [[0.0, 1.0], [0.0, 0.0]]) Byaw = np.array( [[0.0], [1 / Iz]]) ####################### solve LQR ####################### Ks = [] # feedback gain matrices K for each subsystem for A, B in ((Ax, Bx), (Ay, By), (Az, Bz), (Ayaw, Byaw)): n = A.shape[0] m = B.shape[1] Q = np.eye(n) Q[0, 0] = 10. # The first state variable is the one we care about. R = np.diag([1., ]) K, _, _ = lqr(A, B, Q, R) Ks.append(K) def TC_Simulate(Mode,initialCondition,time_bound): ######################## simulate ####################### # time instants for simulation t_max = time_bound t = np.arange(0., t_max, 0.01) def cl_nonlinear(x, t, u): x = np.array(x) dot_x = f(x, u(x, t) + np.array([m * g, 0, 0, 0])) noise = np.zeros(12) # noise[[0,2,4]] = 1e-1*np.random.randn(3) return dot_x + 0.1*np.random.randn(12)#+ noise if Mode == 'waypoints': # waypoints = [[1, 1, 1], [1, 1, 2], [0, 0, 0]] # follow waypoints signal = np.zeros([len(t), 3]) num_w = len(waypoints) for i, w in enumerate(waypoints): assert len(w) == 3 signal[len(t) // num_w * i:len(t) // num_w * (i + 1), :] = np.array(w).reshape(1, -1) # X0 = np.zeros(12) signalx = signal[:, 0] signaly = signal[:, 1] signalz = signal[:, 2] else: # Create an random signal to track num_dim = 3 freqs = np.arange(0.1, 2., 0.1) with temp_seed(0): weights = np.random.randn(len(freqs), num_dim) # F x n weights = weights / \ np.sqrt((weights**2).sum(axis=0, keepdims=True)) # F x n signal_AC = np.sin(freqs.reshape(1, -1) * t.reshape(-1, 1) ).dot(weights) # T x F * F x n = T x n with temp_seed(0): signal_DC = np.random.randn(num_dim).reshape(1, -1) # offset signal = signal_AC + signal_DC signalx = signal[:, 0] signaly = signal[:, 1] signalz = 0.1 * t # initial state # _X0 = 0.1 * np.random.randn(num_dim) + signal_DC.reshape(-1) # X0 = np.zeros(12) # X0[[0, 2, 4]] = _X0 signalyaw = np.zeros_like(signalz) # we do not care about yaw def u(x, _t): # the controller dis = _t - t dis[dis < 0] = np.inf idx = dis.argmin() UX = Ks[0].dot(np.array([signalx[idx], 0, 0, 0]) - x[[0, 1, 8, 9]])[0] UY = Ks[1].dot(np.array([signaly[idx], 0, 0, 0]) - x[[2, 3, 6, 7]])[0] UZ = Ks[2].dot(np.array([signalz[idx], 0]) - x[[4, 5]])[0] UYaw = Ks[3].dot(np.array([signalyaw[idx], 0]) - x[[10, 11]])[0] return np.array([UZ, UY, UX, UYaw]) X0 = np.array(initialCondition) # simulate x_nl = odeint(cl_nonlinear, X0, t, args=(u,)) return np.concatenate([t.reshape(-1,1), x_nl], axis=1) if __name__ == '__main__': import argparse import time ######################## plot ####################### fig = plt.figure(figsize=(20, 10)) track = fig.add_subplot(1, 1, 1, projection="3d") for i in range(10): # x_nl = TC_Simulate("waypoints", np.random.randn(12), 10) # for w in waypoints: # track.plot(w[0:1], w[1:2], w[2:3], 'ro', markersize=10.) np.random.seed(int(time.time()*1000)%(2**32-1)) x_nl = TC_Simulate("random", 2*(np.random.rand(12) - 0.5), 10) x_nl = x_nl[:,1:] track.plot(x_nl[:, 0], x_nl[:, 2], x_nl[:, 4], color="g") # track.text(x_nl[0,0], x_nl[0,2], x_nl[0,4], "start", color='red') # track.text(x_nl[-1,0], x_nl[-1,2], x_nl[-1,4], "finish", color='red') track.set_xlabel('x') track.set_ylabel('y') track.set_zlabel('z') plt.show()
UTF-8
Python
false
false
6,204
py
31
quadrotor_LQR.py
28
0.522888
0.471954
0
203
29.561576
138
felixwsiu/SudoSolve
16,295,105,937,226
f71a65a5cfbdbc2232d34ae07d71ecdedccf67dc
968849bc95d62e2bd8d82c7c23c24846e1254630
/sudoparser.py
c05b01cfc1aef41a524a948c8970fa4bd37354b0
[]
no_license
https://github.com/felixwsiu/SudoSolve
ecadac262db3e56347ca12ce6ad27ec526a1f818
1b3662644ee80a4a14ea4afffc9ea4445f621bad
refs/heads/master
2021-07-01T19:02:36.804085
2020-09-26T21:24:02
2020-09-26T21:24:02
168,605,628
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests from bs4 import BeautifulSoup def parsePuzzle(difficulty): if difficulty == 3: URL = "http://www.cs.utep.edu/cheon/ws/sudoku/new/?size=9&level=3" elif difficulty == 2: URL = "http://www.cs.utep.edu/cheon/ws/sudoku/new/?size=9&level=2" elif difficulty == 1: URL = "http://www.cs.utep.edu/cheon/ws/sudoku/new/?size=9&level=1" r = requests.get(URL) soup = BeautifulSoup(r.content,'html5lib') soup.prettify() info=[] # a list to store quotes info = soup.find('body').get_text() info = info.split('{') cells = [] for x in info: text = list(x) if len(text) < 24 and len(text)!=0: cells.append([text[4],text[10],text[20]]) return cells
UTF-8
Python
false
false
764
py
3
sudoparser.py
2
0.586387
0.561518
0
30
24.466667
74
cottyard/PythonToolsCollection
12,189,117,186,183
130bbe374e303e0ddc26b391bf813d7393ca4fd9
112815b0452074504bd4b9f36fb296a29149a3e2
/JsObject/jsobject.py
0d2172d6d209fd9cc3bd9844cd237f0d613f0665
[]
no_license
https://github.com/cottyard/PythonToolsCollection
bca8c1639782be0c9cb8e16bd37254618a4078b2
5605ad818b7ed4ab97c9ecfdfb1f00e40da3d01f
refs/heads/master
2021-06-06T10:45:33.009065
2016-10-24T11:12:03
2016-10-24T11:12:03
19,297,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# a python object that thinks it's a js object def map_dict(func, dict): return {k: func(v) for k, v in dict.items()} class JsObject: def __init__(self, json={}): self.from_json(json) def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): raise AttributeError(name) if name not in self._storage: raise AttributeError( 'JsObject "%s" has no attribute "%s"' % (str(self), name)) return self._storage[name] def __setattr__(self, name, value): if name in ('_storage', '_datatype'): self.__dict__[name] = value else: self._storage[name] = value def __getitem__(self, index): return self._storage[index] def __setitem__(self, index, value): setattr(self, index, value) def is_convertible_json(self, data): """ whether or not some json data can be converted to a JsObject """ return isinstance(data, (dict, list)) def from_json(self, json): self._storage = {} def construct(data): return JsObject(data) if self.is_convertible_json(data) else data if isinstance(json, dict): self._datatype = dict for k in json: self._storage[k] = construct(json[k]) elif isinstance(json, list): self._datatype = list for i in range(0, len(json)): self._storage[i] = construct(json[i]) else: raise TypeError('not a json object') def to_json(self): def construct(jsobj_or_json): if not isinstance(jsobj_or_json, JsObject): return jsobj_or_json else: return jsobj_or_json.to_json() json_dict = map_dict(construct, self._storage) if self.datatype() is dict: return json_dict else: return list(json_dict.values()) def as_tuple(self): return tuple(self._storage.values()) def as_list(self): return list(self._storage.values()) def as_dict(self): return dict(self._storage) def datatype(self): return self._datatype def has_attr(self, name): return name in self._storage def remove_attr(self, name): del self._storage[name] def attrs(self): return self._storage.keys() def values(self): return self._storage.values() def __iter__(self): return iter(self._storage) def __repr__(self): return str(self) def __str__(self): return "{%s}" % ", ".join( ("%s: %s" % item for item in self._storage.items()))
UTF-8
Python
false
false
2,706
py
27
jsobject.py
14
0.545085
0.544715
0
99
26.333333
77
kobaltkween/python2
2,302,102,487,561
6e306bc978ebc9bbf9988f68341522590361a2d4
b65f31d9d273c3d4bb826ff83a805368570bcd4d
/Lesson 04 - File Handling/testLatest.py
b9a1605a194166c6a17769b003975bb88c350905
[]
no_license
https://github.com/kobaltkween/python2
3fde6cc9ca1413b900c87656d8ceb99cb3f34f42
f7e529abd303b65f0b794c8a9ed87dbf085541a8
refs/heads/master
2020-12-31T05:09:39.297693
2016-04-13T23:27:10
2016-04-13T23:27:10
56,192,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest import latest import time import os PATHSTEM = "v:\\workspace\\FileHandling\\src\\" class TestLatest(unittest.TestCase): def setUp(self): self.path = PATHSTEM self.fileNames = ["file.old", "file.bak", "file.new"] for fn in self.fileNames: f = open(self.path + fn, "w") f.close() time.sleep(1) def testLatestNoNumber(self): """ Ensure that calling the function with no arguments returns the single most recently-created file. """ expected = [self.path + "file.new"] latestFile = latest.latest(path = self.path) self.assertEqual(latestFile, expected, ) \ def testLatestWithArgs(self): """ Ensure that calling the function with the arguments of 2 and some directory returns the two most recently created files in the directory. """ expected = set([self.path + "file.new", self.path + "file.bak"]) latestFiles = set(latest.latest(2, self.path)) self.assertEqual(latestFiles, expected) def tearDown(self): for fn in self.fileNames: os.remove(self.path + fn) if __name__ == "__main__": unittest.main()
UTF-8
Python
false
false
1,270
py
40
testLatest.py
38
0.585039
0.582677
0
41
30
81
sharithomas/more-examples
16,767,552,362,790
a79ef2fef377f46f1168deebad8353cb30dcc33c
4c1f8e7b02cfe60da4be1300c051c6525776cc00
/function_programs/check_number_inrange_fun.py
a74b581172876e08c34645ace9a69fcd85d5b80a
[]
no_license
https://github.com/sharithomas/more-examples
04fea9dcc912eb4546dae1d03090b9e89d5bc157
e0672e2440968cc6041ca8c2567cbd572515fb7c
refs/heads/master
2021-02-27T11:50:05.103096
2020-10-02T11:46:43
2020-10-02T11:46:43
245,603,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Write a Python function to check whether a number is in a given range. number=int(input("enter number")) #function definition to check whether given number is in the range of 1 to 10 def test_range(n): if n in range(1,10): print( str(n) + " is in the range of (1,10)") else : print("The number is outside the given range of (1,10).") test_range(number)
UTF-8
Python
false
false
380
py
241
check_number_inrange_fun.py
241
0.671053
0.639474
0
10
37
77
24jcarter/lab2
19,318,762,932,490
b5836947b974085642ff8e007adad2072554e5cd
1ecaebc5abd94bc54c5007a6624501ed1d564c2d
/util.py
2a6f116789ad5aa20d1b368ea004c25f8254feec
[]
no_license
https://github.com/24jcarter/lab2
35e69f2c455553c102bf8d21a3dc327484c06c63
040af42339c57659fe436bf3be690e61207aff04
refs/heads/master
2023-08-20T07:29:40.666160
2021-09-27T23:49:58
2021-09-27T23:49:58
411,024,120
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import RPi.GPIO as GPIO from time import sleep def switchPressed(pin): ledpwm = GPIO.PWM(pin, 100) ledpwm.start(0) for duty in range(101): ledpwm.ChangeDutyCycle(duty) sleep(0.01) for duty in range(100, -1, -1): ledpwm.ChangeDutyCycle(duty) sleep(0.01)
UTF-8
Python
false
false
268
py
2
util.py
2
0.708955
0.641791
0
12
21.25
32
cloudfly-group/backendfleio-test
8,693,013,854,501
199f2306539921fd67162dd6add64e2e64ee3471
2ae8c06383fc51ba6651760509e8eda9d189dc52
/project/fleio/openstack/models/image_members.py
58e544e0db5813bf6ebbc7c330dc1a32183ff0a3
[]
no_license
https://github.com/cloudfly-group/backendfleio-test
8d0d2117e11f0400067b04fc28054b92c0bdb811
ef9d5bc66459380db85ba70e442cfd4d9ed2db5e
refs/heads/master
2021-03-01T00:06:37.591171
2020-01-06T02:53:54
2020-01-06T02:53:54
245,741,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.utils.translation import ugettext_lazy as _ class ImageMemberStatus: PENDING = 'pending' ACCEPTED = 'accepted' REJECTED = 'rejected' choices = ( (PENDING, _('Pending')), (ACCEPTED, _('Accepted')), (REJECTED, _('Rejected')) ) class ImageMembers(models.Model): IMAGE_MEMBER_STATUS = ImageMemberStatus.choices image = models.ForeignKey('openstack.Image', db_constraint=False, null=True, blank=True, on_delete=models.DO_NOTHING, related_name='members') # NOTE(tomo): Using a FK to Projects forces the images and images members to use tenant/project ownership member = models.ForeignKey('openstack.Project', db_constraint=False, null=True, blank=True, on_delete=models.DO_NOTHING, to_field='project_id') status = models.CharField(choices=IMAGE_MEMBER_STATUS, max_length=15, default='pending', db_index=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) deleted_at = models.DateTimeField(blank=True, null=True) sync_version = models.BigIntegerField(default=0) class Meta: verbose_name_plural = 'Image members'
UTF-8
Python
false
false
1,333
py
1,224
image_members.py
1,131
0.644411
0.642161
0
33
39.393939
109
scottyyf/Python004
12,764,642,839,593
44c7dae4af986b3c996d83be98ed9c77c86600b7
6316542865d55af5d6fa4565e5a60d6940eabbc9
/my_test_follow_teacher/week6/testabc.py
0031dc052bfec3d02d631d93b56da4ef1eb55a5f
[]
no_license
https://github.com/scottyyf/Python004
e8413c0da7468a06813e4d229e82b81e34fac722
2847f4c48f1fc746a166027e46ee238da0d720ed
refs/heads/master
2023-01-29T07:09:43.781799
2020-12-02T07:42:01
2020-12-02T07:42:01
295,947,174
0
0
null
true
2020-09-29T02:56:57
2020-09-16T06:46:32
2020-09-16T06:46:34
2020-09-29T02:56:56
26
0
0
0
null
false
false
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: testabc.py.py Author: Scott Yang(Scott) Email: yangyingfa@skybility.com Copyright: Copyright (c) 2020, Skybility Software Co.,Ltd. All rights reserved. Description: """ # from abc import ABCMeta, abstractmethod, ABC, get_cache_token # # class Base(ABC): # @abstractmethod # def foo(self): # pass # # # class Concrete(Base): # def __init__(self): # pass # # def foo(self): # pass # # # c = Concrete() # print(get_cache_token()) class Display(): def display(self, message): print(message) class LoggerMixin(): def log(self, message, filename='logfile.txt'): with open(filename, 'a') as fh: fh.write(message) def display(self, message): super().display(message) self.log(message) class MysubClass(LoggerMixin, Display): def log(self, message): super().log(message, filename='subclass.txt') sub_class = MysubClass() sub_class.display('this is subclass display') print(MysubClass.mro())
UTF-8
Python
false
false
1,058
py
67
testabc.py
58
0.627599
0.622873
0
55
18.236364
79
hademircii/financial_market_simulator
17,626,545,797,955
6333fec4a696e740799168f5002a9657090abbea
680d1f15a3f7166367aa8db583b95a9eaf5ddcc8
/draw.py
87cccc4603ee4fea25df0445bf658bee4b45fd9a
[]
no_license
https://github.com/hademircii/financial_market_simulator
19243bec2491ff53d4f30f980359b4c8b1e85b85
bb8ef1e370c7224baeb4fdfed66aaa2167f84567
refs/heads/master
2022-12-09T13:30:18.131168
2019-09-08T20:54:42
2019-09-08T20:54:42
188,909,952
4
1
null
false
2022-12-08T05:18:12
2019-05-27T21:15:03
2020-07-25T16:38:21
2022-12-08T05:18:12
922
4
1
16
Jupyter Notebook
false
false
import numpy as np from high_frequency_trading.hft.equations import price_grid import utility import logging import settings log = logging.getLogger(__name__) class ContextSeed: """ context manager to ensure sample draws are shared among different agents """ def __init__(self, seed): self.seed = seed def __enter__(self): np.random.seed(self.seed) def __exit__(self, *_): np.random.seed(np.random.randint(0, high=100)) def asof(a, b): """ assumes a and b are sorted array of times return indexes of a so values of b at such indexes are 'as of' a, commonly used when dealing with timeseries data (so the closest numpy gets to this is via searchsorted, which is still not the tool, wtf numpy folks ?) """ current_index = 0 last_a_index = len(a) - 1 result = np.zeros(b.size, dtype=int) for ix, t in enumerate(b): try: while t >= a[current_index]: current_index += 1 except IndexError: current_index = last_a_index + 1 result[ix] = current_index - 1 return result def draw_arrival_times(size, period_length, distribution=np.random.uniform, **kwargs): """ given a distributon, draw a sample of time points sort and cum sum them so you have arrival times spread over the period length """ arr = distribution(size=size, **kwargs) arr.sort() arr.cumsum() sub_arr = arr[arr < period_length].round(decimals=3) return sub_arr def draw_noise(size, period_length, distribution=np.random.normal, cumsum=False, **kwargs): arr = distribution(size=size, **kwargs) if cumsum: arr.cumsum() return arr def _elo_asset_value_arr(initial_price, period_length, loc_delta, scale_delta, lambdaJ): """ generate a sequence of asset values and asset value jump times """ f_size = int(lambdaJ * period_length) f_price_change_times = draw_arrival_times( f_size, period_length, low=0.0, high=period_length) num_f_price_changes = f_price_change_times.size f_prices = np.random.normal( size=num_f_price_changes, loc=loc_delta, scale=scale_delta).cumsum() + initial_price return np.vstack((f_price_change_times, f_prices)).round(3) def elo_random_order_sequence( asset_value_arr, period_length, loc_noise, scale_noise, bid_ask_offset, lambdaI, time_in_force, buy_prob=0.5): """ draws bid/ask prices around fundamental value, generate input sequnce for random orders with arrival times as array """ orders_size = np.random.poisson(lam=(1 / lambdaI) * period_length, size=1) order_times = draw_arrival_times( orders_size, period_length, low=0.0, high=period_length) unstacked_asset_values = np.swapaxes(asset_value_arr, 0, 1) asset_value_jump_times, asset_values = unstacked_asset_values[0], unstacked_asset_values[1] asset_value_indexes = asof(asset_value_jump_times, order_times) asset_value_asof = asset_values[asset_value_indexes] order_directions = np.random.binomial(1, buy_prob, orders_size) noise_by_order_side = np.vectorize( lambda x: np.random.normal(loc_noise - bid_ask_offset, scale_noise ) if x == 0 else np.random.normal(loc_noise + bid_ask_offset, scale_noise)) noise_around_asset_value = noise_by_order_side(order_directions) order_prices = (asset_value_asof + noise_around_asset_value).astype(int) grid = np.vectorize(price_grid) gridded_order_prices = grid(order_prices) orders_tif = np.full(orders_size, time_in_force).astype(int) convert_to_string = np.vectorize(lambda x: 'B' if x is 0 else 'S') order_directions = convert_to_string(order_directions) stacked = np.vstack(( order_times, asset_value_asof, gridded_order_prices, order_directions, orders_tif)) return stacked def elo_draw(period_length, conf: dict, seed=np.random.randint(0, high=2 ** 8), config_num=0): """ generates random order sequence as specified in ELO market research plan first draws fundamental value series or read from a csv file then pipes this sequence to random order producer function """ if conf['read_fundamental_values_from_file']: path = settings.fundamental_values_config_path fundamental_values = utility.read_fundamental_values_from_csv(path) fundamental_values.insert(0, (0, conf['initial_price'])) fundamental_values = np.array(fundamental_values) log.info('read fundamental value sequence from %s.' % path) else: with ContextSeed(seed): fundamental_values = _elo_asset_value_arr( conf['initial_price'], period_length, conf['fundamental_value_noise_mean'], conf['fundamental_value_noise_std'], conf['lambdaJ']) log.info('drew fundamental value sequence, initial price %s' '%s jumps per second.' % ( conf['initial_price'], round(len(fundamental_values) / period_length, 2))) log.info('fundamental values: %s' % (', '.join('{0}:{1}'.format(t, v) for t, v in fundamental_values))) random_orders = elo_random_order_sequence( fundamental_values, period_length, conf['exogenous_order_price_noise_mean'], conf['exogenous_order_price_noise_std'], conf['bid_ask_offset'], conf['lambdaI'][config_num], # so rabbits differ in arrival rate.. conf['time_in_force']) random_orders = np.swapaxes(random_orders, 0, 1) log.info( '%s random orders generated. period length: %s, per second: %s.' % ( random_orders.shape[0], period_length, round(random_orders.shape[0] / period_length, 2))) log.info('random orders (format: [fundamental price]:[order price]:[order direction]:[time in force]): %s' % ( ', '.join('{0}:{1}:{2}:{3}'.format(row[1], row[2], row[3], row[4]) for row in random_orders))) return random_orders if __name__ == '__main__': d = elo_draw(20, utility.get_simulation_parameters()) for r in d: print(r)
UTF-8
Python
false
false
6,409
py
36
draw.py
20
0.618973
0.611172
0
164
38.036585
114
SirjanK/Multivac
10,977,936,418,551
25824dd4209bf6369bedfc3479e09514e0583e5f
2fd41fccf46b173da1ab4369beba39f2e91d1dcc
/frontend/frontend_constants.py
c012408c68cfc3ff3efe9851f40836860ac364b5
[ "MIT" ]
permissive
https://github.com/SirjanK/Multivac
cd64d2c4fbde3556647733fea9fe5833e53deb63
27b5d490c015b68e268d4d44a0ff17b8ab519274
refs/heads/master
2022-11-26T11:36:39.913140
2020-04-15T03:44:21
2020-04-15T03:44:21
155,824,102
0
0
MIT
false
2022-11-22T04:55:51
2018-11-02T06:34:45
2020-04-15T03:44:25
2022-11-22T04:55:48
2,938
0
0
7
CSS
false
false
# HTML page names INDEX_HTML = 'index.html' SESSION_HTML = 'session.html' # Parameter keys between pages ENVIRONMENT_NAME_KEY = 'environmentName' AGENT_NAME_KEY = 'agentName' NUM_STEPS_KEY = 'numSteps' OBSERVATION_DELTA_KEY = 'observationDelta' VIDEO_FPS_KEY = 'videoFps' # Return values by the / and /session endpoints SUCCESS_DESIGNATION = "success" FAILED_DESIGNATION = "failed" INVALID_POST_PARAMETERS_DESIGNATION = "Invalid POST parameters"
UTF-8
Python
false
false
448
py
34
frontend_constants.py
28
0.763393
0.763393
0
15
28.866667
63
Lucass96/Python-Faculdade
8,074,538,524,444
2952456aaf6a8bfe5b966e47c756ff525bacac79
344145de0b0d5ec2ac3b83c92347f12fc1390e9e
/Python-LP/aula05/ParametroExercicio.py
fc478d9d4b0cb60f5e19e1ecddd5e843fdf80696
[]
no_license
https://github.com/Lucass96/Python-Faculdade
dc405d087393eaf169ad40d13a0d065fb44d1604
8abaebd95f0db18d8321062eb04a15894a069901
refs/heads/master
2023-06-16T19:55:54.047700
2021-07-09T16:58:47
2021-07-09T16:58:47
384,498,164
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Exercicio 1 def borda(s1): tam = len(s1) # so imprime caso exista algum caractere if tam: print('+','-' * tam,'+') print('|',s1,'|') print('+', '-' * tam, '+') #Programa Principal borda('Ola, Mundo!') borda('Logica de Programacao e Algoritmos')
UTF-8
Python
false
false
283
py
60
ParametroExercicio.py
60
0.54417
0.530035
0
12
22.666667
44
sheltowt/data_munging
4,148,938,437,194
49916287b09349f5aa8676970e9c7392812c36db
51573e14301533cdc5aaea8e67384b57741ca02c
/parallel_textbag.py
808c6e00b9496b92c2b2cfdcd38d6be3974013d7
[]
no_license
https://github.com/sheltowt/data_munging
ca790a85cc85cb6db1173e56ae4bb0ddfb6c1255
53cf38510eb4e7a448af2918f73059c87bc9219e
refs/heads/master
2021-01-10T04:18:57.429538
2013-03-12T20:40:53
2013-03-12T20:40:53
8,529,972
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from __future__ import division import pp import nltk import re, pprint import pandas as pandas import random import csv newt = pandas.read_csv("/home/williamshelton/Desktop/Data/good_test.csv") header = pandas.read_csv("/home/williamshelton/Desktop/Data/good_test.csv", header= None) rows1 = range(0,300) rows2 = range(301,len(newt['FullDescription'])) head = header.ix[0] print head newt1 = newt.ix[rows1] print newt1 #newt21 = newt.ix[rows2] #newt2 = newt21.reindex(columns=head) newt2 = newt.ix[rows2] print newt2 count1 = 0 count2 = 301 def word_process(newt3, count): new = newt3 new['NN'] = "Hello" new['NNP'] = "Hello" new['NNS'] = "Hello" new['NNPS'] = "Hello" new['VB'] = "Hello" new['VBD'] = "Hello" new['VBG'] = "Hello" new['VBP'] = "Hello" new['VBP'] = "Hello" new['VBZ'] = "Hello" new['VBN'] = "Hello" new['JJ'] = "Hello" new['JJS'] = "Hello" new['JJR'] = "Hello" new['CC'] = "Hello" new['CD'] = "Hello" new['TO'] = "Hello" new['MD'] = "Hello" new['RB'] = "Hello" new['RBR'] = "Hello" new['RBS'] = "Hello" new['FW'] = "Hello" for x in new['ContractTime']: if x == None: x = "Hello" for x in new['Company']: if x == None: x = "Hello" print new for x in new['FullDescription']: clean = [] y = nltk.word_tokenize(x) y = [nltk.word_tokenize(a) for a in y] y = [nltk.pos_tag(a) for a in y] clean.append(y) for c in clean: nn = " " nnp = " " nns = " " nnps = " " vb = " " vbd = " " vbg = " " vbp = " " vbz = " " vbn = " " jj = " " jjs = " " jjr = " " cc = " " cd = " " to = " " md = " " rb = " " rbr = " " rbs = " " fw = " " for x in c: if x[0][1] == 'NN': nn = nn + " " + x[0][0] for x in c: if x[0][1] == 'NNP': nnp = nnp + " " + x[0][0] for x in c: if x[0][1] == 'NNS': nns = nns + " " + x[0][0] for x in c: if x[0][1] == 'NNPS': nns = nnps + " " + x[0][0] for x in c: if x[0][1] == 'VB': vb = vb + " " + x[0][0] for x in c: if x[0][1] == 'VBD': vbd = vbd + " " + x[0][0] for x in c: if x[0][1] == 'VBG': vbg = vbg + " " + x[0][0] for x in c: if x[0][1] == 'VBP': vbp = vbp + " " + x[0][0] for x in c: if x[0][1] == 'VBZ': vbz = vbz + " " + x[0][0] for x in c: if x[0][1] == 'VBN': vbn = vbn + " " + x[0][0] for x in c: if x[0][1] == 'JJ': jj = jj + " " + x[0][0] for x in c: if x[0][1] == 'JJS': jjs = jjs + " " + x[0][0] for x in c: if x[0][1] == 'JJR': jjr = jjr + " " + x[0][0] for x in c: if x[0][1] == 'CC': if x[0][0] is None: pass else: cc = cc + " " + x[0][0] for x in c: if x[0][1] == 'CD': cd = cd + " " + x[0][0] for x in c: if x[0][1] == 'TO': to = to + " " + x[0][0] for x in c: if x[0][1] == 'MD': md = md + " " + x[0][0] for x in c: if x[0][1] == 'RB': rb = rb + " " + x[0][0] for x in c: if x[0][1] == 'RBR': rbr = rbr + " " + x[0][0] for x in c: if x[0][1] == 'RBS': rbs = rbs + " " + x[0][0] for x in c: if x[0][1] == 'FW': fw = fw + " " + x[0][0] new['NN'][count] = nn new['NNP'][count] = nnp new['NNS'][count] = nns new['NNPS'][count] = nnps new['VB'][count] = vb new['VBD'][count] = vbd new['VBG'][count] = vbg new['VBP'][count] = vbp new['VBZ'][count] = vbz new['VBN'][count] = vbn new['JJ'][count] = jj new['JJS'][count] = jjs new['JJR'][count] = jjr new['CC'][count] = cc new['CD'][count] = cd new['TO'][count] = to new['MD'][count] = md new['RB'][count] = rb new['RBR'][count] = rbr new['RBS'][count] = rbs new['FW'][count] = fw count+=1 return new ppservers = () job_server = pp.Server(ppservers=ppservers) f1 = job_server.submit(word_process, (newt1,count1), modules=("nltk","pandas", "re", "pprint", "pp")) f2 = job_server.submit(word_process, (newt2,count2), modules=("nltk", "pandas", "pp", "re", "pprint")) r1 = f1() print "this is r1" print r1 r2 = f2() print "this is r2" print r2 r3 = pandas.concat([r1,r2], axis=0) r3.to_csv("/home/williamshelton/Desktop/Data/badass3.csv")
UTF-8
Python
false
false
4,185
py
7
parallel_textbag.py
6
0.477419
0.444683
0
189
21.126984
102
dhanya07/project
15,857,019,289,468
0a97dd90cca53e2b33ddce8f6df34d1634063ff8
da2413bf169509213763444d28156d565dd38b48
/siteadmin/migrations/0004_auto_20200505_1603.py
1d3f5c7c1682bd5f05bfb816069926e1d1e5355f
[]
no_license
https://github.com/dhanya07/project
a8028caed596cd617d1d2a8082d97ebd64ad321c
fd4c3e01ca854ada016f0510e6edbfcabb3f8fce
refs/heads/master
2022-07-04T06:52:29.449386
2020-05-15T05:28:52
2020-05-15T05:28:52
264,094,608
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 2.2.7 on 2020-05-05 10:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('siteadmin', '0003_user_tb'), ] operations = [ migrations.RenameField( model_name='user_tb', old_name='contacno', new_name='contactno', ), ]
UTF-8
Python
false
false
360
py
37
0004_auto_20200505_1603.py
20
0.563889
0.511111
0
18
19
47
dvserrano/Tribolium
7,138,235,681,770
07f6922c74d3859534ce5a8497f2499bbbc4ed40
731398c0be15d825b388a55b62d136ef34575035
/Tribolium castaneum/imageserver/imageserver_venv/routes.py
065151020b9797e499f86779e5f3d8ac9f95a407
[]
no_license
https://github.com/dvserrano/Tribolium
eac78a8cabb45fb02a41d9be75708817d2708e05
719dcc97ad0dda3a83de380cc62269ba459291bc
refs/heads/main
2023-08-22T00:06:33.107533
2021-10-30T17:36:39
2021-10-30T17:36:39
414,007,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os from flask.helpers import send_from_directory from flask import Blueprint, request api_images = Blueprint('api_images', __name__) @api_images.route("/upload", methods=['POST']) def upload_image(): if request.method == "POST": file = request.files['file'] try: file.save(os.getcwd() + "/images/" + file.filename) return "Imagen guardada" except FileNotFoundError: return "Folder no existe" @api_images.route('/images/<string:filename>') def get_image(filename): return send_from_directory(os.getcwd() + "/images/", filename = filename, as_attachment=False) @api_images.route('/download/images/<string:filename>') def download_image(filename): return send_from_directory(os.getcwd() + "/images/", filename=filename, as_attachment=True) @api_images.route('/delete', methods=['POST']) def remove_image(): filename = request.form['filename'] #Verificamos si es un fichero if os.path.isfile(os.getcwd() + "/images/" + filename) == False: return "Esto no es un archivo" else: try: os.remove(os.getcwd() + "/images/" + filename) return "Imagen eliminada" except OSError: return "No se elimino el archivo"
UTF-8
Python
false
false
1,265
py
21
routes.py
5
0.638735
0.638735
0
41
29.853659
98
amakurin/CarND-Capstone
103,079,237,404
1505cb184fd6a843ca1c4605dedc4d597094494f
d5cb96088e2adb23705ece9abd5aa726ca9f7808
/ros/src/twist_controller/twist_controller.py
09433058e0e372c7fe5570aac036b06e43db8717
[]
no_license
https://github.com/amakurin/CarND-Capstone
dc5a0ff34618cb29594c13f9b3e8aeb5db00f81c
a13284ff7f9827cb316ab8d4ef3d9ce70ffa6884
refs/heads/master
2021-01-18T16:38:02.494891
2017-10-14T19:53:50
2017-10-14T19:53:50
100,465,295
4
8
null
true
2017-09-22T08:46:06
2017-08-16T08:15:58
2017-09-17T17:18:56
2017-09-22T08:46:06
2,332
0
3
0
Python
null
null
from yaw_controller import YawController from pid import PID from lowpass import LowPassFilter import math import rospy from styx_msgs.msg import Lane, Waypoint from geometry_msgs.msg import PoseStamped, Pose GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, *args, **kwargs): vehicle_mass = kwargs['vehicle_mass'] fuel_capacity = kwargs['fuel_capacity'] self.brake_deadband = kwargs['brake_deadband'] self.decel_limit = kwargs['decel_limit'] accel_limit = kwargs['accel_limit'] wheel_radius = kwargs['wheel_radius'] wheel_base = kwargs['wheel_base'] steer_ratio = kwargs['steer_ratio'] max_lat_accel = kwargs['max_lat_accel'] max_steer_angle = kwargs['max_steer_angle'] self.brake_tourque_const = (vehicle_mass + fuel_capacity * GAS_DENSITY) * wheel_radius self.current_dbw_enabled = False yaw_params = [wheel_base, steer_ratio, max_lat_accel, max_steer_angle] self.yaw_controller = YawController(*yaw_params) self.linear_pid = PID(0.9, 0.0005, 0.07, self.decel_limit, accel_limit) self.tau_correction = 0.2 self.ts_correction = 0.1 self.low_pass_filter_correction = LowPassFilter(self.tau_correction, self.ts_correction) self.previous_time = None pass def update_sample_step(self): current_time = rospy.get_time() sample_step = current_time - self.previous_time if self.previous_time else 0.05 self.previous_time = current_time return sample_step def control(self, linear_velocity_setpoint, angular_velocity_setpoint, linear_current_velocity, angular_current, dbw_enabled, final_waypoint1, final_waypoint2, current_location): if (not self.current_dbw_enabled) and dbw_enabled: self.current_dbw_enabled = True self.linear_pid.reset() self.previous_time = None else: self.current_dbw_enabled = False linear_velocity_error = linear_velocity_setpoint - linear_current_velocity sample_step = self.update_sample_step() velocity_correction = self.linear_pid.step(linear_velocity_error, sample_step) velocity_correction = self.low_pass_filter_correction.filt(velocity_correction) if abs(linear_velocity_setpoint)<0.01 and abs(linear_current_velocity) < 0.1: velocity_correction = self.decel_limit throttle = velocity_correction brake = 0. if throttle < 0.: decel = abs(throttle) #[alexm]NOTE: let engine decelerate the car if required deceleration below brake_deadband brake = self.brake_tourque_const * decel if decel > self.brake_deadband else 0. throttle = 0. #[alexm]::NOTE this lowpass leads to sending both throttle and brake nonzero. Maybe it is better to filter velocity_correction #brake = self.low_pass_filter_brake.filt(brake) #steering = self.yaw_controller.get_steering_pid(angular_velocity_setpoint, angular_current, dbw_enabled) #steering = 0. #if final_waypoint1 and final_waypoint2 and linear_current_velocity < 1.: # steering = self.yaw_controller.get_steering_pid_cte(final_waypoint1, final_waypoint2, current_location, dbw_enabled) #else: steering = self.yaw_controller.get_steering_calculated(linear_velocity_setpoint, angular_velocity_setpoint, linear_current_velocity) return throttle, brake, steering
UTF-8
Python
false
false
3,551
py
14
twist_controller.py
8
0.668262
0.655872
0
75
46.346667
182
CamilaTermine/programitas
10,058,813,416,574
064f8b39229be7aaca612e7b4ad829068fe46b3f
355413de94461705eafd40737fc3f098e85eb056
/Python/Parte1/14-07-2021/triangulo.py
0b052590c77db20922b4b01ac67a506028e4238d
[]
no_license
https://github.com/CamilaTermine/programitas
0972845cbb1a596a33d7b7bac1dce9048b7f5ed6
7c1728e280c2ec292a4c8cb4402499952c3ba80c
refs/heads/main
2023-07-13T02:12:51.908053
2021-08-25T02:14:40
2021-08-25T02:14:40
399,661,602
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
mensaje = "*" altura = int(input("ingrese la altura deseada: ")); for i in range (0, altura): for i2 in range (0,i): mensaje = mensaje + "*" mensaje = mensaje + '\n' for i in range (0, altura): for i2 in range (altura - i): mensaje = mensaje + "*" mensaje = mensaje + '\n' print(f"{mensaje}")
UTF-8
Python
false
false
328
py
68
triangulo.py
66
0.557927
0.542683
0
14
22.428571
51
gnd/smogdance
9,466,107,950,514
f92fda03e15a98fb6fbe2129179198102b4db3da
601122d5067773c7cb07c5799128cd803b3e64b8
/cleanup-monthly.py
7fe7c56fd21311b6d92bb20a5357919a285b51d7
[]
no_license
https://github.com/gnd/smogdance
eb6599e2da59892bf0a105e05a77136f0c69c2b9
2221db0a5827ddb85b2bca5afb9a2cb7875f79f2
refs/heads/master
2021-05-09T19:42:02.617667
2020-03-31T00:14:57
2020-03-31T00:14:57
118,653,520
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # -*- coding: utf-8 -*- """ Smogdance An open-source collection of scripts to collect, store and graph air quality data from publicly available sources. This runs once daily to remove records older than 30 days from the DATA_TABLE_MONTH table gnd, 2017 - 2018 """ import os import sys import time import shlex import MySQLdb import subprocess import ConfigParser ### load config settings_file = os.path.join(sys.path[0], 'settings_python') config = ConfigParser.ConfigParser() config.readfp(open(settings_file)) ### connect to the db DB_HOST = config.get('database', 'DB_HOST') DB_USER = config.get('database', 'DB_USER') DB_PASS = config.get('database', 'DB_PASS') DB_NAME = config.get('database', 'DB_NAME') DATA_TABLE_MONTH = config.get('database', 'DATA_TABLE_MONTH') db = MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME, use_unicode=True, charset="utf8") cur = db.cursor() ##### ##### Remove records older than 30 days ##### query = "DELETE FROM %s where timestamp < DATA_SUB(now() - INTERVAL 30 day)" % (DATA_TABLE_MONTH) cur.execute(query) db.commit() db.close()
UTF-8
Python
false
false
1,145
py
31
cleanup-monthly.py
30
0.700437
0.68559
0
43
25.627907
110
KarthikeyaSarma30/PROJECT_EULER
8,392,366,121,126
4fb093a455f1ea918620a4e2093928de6ebe2b50
87571e863a3b0aeec8cf03111ae753107103f70f
/projecteuler6.py
7e94f07c3f308fb6a1ffdb341ee6eaa652b7e55f
[]
no_license
https://github.com/KarthikeyaSarma30/PROJECT_EULER
601e4178d68be1b5bfc6ab5b4f84683b17556bec
6ff70b1f1f267965c5e4378a83936364bac5b9d2
refs/heads/main
2023-05-10T08:47:43.944846
2021-06-23T14:34:10
2021-06-23T14:34:10
379,562,421
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
n=100 squ_sum=((n*(n+1))/2)**2 sum_squ=((n*(n+1)*(2*n+1))/6) print(squ_sum-sum_squ)
UTF-8
Python
false
false
88
py
4
projecteuler6.py
4
0.511364
0.397727
0
4
20
29
tburgin/pycreateuserpkg
4,080,218,953,955
8150b39ec370761d3c8a9b1f34d890c320808007
b5a8f27a79a618affb7620585d5c07195dbe8be8
/locallibs/shadowhash.py
530f8fcaebbb539f6348373da18a08f5906ad3c8
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
https://github.com/tburgin/pycreateuserpkg
aa175a46f8d7cdc46f81bff6a64385742daa0d50
e4c1ce5ed718da68e90c6b21d54e5141f5acecb3
refs/heads/master
2020-12-18T12:55:08.732819
2020-01-24T21:01:44
2020-01-24T21:01:44
235,390,150
1
0
NOASSERTION
true
2020-01-21T16:38:00
2020-01-21T16:37:59
2020-01-11T17:39:49
2019-11-03T17:41:16
76
0
0
0
null
false
false
# Copyright 2017 Greg Neagle. # # 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. '''Functions for generating ShadowHashData''' import hashlib from . import arc4random from . import pbkdf2 from . import plistutils def make_salt(saltlen): '''Generate a random salt''' salt = '' for char in arc4random.randsample(0, 255, saltlen): salt += chr(char) return salt def generate(password): '''Generate a ShadowHashData structure as used by macOS 10.8+''' iterations = arc4random.randrange(30000, 50000) salt = make_salt(32) keylen = 128 try: entropy = hashlib.pbkdf2_hmac( 'sha512', password, salt, iterations, dklen=keylen) except AttributeError: # old Python, do it a different way entropy = pbkdf2.pbkdf2_bin( password, salt, iterations=iterations, keylen=keylen, hashfunc=hashlib.sha512) data = { 'SALTED-SHA512-PBKDF2': { 'entropy': buffer(entropy), 'iterations': iterations, 'salt': buffer(salt) }, } return plistutils.write_plist(data, plist_format='binary')
UTF-8
Python
false
false
1,635
py
9
shadowhash.py
5
0.670948
0.642202
0
54
29.277778
74
premandfriends/boardfarm-1
12,060,268,167,340
0de30a5990ed145ec01eec880e4c1faa07a49a2d
92b6091b6b37d55649aa31c606022923931085ad
/devices/base.py
a62d46fe1b4b4dc59b33a7b05c577988d1bbd5fa
[]
permissive
https://github.com/premandfriends/boardfarm-1
043d5db7d5cf09826eb4498f8ce8105fa065f5c2
3c952c94507fff25ba9955cad993610ea4a95e2e
refs/heads/master
2020-04-06T11:09:29.868388
2019-04-29T09:12:43
2019-04-30T14:10:50
157,405,854
0
0
BSD-3-Clause-Clear
true
2018-11-13T15:52:11
2018-11-13T15:52:10
2018-11-13T09:07:48
2018-11-13T15:37:45
730
0
0
0
null
false
null
# Copyright (c) 2015 # # All rights reserved. # # This file is distributed under the Clear BSD license. # The full text can be found in LICENSE in the root directory. import pexpect from datetime import datetime import re import os import time import common import error_detect import ipaddress from lib.regexlib import LinuxMacFormat, AllValidIpv6AddressesRegex from lib.logging import LoggerMeta, o_helper # To Do: maybe make this config variable BFT_DEBUG = "BFT_DEBUG" in os.environ class BaseDevice(pexpect.spawn): __metaclass__ = LoggerMeta log = "" log_calls = "" prompt = ['root\\@.*:.*#', ] delaybetweenchar = None def get_interface_ipaddr(self, interface): self.sendline("\nifconfig %s" % interface) self.expect('addr:(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}).*(Bcast|P-t-P):', timeout=5) ipaddr = self.match.group(1) self.expect(self.prompt) return ipaddr def get_interface_ip6addr(self, interface): self.sendline("\nifconfig %s" % interface) self.expect_exact("ifconfig %s" % interface) self.expect(self.prompt) for match in re.findall(AllValidIpv6AddressesRegex, self.before): ip6addr = ipaddress.IPv6Address(unicode(match)) if not ip6addr.is_link_local: # TODO: at some point just return ip6addr return match raise Exception("Did not find non-link-local ipv6 address") def get_interface_macaddr(self, interface): self.sendline('cat /sys/class/net/%s/address' % interface) self.expect_exact('cat /sys/class/net/%s/address' % interface) self.expect(LinuxMacFormat) macaddr = self.match.group() self.expect(self.prompt) return macaddr def get_seconds_uptime(self): '''Return seconds since last reboot. Stored in /proc/uptime''' self.sendcontrol('c') self.expect(self.prompt) self.sendline('\ncat /proc/uptime') self.expect('((\d+)\.(\d{2}))(\s)(\d+)\.(\d{2})') seconds_up = float(self.match.group(1)) self.expect(self.prompt) return seconds_up def get_logfile_read(self): if hasattr(self, "_logfile_read"): return self._logfile_read else: return None def expect_prompt(self, timeout=30): self.expect(self.prompt, timeout=timeout) def check_output(self, cmd, timeout=30): '''Send a string to device, then return the output between that string and the next prompt.''' self.sendline("\n" + cmd) self.expect_exact(cmd, timeout=5) try: self.expect(self.prompt, timeout=timeout) except Exception as e: self.sendcontrol('c') raise Exception("Command did not complete within %s seconds. Prompt was not seen." % timeout) return self.before.strip() def write(self, string): self._logfile_read.write(string) def set_logfile_read(self, value): if value == None: self._logfile_read = None return if isinstance(value, o_helper): self._logfile_read = value elif value is not None: self._logfile_read = o_helper(self, value, getattr(self, "color", None)) logfile_read = property(get_logfile_read, set_logfile_read) def interact(self, escape_character=chr(29), input_filter=None, output_filter=None): o = self._logfile_read self.logfile_read = None ret = super(BaseDevice, self).interact(escape_character, input_filter, output_filter) self.logfile_read = o return ret # perf related def parse_sar_iface_pkts(self, wan, lan): self.expect('Average.*idle\r\nAverage:\s+all(\s+[0-9]+.[0-9]+){6}\r\n') idle = float(self.match.group(1)) self.expect("Average.*rxmcst/s.*\r\n") wan_pps = None client_pps = None if lan is None: exp = [wan] else: exp = [wan,lan] for x in range(0, len(exp)): i = self.expect(exp) if i == 0: # parse wan stats self.expect("(\d+.\d+)\s+(\d+.\d+)") wan_pps = float(self.match.group(1)) + float(self.match.group(2)) if i == 1: self.expect("(\d+.\d+)\s+(\d+.\d+)") client_pps = float(self.match.group(1)) + float(self.match.group(2)) return idle, wan_pps, client_pps def check_perf(self): self.sendline('uname -r') self.expect('uname -r') self.expect(self.prompt) self.kernel_version = self.before self.sendline('\nperf --version') i = self.expect(['not found', 'perf version']) self.expect(self.prompt) if i == 0: return False return True def check_output_perf(self, cmd, events): perf_args = self.perf_args(events) self.sendline("perf stat -a -e %s time %s" % (perf_args, cmd)) def parse_perf(self, events): mapping = self.parse_perf_board() ret = [] for e in mapping: if e['name'] not in events: continue self.expect("(\d+) %s" % e['expect']) e['value'] = int(self.match.group(1)) ret.append(e) return ret # end perf related # Optional send and expect functions to try and be fancy at catching errors def send(self, s): if BFT_DEBUG: if 'pexpect/__init__.py: sendline():' in error_detect.caller_file_line(3): idx = 4 else: idx = 3 common.print_bold("%s = sending: %s" % (error_detect.caller_file_line(idx), repr(s))) if self.delaybetweenchar is not None: ret = 0 for char in s: ret += super(BaseDevice, self).send(char) time.sleep(self.delaybetweenchar) return ret return super(BaseDevice, self).send(s) def expect_helper(self, pattern, wrapper, *args, **kwargs): if not BFT_DEBUG: return wrapper(pattern, *args, **kwargs) if 'base.py: expect():' in error_detect.caller_file_line(3) or \ 'base.py: expect_exact():' in error_detect.caller_file_line(3): idx = 5 else: idx = 3 common.print_bold("%s = expecting: %s" % (error_detect.caller_file_line(idx), repr(pattern))) try: ret = wrapper(pattern, *args, **kwargs) frame = error_detect.caller_file_line(idx) if hasattr(self.match, "group"): common.print_bold("%s = matched: %s" % (frame, repr(self.match.group()))) else: common.print_bold("%s = matched: %s" % (frame, repr(pattern))) return ret except: common.print_bold("expired") raise def expect(self, pattern, *args, **kwargs): wrapper = super(BaseDevice, self).expect return self.expect_helper(pattern, wrapper, *args, **kwargs) def expect_exact(self, pattern, *args, **kwargs): wrapper = super(BaseDevice, self).expect_exact return self.expect_helper(pattern, wrapper, *args, **kwargs) def sendcontrol(self, char): if BFT_DEBUG: common.print_bold("%s = sending: control-%s" % (error_detect.caller_file_line(3), repr(char))) return super(BaseDevice, self).sendcontrol(char) def expect_exact_split(self, pattern, nsplit=1, *args, **kwargs): pass def enable_ipv6(self, interface): self.sendline("sysctl net.ipv6.conf."+interface+".accept_ra=2") self.expect(self.prompt, timeout=30) self.sendline("sysctl net.ipv6.conf."+interface+".disable_ipv6=0") self.expect(self.prompt, timeout=30) def disable_ipv6(self, interface): self.sendline("sysctl net.ipv6.conf."+interface+".disable_ipv6=1") self.expect(self.prompt, timeout=30) def set_printk(self, CUR=1, DEF=1, MIN=1, BTDEF=7): try: self.sendline('echo "%d %d %d %d" > /proc/sys/kernel/printk'% (CUR, DEF, MIN, BTDEF)) self.expect(self.prompt, timeout=10) if not BFT_DEBUG: common.print_bold("printk set to %d %d %d %d" % (CUR, DEF, MIN, BTDEF)) except: pass def prefer_ipv4(self, pref=True): """Edits the /etc/gai.conf file This is to give/remove ipv4 preference (by default ipv6 is preferred) See /etc/gai.conf inline comments for more details """ if pref is True: self.sendline("sed -i 's/^#precedence ::ffff:0:0\/96 100/precedence ::ffff:0:0\/96 100/' /etc/gai.conf") else: self.sendline("sed -i 's/^precedence ::ffff:0:0\/96 100/#precedence ::ffff:0:0\/96 100/' /etc/gai.conf") self.expect(self.prompt)
UTF-8
Python
false
false
9,126
py
5
base.py
5
0.564541
0.552487
0
271
32.671587
119
ethanjli/onshape-laser-cutting
4,320,737,150,643
3a1d7f4ef19ebfe6eab129bd293aaa00289daaae
a3ea097db7fc228e21ad44f634c18d3158f13dc9
/preprocess.py
e5cb5a8b26eebbd4527b799202b5257378118548
[ "BSD-3-Clause" ]
permissive
https://github.com/ethanjli/onshape-laser-cutting
8355b69f70fad858d06bfa6ba2916bbc076032a9
c2069154d1bb68c1c494a48cd3a8a3b4fa347eba
refs/heads/master
2021-05-14T03:56:59.124051
2018-01-08T21:51:12
2018-01-08T21:51:12
116,631,599
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 import os import subprocess import argparse from lxml import etree # File path utilities class FileTypeError(ValueError): """Exception raised when attempting to process unsupported file types.""" pass def get_file_ext(file_path: str) -> str: """Returns the file extension for the provided file path. Args: file_path: a file path with or without a file extension. Returns: The file extension, including the leading '.', of file_path. Empty string when no file extension exists. """ return os.path.splitext(os.path.basename(file_path))[1] def get_svg_name(dxf_path: str) -> str: """Returns the path the provided dxf file path renamed to an svg file. Args: dxf_path: a file path, such as for a dxf file. Returns: A file path which is identical to dxf_path but with a '.svg' file extension instead of whatever file extension was in dxf_path. """ (input_name, __) = os.path.splitext(os.path.basename(dxf_path)) svg_name = input_name + '.svg' return svg_name # Preprocessing def convert(dxf_path: str, svg_path: str) -> None: """Runs Inkscape to import a dxf file and save it as an svg file. Args: dxf_path: a file path to a dxf file. Must have '.dxf' as its file extension. svg_path: a file path to the svg file to create. """ subprocess.run(['inkscape', '-l', svg_path, dxf_path]) def style_strokes(svg_path: str, stroke_color: str='#ff0000', stroke_width: float=0.07559055) -> etree.ElementTree: """Modifies a svg file so that all black paths become laser cutting paths. Args: svg_path: a file path to the svg file to modify and overwrite. stroke_color: the color, as a hex code, to set paths to. stroke_width: the stroke width, in pixels (at 96 pixels per inch), to set paths to. Returns: The modified XML tree. """ xml = etree.parse(svg_path) svg = xml.getroot() paths = svg.findall('.//{http://www.w3.org/2000/svg}path' '[@style="stroke:#000000;fill:none"]') for path in paths: path.set('style', ( 'fill:none;stroke:{};stroke-opacity:1;stroke-width:{};' 'stroke-miterlimit:4;stroke-dasharray:none' ).format(stroke_color, stroke_width)) return xml def preprocess(dxf_path: str, svg_path: str=None) -> None: """Preprocesses the specified dxf file and saves the result. Args: dxf_path: the path of the dxf file to preprocess. Must end in '.dxf'. svg_path: the path of the file to save the preprocessed svg result. Defaults to dxf_path, but ending in '.svg' instead of '.dxf'. Raises: FileTypeError: if dxf_path does not end in '.dxf'. """ dxf_ext = get_file_ext(dxf_path) if dxf_ext != '.dxf': raise FileTypeError('Unsupported file extension {} on input file {}!' .format(dxf_ext, dxf_path)) if svg_path is None: parent_path = os.path.dirname(dxf_path) svg_path = os.path.join(parent_path, get_svg_name(dxf_path)) elif not get_file_ext(svg_path): parent_path = svg_path svg_path = os.path.join(parent_path, get_svg_name(dxf_path)) convert(dxf_path, svg_path) print('Converted {} to {}.'.format(dxf_path, svg_path)) xml = style_strokes(svg_path) xml.write(svg_path) print('Set stroke styles on {}.'.format(svg_path)) def main(input_path: str, output_path: str) -> None: """Preprocesses the specified dxf file(s) and saves the result(s). Args: dxf_path: the path of the dxf file to preprocess, or the directory containing the dxf files to preprocess. svg_path: the path of the file to save the preprocessed svg result, or the path of the directory of the files to save the preprocessed svg results. If dxf_path is a single file, defaults to dxf_path, but with a '.svg' file extension instead of '.dxf'. If dxf_path is a directory, defaults to dxf_path. """ input_ext = get_file_ext(input_path) if input_ext: preprocess(input_path, output_path) return for filename in os.listdir(input_path): input_ext = get_file_ext(filename) try: preprocess(os.path.join(input_path, filename), output_path) except FileTypeError: print('Skipped {}'.format(filename)) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Preprocess an Onshape DXF drawing export for laser cutting.' ) parser.add_argument( 'input', type=str, help=('Path to the DXF file to preprocess, or path to ' 'the directory of DXF files to preprocess.') ) parser.add_argument( '-o', '--output', type=str, default=None, help=('Path to the output SVG file to generate, or path to the intended ' 'parent directory of the output SVG file. Default for a svg input ' 'path: the input path, but with .dxf replaced by .svg. Default ' 'for a directory input path: the input directory.') ) args = parser.parse_args() main(args.input, args.output)
UTF-8
Python
false
false
5,322
py
2
preprocess.py
1
0.62251
0.616873
0
144
35.951389
82
databand-ai/dbnd
6,073,083,805,001
472202b115c9f0fc10771a32085e549c4b64ca4f
b7163b44b679e082fe97cf7fcd0c73b2fcdb38eb
/modules/dbnd/src/dbnd/_core/utils/dotdict.py
cf8236029bd697b970b97da06b4ae4e5a739e1ad
[ "Apache-2.0" ]
permissive
https://github.com/databand-ai/dbnd
70c95d95e12bfb8ab471a6dce27691ed658cb92d
d59c99dcdcd280d7eec36a693dd80f8c8c831ea2
refs/heads/develop
2023-06-24T18:07:56.524526
2023-05-28T07:57:36
2023-05-28T07:57:36
231,361,064
257
33
Apache-2.0
false
2023-08-06T08:30:28
2020-01-02T10:42:47
2023-06-08T05:46:38
2023-08-06T08:30:27
11,951
239
33
24
Python
false
false
# © Copyright Databand.ai, an IBM Company 2022 import inspect class dotdict(dict): """dot.notation access to dictionary attributes""" __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def _as_dotted_dict(**dict_obj): return dotdict(**dict_obj) def build_dict_from_instance_properties(class_instance) -> dict: """Returns dict of all class properties including @property methods""" properties = {} for prop_name in dir(class_instance): prop_value = getattr(class_instance, prop_name) if not prop_name.startswith("__") and not inspect.ismethod(prop_value): properties[prop_name] = prop_value return properties class rdotdict(dict): """ this is "recursive" dotdict - provides dot-notation access to dict, and recursively adds itself for internal values (dicts and lists). So this code is valid: ``` d = {"a": [{"b": 42}]} rdotdict(d).a[0].b == 42 ``` """ def __getattr__(self, item): return self[item] def __getitem__(self, item): return rdotdict.try_create(dict.__getitem__(self, item)) @staticmethod def try_create(val): """Applies rdotdict for rdotdict-able object (i.e dict or list)""" if isinstance(val, dict): return rdotdict(**val) if isinstance(val, list): return [rdotdict.try_create(x) for x in val] return val
UTF-8
Python
false
false
1,450
py
1,775
dotdict.py
1,513
0.619048
0.612836
0
51
27.411765
87
bpinkert/portfolio
9,594,956,974,558
721e4c0b91ec491ff9729d374d49bbc67ce0657f
be652b0b1b255df320d244caf115e6fabb60c77d
/savvystripe/checkout/urls.py
bcb8bf4a3155f11f2353aa10d76b6a0c83aa76b7
[]
no_license
https://github.com/bpinkert/portfolio
4b505458bbdca3bada05039ea791c6cba3e58ffd
d8ff0582611f9dabaeee6d6ae94113fd17b98ccb
refs/heads/master
2022-12-05T08:25:10.105766
2019-06-24T22:25:59
2019-06-24T22:25:59
192,994,316
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import views as checkout_views from .models import Item, Service urlpatterns=[ url(r'^add-to-cart/$', checkout_views.add_to_cart, name='add-to-cart' ), url(r'^add-subscription/$', checkout_views.add_subscription, name='add-subscription'), url(r'^before-checkout/$', checkout_views.before_checkout, name='before-checkout'), url(r'^cart/$', checkout_views.get_cart, name='cart'), url(r'^cart-subscribe/$', checkout_views.cart_subscribe, name='cart-subscribe'), url(r'^cart-total/$', checkout_views.get_cart_total, name='cart-total'), url(r'^checkout/$', checkout_views.checkout, name='checkout'), url(r'^checkout-thanks/$', checkout_views.checkoutThanks, name='checkoutThanks'), url(r'^remove-from-cart/$', checkout_views.remove_from_cart, name='remove-from-cart'), url(r'^remove-subscription/$', checkout_views.remove_subscription, name='remove-subscription'), url(r'^unsubscribe/$', checkout_views.unsubscribe, name='ubsubscribe'), url(r'^subscribe/$', checkout_views.subscribe, name='subscribe'), url(r'^subscribe-card/$', checkout_views.subscribe_savecard, name='subscribe-card'), ]
UTF-8
Python
false
false
1,302
py
200
urls.py
117
0.718126
0.718126
0
24
53.291667
99
chibi314/2015-soft3
12,532,714,610,161
b9d97ab175ca89e94452ee7142f67527debc652b
6656ad45508c039cc0b171e76f6808e00803999d
/20151021/src/enshu_20151021/test/check_topic.py
2432284fbe1b0795e2e94129b756db8c825d0e5d
[]
no_license
https://github.com/chibi314/2015-soft3
25a9a016f2ee8e80255ad4fce5dffa6f6a5be095
bcb5329395e74c8b7612d70347360fabc20c8240
refs/heads/master
2020-12-26T02:21:52.297158
2016-10-14T09:17:49
2016-10-14T09:17:49
43,403,433
0
0
null
true
2015-10-07T02:14:01
2015-09-30T01:02:00
2015-09-29T08:51:37
2015-10-07T02:13:01
57
0
0
0
null
null
null
#!/usr/bin/env python import rospy import sys, time import unittest from rostopic import _rostopic_info ## A sample python unit test class TestCheckTopic(unittest.TestCase): def test_check_topic(self): time.sleep(3) topic = rospy.get_param("/test/topic") info = _rostopic_info(topic) self.assertTrue(not info) if __name__ == '__main__': import rostest rostest.rosrun('enshu_20151021', 'test_check_topic', TestCheckTopic)
UTF-8
Python
false
false
468
py
36
check_topic.py
11
0.675214
0.655983
0
18
25
72
cnxtech/supply-claim
17,824,114,307,360
2f0dda6899cddb3fb4d235b221bac5d2f644add1
3aca27d7522fb2ee7ebb31898b9f2785ee0210cc
/backend/epcis_api/routes.py
3df03ea975305a04494f09a5059b94149aec66f7
[]
no_license
https://github.com/cnxtech/supply-claim
62285d578537e96d07d3e9dc525110cfc16dd7b1
cd3e5894b47ef63887d4fd8ebc1ab9e1a42d420c
refs/heads/master
2023-05-15T05:04:16.986853
2017-10-12T13:20:33
2017-10-12T13:20:33
190,126,547
0
0
null
true
2023-05-01T20:12:23
2019-06-04T04:03:22
2019-06-04T04:03:25
2023-05-01T20:12:20
28
0
0
2
Python
false
false
# -*- coding: utf-8 -* from epcis_api import api from epcis_api.api import EPCISEventAPI api.add_resource(EPCISEventAPI, '/epcis/', endpoint='epcis') api.add_resource(EPCISEventAPI, '/epcis/<string:id>', endpoint='epcisId')
UTF-8
Python
false
false
225
py
15
routes.py
7
0.733333
0.728889
0
7
31.285714
73
ydimtirov/Personal
16,664,473,116,023
ceb24d2de65265dd3b231e9f07c105e2916ae2a4
fc9d4a6330c771a4b4805b501dcad3fab6128e86
/python_scripts/kmeans.py
94b34af3c9bfeb960b29c23b8e53a7401cf52420
[]
no_license
https://github.com/ydimtirov/Personal
9f0659f2a1ac3e33bcd85300ed5239c85e8d9a84
7ee57a6696cd543b7cd28373149b924dad8100b8
refs/heads/master
2021-01-11T11:58:39.857005
2017-02-11T08:53:25
2017-02-11T08:53:25
79,540,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import urllib # url with dataset url = "http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" # download the file raw_data = urllib.urlopen(url) # load the CSV file as a numpy matrix dataset = np.loadtxt(raw_data, delimiter=",") # separate the data from the target attributes X = dataset[:,0:8] y = dataset[:,8] from sklearn import preprocessing # normalize the data attributes normalized_X = preprocessing.normalize(X) # standardize the data attributes standardized_X = preprocessing.scale(X) from sklearn import metrics from sklearn.ensemble import ExtraTreesClassifier model = ExtraTreesClassifier() model.fit(X, y) # display the relative importance of each attribute # print(model.feature_importances_) from sklearn.feature_selection import RFE from sklearn.linear_model import LogisticRegression model = LogisticRegression() # create the RFE model and select 3 attributes rfe = RFE(model, 3) rfe = rfe.fit(X, y) # summarize the selection of the attributes # print(rfe.support_) # print(rfe.ranking_) from sklearn import metrics from sklearn.linear_model import LogisticRegression model = LogisticRegression() model.fit(X, y) print(model) # make predictions expected = y predicted = model.predict(X) # summarize the fit of the model print(metrics.classification_report(expected, predicted)) print(metrics.confusion_matrix(expected, predicted))
UTF-8
Python
false
false
1,426
py
35
kmeans.py
20
0.785414
0.781907
0
49
28.122449
113
tensorflow/tensorflow
5,085,241,294,089
39f17e04f76e836cc39d5b419f81914df9f2da5a
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/python/ops/resources.py
b1afb75d51f9a0308f4b3feff6bc26a94ecbc67b
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
https://github.com/tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
false
2023-09-14T20:55:50
2015-11-07T01:19:20
2023-09-14T19:53:18
2023-09-14T20:55:50
933,151
177,590
88,918
2,038
C++
false
false
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for using generic resources.""" # pylint: disable=g-bad-name import collections import os from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import array_ops_stack from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.util import tf_should_use _Resource = collections.namedtuple("_Resource", ["handle", "create", "is_initialized"]) def register_resource(handle, create_op, is_initialized_op, is_shared=True): """Registers a resource into the appropriate collections. This makes the resource findable in either the shared or local resources collection. Args: handle: op which returns a handle for the resource. create_op: op which initializes the resource. is_initialized_op: op which returns a scalar boolean tensor of whether the resource has been initialized. is_shared: if True, the resource gets added to the shared resource collection; otherwise it gets added to the local resource collection. """ resource = _Resource(handle, create_op, is_initialized_op) if is_shared: ops.add_to_collection(ops.GraphKeys.RESOURCES, resource) else: ops.add_to_collection(ops.GraphKeys.LOCAL_RESOURCES, resource) def shared_resources(): """Returns resources visible to all tasks in the cluster.""" return ops.get_collection(ops.GraphKeys.RESOURCES) def local_resources(): """Returns resources intended to be local to this session.""" return ops.get_collection(ops.GraphKeys.LOCAL_RESOURCES) def report_uninitialized_resources(resource_list=None, name="report_uninitialized_resources"): """Returns the names of all uninitialized resources in resource_list. If the returned tensor is empty then all resources have been initialized. Args: resource_list: resources to check. If None, will use shared_resources() + local_resources(). name: name for the resource-checking op. Returns: Tensor containing names of the handles of all resources which have not yet been initialized. """ if resource_list is None: resource_list = shared_resources() + local_resources() with ops.name_scope(name): # Run all operations on CPU local_device = os.environ.get( "TF_DEVICE_FOR_UNINITIALIZED_VARIABLE_REPORTING", "/cpu:0") with ops.device(local_device): if not resource_list: # Return an empty tensor so we only need to check for returned tensor # size being 0 as an indication of model ready. return array_ops.constant([], dtype=dtypes.string) # Get a 1-D boolean tensor listing whether each resource is initialized. variables_mask = math_ops.logical_not( array_ops_stack.stack([r.is_initialized for r in resource_list])) # Get a 1-D string tensor containing all the resource names. variable_names_tensor = array_ops.constant( [s.handle.name for s in resource_list]) # Return a 1-D tensor containing all the names of uninitialized resources. return array_ops.boolean_mask(variable_names_tensor, variables_mask) @tf_should_use.should_use_result def initialize_resources(resource_list, name="init"): """Initializes the resources in the given list. Args: resource_list: list of resources to initialize. name: name of the initialization op. Returns: op responsible for initializing all resources. """ if resource_list: return control_flow_ops.group(*[r.create for r in resource_list], name=name) return control_flow_ops.no_op(name=name)
UTF-8
Python
false
false
4,390
py
20,451
resources.py
13,396
0.715034
0.712073
0
117
36.521368
80
jorzel/codefights
4,724,464,065,452
e0259143fb743f31d30c3bb7972bdc7dab0bed6f
e748e6d96aace1c9149327f384e0de07d743715a
/arcade/core/drawRectangle.py
545d9c16759d437660b2a1171de9b9e4a853a6ac
[]
no_license
https://github.com/jorzel/codefights
cdfc4cb32261b064ffc605bfd927bf237885b5d2
28b62a2ae3809f0eb487198044c0fe74be09d4e8
refs/heads/master
2022-04-28T06:54:26.170503
2022-03-23T22:22:20
2022-03-23T22:22:20
110,818,719
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
""" You are implementing a command-line version of the Paint app. Since the command line doesn't support colors, you are using different characters to represent pixels. Your current goal is to support rectangle x1 y1 x2 y2 operation, which draws a rectangle that has an upper left corner at (x1, y1) and a lower right corner at (x2, y2). Here the x-axis points from left to right, and the y-axis points from top to bottom. Given the initial canvas state and the array that represents the coordinates of the two corners, return the canvas state after the operation is applied. For the details about how rectangles are painted, see the example. Example For canvas = [['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'], ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'], ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'], ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'], ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']] and rectangle = [1, 1, 4, 3], the output should be drawRectangle(canvas, rectangle) = [['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'], ['a', '*', '-', '-', '*', 'a', 'a', 'a'], ['a', '|', 'a', 'a', '|', 'a', 'a', 'a'], ['b', '*', '-', '-', '*', 'b', 'b', 'b'], ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']] Note that rectangle sides are depicted as -s and |s, asterisks (*) stand for its corners and all of the other "pixels" remain the same. Color in the example is used only for illustration. """ def drawRectangle(canvas, rectangle): lt = rectangle[0], rectangle[1] rt = rectangle[2], rectangle[1] lb = rectangle[0], rectangle[3] rb = rectangle[2], rectangle[3] for row in range(lt[1], lb[1] + 1): for col in range(lt[0], rt[0] + 1): if (col, row) in [lt, rt, lb, rb]: canvas[row][col] = '*' elif row in (lt[1], lb[1]): canvas[row][col] = '-' elif col in (lt[0], rt[0]): canvas[row][col] = '|' return canvas
UTF-8
Python
false
false
2,082
py
305
drawRectangle.py
304
0.506244
0.491835
0
39
52.410256
418
dopamine333/ARPG_Prototype
5,257,039,971,339
9cc83d5c5ba0c1811f323892bc9483d9c21ebdca
3b687583c29e44b5d6d835b9b770a3a19119699f
/Scripts/Factory/FactoryManager.py
f84c37f1261be29938cf4de657a12d2672447f96
[]
no_license
https://github.com/dopamine333/ARPG_Prototype
3acc7dfe358eb9501168b0a5eae632644f8015d2
ec241f69194e957a9d421bd6395f4aa54dc1749b
refs/heads/main
2023-07-16T11:43:55.206606
2021-08-14T15:12:06
2021-08-14T15:12:06
384,057,838
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from Scripts.Factory.OnLevelGameObjectFactory import OnLevelGameObjectFactory from Scripts.Factory.CharacterFactory import CharacterFactory from Scripts.Tools.Singleton import Singleton class FactoryManager(Singleton): def __init__(self) -> None: self.characterfactory = CharacterFactory() self.onlevelgameobjectfactory = OnLevelGameObjectFactory() def get_characterfactory(self): return self.characterfactory def get_onlevelgameobjectfactory(self): return self.onlevelgameobjectfactory
UTF-8
Python
false
false
535
py
65
FactoryManager.py
65
0.783178
0.783178
0
15
34.666667
77
xcooo/scrapy-plus
10,866,267,259,210
edf8871eb3a9d1a2a8acc1467aa16d72b4bb99f5
63c67a26814a6fc6a68c21e1151cb5c760eeac86
/scrapy_plus/core/downloader.py
1ca1c82a5920ceb84a5bf6a6970443a9d7887f16
[]
no_license
https://github.com/xcooo/scrapy-plus
0fc519fcb5e08653e716409889a0a972e4e9e5df
4bceb69d054d3a54c558383de79cc8187dbdaeec
refs/heads/master
2022-01-21T21:05:03.829997
2019-07-29T02:48:38
2019-07-29T02:48:38
198,324,315
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# encoding: utf-8 # !/usr/bin/env python """ @file: downloader.py @author: www.xcooo.cn @Mail: 602006050@qq.com """ # 下载器 import requests from ..http.response import Response from ..utils.log import logger class Downloader(): # 完成对下载器的封装 def get_response(self, request): """ 实现构造请求对象,发送请求,返回响应 :param request: request :return: response """ if request.method.upper() == 'GET': resp = requests.get(request.url, headers=request.headers, params=request.params) elif request.method.upper() == 'POST': resp = requests.post(request.url, headers=request.headers, params=request.params, data=request.data) else: raise Exception('请求方法不支持: <{}>'.format(request.method)) logger.info('<{} {}>'.format(resp.status_code,resp.request.url)) return Response(url=resp.url, headers=resp.headers, body=resp.content, status_code=resp.status_code)
UTF-8
Python
false
false
1,023
py
20
downloader.py
19
0.640084
0.629591
0
30
30.733333
112
tanvir43/daily-eCommerce
4,114,578,703,234
eebe98c2051a8dd59c1b636a221cf6337b6135ee
8575c8e29ac5bdac7736e39535fdbadbd3ce2b3d
/products/migrations/0008_delete_categorymanager.py
76040a3783cd09236297871f963628b419f5500a
[]
no_license
https://github.com/tanvir43/daily-eCommerce
795bf4abb4e3021dfc05b7a42b194f66fd591ab1
418158b3e3559c3a644c2b34ca63170b1b1cb8d2
refs/heads/master
2022-12-17T23:30:08.348855
2020-09-22T05:06:13
2020-09-22T05:06:13
255,512,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.0.4 on 2020-04-23 13:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('products', '0007_auto_20200419_1150'), ] operations = [ migrations.DeleteModel( name='CategoryManager', ), ]
UTF-8
Python
false
false
305
py
96
0008_delete_categorymanager.py
93
0.606557
0.504918
0
16
18.0625
48
Raushan-Raj2552/Codeforces-solution
11,897,059,457,704
0103347671f685824fbe93407548e6e2c4652b90
f7404cbbabf00d49cd89765c5bbae328ab973591
/208A.py
b5449a979100b6906cb1bf221e7d4bbfdf96f36f
[]
no_license
https://github.com/Raushan-Raj2552/Codeforces-solution
2aab9580339eb2e3c4d65edb14021dd83d55879b
bcdecbed3b9d7369386e37ef4b366c3786e9e082
refs/heads/master
2022-10-15T16:18:17.189762
2020-05-30T06:20:55
2020-05-30T06:20:55
259,187,175
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
orig = str(input()) rem = "WUB" res = orig.replace(rem,"") print(res)
UTF-8
Python
false
false
72
py
98
208A.py
97
0.597222
0.597222
0
4
16.5
26
tiger1016/mb_app
6,133,213,343,681
a3f806d76bda640f5f6ca64ce2ce1af21e26a4f9
347b5682618a26efe04a8baa4e059dc68051f253
/pages/tests.py
b4bd5b648315eebd52e0b143b09aefe4827dc797
[]
no_license
https://github.com/tiger1016/mb_app
95db485aa6dd9b18a647074cbfec00c3eb6a698f
d631b8c0509c4948c504bedd1178c63e07f88643
refs/heads/master
2020-11-28T06:20:38.551059
2019-12-23T10:41:10
2019-12-23T10:41:10
229,726,668
0
0
null
false
2019-12-23T10:41:11
2019-12-23T10:08:53
2019-12-23T10:28:27
2019-12-23T10:41:11
0
0
0
0
Python
false
false
from django.test import SimpleTestCase # Create your tests here. class SimpleTests(SimpleTestCase): def test_homepage_status(self): request = self.client.get('/pages/about/') self.assertEqual(request.status_code, 200) def test_aboutpage_status(self): request = self.client.get('/pages/home/') self.assertEqual(request.status_code, 200)
UTF-8
Python
false
false
383
py
4
tests.py
4
0.686684
0.671018
0
13
28.538462
50
CarlSpacklersGopher/DailyCodingProblems
14,946,486,213,538
377704aae8d79e4a1c8bd7a0510ee152e9955c39
1cffaf09df21078fec1b0485cbb281555dc67933
/2020_01_08_SumInList/test_sum_in_list.py
639dfb300fe4a928d59b479978d71d747c92ad8a
[]
no_license
https://github.com/CarlSpacklersGopher/DailyCodingProblems
52fc9fcefd63e0756f19dbd8e85d933a7518abc5
003ee64a75e4ccda85e31244ddd09bdb426c736f
refs/heads/master
2020-12-07T13:06:10.205936
2020-01-09T06:18:31
2020-01-09T06:18:31
232,708,919
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from sum_in_list import is_sum_in_list class SumInListTestCase(unittest.TestCase): """Tests for 'sum_in_list.py'""" def test_example(self): """Using the example in the problem statement""" self.assertTrue(is_sum_in_list([10, 15, 3, 7], 17)) self.assertFalse(is_sum_in_list([10, 15, 3, 7], 19)) def test_k_not_present(self): """Purpose: Verify 2 numbers in the list do not sum to k""" list_of_numbers = [10, 15, 3, 7] k = 12 self.assertFalse(is_sum_in_list(list_of_numbers, k)) def test_big_list(self): """Purpose: Verify 2 numbers in the list sum to k.""" list_of_numbers = [] for i in range(1, 1000): list_of_numbers.append(i) # Make desired sum the sum of the last 2 numbers to maximize the number of items processed. k = list_of_numbers[-1] + list_of_numbers[-2] self.assertTrue(is_sum_in_list(list_of_numbers, k)) def test_negative_sum(self): """Purpose: Verify the handling of negative numbers""" self.assertTrue(is_sum_in_list([-1, 0, 5, 9, -3], -4)) if __name__ == '__main__': # Run tests. Dump output to log. log_file_name = 'test_sum_in_list.log' with open(log_file_name, 'w') as log_file: runner = unittest.TextTestRunner(log_file) unittest.main(testRunner=runner) print("running tests")
UTF-8
Python
false
false
1,413
py
2
test_sum_in_list.py
2
0.60368
0.575372
0
40
34.3
99
iostapyshyn/assp3
10,350,871,226,254
ef2beb7dc1765aadb1cacc2d1a8de1db4003f8a3
3b6fc08a852a9204aa85c2a1f748af98772d783b
/c.py
c280be59936afb2b210016a714f1339f28f8f6e9
[]
no_license
https://github.com/iostapyshyn/assp3
141a23cc76ae6f0c7ff54c7371412555ed35f32a
3bd26f11f64def7c5992732026ad23c2966522ee
refs/heads/master
2020-12-20T11:44:38.098100
2020-01-24T18:58:01
2020-01-24T18:58:01
236,064,145
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import scipy.io.wavfile plt.style.use('ggplot') from a import * FILENAME = 'audio/aeiou_16000.wav' DURATION = 100 # Computes CEPSTRUM for whole signal. # The FFT size depends on the supplied window size # window - analysis window # hop - hop size # count - the size of the matrix column def stcep(y, window, hop, count): N = len(window) hops = len(y)//hop kmat = np.zeros((hops, count)) for i in range(hops): buf = y[i*hop:(i*hop)+N] buf *= window[:len(buf)] fftbuf = np.fft.fft(buf) cepbuf = cepstrum(fftbuf) kmat[i] = cepbuf[0:count] return kmat if __name__ == '__main__': # Read and normalize the audio file fs, y = scipy.io.wavfile.read(FILENAME) y = y * (0.99 / max(abs(y))) # Normalize # Calculate the number of samples for analysis sample_duration_ms = 1/fs * 1000 # duration of one sample in ms samples = int(DURATION / sample_duration_ms) kmat = stcep(y, np.hanning(samples), 512, 200) fig = plt.figure() sub = fig.add_subplot(111) for i in kmat: plot_cepstrum(sub, i, fs) plt.pause(DURATION/1000) plt.cla() plt.show()
UTF-8
Python
false
false
1,243
py
3
c.py
3
0.621883
0.596943
0
52
22.903846
67
shantanaBernados/ootd
14,508,399,533,593
849cd1f4827cd3c5dbc3317304b16e2405b92e7f
240c0a54fb7d5d0748c13ded542e3e7c2836bc09
/OOTD/main/feature_extraction.py
6b64ad1564b5bbcf4f3b2bef98fe0baaa878cc2a
[]
no_license
https://github.com/shantanaBernados/ootd
57fd7bbc237452d3c84326bff62883c2118e922a
063fc462973fd0f7567c588ca516ff13fae12c2b
refs/heads/master
2020-08-09T18:13:31.851444
2015-05-19T05:19:26
2015-05-19T05:19:26
35,711,526
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
from sklearn.cluster import KMeans from scipy.stats import itemfreq from PIL import Image import numpy as np import operator def recreate_image(codebook, labels, w, h): """Recreate the (compressed) image from the code book & labels""" d = codebook.shape[1] image = np.zeros((w, h, d)) label_idx = 0 for i in range(w): for j in range(h): image[i][j] = codebook[labels[label_idx]] label_idx += 1 return np.asarray(image, dtype=np.uint8) def get_dominant_color(image, n_colors=3, show=False): input_image = image image_array = np.array(input_image, dtype=np.uint8) #Convert to numpy array of type uint8 # Load Image and transform to a 2D numpy array. w, h, d = original_shape = tuple(image_array.shape) # shape returns width, height, color space (rbg) image_array = np.reshape(input_image, (w * h, d)) # w*h = number of pixels, d = rgb kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array) labels = kmeans.labels_ new = recreate_image(kmeans.cluster_centers_, labels, w, h) # Converting the image to uint8 datatype if show: # Display quantized image im = Image.fromarray(new) im.show() im.save("out.bmp") # Get int conversions from center clusters clusters = np.uint8(kmeans.cluster_centers_) # Look for dominant r, c = new.shape[0], new.shape[1] # Get shape px1 = [p for p in new[0][0]] # Pixel value for topmost, leftmost pixel, indicates background px2 = [p for p in new[r - 1][0]] # Pixel value for bottommost, leftmost pixel, indicates background px3 = [p for p in new[0][c - 1]] # Pixel value for topmost, rightmost pixel, indicates background px4 = [p for p in new[r - 1][c - 1]] # Pixel value for bottommost, rightmost pixel, indicates background # Sort by cluster sizes, the larger the cluster, the more dominant cluster_sizes = dict(itemfreq(labels)) sorted_cluster = sorted(cluster_sizes.items(), key=operator.itemgetter(1), reverse=True) # print clusters # print sorted_cluster # Loop through list of cluster indices, sorted by cluster size dominant = None for c in sorted_cluster: index = c[0] # If cluster values are not equal to the values in px1-px4, it is not background! THIS IS IT if not (px1 == list(clusters[index]) or px2 == list(clusters[index]) or px3 == list(clusters[index]) or px4 == list(clusters[index])): dominant = list(clusters[index]) break if dominant == None: # Was not able to extract, just get second dominant color dominant = list(clusters[1]) # for i in range(len(dominant)): # dominant[i] = dominant[i] - 255 dominant = (int(dominant[0]) * 65536) + (int(dominant[1]) * 256) + int(dominant[2]) return dominant
UTF-8
Python
false
false
2,861
py
12
feature_extraction.py
6
0.649074
0.632296
0
70
39.857143
108
mariebedniakova/ProjectLib
15,857,019,305,101
5332b25e7282090c92f6fcb1ebf39973b18b8f5d
943a4a5ef8dbfd73d46f69117a8bb2840335af58
/Web/add_books.py
b25e30b8711e4d6bbb8b238d29fedc2a20da78da
[]
no_license
https://github.com/mariebedniakova/ProjectLib
08245dc305d5eaa11db3812eb06093964a54bfe4
46e8f1f5dec03f82810ffc2727cf60fb1c520482
refs/heads/master
2023-05-02T20:31:23.828170
2021-04-28T14:34:47
2021-04-28T14:34:47
357,057,033
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# noinspection PyUnresolvedReferences from data.books import Book # noinspection PyUnresolvedReferences from data.db_session import global_init, create_session from flask_wtf import FlaskForm from wtforms import TextField, BooleanField, SubmitField from wtforms import IntegerField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import DataRequired from flask import Flask, render_template, redirect from flask_login import LoginManager, login_user, login_required, current_user class AccessError(Exception): pass app = Flask(__name__) app.config['SECRET_KEY'] = 'yandexlyceum_secret_key' login_manager = LoginManager() login_manager.init_app(app) global_init("db/library.db") @app.route('/addbook', methods=['GET', 'POST']) @login_required def add_job(): try: if not current_user.is_authenticated: return redirect('/library/login') if not current_user.admin: return AccessError form = BooksForm() if form.validate_on_submit(): db_sess = create_session() book = Book() book.title = form.title.data book.author = form.author.data book.year = form.year.data book.genre = form.genre.data book.description = form.description.data db_sess.add(book) db_sess.merge(current_user) db_sess.commit() return redirect('/library') except AccessError: return # ругается на отсутствие прав доступа return render_template('books.html', title='Добавление книги', form=form) if __name__ == '__main__': app.run(port=8080, host='127.0.0.1') # to do: возможность зарегестрироваться при входе и войти при регистрации # редактирование удаление и получение книги. примитивные html
UTF-8
Python
false
false
1,995
py
19
add_books.py
7
0.674078
0.668113
0
57
31.350877
78
cds88/Housecrawler
15,539,191,686,049
d6a1c240d1aa42d01d96ab0614131d26fd2bd454
fc7983152bc7709e7f0fb53919adfe286d7e44ab
/root/frontend/urls.py
52ebf5a56c66d3b415c3d8ebb2765ea3364c8375
[]
no_license
https://github.com/cds88/Housecrawler
a6310294415a26942c1e3e9200c460026ab20b8b
5afea9b1de810a1ff3ef224f4ede74735b9d6fee
refs/heads/master
2021-09-06T12:38:33.816980
2019-11-15T22:42:52
2019-11-15T22:42:52
220,566,278
0
0
null
false
2021-08-11T16:56:41
2019-11-08T23:57:49
2019-11-19T22:17:09
2021-08-11T16:56:41
1,978
0
0
12
JavaScript
false
false
from django.urls import path from . import views urlpatterns =[ path('', views.homepage), path('der/', views.homepage), path('accounts/', views.homepage), path('map/', views.homepage), path('profile/', views.homepage), path('advertisements/', views.homepage) ]
UTF-8
Python
false
false
297
py
50
urls.py
10
0.62963
0.62963
0
13
21.615385
43
olmokramer/fb.py
11,003,706,244,026
e20d9fa67fbfb1fec90a88f3f10f898dc0005a92
8616cbad9fdccb7c90e20238b7f8ee55cd022e12
/fb/env.py
02b849fc9dfce2b36e6b9e2e93266bc4b7787573
[]
no_license
https://github.com/olmokramer/fb.py
7feed33c860fb47c898c22c5369907550c61cbc5
63ad45cae2e878bfcd7d45e46cc0e727ba4b5699
refs/heads/master
2018-12-20T14:28:24.215076
2018-10-23T17:21:02
2018-10-23T17:21:02
145,055,143
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (c) 2018, Olmo Kramer <olmo.kramer@protonmail.com> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ''' Environment variables. ''' import os EDITOR = os.getenv('EDITOR', 'vi') MIME = os.getenv('MIME', 'xdg-mime query filetype') OPEN = os.getenv('OPEN', 'xdg-open') PAGER = os.getenv('PAGER', 'less') SHELL = os.getenv('SHELL', 'sh') SUDOEDIT = os.getenv('SUDOEDIT', 'sudoedit')
UTF-8
Python
false
false
1,398
py
32
env.py
28
0.755365
0.752504
0
32
42.6875
79
rbrecheisen/rappy
6,803,228,214,300
579d997dc202478d500b4d619e2b1b892e757817
054e97e7e9742e31658837479708d2c4b66930ee
/archive/lib/rappy/rest/api/dcm2masks.py
064d3c94878044a117d6dde5ae62743608b1cac8
[]
no_license
https://github.com/rbrecheisen/rappy
0a9ebb94c21fa5ae2e5f300a7c6a628a7274c7ec
f2f9cd374ffd00685c6854bdcb5fa32302fe7c02
refs/heads/master
2021-01-24T00:28:06.542758
2018-09-13T20:47:44
2018-09-13T20:47:44
122,767,162
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os from flask import request, current_app, send_from_directory, after_this_request from flask_restful import Resource from rappy.radiomics import Dcm2Masks class Dcm2MasksResourceList(Resource): @staticmethod def post(): files = request.files.getlist('files') dcm_file = files[0] n = Dcm2Masks() n.set_input('dcm_file', dcm_file) n.set_param('labels', {}) n.set_param('target_dir_path', os.path.join(current_app.config['UPLOAD_FOLDER'], 'dcm2masks')) output_file_paths = n.get_output('output_file_paths') output_file_names = [] for x in output_file_paths: output_file_names.append(os.path.split(x)[1]) return {'output_file_names': output_file_names} class Dcm2MasksResource(Resource): @staticmethod def get(file_name): output_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], 'dcm2masks') output_file_name = file_name @after_this_request # Warning: this may not work on Windows! def remove_file(response): file_path = os.path.join(output_dir, output_file_name) os.remove(file_path) return response return send_from_directory(output_dir, output_file_name) @staticmethod def delete(file_name): os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], 'dcm2masks', file_name))
UTF-8
Python
false
false
1,411
py
45
dcm2masks.py
41
0.64068
0.634302
0
46
29.673913
102
timniederhausen/django-auth-remember
4,011,499,476,002
6209c34c6bdeddeb5d1aefab9bf40548bf39af87
325cd742d5e0fc3daaee947496783b5b7a40dd79
/auth_remember/migrations/0002_auto_20161016_0239.py
cb8ab60a781fddd4e826c542217d4b1d8cece6bb
[]
no_license
https://github.com/timniederhausen/django-auth-remember
41ab44bd1d2d8316c559457609e0e1cb2f0779ab
21842dc22cc1cd5bf262f4071a73fc6320277b91
refs/heads/master
2021-01-12T04:58:37.456070
2016-10-17T01:56:51
2016-10-17T01:56:51
77,816,624
0
1
null
true
2017-01-02T07:01:37
2017-01-02T07:01:37
2016-10-12T00:52:05
2016-10-17T01:56:56
47
0
0
0
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-16 00:39 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth_remember', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='remembertoken', options={'ordering': ('-created',), 'verbose_name': 'Remember Token', 'verbose_name_plural': 'Remember Tokens'}, ), migrations.AlterField( model_name='remembertoken', name='created', field=models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Created'), ), migrations.AlterField( model_name='remembertoken', name='created_initial', field=models.DateTimeField(editable=False, verbose_name='Created Initially'), ), migrations.AlterField( model_name='remembertoken', name='token_hash', field=models.CharField(max_length=60, primary_key=True, serialize=False, verbose_name='Token Hash'), ), migrations.AlterField( model_name='remembertoken', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='remember_me_tokens', to=settings.AUTH_USER_MODEL, verbose_name='User'), ), ]
UTF-8
Python
false
false
1,529
py
1
0002_auto_20161016_0239.py
1
0.626553
0.611511
0
42
35.404762
166
mohsinkd786/machine-learning
1,967,095,069,086
44a70f6f3b4c0c729c53b9b17af52b900cbb7565
24636ee5821ed1a3ebff622a77171a7cc863ed55
/basics/utilities/UserService.py
4eec9a336df5641015cdfe90972526f67d23d63d
[]
no_license
https://github.com/mohsinkd786/machine-learning
5f8d72d5d2c77a952b666dc7b1908e7876b14f01
16ac56f2e1510e561a0f4eff7babbe59826795e2
refs/heads/master
2020-04-21T16:11:10.426244
2019-04-19T06:45:53
2019-04-19T06:45:53
169,692,288
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# user service class class UserService: userId = 1120 __uuid = 1119873636 def __init__(self,firstName,lastName): self.firstName = firstName self.lastName = lastName print('User') def getUser(self,age): print('Hello ',self.firstName,age) def __getUuid(self): print('UUid ',__uuid) uService = UserService('John','Doe') uService.getUser(22) print(uService.userId) # private method # print(uService.__getUuid()) # private variable # print(uService.__uuid) # print(uService.getUuid()) class Human : def __init__(self,ethinic): self.ethinic = ethinic class EmployeeService(UserService,Human) : def __init__(self,firstName,lastName,ethinic): #self.firstName = firstName #self.lastName = lastName UserService.__init__(self,firstName,lastName) Human.__init__(self,ethinic) #print('Employee Service ',self.ethinic) def eDetails(self): print('Hello! ',self.firstName,self.lastName,self.ethinic) eService = EmployeeService('John','Doe','Asian') eService.eDetails() sortedMatrix =[[1,2,3], [4,5,6], [7,8,9]] inputMatrix =[[9,6,1], [5,3,7], [4,2,8]] #inputMatrix.index([4,2,8])
UTF-8
Python
false
false
1,297
py
35
UserService.py
30
0.593678
0.56515
0
56
22.160714
66