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
list
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
cuihaoleo/freeshell-lxc-panel
6,614,249,637,502
f6eff2fb88a5c949fa72750541cfd43af30f57a0
3357333ce6c70f8052f3b26b5132613b21ef55f1
/lxc_panel/models.py
d16ce8c6f6b8a109d8b922630781ac53ea2ca241
[]
no_license
https://github.com/cuihaoleo/freeshell-lxc-panel
6f00970e0e38c0d40d13328e9ce786c8ea953917
bb776e3f140e038e86060be8ad7862a9c11181da
refs/heads/master
2016-09-11T04:27:33.601511
2015-02-21T14:17:58
2015-02-21T14:17:58
31,127,534
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.contrib.auth.models import User import requests from urllib.parse import urljoin import json # Create your models here. class NodeConnectionError (Exception): pass class NodeAPIError (Exception): pass class ShellUnsupportedTaskError (Exception): pass class ShellFailedToCreate (Exception): pass class Node (models.Model): name = models.CharField(max_length=32) ipv4 = models.GenericIPAddressField(protocol='IPv4') secret = models.CharField(max_length=32) api_url = models.URLField() def __request (self, relurl, data = None): url = urljoin(self.api_url, relurl) cookies = {"secret": self.secret} headers = {'Content-type': 'application/json'} try: if data: response = requests.post(url, data=json.dumps(data), cookies=cookies, headers=headers, timeout=1 ) else: response = requests.get(url, cookies=cookies, timeout=1) except requests.exceptions.ConnectionError: raise NodeConnectionError("Cannot connect node API.") else: if response.status_code != 200 \ or response.headers['Content-Type'] != "application/json": raise NodeConnectionError("Node API didn't give a valid response.") return response.json() def checkTask (self, task_id): j = self.__request("/task/" + task_id) if "error" in j: raise NodeAPIError(j['error']) return j def sendTask (self, task_type, kwargs={}, wait = False): data = { "type": task_type, "args": kwargs } if wait: data["wait"] = True j = self.__request("/task", data) if "error" in j: raise NodeAPIError(j['error']) return j def ping (self): ret = self.sendTask("alwaysSuccess", wait=True) return ret def listTemplates (self): ret = self.sendTask("listTemplates", wait=True) return ret['result'][1] class Shell (models.Model): utsname = models.CharField(max_length=32,unique=True) template = models.CharField(max_length=32) passwd = models.CharField(max_length=128,blank=True) node = models.ForeignKey(Node) user = models.ForeignKey(User) def create (self): j = self.node.sendTask("createShell", wait=True, kwargs={ "utsname": self.utsname, "template": self.template, }) if j['state'] != "SUCCESS": raise ShellFailedToCreate elif j['result'][0] == False: raise ShellFailedToCreate(ret['result'][1]) j = self.node.sendTask("resetPassword", wait=True, kwargs={ "utsname": self.utsname, }) if j['state'] == "SUCCESS" and j['result'][0]: self.passwd = j['result'][1] return True def info (self): ret = self.node.sendTask("getShellInfo", wait=True, kwargs={ "utsname": self.utsname, }) if ret['state'] == 'SUCCESS' and ret['result'][0]: return ret['result'][1] def newTask (self, task_type, args = {}): task_table = { "start": ("startShell", ()), "shutdown": ("shutdownShell", ()), "true": ("alwaysSuccess", ()), "reset_passwd": ("resetPassword", ()) } if task_type not in task_table: raise ShellUnsupportedTaskError send_task_type, keys = task_table[task_type] send_args = { "utsname": self.utsname } for k in keys: try: print(k) send_args[k] = args[k] except KeyError: return False ret = self.node.sendTask(send_task_type, kwargs=send_args) task = Task(task_type=task_type, shell=self, task_id=ret['task_id']) task.save() return task class Task (models.Model): TASK_STATES = ( ('P', 'PENDING'), ('R', 'RUNNING'), ('S', 'SUCCESS'), ('F', 'FAILED'), ) shell = models.ForeignKey(Shell) task_type = models.CharField(max_length=10) state = models.CharField(max_length=1, choices=TASK_STATES, default = "P") start_time = models.DateTimeField(auto_now_add=True) task_id = models.CharField(max_length=128) def checkResult (self): ret = self.shell.node.checkTask(self.task_id) if ret['state'] in ['PENDING', 'RECEIVED', 'RETRY']: self.state = "P" elif ret['state'] in ['RECEIVED', 'STARTED']: self.state = "R" elif ret['state'] in ['REVOKED', 'RETRY']: self.state = "F" elif ret['state'] == 'SUCCESS': if ret['result'][0]: self.state = "S" else: self.state = "F" self.save() return ret
UTF-8
Python
false
false
5,076
py
10
models.py
5
0.539992
0.533688
0
172
28.482558
83
pujanrajrai/ecommerece
326,417,552,518
56b89959fa8a70f795c0cf2b2a67e7cfbc5464f0
455580d19302f6147d9f6c1396a9f77f2eb3eb73
/dashboard/urls.py
23186a5895250516efcdbe9ba4639bc378a3fe65
[]
no_license
https://github.com/pujanrajrai/ecommerece
1b46dfbacee267c86ce2fceeb7aa8c32b27ae7ad
996a0289a2a2002db5fdecc6f982966605c778f0
refs/heads/main
2023-04-13T18:23:07.224226
2021-04-24T07:22:56
2021-04-24T07:22:56
328,195,874
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.urls import path from . import views app_name = 'dashboard' urlpatterns = [ path('',views.Home.as_view(),name='home'), path('delete/<int:id>',views.DeleteProduct.as_view(),name='delete'), path('showproduct/',views.ShowProduct.as_view(),name='show_product'), path('addproduct/',views.AddPhoto.as_view(),name='add_product'), path('updateproduct/<int:id>',views.UpdateProduct.as_view(),name='update_product'), ]
UTF-8
Python
false
false
444
py
20
urls.py
10
0.684685
0.684685
0
13
33.153846
87
krcb197/py_std_logic_1164
17,970,143,178,785
82c1d2bf168641fb06f89e0dcb388b14b3effddf
3fbacdffaf7e3c431dbaea19e4e39c44cbd93986
/py_std_logic_1164/std_logic.py
f7032136be940769cd29b8db7635b5bf9b375e79
[ "MIT" ]
permissive
https://github.com/krcb197/py_std_logic_1164
2b9b1a567a2ad2d77004c998b97b019258788af2
66ae8b644db4d96b222132e92768d52ee1b98f7b
refs/heads/master
2020-03-19T05:22:23.615804
2018-06-17T15:48:59
2018-06-17T15:48:59
135,924,178
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class std_logic(): """ class to represent a digital bit allowing for the same 9 values of a bit supported by IEEE 1164. ====== =============== Value Interpreatation ------ --------------- U Unitialized X Unknown 0 Strong 0 1 Strong 1 Z High Impedance W Weak unknown logic L Weak logic 0 H Weak logic 1 - Don't care ====== =============== Refer to https://en.wikipedia.org/wiki/IEEE_1164 for more details """ def __init__(self,initialvalue='U'): """ :param initialvalue: value to be loaded into the bit :type initialvalue: int, bool, str """ self._value = 'U' self.set(value=initialvalue) def __str__(self): return self._value def __repr__(self): base_repr = super().__repr__() return base_repr[:-2] + ':%s>'%self._value def __eq__(self, other): if issubclass(other.__class__,std_logic): return self._value == other._value else: raise NotImplementedError def __and__(self,other): return_value = NotImplemented if issubclass(other.__class__,std_logic): """ truth table from std_logic_1164-body.vhdl ---------------------------------------------------- | U X 0 1 Z W L H - | | ---------------------------------------------------- ( 'U', 'U', '0', 'U', 'U', 'U', '0', 'U', 'U' ), -- | U | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ), -- | X | ( '0', '0', '0', '0', '0', '0', '0', '0', '0' ), -- | 0 | ( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | 1 | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ), -- | Z | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ), -- | W | ( '0', '0', '0', '0', '0', '0', '0', '0', '0' ), -- | L | ( 'U', 'X', '0', '1', 'X', 'X', '0', '1', 'X' ), -- | H | ( 'U', 'X', '0', 'X', 'X', 'X', '0', 'X', 'X' ) -- | - | """ if self == std_logic('U'): if other == std_logic('0') or other == std_logic('L'): return_value = std_logic(0) else: return_value = std_logic('U') elif self == std_logic('X') or self == std_logic('-') or self == std_logic('W') or self == std_logic('Z'): if other == std_logic('U'): return_value = std_logic('U') elif other == std_logic('0') or other == std_logic('L'): return_value = std_logic(0) else: return_value = std_logic('X') elif self == std_logic('0') or self == std_logic('L'): return_value = std_logic(0) elif self == std_logic('1') or self == std_logic('H'): if other == std_logic('U'): return_value = std_logic('U') elif other == std_logic('0') or other == std_logic('L'): return_value = std_logic(0) elif other == std_logic('1') or other == std_logic('H'): return_value = std_logic(1) else: return_value = std_logic('X') else: raise TypeError('can not perform operation on classes') return return_value def __xor__(self, other): """ perfroms a bitwise xor operation :param other: :return: self ^ other """ return_value = NotImplemented if issubclass(other.__class__,std_logic): """ truth table from std_logic_1164-body.vhdl ---------------------------------------------------- | U X 0 1 Z W L H - | | ---------------------------------------------------- ('U', 'U', 'U', 'U', 'U', 'U', 'U', 'U', 'U'), -- | U | ('U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'), -- | X | ('U', 'X', '0', '1', 'X', 'X', '0', '1', 'X'), -- | 0 | ('U', 'X', '1', '0', 'X', 'X', '1', '0', 'X'), -- | 1 | ('U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'), -- | Z | ('U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'), -- | W | ('U', 'X', '0', '1', 'X', 'X', '0', '1', 'X'), -- | L | ('U', 'X', '1', '0', 'X', 'X', '1', '0', 'X'), -- | H | ('U', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X') -- | - | ); """ if self == std_logic('U'): return_value = std_logic('U') elif self == std_logic('X') or self == std_logic('-') or self == std_logic('W') or self == std_logic('Z'): if other == std_logic('U'): return_value = std_logic('U') else: return_value = std_logic('X') elif self == std_logic('1') or self == std_logic('H'): if other == std_logic('U'): return_value = std_logic('U') elif other == std_logic('0') or other == std_logic('L'): return_value = std_logic(1) elif other == std_logic('1') or other == std_logic('H'): return_value = std_logic(0) else: return_value = std_logic('X') elif self == std_logic('0') or self == std_logic('L'): if other == std_logic('U'): return_value = std_logic('U') elif other == std_logic('0') or other == std_logic('L'): return_value = std_logic(0) elif other == std_logic('1') or other == std_logic('H'): return_value = std_logic(1) else: return_value = std_logic('X') else: raise TypeError('can not perform operation on classes') return return_value def __or__(self,other): return_value = NotImplemented if issubclass(other.__class__,std_logic): """ truth table from std_logic_1164-body.vhdl ---------------------------------------------------- | U X 0 1 Z W L H - | | ---------------------------------------------------- ('U', 'U', 'U', '1', 'U', 'U', 'U', '1', 'U'), -- | U | ('U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X'), -- | X | ('U', 'X', '0', '1', 'X', 'X', '0', '1', 'X'), -- | 0 | ('1', '1', '1', '1', '1', '1', '1', '1', '1'), -- | 1 | ('U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X'), -- | Z | ('U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X'), -- | W | ('U', 'X', '0', '1', 'X', 'X', '0', '1', 'X'), -- | L | ('1', '1', '1', '1', '1', '1', '1', '1', '1'), -- | H | ('U', 'X', 'X', '1', 'X', 'X', 'X', '1', 'X') -- | - | ) """ if self == std_logic('U'): if other == std_logic('1') or other == std_logic('H'): return_value = std_logic(1) else: return_value = std_logic('U') elif self == std_logic('X') or self == std_logic('-') or self == std_logic('W') or self == std_logic('Z'): if other == std_logic('U'): return_value = std_logic('U') elif other == std_logic('1') or other == std_logic('H'): return_value = std_logic(1) else: return_value = std_logic('X') elif self == std_logic('1') or self == std_logic('H'): return_value = std_logic(1) elif self == std_logic('0') or self == std_logic('L'): if other == std_logic('U'): return_value = std_logic('U') elif other == std_logic('0') or other == std_logic('L'): return_value = std_logic(0) elif other == std_logic('1') or other == std_logic('H'): return_value = std_logic(1) else: return_value = std_logic('X') else: raise TypeError('can not perform operation on classes') return return_value def __invert__(self): """ truth table from std_logic_1164-body.vhdl ------------------------------------------------- | U X 0 1 Z W L H - | ------------------------------------------------- ('U', 'X', '1', '0', 'X', 'X', '1', '0', 'X') """ if self == std_logic('U'): return_value = std_logic('U') elif self == std_logic('X') or self == std_logic('-') or self == std_logic('W') or self == std_logic('Z'): return_value = std_logic('X') elif self == std_logic('0') or self == std_logic('L'): return_value = std_logic(1) elif self == std_logic('1') or self == std_logic('H'): return_value = std_logic(0) return return_value def set(self,value): """ in place value set :param value: value to be loaded into the bit :type value: int, bool, str """ if isinstance(value,str): if len(value) != 1: raise ValueError('length is not 1') if ((value == 'U') or (value == 'X') or (value == '0') or (value == '1') or (value == 'Z') or (value == 'W') or (value == 'L') or (value == 'H') or (value == '-')): self._value = value else: raise ValueError('Unsupported value, only U,X,0,1,Z,W,L,H or - is permitted') elif isinstance(value,bool): if value is False: self._value = '0' elif value is True: self._value = '1' else: raise ValueError('Illegal boolean value') elif isinstance(value,int): if (value == 0) or (value == 1): self._value = str(value) assert (self._value == '1') or (self._value == '0') else: raise ValueError('Unsupported integer value, only 0 or 1 is permitted') else: raise ValueError('Unsupported type')
UTF-8
Python
false
false
10,735
py
7
std_logic.py
5
0.361528
0.344015
0
267
39.179775
118
nikhild673/Acadpy
2,731,599,213,627
c97549881997344070698cf75ce959db7838078e
6e3b8b9b2e79f5970d7e1d7cb8d64b716b11988c
/CL14/q2.py
bd8bd37e095197cc4d6d75e54db2c3dd4b8ee36a
[]
no_license
https://github.com/nikhild673/Acadpy
791569c7e46bfecbbeb1585a5fe8b9d6330e53c8
d874b9dbb614b238b7f841dd0b823e7746016a8d
refs/heads/master
2020-03-20T17:01:45.131980
2018-08-26T14:57:39
2018-08-26T14:57:39
137,550,327
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Retrieve all the words starting with ‘b’ or ‘B’ from the following text. # text = "Betty bought a bit of butter, But the butter was so bitter, " \ # "So she bought some better butter, To make the bitter butter better." import re text="""Betty bought a bit of butter, But the butter was so bitter, So she bought some better butter, To make the bitter butter better.""" p = re.compile(r"\b[bB]\w+") result=p.findall(text) print(result)
UTF-8
Python
false
false
468
py
91
q2.py
82
0.684783
0.684783
0
9
49.111111
78
craigpauga/Data-Structure-and-Algorithms
12,111,807,818,613
d1e157f948380bb0b0d3ceb5b69258a369e1ddc1
59339fbfab6ef6f65236719e1e32345381a90a88
/1. Algorithm Toolbox/week2_algorithmic_warmup/4_least_common_multiple/least.py
d202aa13108d0e15464e1bb394a284092aafe490
[]
no_license
https://github.com/craigpauga/Data-Structure-and-Algorithms
24cce4540129821de0f0b390bb86520c7d9033ea
be236e02d0a617636bb2c5d3df1072db4ccfc8f7
refs/heads/master
2020-05-19T16:02:11.622400
2019-05-06T00:28:47
2019-05-06T00:28:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Uses python3 import math import sys def gcd(a, b): current_gcd = 1 if b == 0: return a else: a_prime = a%b a = gcd(b,a_prime) return a def lcm(a, b): greatcd = gcd(a,b) top = a * b ans = int(top//greatcd) #ans = int(int((a*b)) // int(gcd(a,b))) return ans if __name__ == '__main__': input = sys.stdin.read() a, b = map(int, input.split()) print(lcm(a, b))
UTF-8
Python
false
false
440
py
52
least.py
49
0.486364
0.479545
0
25
16.56
44
danielgitk/competitive-programming
9,552,007,306,895
e1aaf909f1ca82a9b20469681a343c372190005a
213aef7d9414df0fc195f18e18203410babb5d8b
/camp 01/week 03/rangeSumBST.py
dd7036bb92c7b86881967cf0dd5bea4f99fae2e9
[]
no_license
https://github.com/danielgitk/competitive-programming
c3cd8c0f89eed71c463b1d703d9c0a1f86afd45f
1c843258fda205973de63c04bd37ac989b61b08f
refs/heads/main
2023-08-23T05:22:06.610726
2021-10-15T12:57:34
2021-10-15T12:57:34
325,812,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 3 17:30:07 2021 @author: daniel """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int: if not root: return 0 else: if low <= root.val <= high: return root.val + self.rangeSumBST(root.left,low,high) + self.rangeSumBST(root.right,low,high) else: return 0 + self.rangeSumBST(root.left,low,high) + self.rangeSumBST(root.right,low,high)
UTF-8
Python
false
false
733
py
66
rangeSumBST.py
66
0.564802
0.542974
0
23
30.521739
110
mnuhurr/audioslicer
8,624,294,358,571
a53a99a6caad296d5d8cc3066e71a75820ab2aaa
55019eb8c6226365818bbf51b3311235562950fc
/slice.py
8ae4b7c583ed36b9664dd8cdca71899fc7fc462b
[ "MIT" ]
permissive
https://github.com/mnuhurr/audioslicer
04dbc27ec50e821e6b4e82081a4d1f29df778379
0be45b826fa63162c282135f0d01c65e6c1092a0
refs/heads/main
2023-07-08T21:14:44.827908
2021-08-09T15:16:11
2021-08-09T15:16:11
303,638,014
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import glob from tqdm import tqdm from common import load_config, check_output_dirs from audioslicer import AudioSlicer def get_file_list(dir_path, ext='.wav'): ''' get list of files from a given directory :param dir_path: path to the dir :param ext: file extension. defaults to .wav :return: list of file paths ''' wav_path = os.path.join(dir_path, '*' + ext) fns = glob.glob(wav_path) # return the file list in lexicographic order fns.sort() return fns def main(): # load configuration cfg = load_config() # create output directories if needed check_output_dirs(cfg) # worker slicer = AudioSlicer(output_dir=cfg['output_dir'], audio_len=cfg['length'], use_hashing=cfg['use_hashing']) # get file list filenames = get_file_list(cfg['audio_dir']) # process for fn in tqdm(filenames): slicer.slice(filename=fn, interval=cfg['interval'], normalize_input=cfg['normalize_input'], normalize_output=cfg['normalize_output']) # summary slicer.write_report(cfg['output_csv']) if __name__ == '__main__': main()
UTF-8
Python
false
false
1,243
py
6
slice.py
4
0.594529
0.594529
0
53
22.433962
62
yeswehack/ywh2bugtracker
6,219,112,676,448
cbf5e81b3f1a2773c1c99a5dd56dce1ca6e75761
27d01ea3adcca7d4de246f3f188526b54a61885b
/stubs/aiosnow/models/attachment/__init__.pyi
e2c5c1ccebf296ee9751a9bf5f607cd5065923b1
[]
no_license
https://github.com/yeswehack/ywh2bugtracker
f9f625b98ae299ff7f8dd0ddabc8cb51ae63e24e
3da2161c3c9e0652c2cfc78ab514359bcf2e436b
refs/heads/master
2023-06-25T20:12:23.899978
2023-04-26T12:46:27
2023-04-26T12:46:27
224,868,730
10
5
null
false
2023-06-07T11:12:16
2019-11-29T14:24:08
2023-05-23T19:42:46
2023-06-07T11:12:16
5,176
9
5
3
Python
false
false
from .model import AttachmentModel as AttachmentModel
UTF-8
Python
false
false
54
pyi
220
__init__.pyi
197
0.87037
0.87037
0
1
53
53
Phytonworks/web_scraping5_instagram
5,231,270,192,630
79d4d0b32c2aac4eb810bd09d807cae0846cc0a0
a1f897498cd61ce65771d43823e8a45b5f91215f
/json_scraping_like.py
86f1ea5be198738c6bdf1437cb8b35187d5b2315
[]
no_license
https://github.com/Phytonworks/web_scraping5_instagram
d1764bfe293ea931d6773cd95cb3e98cf0af4e90
229d93d68983ae615e0ae9cd59bf86943991bbd3
refs/heads/main
2023-03-12T22:29:16.391822
2021-03-01T16:20:19
2021-03-01T16:20:19
343,121,676
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests import json url = 'https://www.instagram.com/graphql/query' variable = {"shortcode": "CLygOc1MFqh", "include_reel": True, "first": 24} params = { 'query_hash': 'd5d763b1e2acf209d62d22d184488e57', 'variables': json.dumps(variable) } r = requests.get(url, params=params).json print(r)
UTF-8
Python
false
false
309
py
1
json_scraping_like.py
1
0.708738
0.631068
0
12
24.75
74
yienyien/dayoff
7,782,480,741,683
176e3e9413c0c275f70f5f20c6f9e57caf2ebb90
025ebe972d5e9f592eaa3d045c7dbbf20608fb53
/vacations/urls.py
72ec6e867c950874d4e2861e7509a7c98c58c900
[ "Apache-2.0" ]
permissive
https://github.com/yienyien/dayoff
adfee3985cbe7b9bbeb43183a013e5f09e0700ec
158795133084931a5fe34c047508ca225ce6fb12
refs/heads/main
2023-01-15T07:39:18.457718
2020-11-20T21:12:31
2020-11-20T21:12:31
313,904,554
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from rest_framework import routers from . import views router = routers.DefaultRouter(trailing_slash=False) router.register("vacations", views.VacationViewSet, basename="vacations") router.register("queries", views.ListUsers, basename="queries") router.register("compare", views.Compare, basename="compare")
UTF-8
Python
false
false
310
py
22
urls.py
15
0.796774
0.796774
0
8
37.75
73
wyaadarsh/LeetCode-Solutions
5,720,896,462,052
545acf3e1e50eeeb957c07e8e50e3906193a09e2
fcc88521f63a3c22c81a9242ae3b203f2ea888fd
/Python3/0856-Score-of-Parentheses/soln-1.py
fd89de5e45bca5edec6a4f5a139c8a8d3da9e268
[ "MIT" ]
permissive
https://github.com/wyaadarsh/LeetCode-Solutions
b5963e3427aa547d485d3a2cb24e6cedc72804fd
3719f5cb059eefd66b83eb8ae990652f4b7fd124
refs/heads/master
2022-12-06T15:50:37.930987
2020-08-30T15:49:27
2020-08-30T15:49:27
291,811,790
0
1
MIT
true
2020-08-31T19:57:35
2020-08-31T19:57:34
2020-08-30T15:49:37
2020-08-30T15:49:34
7,769
0
0
0
null
false
false
class Solution: def scoreOfParentheses(self, S): """ :type S: str :rtype: int """ cnt, layer = 0, 0 for a, b in zip(S, S[1:]): layer += (1 if a == '(' else -1) if a + b == '()': cnt += 2 ** (layer - 1) return cnt
UTF-8
Python
false
false
312
py
3,904
soln-1.py
3,904
0.36859
0.346154
0
12
25.083333
44
jayrbolton/arango_backdoor_test
1,030,792,158,621
83e2e8cb5a75d7b0ce25f9fb1908447579084c5b
3286f5dd39a6ebab9ecb8fa740e1f1a5aec83554
/src/main.py
d855417b5737afd75ef6850423589eeba7882105
[]
no_license
https://github.com/jayrbolton/arango_backdoor_test
f9aaccb9ccc9864c0c389797bab52f325b28b0e3
636dc2093233414777e3508462f3aaf0a7f12edb
refs/heads/master
2020-04-16T00:00:16.948842
2019-01-10T20:17:37
2019-01-10T20:17:37
165,120,510
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" This file contains all the methods for this KBase SDK module. """ import requests def echo(params): """Echo back the given message.""" resp = requests.get("http://10.58.1.211:8529") return resp.text
UTF-8
Python
false
false
217
py
4
main.py
1
0.668203
0.612903
0
10
20.7
61
notarandomusername/Classwork
16,973,710,760,231
ce19605b28ab608c285153651499ae93647bc069
961dab5241acd1b7b15decc17d149807ced65b6a
/day06.py
53ac462455f30337c9e2de7a0587425b153b7917
[]
no_license
https://github.com/notarandomusername/Classwork
97824b713ab492af211a207e82ee66e3c05cb2f1
5cf343c8a094cbac36656ddeed27b347eba3a958
refs/heads/master
2021-08-15T07:49:50.367260
2017-11-17T15:41:12
2017-11-17T15:41:12
111,114,770
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#basic strings a = "hi" b = "hello" print(a, b) print("greetings") #using f for strings import random a = random.randint(1,10) print(f"{a}") #brackets x = "Life" y = "fun!" print("{} is {}".format(x, y)) print("{1} is {0}".format(x, y)) f_string = "{} {}" print(f_string.format("hello", "friend")) math_string = "{} + {} = {}" print(math_string.format(2, 2, 4)) #join a = "Hello" b = "friend!" print(" ".join((a, b))) #new line print("new\nline") #long string long_string = """h e l l o """ print(long_string)
UTF-8
Python
false
false
523
py
14
day06.py
14
0.575526
0.560229
0
46
10.391304
41
LT17855/bw_2004
19,026,705,135,639
0b73b039ffeaca788ccc7d5611034d1034f4937f
f201bc51ff96d2d73fecac0831b48ef18916d70b
/dingding.py
af211e7af3d5dec4417fb10524f6bc6320ff3600
[]
no_license
https://github.com/LT17855/bw_2004
e9e804a952a53e4ceeeeabfd9ec4359496ac4c8a
f2df13fb6417452e6bf71bfaf31b59323702088a
refs/heads/master
2022-12-27T16:35:51.076741
2020-10-05T12:06:48
2020-10-05T12:06:48
292,777,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# !/usr/bin/env python # -*-coding:utf8-*- # Project_name:bw_2004 # File_name:dingding.py.py # Author: lt # Time:2020年09月04日 import json import requests class Ding(): def message(link=1): url = 'https://oapi.dingtalk.com/robot/send?access_token=6e2e35a5591b4bd70a1249ca938e0d99355ceb4a63929c61fc2711792fb28424' pagrem = { "msgtype": "text", "text": { "content": ":%s " % ('你好坏哦~') }, "at": { "atMobiles": [ "17691125909" # 需要填写自己的手机号,钉钉通过手机号@对应人 ], "isAtAll": True # 是否@所有人,默认否 } } headers = { 'Content-Type': 'application/json' } requests.post(url, data=json.dumps(pagrem), headers=headers) if __name__ == "__main__": Ding.message()
UTF-8
Python
false
false
925
py
3
dingding.py
2
0.513545
0.432273
0
31
26.387097
130
rajatthosar/leetcode
6,640,019,475,751
5ccdade929ee37324759b75ba8a010c477ccfe7e
5784163b89b872f19facdd0e111ac38abfb8dfc3
/371_sum_of_two_ints.py
87dcbef4673239c2ca48620d9a63f512efacfcbf
[]
no_license
https://github.com/rajatthosar/leetcode
ae8a1d4b0cd448549d62549bfdc1a492f9282622
a9f448a816c38d76e8f5582d01d05c16e3f8e513
refs/heads/main
2023-02-23T08:42:44.595898
2021-01-18T02:23:28
2021-01-18T02:23:28
330,525,895
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution: def getSum(self, a: int, b: int) -> int: if a < 0: a = (~a) + 1 if b < 0: b = (~b) + 1 return a | b if __name__ == '__main__': sol = Solution() print(sol.getSum(1, 2)) print(sol.getSum(-2, 3)) print(sol.getSum(-2, -3)) print(sol.getSum(2, -1))
UTF-8
Python
false
false
335
py
114
371_sum_of_two_ints.py
114
0.429851
0.39403
0
15
21.266667
44
cfshanxidj/Iniciando
7,610,682,054,256
86316e3529d6d983abe0b0f835086029f9791902
3488d0a8fb7949b1214557204832a249bed59da4
/01_Hola-python.py
a89cd7949d253dd2a505859d71e19b0b76184f65
[]
no_license
https://github.com/cfshanxidj/Iniciando
eba7173be04d34e7c234a16b22a1966ca4b2abe5
2d47c8bb8add9a6df5121cc0982f1e1ecbb9e088
refs/heads/master
2020-06-29T02:00:23.245499
2019-08-03T17:47:37
2019-08-03T17:47:37
200,404,633
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print("hola python desde netacad!")
UTF-8
Python
false
false
37
py
1
01_Hola-python.py
1
0.72973
0.72973
0
1
35
35
owenbrown/email-sender
15,779,709,879,933
96b600757c5389ceecc0f805d345dcd37d5862b5
11673ba938c724e20fffdce3687172e1f7aa5c57
/app.py
b29d4a177bf4d63bb5a4328c9483b4a69f4ffbcd
[]
no_license
https://github.com/owenbrown/email-sender
0fcda5c7d57b481f5b736ac11f8e620f42e4008f
c9931dd0893e8a71a7d9b67932849ef2b17d4567
refs/heads/master
2021-05-06T11:03:45.645985
2017-12-14T03:28:35
2017-12-14T03:28:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from chalice import Chalice from botocore.exceptions import ClientError from boto3.dynamodb.conditions import Key, Attr import boto3 import random import csv import time import os app = Chalice(app_name="emailsender") app.debug = True client = boto3.client("ses") reasons = "Reasons" dynamodb_resource = boto3.resource("dynamodb", region_name="us-west-2", endpoint_url="https://dynamodb.us-" + "west-2.amazonaws.com") dynamodb_client = boto3.client("dynamodb", region_name="us-west-2", endpoint_url="https://dynamodb.us-" + "west-2.amazonaws.com") """AWS DynamoDB checks to see if a table "Reasons" exists. If not, it creates a new table called "Reasons", and populates it with information from Reasons.csv. """ if reasons not in dynamodb_client.list_tables()["TableNames"]: dynamodb_client.create_table( TableName=reasons, KeySchema=[ { "AttributeName": "ID", "KeyType": "HASH" }, { "AttributeName": "Reasons", "KeyType": "RANGE" } ], AttributeDefinitions=[ { "AttributeName": "ID", "AttributeType": "N" }, { "AttributeName": "Reasons", "AttributeType": "S" } ], ProvisionedThroughput={ "ReadCapacityUnits": 10, "WriteCapacityUnits": 10 } ) # This holds the code from running, giving # time for the server to create the table. time.sleep(15) reasons_table = dynamodb_resource.Table(reasons) with open("Reasons.csv", "r") as csvfile: reasons_file = csv.reader(csvfile, delimiter=" ") counter = 0 for reason in reasons_file: reasons_table.put_item( Item={ "ID": counter, "Reasons": " ".join(reason) } ) counter += 1 @app.schedule('rate(1 hour)') def email_lambda_function(event): """AWS Lambda function that pulls from the "Reasons" DynamoDB table and uses SES to send an email. The decorator is an indicator for CloudWatch to create a rule and schedule an event for this Lambda function to run every hour. """ try: reasons_table = dynamodb_resource.Table(reasons) rand_int = random.randint(0, 25) response = reasons_table.query( KeyConditionExpression=Key("ID").eq(rand_int)) client.send_email( Destination={ "ToAddresses": [os.environ['RECEIVER_1']] + [os.environ['RECEIVER_2']] }, Message={ "Body": { "Text": { "Data": response["Items"][0]["Reasons"] } }, "Subject": { "Data": "Another reason why you should hire Justin Picar." } }, Source=os.environ['SENDER'] ) except ClientError as c: app.log.error(c) @app.route("/") def index(): """AWS Chalice app requires one function to use the above decorator as a default. Otherwise, this function serves no purpose. """ pass
UTF-8
Python
false
false
3,428
py
2
app.py
1
0.523921
0.516919
0
119
27.806723
78
militomba/diseno_de_sistemas
13,580,686,604,367
7ff9ea26b948c26c2c1087f516bafedd76606b07
885836f9c3dd1a4c699a8b2dd74e064b41a22ce9
/Patron inyeccion de dependencias/main.py
c91302504e24a780d5f1a1a21283f50a8f872d8f
[]
no_license
https://github.com/militomba/diseno_de_sistemas
65b8a37177341662eb3f00013b07ad2d8fc4b593
04a4cfb6d5a6955d8da7312a5fc07c114875db17
refs/heads/main
2023-08-23T12:51:08.102956
2021-11-03T19:48:02
2021-11-03T19:48:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from computadora import * from mouse import * from monitor import * from teclado import * def main(): teclado1 = Teclado_genius("Genius", "Inalambrico") mouse1 = Mouse_redDragon("Red Dragon", "Alambrico") monitor1 = Monitor_asus("180", "Asus") computadora = Computadora(monitor1, teclado1, mouse1) computadora.componentes() if __name__=="__main__": main()
UTF-8
Python
false
false
384
py
45
main.py
45
0.674479
0.651042
0
16
23.0625
57
newsdev/nyt-docket
10,625,749,109,614
67a85cc8ee224f0ab198070e95f436cb4ae89736
92cba6f8bc0b95133207625f2658b39ea3bcc88d
/docket/cli.py
7bce9aaee122160c11b8b85f7efc4f976218b1ba
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
https://github.com/newsdev/nyt-docket
7a584c31f94b39a28be5a4c964bba0a1574dd8fd
5f57f510328993492f0c47879609073c006d178e
refs/heads/master
2021-01-19T04:06:01.443165
2017-09-28T19:11:59
2017-09-28T19:11:59
43,657,101
14
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import bson from functools import wraps import pkg_resources from docket import grants from docket import orders from docket import slipopinions from clint.textui import puts, colored from cement.core.foundation import CementApp from cement.ext.ext_logging import LoggingLogHandler from cement.core.controller import CementBaseController, expose VERSION = pkg_resources.get_distribution('nyt-docket').version LOG_FORMAT = '%(asctime)s (%(levelname)s) %(namespace)s (v{0}) : \ %(message)s'.format(VERSION) BANNER = "NYT Docket version {0}".format(VERSION) class DocketBaseController(CementBaseController): class Meta: label = 'base' description = "Get and process Supreme Court opinions, \ grants and orders." arguments = [ (['term'], dict( nargs='*', action='store', help='Term year as a four-digit number, e.g., 2008. Remember \ that term years represent the year the term began, not ended.' )), (['--format-json'], dict( action='store_true', help='Pretty print JSON when using `-o json`.' )), (['-v', '--version'], dict( action='version', version=BANNER )), ] @expose(hide=True) def default(self): """ Print help """ self.app.args.print_help() @expose(help="Get opinions") def opinions(self): """ Initialize opinions """ self.app.log.info( 'Getting opinions for term {0}'.format( self.app.pargs.term[0] ) ) l = slipopinions.Load(terms=[self.app.pargs.term[0]]) l.scrape() data = l.cases self.app.render(data) @expose(help="Get grants") def grants(self): """ Initialize grants """ self.app.log.info( 'Getting grants for term {0}'.format( self.app.pargs.term[0] ) ) l = grants.Load(terms=[self.app.pargs.term[0]]) l.scrape() data = l.cases self.app.render(data) @expose(help="Get orders") def orders(self): """ Initialize orders """ self.app.log.info( 'Getting orders for term {0}'.format( self.app.pargs.term[0] ) ) l = orders.Load(terms=[self.app.pargs.term[0]]) l.scrape() data = l.orders self.app.render(data) class DocketApp(CementApp): class Meta: label = 'docket' base_controller = DocketBaseController hooks = [] extensions = [ 'docket.ext_csv', 'docket.ext_json' ] output_handler = 'csv' handler_override_options = dict( output=(['-o'], dict(help='output format (default: csv)')), ) log_handler = LoggingLogHandler( console_format=LOG_FORMAT, file_format=LOG_FORMAT ) def main(): with DocketApp() as app: app.run()
UTF-8
Python
false
false
3,135
py
11
cli.py
6
0.534928
0.530144
0
115
26.269565
78
cipherSh/ISSPENM_new
1,838,246,008,258
357683cd9d7e9d340a86183457bf128857c62239
5dd65e38a13b0695ec37f51f28d8f3c5b78f7c04
/ISRTE/users/views.py
3f7ede47cec7cfc6b5349f623ea6a9c2e04986ea
[]
no_license
https://github.com/cipherSh/ISSPENM_new
83be2db056334fa67cbf7f8811f35670fb0f23f7
157c78f1daa0067f3ed05e9b1d5a6a5432cd58cd
refs/heads/master
2020-05-25T22:52:48.237123
2019-06-23T14:18:04
2019-06-23T14:18:04
188,023,384
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json from django.shortcuts import render, redirect, Http404, HttpResponse, reverse from django.http import HttpResponseNotFound from django.contrib.auth import login, logout, authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group, User from datetime import datetime, timedelta, date from django.utils.timezone import get_current_timezone from django.utils import timezone from django.views.generic import View from django.core.paginator import Paginator from io import BytesIO from reportlab.pdfgen import canvas import pytz from django.contrib.auth import update_session_auth_hash from django.contrib import messages # models from .models import Profile, Audit, UserLogs from reestr.models import Criminals from django.contrib.contenttypes.models import ContentType # forms from .forms import UserUpdateForm, ProfileUpdateForm, UserLogsSearchForm from django.contrib.auth.forms import PasswordChangeForm # Create your views here. # Функция авторизации def login_view(request): if request.POST: # Если пришел POST запрос # Вывод данных из post-запроса username = request.POST['username'] password = request.POST['password'] # Проверка наличия пользователя в системе user = authenticate(username=username, password=password) if user is not None: # Еcли пользователь зарегистрирован в системе if user.is_active:# Проверка доступа пользователя к систему # Если у пользователя есть доступ к системе login(request, user)# авторизация пользователя Audit.objects.create(user=request.user.profile, act='Вход в систему', data=datetime.now( tz=get_current_timezone()))# Запись в журнал действий пользователя if request.user.profile.initial_pass: # Если пароль пользователя является начальной return redirect(reverse('change_initial_pass_url'))# Вызов функции смены пароля key_term = timezone.now() - timedelta(minutes=60*24*30)# Нахождение даты 30 дней назад if key_term >= request.user.profile.pass_change_date: # Если срок пароля истек return redirect(reverse('change_initial_pass_url'))# Вызов функции смены пароля return redirect("/")# Переход в главную страницу else: # Если у пользователя нет доступа к системе login_error = "Вам закрыто вход в систему" # сообщение с ощибкой return render(request, "login.html", {"login_error": login_error})# Переход в форму авторизации else: # Еcли пользователь не зарегистрирован в системе login_error = 'Введено неправильные данные' return render(request, "login.html", {"login_error": login_error}) else: # Если пришел GET запрос return render(request, "login.html")# Переход в форму авторизации # Функция LOGOUT def logout_view(request): # Запись в журнале действии Audit.objects.create(user=request.user.profile, act='Выход из системы', data=datetime.now( tz=get_current_timezone())) logout(request)# Удаление сессии return redirect('/users/login/')# Переход в форму авторизации # Функция регистрации пользователя @login_required # Проверка авторизован ли пользователь def user_create(request): message = None context = { 'wrapper_title': "Создание пользователя", 'message': message } if request.POST: # Если пришел POST запрос # Вывод имени пользователя из post-запроса username = request.POST['username'] # Генерация начального пароля password = User.objects.make_random_password(15) # Если пользователь зарегистрирован в системе if User.objects.filter(username=username).count(): # Сообщение с ошибкой message = "Пользователь c именем {} уже зарегистрирован".format(username) context = { 'wrapper_title': "Создание пользователя", 'message': message } # Переход в форму регистрации return render(request, 'profiles/user_create.html', context=context) # Если не задано имени пользователя elif username == '': message = "Пожалуйста введите имени пользователя!" context = { 'wrapper_title': "Создание пользователя", 'message': message } return render(request, 'profiles/user_create.html', context=context) else: # Запись в базе данных user = User.objects.create_user(username=username, password=password) profile = Profile.objects.get(user=user) # Галочка на поле начального пароля user.profile.initial_pass = True # Дата последнего изменение пароля user.profile.pass_change_date = datetime.now() user.profile.save() # Запись в журнале действий пользователя action_logging_create(request, user) context = { 'wrapper_title': "Создание пользователя", 'user': user, 'password': password } return render(request, 'profiles/success_create.html', context=context) return render(request, 'profiles/user_create.html', context=context) # Функция изменение начального пароля @login_required # Проверка авторизован ли пользователь def change_initial_pass(request): error_message = '' message = '' # Если пароль явялется начальным if request.user.profile.initial_pass: message = 'Пожалуйста измените начальный пароль' else: message = 'Срок пароля истек. Пожалуйста измените пароль' # Если пришел POST запрос if request.POST: password = request.POST['password'] confirm = request.POST['confirm'] # Проверка паролей на совпадение if password == confirm: u = request.user u.set_password(password) u.profile.initial_pass = False u.profile.pass_change_date = timezone.now() u.save() # обновление сессии пользователя update_session_auth_hash(request, u) log_message = 'Начальный пароль изменен' # запись в журнале action_logging_other(request, u.profile, log_message) # Главная страница return redirect('/') else: error_message = 'Пароли не совпадает. Пожалуйста введите пароль еще раз' context = { 'wrapper_title': 'Изменение пароля', 'error_message': error_message, 'message': message } # форма изменение пароля return render(request, 'profiles/change_initial_pass.html', context=context) # Функция обновление профиля пользователя class UserUpdateView(View): # Вывод форму обновление профиля пользователя def get(self, request, pk): profile = Profile.objects.get(id=pk) user_form = UserUpdateForm(instance=profile.user) profile_form = ProfileUpdateForm(instance=profile) context = { 'wrapper_title': 'Обновление профиля пользователя', 'profile': profile, 'user_form': user_form, 'profile_form': profile_form } return render(request, 'profiles/profile_update.html', context=context) # обновление данных пользователя def post(self, request, pk): profile = Profile.objects.get(id=pk) bound_user_form = UserUpdateForm(request.POST, instance=profile.user) bound_profile_form = ProfileUpdateForm(request.POST, instance=profile) context = { 'wrapper_title': 'Обновление профиля пользователя', 'profile': profile, 'user_form': bound_user_form, 'profile_form': bound_profile_form } # если введено правильные данные if bound_user_form.is_valid() and bound_profile_form.is_valid(): up_user = bound_user_form.save() up_profile = bound_profile_form.save() if profile.role_id: last_group = profile.role_id.group new_group = up_profile.role_id.group up_profile.user.groups.remove(last_group) up_profile.user.groups.add(new_group) else: new_group = up_profile.role_id.group up_profile.user.groups.add(new_group) context = { 'wrapper_title': 'Обновление профиля пользователя', 'profile': up_profile } # Запись в журнал action_logging_update(request, profile) return redirect(profile) # Если введено неправильные данные return render(request, 'profiles/profile_update.html', context=context) # Функция изменение пароля @login_required def password_edit(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() # Обновление сессии пользователя update_session_auth_hash(request, user) messages.success(request, 'Ваш пароль успешно изменен!') # переход в профиль пользователя return redirect(request.user.profile) else: messages.error(request, 'Исправьте ошибки!') else: form = PasswordChangeForm(request.user) return render(request, 'profiles/password_edit.html', { 'form': form, 'wrapper_title': 'Изменение пароля' }) # Функция вывода списка пользователей @login_required def users_list(request): # Проверка явялется ли пользователь администратором if request.user.is_superuser: # Список пользователей users_list = Profile.objects.all().order_by('role_id') # Поисковый запрос, если нет то пустое значение search_query = request.GET.get('search_query_text', '') # Если пришел поисковый запрос if search_query: users_list = Profile.objects.all().order_by('role_id') context = { 'wrapper_title': "Пользователи", 'search_url': 'users_list_url', "users": users_list } return render(request, "profiles/users_list.html", context) # Если пользователь не явяляется алминистратором return HttpResponseNotFound('') # Функция вывода профиля поьзователя @login_required def user_profile(request, pk): # данные пользователя profile = Profile.objects.get(id=pk) # проверка есть ли у пользователя права на просмотр профиля пользователя if request.user.has_perm('view_user') or request.user.profile == profile: #Список документов пользователя user_docs = Criminals.objects.filter(owner=profile) # p_acc = PersonAccess.objects.filter(user_id=profile) if request.user.profile == profile: wrapper_title = "Мой профиль" else: wrapper_title = "Профиль пользователя" context = { 'profile': profile, 'user_docs': user_docs, 'wrapper_title': wrapper_title, # 'p_acc': p_acc } return render(request, 'profiles/user_profile.html', context=context) # если у пользователя нету прав на просмотр профиля пользователя return HttpResponseNotFound('') # Удаление пользователя @login_required def user_delete(request, pk): profile = Profile.objects.get(id=pk) profile.user.delete() return redirect(reverse('users_list_url')) # Функция вывода журнал вход\выхода @login_required def users_audit(request): audit = Audit.objects.all().order_by('-data') # разделение весь журнал на страницы paginator = Paginator(audit, 20) page_number = request.GET.get('page', 1) # страницы page = paginator.get_page(page_number) # если есть другие страницы is_paginated = page.has_other_pages() # проверка есть ли предыдущая страница if page.has_previous(): prev_url = '?page={}'.format(page.previous_page_number()) else: prev_url = '' if page.has_next(): next_url = '?page={}'.format(page.next_page_number()) else: next_url = '' start_url = 1 last_url = '' # Данные передаваемые в страницу context = { 'audit': page, 'is_paginated': is_paginated, 'next_url': next_url, 'prev_url': prev_url, 'start_url': start_url, 'last_url': last_url, 'wrapper_title': "Журнал авторизации" } return render(request, 'profiles/audit.html', context=context) # журнал действий @login_required def users_logs(request): search_form = UserLogsSearchForm() logs = '' if request.POST: bound_form = UserLogsSearchForm(request.POST) if bound_form.is_valid(): search = bound_form.save(commit=False) search_query = search.user logs = UserLogs.objects.filter(user=search_query).order_by('-action_time') else: logs = UserLogs.objects.all().order_by('-action_time') # Постраничный вывод данных paginator = Paginator(logs, 50) page_number = request.GET.get('page', 1) page = paginator.get_page(page_number) is_paginated = page.has_other_pages() if page.has_previous(): prev_url = '?page={}'.format(page.previous_page_number()) else: prev_url = '' if page.has_next(): next_url = '?page={}'.format(page.next_page_number()) else: next_url = '' # Данные передаваемые в страницу context = { 'logs': page, 'search_form': search_form, 'is_paginated': is_paginated, 'next_url': next_url, 'prev_url': prev_url, 'wrapper_title': "Журнал действий" } return render(request, 'profiles/logs.html', context=context) # Функция вывода список групп @login_required def group_list(request): # список групп groups = Group.objects.all() # Данные передаваемые в страницу context = { 'wrapper_title': "Группы", 'search_url': 'manhunt_list_url', "groups": groups } return render(request, "profiles/group_list.html", context=context) # Функция предоставление доступа к систему @login_required def inactive_user(request, pk): # пользователь profile = Profile.objects.get(id=pk) log_message = '' if profile.user.is_active: profile.user.is_active = False profile.user.save() log_message = 'Доступ к систему закрыть' else: profile.user.is_active = True profile.user.save() log_message = 'Доступ к систему открыть' # Запсиь в журнале action_logging_other(request, profile, log_message) return redirect(profile) # Функция вывода логи пользователя для конкретного объекта @login_required def profile_logs(request, pk): profile = Profile.objects.get(id=pk) logs = object_logs(request, profile) context = { 'profile': profile, 'logs': logs, 'wrapper_title': 'Пользователи' } return render(request, 'reestr/logs/criminal_logs.html', context=context) # Функция вывода логи пользователя @login_required def user_acts(request, pk): profile = Profile.objects.get(id=pk) acts = UserLogs.objects.filter(user=profile) context = { 'profile': profile, 'logs': acts, 'wrapper_title': 'Пользователи' } return render(request, 'profiles/user_logs.html', context=context) # Логи объекта def object_logs(request, object): content_type = ContentType.objects.get_for_model(object) logs = UserLogs.objects.filter(content_type=content_type).filter(object_id=object.id) return logs # Логгирование # Запись в журнале при создание какого объекта def action_logging_create(request, object): content_type = ContentType.objects.get_for_model(object) log = UserLogs.objects.create(action_time=datetime.now(tz=get_current_timezone()), object_id=object.id, object_repr=object, action_flag=1, message={'create': {}}, content_type=content_type, user=request.user.profile) # Запись в журнале при просмотре объекта def action_logging_view(request, object): content_type = ContentType.objects.get_for_model(object) log = UserLogs.objects.create(action_time=datetime.now(tz=get_current_timezone()), object_id=object.id, object_repr=object, action_flag=2, message={'view': {}}, content_type=content_type, user=request.user.profile) # Запись в журнале при изменении объекта def action_logging_update(request, object): content_type = ContentType.objects.get_for_model(object) log = UserLogs.objects.create(action_time=datetime.now(tz=get_current_timezone()), object_id=object.id, object_repr=object, action_flag=3, message={'update': {}}, content_type=content_type, user=request.user.profile) # Запись в журнале при удаление объекта def action_logging_delete(request, object): content_type = ContentType.objects.get_for_model(object) log = UserLogs.objects.create(action_time=datetime.now(tz=get_current_timezone()), object_id=object.id, object_repr=object, action_flag=4, message={'delete': {}}, content_type=content_type, user=request.user.profile) # Запись в журнале при добавление данных к объекту def action_logging_added(request, object, addedobject): content_type = ContentType.objects.get_for_model(object) ao_content_type = ContentType.objects.get_for_model(addedobject) ao_name = ao_content_type.name ob = addedobject mes = {'added': {ao_name: str(ob)}} log = UserLogs.objects.create(action_time=datetime.now(tz=get_current_timezone()), object_id=object.id, object_repr=object, action_flag=5, message=mes, content_type=content_type, user=request.user.profile) # Запись в журнале при удаление данных с объекта def action_logging_exclude(request, object, excludedobject): content_type = ContentType.objects.get_for_model(object) ao_content_type = ContentType.objects.get_for_model(excludedobject) ao_name = ao_content_type.name ob = excludedobject mes = {'exclude': {ao_name: str(ob)}} log = UserLogs.objects.create(action_time=datetime.now(tz=get_current_timezone()), object_id=object.id, object_repr=object, action_flag=6, message=mes, content_type=content_type, user=request.user.profile) # Запись в журнале в других случаях def action_logging_other(request, object, message): content_type = ContentType.objects.get_for_model(object) log = UserLogs.objects.create(action_time=datetime.now(tz=get_current_timezone()), object_id=object.id, object_repr=object, action_flag=7, message=message, content_type=content_type, user=request.user.profile) # формирование PDF файл с начальным паролем пользователя def user_initial_pass(request, profile, password): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=profile.user.username' print('i am') buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(50, 790, "OPKK") p.drawString(10, 770, "Username:") p.drawString(100, 770, profile.user.username) p.drawString(10, 750, "Password:") p.drawString(100, 750, password) # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response def some_view(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="akylbekov.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(50, 790, "OPKK") p.drawString(100, 780, "Password was dropped") p.drawString(10, 770, "Username:") p.drawString(100, 770, "akylbekov") p.drawString(10, 750, "Password:") p.drawString(100, 750, "GDnNS7R2q5SaJE5") # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
UTF-8
Python
false
false
24,562
py
90
views.py
37
0.643152
0.638884
0
548
37.905109
117
kakabara/p2p_shop_server
223,338,302,586
d68e23423dba29adbe011ca663cbbebd6f57f902
31525c85e27bd41f8e9a577fe9ef1e25488edd0a
/server/config.py
26b58af79475b48276ae5f03991969b540cac649
[]
no_license
https://github.com/kakabara/p2p_shop_server
25587d887cf0234663c9d1746eb7df7463f2898a
dda254a154ec17d80b67626917988c67a26d7b8f
refs/heads/master
2020-03-15T15:50:22.091567
2018-05-29T01:32:39
2018-05-29T01:32:39
132,221,625
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SQLALCHEMY_DATABASE_URI = "postgres://shopagent:MAaMr6M3OG@127.0.0.1/p2p_shop" SQLALCHEMY_TRACK_MODIFICATIONS = True
UTF-8
Python
false
false
212
py
8
config.py
7
0.731132
0.688679
0
7
29.285714
82
ConnectionMaster/pytorchpipe
11,596,411,743,412
369e14fcd22d3067d9b691234174aa6892414343
9cb7670c64c13f09abee315f85f1f6b67b8eb1ad
/ptp/components/viewers/stream_viewer.py
e44fb4cc8d7f5b754e51def281d6ed85591b2308
[ "Apache-2.0" ]
permissive
https://github.com/ConnectionMaster/pytorchpipe
057325a5d4e8e6ce2198a953a705721388531add
9cb17271666061cb19fe24197ecd5e4c8d32c5da
refs/heads/develop
2023-04-07T17:46:26.451692
2019-11-05T23:36:13
2019-11-05T23:36:13
183,084,219
1
0
Apache-2.0
true
2023-04-03T23:18:43
2019-04-23T19:38:29
2021-01-23T07:09:57
2023-03-24T03:37:29
6,128
1
0
1
Python
false
false
# -*- coding: utf-8 -*- # # Copyright (C) tkornuta, IBM Corporation 2019 # # 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. __author__ = "Tomasz Kornuta" import numpy as np from ptp.configuration.config_parsing import get_value_list_from_dictionary from ptp.components.component import Component from ptp.data_types.data_definition import DataDefinition class StreamViewer(Component): """ Utility for displaying contents of streams of a single sample from the batch. """ def __init__(self, name, config): """ Initializes loss object. :param name: Loss name. :type name: str :param config: Dictionary of parameters (read from the configuration ``.yaml`` file). :type config: :py:class:`ptp.configuration.ConfigInterface` """ # Call constructors of parent classes. Component.__init__(self, name, StreamViewer, config) # Get key mappings for indices. self.key_indices = self.stream_keys["indices"] # Load list of streams names (keys). self.input_stream_keys = get_value_list_from_dictionary("input_streams", self.config) # Get sample number. self.sample_number = self.config["sample_number"] def input_data_definitions(self): """ Function returns a dictionary with definitions of input data that are required by the component. :return: dictionary containing input data definitions (each of type :py:class:`ptp.data_types.DataDefinition`). """ return { self.key_indices: DataDefinition([-1, 1], [list, int], "Batch of sample indices [BATCH_SIZE] x [1]"), } def output_data_definitions(self): """ Function returns a dictionary with definitions of output data produced the component. :return: dictionary containing output data definitions (each of type :py:class:`ptp.data_types.DataDefinition`). """ return { } def __call__(self, data_streams): """ Encodes batch, or, in fact, only one field of batch ("inputs"). Stores result in "outputs" field of data_streams. :param data_streams: :py:class:`ptp.utils.DataStreams` object containing (among others) "indices". """ # Use worker interval. if self.app_state.episode % self.app_state.args.logging_interval == 0: # Get indices. indices = data_streams[self.key_indices] # Get sample number. if self.sample_number == -1: # Random sample_number = np.random.randint(0, len(indices)) else: sample_number = self.sample_number # Generate displayed string. absent_streams = [] disp_str = "Showing selected streams for sample {} (index: {}):\n".format(sample_number, indices[sample_number]) for stream_key in self.input_stream_keys: if stream_key in data_streams.keys(): disp_str += " '{}': {}\n".format(stream_key, data_streams[stream_key][sample_number]) else: absent_streams.append(stream_key) # Log values and inform about missing streams. self.logger.info(disp_str) if len(absent_streams) > 0: self.logger.warning("Could not display the following (absent) streams: {}".format(absent_streams))
UTF-8
Python
false
false
3,970
py
188
stream_viewer.py
101
0.627204
0.623174
0
108
35.759259
124
richiurb/physics
11,725,260,730,139
2477d0c81324d29cf27d768ac7a068aacbe6855e
01ec486f2456a4a33031e7ef7db8c2b68d53b701
/heat_distribution_in_the_rod/main.py
a8d177f9b93b94213adbdb4ab015dcef48fb8939
[ "MIT" ]
permissive
https://github.com/richiurb/physics
a90c95ce388ef588b8ba42c07170ea0fc24ec39a
46e8a44790a7c6c29af11f29a846057026348cd2
refs/heads/master
2023-05-13T02:32:32.223265
2021-06-08T15:23:06
2021-06-08T15:23:06
273,761,990
0
0
MIT
false
2020-06-21T10:29:12
2020-06-20T18:20:44
2020-06-20T20:20:29
2020-06-21T10:29:11
1
0
0
0
null
false
false
from graphic import Graphic import start if __name__ == '__main__': a = float(input("Введите тепловой коэффициент: ")) start_u = start.get() print(start_u) Graphic(a, start_u).get()
UTF-8
Python
false
false
225
py
6
main.py
5
0.623116
0.623116
0
8
23.875
54
Sudoblark/Butterchase
10,153,302,690,650
b7548ea199c5f7ef37881ea187552e96056f688f
79c6db017b6e3feae0fda4c150851061fff92e9b
/Butterchase/TreasureClasses/Basic/Player/Items.py
dab0a9a9ea6254466e78de0cfd5f88cce16cf6be
[]
no_license
https://github.com/Sudoblark/Butterchase
f4d81675a0b9a1166f5d3c479cb0e34036237218
ff7f96f57374981c0fb96fc0b067464d8ea4ee15
refs/heads/master
2020-08-31T00:26:51.067365
2019-12-09T11:11:46
2019-12-09T11:11:46
218,533,704
0
0
null
false
2019-12-03T18:01:40
2019-10-30T13:27:37
2019-11-21T16:46:58
2019-12-03T18:01:40
132
0
0
2
Python
false
false
# Will import complete weapons and armour here from TreasureClasses.Basic.Player.Armour import ( Doublet, LeatherArmour, LoinCloth, Scutum, StuddedLeatherArmour ) from TreasureClasses.Basic.Player.Weapons import ( BareHands, IdioticSword, Seax, Spear, WoodenClub ) # Item arrays that get reference Weapons = [BareHands.BareHands(), IdioticSword.IdioticSword(), WoodenClub.WoodenClub()] Armour = [LoinCloth.LoinCloth(), Scutum.Scutum()]
UTF-8
Python
false
false
457
py
74
Items.py
73
0.763676
0.763676
0
14
31.571429
63
allena29/python-yang-voodoo
11,759,620,460,127
e8cb6e672c918b6ddb98b9e201fd47ae895ae818
380e97726c06871594f3145504c8d76e92002bae
/yangvoodoo/DiffEngine.py
c6ceff36c973a3e22feb8597d5c055c8f7ebebfc
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
permissive
https://github.com/allena29/python-yang-voodoo
36e1bb19a13ad005bf1c67c6ab8ab1815c8443fe
c4ad7b061dd43f1035f5dc7589d2614e9a28506d
refs/heads/master
2023-08-28T13:41:05.877911
2023-08-21T20:55:13
2023-08-21T20:55:13
180,037,820
5
1
Apache-2.0
false
2023-08-21T20:55:14
2019-04-07T23:48:16
2023-01-15T13:31:06
2023-08-21T20:55:13
5,855
5
1
1
Python
false
false
#!/usr/bin/env python3 # from dictdiffer import diff, patch, swap, revert from dictdiffer import diff import yangvoodoo class DiffIterator: """ This call return a diffset for a particular part of a dataset. The return value is an ordered set of (path, old-value, new-value, operation) Example usage: differ = DiffIterator(dataset_A, dataset_B, filter='/integrationtest:diffs', end_filter='/name') The resulting object can be used with. differ.all() - return all results from remove, add and modify differ.remove() - return only XPATH's that have been removed from dataset_B (in dataset_A) differ.add() - return only XPATH's that have been added from dataset_B (not in dataset_A) differ.modified() - return only XPATH's that have been modified (different values in dataset_A and dataset_B) differ.remove_modify_then_add() - a convenience function of the above differ.modify_then_add() - a convenience function of the above differ.remove_then_modify() - a convenience function of the above The filters TODO: this implementation is not optimal - the format data comes back from dictdiffer is a little different depending on the exact nature of the diff. Leaf-lists are more difficult. """ ADD = 1 MODIFY = 2 REMOVE = 3 def __init__(self, dataset_a, dataset_b, start_filter="", end_filter=""): if isinstance(dataset_a, yangvoodoo.VoodooNode.Node): dataset_a = dataset_a._context.dal.dump_xpaths() if isinstance(dataset_b, yangvoodoo.VoodooNode.Node): dataset_b = dataset_b._context.dal.dump_xpaths() self.a = dataset_a self.b = dataset_b self.start_filter = start_filter self.end_filter = end_filter self.diffset = diff(self.a, self.b) self.results = [] for (op, path, values) in self.diffset: if isinstance(path, list): path = path[0] if op == "change": if not DiffIterator.is_filtered(path, start_filter, end_filter): self._handle_modify(path, values) else: self._handle_add_or_remove(op, path, values) @staticmethod def is_filtered(path, filter, end_filter): return ( path[0 : len(filter)] != filter or end_filter != "" and path[-len(end_filter) :] != end_filter ) def _handle_add_or_remove(self, op, path, values): for (leaf_path, value) in values: if isinstance(leaf_path, str): path = leaf_path if DiffIterator.is_filtered(path, self.start_filter, self.end_filter): continue # This is specific to stub_store which uses lists/tuples for things it creates as covenient # lookups. if isinstance(value, tuple): continue if not isinstance(value, list): value = [value] for v in value: if op == "remove": self.results.append((path, v, None, self.REMOVE)) else: self.results.append((path, None, v, self.ADD)) def _handle_modify(self, path, values): (old, new) = values # This is specific to stub_store which uses lists/tuples for things it creates as covenient # lookups. if not isinstance(new, tuple): self.results.append((path, old, new, self.MODIFY)) def all(self, start_filter="", end_filter=""): for (path, oldval, newval, op) in self.results: if self.is_filtered(path, start_filter, end_filter): continue yield (path, oldval, newval, op) def remove(self, start_filter="", end_filter=""): for (path, old, new, op) in self.results: if op == self.REMOVE and not self.is_filtered( path, start_filter, end_filter ): yield (path, old, new, op) def add(self, start_filter="", end_filter=""): for (path, old, new, op) in self.results: if op == self.ADD and not self.is_filtered(path, start_filter, end_filter): yield (path, old, new, op) def modified(self, start_filter="", end_filter=""): for (path, old, new, op) in self.results: if op == self.MODIFY and not self.is_filtered( path, start_filter, end_filter ): yield (path, old, new, op) def remove_modify_then_add(self, start_filter="", end_filter=""): for (path, old, new, op) in self.results: if op == self.REMOVE and not self.is_filtered( path, start_filter, end_filter ): yield (path, old, new, op) for (path, old, new, op) in self.results: if op == self.MODIFY and not self.is_filtered( path, start_filter, end_filter ): yield (path, old, new, op) for (path, old, new, op) in self.results: if op == self.ADD and not self.is_filtered(path, start_filter, end_filter): yield (path, old, new, op) def modify_then_add(self, start_filter="", end_filter=""): for (path, old, new, op) in self.results: if op == self.MODIFY and not self.is_filtered( path, start_filter, end_filter ): yield (path, old, new, op) for (path, old, new, op) in self.results: if op == self.ADD and not self.is_filtered(path, start_filter, end_filter): yield (path, old, new, op) def remove_then_modify(self, start_filter="", end_filter=""): for (path, old, new, op) in self.results: if op == self.REMOVE and not self.is_filtered( path, start_filter, end_filter ): yield (path, old, new, op) for (path, old, new, op) in self.results: if op == self.MODIFY and not self.is_filtered( path, start_filter, end_filter ): yield (path, old, new, op)
UTF-8
Python
false
false
6,205
py
133
DiffEngine.py
67
0.565189
0.564222
0
156
38.775641
121
opsxcq/pastes
16,226,386,479,258
9e12d20ebe409ca45cd556bc4a96563e9f359a88
f5f8871fb63e52036ffc822a79f10a091a8dc04d
/codepad.org/2015/08/08/utLYK0pB
77765b72bec1b9be9b1981c944d98ddd55298f48
[]
no_license
https://github.com/opsxcq/pastes
d8c0d20db2ee7035d923f7172e6d9a00f2f70731
6ff8513ca56e78f705cf35a07f46a212ca0eb580
refs/heads/master
2016-04-21T08:43:32.701647
2016-04-21T05:45:46
2016-04-21T05:45:46
55,317,443
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python print '''''j'''''
UTF-8
Python
false
false
36
8,503
utLYK0pB
5,561
0.5
0.5
0
2
17
17
dpark6060/FilterShift
13,615,046,355,835
b76c0f8be3cdd75bd879acbb73423a35144457f6
eb5a9183efbf1337391cb1f4cfe98821a904739a
/CheckResults.py
cea675244b53b2f1cf3fb60fb83e7dc4b801f4fc
[]
no_license
https://github.com/dpark6060/FilterShift
96d0ec77d5503510e2c3c22b2d3e97b070395d33
6171a3038aba4ce345c70fc0c50f5841fda9cd71
refs/heads/master
2016-09-06T05:07:38.753404
2014-08-20T19:27:00
2014-08-20T19:27:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import numpy as np import ZeroNorm def Error(Corrected,Tru): Corrected=ZeroNorm.Normalize(ZeroNorm.Zero(Corrected)) Tru=ZeroNorm.Normalize(ZeroNorm.Zero(Tru)) MSE=np.sum(np.square(np.subtract(Corrected,Tru)))/(np.nonzero(np.sum(Tru,axis=3))[1].shape[-1]*Tru.shape[-1]) MAXERR=np.amax(np.square(np.subtract(Corrected,Tru))) return (MSE,MAXERR)
UTF-8
Python
false
false
408
py
20
CheckResults.py
20
0.683824
0.67402
0
14
27.714286
113
lilitotaryan/eventnet-back-end
16,372,415,338,257
f54bb9e1f8ad44e29224070b4a436c402d6eb3dc
7a0334693cd31fe4fdef06324ede0d72c6530c40
/buy_ticket/filters.py
11e4c181b6b3f60f055f5b692c9bd0c1973b743b
[]
no_license
https://github.com/lilitotaryan/eventnet-back-end
7949668a4108b36a6e1a2f6439d6e966991d64ba
5828b1520b8feeb363fdac0b85b08e001572991e
refs/heads/main
2023-02-18T02:24:45.475978
2021-01-22T18:15:42
2021-01-22T18:15:42
332,027,025
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import django_filters from authentication.utils import string_to_bool, get_current_time from .models import Event, Ticket from user_crud.models import Category import re from rest_framework import filters from django.db.models import Q class TicketFilter(django_filters.FilterSet): is_used = django_filters.CharFilter(field_name="is_used", method='filter_is_used') search = django_filters.CharFilter(method='filter_search') order_by_field = 'ordering' ordering = django_filters.OrderingFilter( # fields(('model field name', 'parameter name'),) fields= ('event__end_date', ) ) class Meta: model = Ticket fields = ('event__end_date', 'is_used') def filter_is_used(self, queryset, name, value): # construct the full lrequest.GET.get('states').split(',') if value: value = string_to_bool(value) if value: queryset = queryset.filter(Q(is_used = value)) # else: # queryset = queryset.filter(Q(is_used=value) | Q(event__end_date__gte=get_current_time())) return queryset def filter_search(self, queryset, name, value): # construct the full lrequest.GET.get('states').split(',') if value: values = value.split('+') for i in values: i = re.sub(r"[^a-zA-Z0-9]", "", i) if value: return queryset.filter(Q(event__title__iregex=values) | Q(public_id__iregex=values))
UTF-8
Python
false
false
1,504
py
99
filters.py
95
0.611702
0.610372
0
43
34
107
Unhackables/sbds
18,459,769,444,169
dccea05930873a1b4f58483cdb8aba9c2d89a751
0f2d2d6fdb4fd5e7e20bd78864a1cf83bfa8eaeb
/sbds/http_server.py
44867e313d590e2252e8553060333c171dccef54
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
https://github.com/Unhackables/sbds
2cc407523c3eb197a976a1fc755075fe70c7dcbc
53bf13a746cb3df5e917b49cf0b75241a25de86a
refs/heads/master
2021-01-21T05:29:30.893706
2017-02-21T18:08:26
2017-02-21T18:08:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import os from datetime import datetime import logging import click import bottle from bottle.ext import sqlalchemy from bottle import request import maya import sbds.logging from sbds.http_client import SimpleSteemAPIClient from sbds.storages.db import Base, Session from sbds.storages.db.tables.core import Block from sbds.storages.db.tables.tx import tx_class_map from sbds.storages.db.utils import configure_engine MAX_DB_ROW_RESULTS = 100000 DB_QUERY_LIMIT = MAX_DB_ROW_RESULTS + 1 logger = sbds.logging.getLogger(__name__, level=logging.DEBUG) rpc_url = os.environ.get('STEEMD_HTTP_URL', 'https://steemd.steemitdev.com') database_url = os.environ.get('DATABASE_URL', 'sqlite:///') rpc = SimpleSteemAPIClient(rpc_url) database_url, url, engine_kwargs, engine = configure_engine( database_url, echo=True) Session.configure(bind=engine) app = bottle.Bottle() # pylint: disable=undefined-variable plugin = sqlalchemy.Plugin( engine, # SQLAlchemy engine created with create_engine function. Base.metadata, # SQLAlchemy metadata, required only if create=True. keyword='db', # Keyword used to inject session database in a route (default 'db'). create=True, # If it is true, execute `metadata.create_all(engine)` when plugin is applied (default False). commit=False, # If it is true, plugin commit changes after route is executed (default True). use_kwargs=False, # If it is true and keyword is not defined, plugin uses **kwargs argument to inject session database (default False). create_session=Session) # pylint: enable=undefined-variable app.install(plugin) ''' Accounts ========= - total accounts SELECT COUNT(type) FROM sbds_transactions WHERE type='account_create' - ''' def match_operation(op_str): return tx_class_map[op_str.lower()] # pylint: disable=unused-argument def operation_filter(config): ''' Matches blockchain operations. ''' regexp = '(%s){1}' % r'|'.join(key for key in tx_class_map.keys()) def to_python(match): return tx_class_map[match] def to_url(tx): return tx.operation_type return regexp, to_python, to_url # pylint: enable=unused-argument app.router.add_filter('operations', operation_filter) class JSONError(bottle.HTTPResponse): default_status = 500 def __init__(self, status=None, body=None, exception=None, traceback=None, **options): self.exception = exception self.traceback = traceback body = dict(error=body) headers = {'Content-Type': 'application/json'} super(JSONError, self).__init__( body, status, headers=headers, **options) def parse_block_num(block_num): return int(block_num) def parse_iso8601(iso_str): return maya.dateparser.parse(iso_str) def parse_to_query_field(to=None): if isinstance(to, tuple): to = to[0] elif isinstance(to, int): return parse_block_num(to) elif isinstance(to, str): try: return parse_block_num(to) except ValueError: return parse_iso8601(to) else: raise ValueError('to must be a iso8601 string or block_num') def parse_from_query_field(_from=None): if isinstance(_from, tuple): _from = _from[0] elif isinstance(_from, int): return parse_block_num(_from) elif isinstance(_from, str): try: return parse_block_num(_from) except ValueError: return parse_iso8601(_from) else: raise ValueError('from must be a iso8601 string or block_num') query_field_parser_map = { 'to': parse_to_query_field, 'from': parse_from_query_field } def parse_query_fields(query_dict): logger.debug('query_dict', extra=query_dict) parsed_fields = dict() for key, value in query_dict.items(): if key in query_field_parser_map: parsed_fields[key] = query_field_parser_map[key](value) else: raise ValueError('received unknown query field: %s', key) logger.debug('parsed_fields', extra=parsed_fields) return parsed_fields def return_query_response(result): if len(result) > MAX_DB_ROW_RESULTS: return JSONError( status=403, body='Too many results (%s rows)' % len(result)) else: return [row.to_json() for row in result] @app.get('/health') def health(db): last_db_block = Block.highest_block(db) last_irreversible_block = rpc.last_irreversible_block_num() diff = last_irreversible_block - last_db_block return dict( last_db_block=last_db_block, last_irreversible_block=last_irreversible_block, diff=diff, timestamp=datetime.utcnow().isoformat()) @app.get('/api/v1/ops/<operation:operations>/count') def count_operation(operation, db): query = db.query(operation) if request.query: try: parsed_fields = parse_query_fields(request.query) except Exception as e: return JSONError(status=400, body='Bad query: %s' % e) _from = parsed_fields.get('from') to = parsed_fields.get('to') query = operation.from_to_filter(query, _from=_from, to=to) return dict(count=query.count()) # '/api/v1/ops/custom/:tid?from=<iso8601-or-block_num>&to=<iso8601-or-blocknum>' @app.get('/api/v1/ops/custom/:tid') def get_custom_json_by_tid(tid, db): cls = tx_class_map['custom'] query = db.query(cls).filter_by(tid=tid) if request.query: try: parsed_fields = parse_query_fields(request.query) except Exception as e: logger.error(e) return JSONError(status=400, body='Bad query: %s' % e) query = cls.from_to_filter( query, _from=parsed_fields.get('from'), to=parsed_fields.get('to')) return return_query_response(result) # Development server @click.command() def dev_server(): _dev_server() def _dev_server(): # pylint: disable=bare-except try: app.run(port=8080, debug=True) except: pass finally: app.close() # pylint: enable=bare-except # WSGI application application = app
UTF-8
Python
false
false
6,234
py
13
http_server.py
12
0.650465
0.641161
0
230
26.104348
121
paolafer/petaloCherenkov
13,434,657,708,926
38d30e40d779df43f4350be571fadc5a92a060f5
27036da89d3b778fcac0187b30f324780821abdd
/cnt/Scintillator.py
b504d2e55286bf281845fe70fe23d3725e07b14d
[]
no_license
https://github.com/paolafer/petaloCherenkov
d9b05e90e584940a6c1373dac4053986aef6ed11
bf61299f8e144f89abd3161ecc17c4cd09c1d2b3
refs/heads/master
2021-01-22T12:26:31.240185
2017-06-22T09:56:10
2017-06-22T09:56:10
92,726,318
0
0
null
true
2017-05-29T09:41:52
2017-05-29T09:41:52
2017-05-29T09:09:39
2017-05-29T09:20:12
0
0
0
0
null
null
null
""" Scintillator Abstract class for scintillators """ from abc import ABCMeta, abstractmethod from Centella.physical_constants import * import sys from Util import * from Xenon import * nm = nanometer mol = mole micron = micrometer LXeRefractionIndex =[ [6.4, 1.58587, 0.0964027], [6.6, 1.61513, 0.508607], [6.8, 1.6505, 1.33957], [7, 1.69447, 1.69005], [7.2, 1.75124, 1.02138], [7.4, 1.82865, 0.295683], [7.6, 1.94333, 0.098714] ] LysoScintSpectrum =[ [2.2543, 0.0643], [2.4797, 0.1929], [2.6436, 0.4], [2.8700, 1.], [3.0996, 0.4071] ] ############################################################ def sortRI(elem): """ A helper function used to sort the hits. The hits are organises like this: (id, [x,y,z,A,t]): the function returns the time as key to sort the hit list """ return elem[0] class Scintillator(object): __metaclass__ = ABCMeta @abstractmethod def Name(self): """ Name of scintillator """ pass @abstractmethod def EffectiveAtomicNumber(self): """ EffectiveAtomicNumber """ pass @abstractmethod def RadiationLength(self): """ Radiation length/Density """ pass @abstractmethod def RefractionIndex(self): """ returns the refraction index to the scintillation light """ pass @abstractmethod def RefractionIndexL(self,lamda): """ returns the refraction index to the scintillation light """ pass @abstractmethod def RefractionIndexBlue(self): """ returns the refraction index to the blue scintillation light """ pass @abstractmethod def DecayConstant(self): """ returns the decay time of the scintillation light """ pass @abstractmethod def Density(self): """ Density """ pass @abstractmethod def ScintillationWavelength(self): """ average scintillation wavelength """ pass @abstractmethod def PhotoelectricFractionAt511KeV(self): """ Photoelectric Xs """ pass @abstractmethod def AttenuationAt511KeV(self,Z): """ Attenuation of a beam of energy E 511 keV in a thickness Z """ pass @abstractmethod def EfficiencyAt511KeV(self,Z): """ Fraction of gammas of energy E 511 keV interacting in thickness Z """ pass #@abstractmethod def PhotoelectricEfficiencyAt511KeV(self,Z): """ Fraction of gammas of energy E 511 keV interacting in thickness Z """ return self.EfficiencyAt511KeV(Z)*self.PhotoelectricFractionAt511KeV() @abstractmethod def ScintillationPhotonsAt511KeV(self): """ Number of scintillation photons produced by a photon of energy 511 keV """ pass def DisplayProperties(self): s= """ Name = %s Z = %d Density = %7.4g g/cm3 X0= %7.4g cm Refraction Index = %7.2f Decay constant = %7.2f ns Number of scintillation photons = %7.2f Scintillation wavelength = %7.2f nm Photoelectric fraction at 511 keV = %7.2f Attenuation per cm = %7.2f Efficiency per cm = %7.2f """%(self.Name(), self.EffectiveAtomicNumber(), self.Density()/(g/cm3),self.RadiationLength()/cm, self.RefractionIndex(), self.DecayConstant()/ns, self.ScintillationPhotonsAt511KeV(), self.ScintillationWavelength()/nm, self.PhotoelectricFractionAt511KeV(), self.AttenuationAt511KeV(1*cm), self.EfficiencyAt511KeV(1*cm)) return s def __str__(self): return self.DisplayProperties() class LXe(Scintillator): def __init__(self,wi=15.6*eV,ws=16.6*eV,lambdaScint=172*nm,rayleigh=36*mm, tau1=2.2*ns,tau2=27*ns,tau3=45*ns, rtau1=0.065,rtau2=0.935,rtau3=0.0,nUV=1.70,nBlue=1.4): self.Z = 54 self.A = 131.29*g/mol self.T = 160*kelvin self.x0 = 8.48 * g/cm2 self.rho = 3*g/cm3 self.dedx=0.35*keV/micron self.wi=wi self.ws=ws self.lambdaScint = lambdaScint self.rayleigh = rayleigh self.tau1=tau1 self.tau2=tau2 self.tau3=tau3 self.rtau1=rtau1 self.rtau2=rtau2 self.rtau3=rtau3 self.nUV = nUV self.nBlue=nBlue lxri =[] #transform to nm for elem in LXeRefractionIndex: ene = elem[0] n = elem[1] f = elem[2] x =[(1240./ene)*nm,n,f] #print x[0]/nm lxri.append(x) self.LXRI = sorted(lxri, key=sortRI) #print self.LXRI l,n = self.AverageLamdaAndRI() self.AverageLamda = l self.AverageRefractionIndexUV = n def Name(self): """ Interface: Name """ return "LXE" def EffectiveAtomicNumber(self): """ Interface: Xenon atomic number """ return self.Z def RadiationLength(self): """ Interface: X0/rho """ return self.x0/self.rho def RefractionIndex(self): """ Interface: Take the UV """ return self.AverageRefractionIndexUV def DecayConstant(self): """ Interface: returns the decay time of the scintillation light In LXe one has 2 constants, return the weighted average """ return (self.Lifetime(1)*self.LifetimeRatio(1)+ self.Lifetime(2)*self.LifetimeRatio(2))/2. def Density(self): """ Interface: Density of LXe """ return self.rho def ScintillationWavelength(self): """ Interface: average scintillation wavelength """ return self.lambdaScint def PhotoelectricFractionAt511KeV(self): """ Interface: PE fraction """ return self.PhotoelectricFraction(511*keV) def AttenuationAt511KeV(self,Z): """ Interface: Attenuation of a beam of energy 511 keV in a thickness Z """ return self.Attenuation(511*keV,Z) def EfficiencyAt511KeV(self,Z): """ Interface. Fraction of gammas of energy 511 keV interacting in thickness E """ return self.Efficiency(511*keV,Z) def ScintillationPhotonsAt511KeV(self): """ Interface: Number of scintillation photons produced by a photon of energy 511 keV """ return self.ScintillationPhotons(511*keV) def AverageLamdaAndRI(self): """ Returns the average lamda and refraction index """ l=0. n=0. w=0. for elem in self.LXRI: l+=elem[0]*elem[2] n+=elem[1]*elem[2] w+=elem[2] return (l/w,n/w) def RmsRI(self): """ Returns the rms of the refraction index """ ns=0. w=0. lw, nw = self.AverageLamdaAndRI() print "nw = %7.2f"%(nw) for elem in self.LXRI: ns+=elem[2]*(elem[1] - nw)**2 w+=elem[2] print " ni = %7.4g, ni - nw = %7.4g, wi =%7.4g ns = %7.4g"%( elem[1],elem[1] - nw,elem[2],ns) N=len(self.LXRI) a = N*ns b = (N-1)*w sw = sqrt(a/b) print " N = %7.2f, ns = %7.2f, w = %7.2f, a = %7.2f b = %7.2f"%( N,ns,w,a,b) return sw def RefractionIndexL(self,lamda): """ returns the refraction index """ if lamda < self.LXRI[0][0]: return self.LXRI[0][1] elif lamda > self.LXRI[6][0]: return self.LXRI[6][1] else: for i in xrange(len(self.LXRI)-1): elem = self.LXRI[i] x0 = elem[0] y0 = elem[1] elem = self.LXRI[i+1] x1 = elem[0] y1 = elem[1] if lamda >= x0 and lamda < x1: break return lin(lamda,x0,y0,x1,y1) def AtomicNumber(self): """ Xenon atomic number """ return self.Z def AtomicMass(self): """ Xenon atomic mass """ return self.A def X0(self): """ X0 in gr/cm2 """ return self.x0 def TemperatureAt1Bar(self): """ LXe Temperature """ return self.T def RefractionIndexUV(self): return self.AverageRefractionIndexUV def RefractionIndexBlue(self): return self.nBlue def Lifetime(self,i): """ i ->(1,3) for the three lifetimes. """ if i == 1: return self.tau1 elif i == 2: return self.tau2 elif i == 3: return self.tau3 else: print "index must be 1,2 or 3" sys.exit(0) def LifetimeRatio(self,i): """ i ->(1,3) for the three lifetimes. """ if i == 1: return self.rtau1 elif i == 2: return self.rtau2 elif i == 3: return self.rtau3 else: print "index must be 1,2 or 3" sys.exit(0) def Wi(self): """ Energy needed to produce an ionization pair """ return self.wi def Ws(self): """ Energy needed to produce scintillation photons """ return self.ws def Rayleigh(self): """ Attenuation due to Rayleigh Scattering """ return self.rayleigh def dEdX(self): return self.dedx def ComptonCrossSection(self,E): """ Compton = Incoherent Scattering """ return ScatterIncoherent(E) def PhotoelectricCrossSection(self,E): """ Photoelectric Xs """ return Photoelectric(E) def TotalCrossSection(self,E): """ Total Xs """ return TotalInteraction(E) def PhotoelectricFraction(self,E): """ Interface: PE fraction """ return self.PhotoelectricCrossSection(E)/self.TotalCrossSection(E) def Attenuation(self,E,Z): """ Attenuation of a beam of energy E in a thickness Z """ return TransmittedBeam(E,Z,self.Density()) def Efficiency(self,E,Z): """ Fraction of gammas of energy E interacting in thickness E """ return InteractionFraction(E,Z,self.Density()) def GammaPathLength(self,E): """ gamma path length in xenon """ xz = self.TotalCrossSection(E)*self.Density() return 1./xz def ScintillationPhotons(self,E): """ Number of scintillation photons produced by a photon of energy E """ return E/self.Ws() def SPhotonsAt511KeV(self,i): if i == 1: return self.ScintillationPhotons(511*keV)*self.LifetimeRatio(1) elif i == 2: return self.ScintillationPhotons(511*keV)*self.LifetimeRatio(2) elif i == 3: return self.ScintillationPhotons(511*keV)*self.LifetimeRatio(3) else: print "index must be 1,2 or 3" sys.exit(0) def IonizationElectrons(self,E): """ Number of ionization electrons produced by a photon of energy E """ return E/self.Wi() def CostPerGram(self): """ Cost per gram """ return 1.0 #in euro def __str__(self): s= """ Name = LXe Z = %d A = %7.4g g/mole Temperature at atm pressure (1 bar) = %7.2f kelvin Density = %7.4g g/cm3 X0= %7.4g g/cm2 X1= %7.4g cm de/dx = %7.4g keV/cm Ws = %7.4g eV Wi = %7.4g eV Rayleigh Scattering = %7.2g cm Scintillation wavelength = %7.2f nm Refraction Index (UV) = %7.2f Refraction Index (Blue) = %7.2f Lifetimes: tau1 = %7.2f ns, ratio tau 1 = %7.2f tau2 = %7.2f ns, ratio tau 2 = %7.2f tau3 = %7.2f ns, ratio tau 3 = %7.2f """%(self.AtomicNumber(),self.AtomicMass()/(g/mol), self.TemperatureAt1Bar()/kelvin, self.Density()/(g/cm3), self.X0()/(g/cm2),(self.X0()/self.Density())/cm, self.dEdX()/(keV/cm),self.Ws()/eV, self.Wi()/eV, self.Rayleigh()/cm, self.ScintillationWavelength()/nm, self.RefractionIndex(), self.nBlue, self.tau1/ns, self.rtau1,self.tau2/ns,self.rtau2, self.tau3/ns, self.rtau3) return s class LYSO(Scintillator): def __init__(self,Z=54,rho=7.3*g/cm3, n=1.82, X0=1.16*cm, LambdaAtt = 0.87*(1./cm), LambdaPeak=420*nm, tau = 50*ns, PhotoFraction = 0.3, Nphot = 15000): """ Represents lyso """ self.x0 = X0 self.Z = Z self.rho = rho self.tau=tau self.n = n self.mu=LambdaAtt self.lambdaScint = LambdaPeak self.tau = tau self.photoF = PhotoFraction self.Nphot = Nphot lysct =[] #transform to nm for elem in LysoScintSpectrum: ene = elem[0] w =elem[1] x =[(1240./ene)*nm,w] lysct.append(x) self.LYSC = sorted(lysct, key=sortRI) print "scintillation spectrum" for elem in self.LYSC: print " lambda = %7.2f nm w= %7.2g"%(elem[0]/nm,elem[1]) l = self.AverageLamda() def Name(self): """ Interface: Name """ return "LYSO" def EffectiveAtomicNumber(self): """ Interface: Lyso atomic number """ return self.Z def RadiationLength(self): """ Interface: X0/rho """ return self.x0/cm def RefractionIndex(self): """ Interface: """ return self.n def RefractionIndexL(self,lamda): """ returns the refraction index """ return self.n def RefractionIndexBlue(self): """ returns the refraction index """ return self.n def DecayConstant(self): """ Interface """ return self.tau def Density(self): """ Interface: Density of LXe """ return self.rho def ScintillationWavelength(self): """ Interface: average scintillation wavelength """ return self.lambdaScint def PhotoelectricFractionAt511KeV(self): """ Interface Photoelectric Xs """ return self.photoF def AttenuationAt511KeV(self,Z): """ Interface: Attenuation of a beam of energy E 511 keV in a thickness Z """ return exp(-Z*self.mu) def EfficiencyAt511KeV(self,Z): """ Interface: Fraction of gammas of energy E 511 keV interacting in thickness Z """ return 1. - self.AttenuationAt511KeV(Z) def ScintillationPhotonsAt511KeV(self): """ Number of scintillation photons produced by a photon of energy 511 keV """ return self.Nphot def AverageLamda(self): """ Returns the average lamda """ l=0. w=0. for elem in self.LYSC: l+=elem[0]*elem[1] w+=elem[1] return (l/w) def X0(self): """ EffectiveAtomicNumber """ return self.x0 def Lifetime(self): """ returns the lifetime """ return self.tau def __str__(self): s= """ Name = LYSO Z = %d Density = %7.4g g/cm3 X0= %7.4g g/cm2 Scintillation wavelength = %7.2f nm Refraction Index (Blue) = %7.2f Lifetime = %7.2f ns ScintillationPhotons = %7.2f Attenuation in 1 cm = %7.2f PhotoelectricFraction = %7.2f """%(self.EffectiveAtomicNumber(), self.Density()/(g/cm3), self.X0()/cm, self.ScintillationWavelength()/nm, self.RefractionIndex(), self.Lifetime(), self.ScintillationPhotonsAt511KeV(), self.AttenuationAt511KeV(1.*cm),self.PhotoelectricFractionAt511KeV()) return s def testLxe(): lxe = LXe() print lxe print lxe.DisplayProperties() for l in drange(150*nm,450*nm,10*nm): print """ for lamda = %7.2f nm (%7.2f eV) n = %7.2f """%(l/nm, 1240./(l/nm), lxe.RefractionIndexL(l)) l,n = lxe.AverageLamdaAndRI() print """ Average lamda = %7.2f nm ; average n = %7.2f """%(l/nm, n) rmsri = lxe.RmsRI() print """ Weighted rms of n = %7.2f """%(rmsri) print """ Dn/n = %7.2f """%(rmsri/n) print "Efficiency for 511 keV photons" for z in drange(1., 11., 1.): print """ z = %7.2g cm LXe eff = %7.2g """%(z, lxe.Efficiency(511*keV,z*cm)) print """Photoelectric fraction at 511 keV photons = %7.2g"""%( lxe.PhotoelectricCrossSection(511*keV)/ lxe.TotalCrossSection(511*keV)) print """ Gamma path lenght in LXe for 511 keV photons = %7.2g cm """%( lxe.GammaPathLength(511*keV)/cm) print """ Number of scintillation photons Ns (511 keV, LXe)= %7.2g with tau1 = %7.2f ns lifetime: = %7.2f with tau2 = %7.2f ns lifetime: = %7.2f with tau3 = %7.2f ns lifetime: = %7.2f """%( lxe.ScintillationPhotons(511*keV),lxe.Lifetime(1), lxe.SPhotonsAt511KeV(1), lxe.Lifetime(2), lxe.SPhotonsAt511KeV(2), lxe.Lifetime(3), lxe.SPhotonsAt511KeV(3) ) def testLyso(): lyso = LYSO() print lyso lyso.DisplayProperties() print "Average Lamda = %7.2f"%(lyso.AverageLamda()/nm) for z in drange(1., 11., 1.): print """ z = %7.2g cm LYSO eff = %7.2g """%(z, lyso.EfficiencyAt511KeV(z*cm)) def plotLXe(): Lambda=[] I=[] N=[] for elem in LXeRefractionIndex: ene = elem[0] n = elem[1] f = elem[2] Lambda.append(1240./ene) I.append(f) N.append(n) plt.plot(Lambda,I) plt.show() plt.plot(Lambda,N) plt.show() def plotLYSO(): Lambda=[] I=[] for elem in LysoScintSpectrum: ene = elem[0] f = elem[1] Lambda.append(1240./ene) I.append(f) plt.plot(Lambda,I) plt.show() if __name__ == '__main__': #testLxe() #testLyso() plotLXe() plotLYSO()
UTF-8
Python
false
false
17,439
py
29
Scintillator.py
24
0.568553
0.52612
0
779
21.368421
89
fffk3045167/desktop2
15,049,565,413,806
0a4df0d067e6f8af216bd0f3bcf265bc85d146ec
3360762f3c870acd245ab2a37954ef75b05247a8
/Core_python/TK/tkLabelandButton.py
4ba10f5cc9d3f9a7bcb71de1f79c5af990a3fc03
[]
no_license
https://github.com/fffk3045167/desktop2
66d335e42100a5942e3beb43bf68b7006b14dcca
5c7b5e67659cae56b5a0093c0c9819fc622a67dc
refs/heads/master
2023-01-19T03:22:15.422108
2020-11-17T13:01:27
2020-11-17T13:01:27
269,377,880
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from tkinter import * # 顶层窗口(根窗口) top = Tk() hello = Label(top, text='Hello World!') hello.pack() Q = Button(top, text='QUIT', command=quit, bg='red', fg='white') Q.pack(fill=X, expand=1) # 运行 top.mainloop()
UTF-8
Python
false
false
244
py
79
tkLabelandButton.py
61
0.60177
0.597345
0
14
15.142857
42
Cyril-Grl/MuGen
9,139,690,419,004
c8612d312a4ae610b34387b9ace410f3c8c397a1
073353de7c23aa42756adfe33f51b41029dd4f87
/src/Convolutional_VAE/cvae_train.py
032c56bae62b185237de695aa81ae0457969d3e9
[ "MIT" ]
permissive
https://github.com/Cyril-Grl/MuGen
e0725f80a8d36b6e4d6cb556a65cde2b8defa992
b4585fe9c1e9bb5d952b79782132e54ba5f0d011
refs/heads/master
2023-09-05T08:26:34.302182
2022-07-05T08:20:01
2022-07-05T08:20:01
216,768,752
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
'''Example of VAE on MNIST dataset using MLP The VAE has a modular design. The encoder, decoder and VAE are 3 models that share weights. After training the VAE model, the encoder can be used to generate latent vectors. The decoder can be used to generate MNIST digits by sampling the latent vector from a Gaussian distribution with mean = 0 and std = 1. # Reference [1] Kingma, Diederik P., and Max Welling. "Auto-Encoding Variational Bayes." https://arxiv.org/abs/1312.6114 ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from keras.layers import Lambda, Input, Dense, LSTM, RepeatVector, Conv2D, Flatten, Conv2DTranspose, Reshape from keras.models import Model from keras.datasets import mnist from keras.losses import mse, binary_crossentropy from keras.utils import plot_model from keras import backend as K, objectives from keras.optimizers import Adam import numpy as np import matplotlib.pyplot as plt import argparse import os import pretty_midi from sklearn.model_selection import train_test_split import pandas as pd from sklearn.utils import shuffle from keras.callbacks import EarlyStopping intermediate_dim = 128 batch_size = 32 latent_dim = 2 epochs = 100 random_state = 42 dataset_size = 10000 list_files_name= [] file_shuffle=[] test_size=0.25 timesteps=1 res = 64 # min 8 filters = 16 kernel_size = 3 range_of_notes_to_extract=16 number_of_data_to_extract=res*2 # reparameterization trick # instead of sampling from Q(z|X), sample epsilon = N(0,I) # z = z_mean + sqrt(var) * epsilon def sampling(args): """Reparameterization trick by sampling from an isotropic unit Gaussian. # Arguments args (tensor): mean and log of variance of Q(z|X) # Returns z (tensor): sampled latent vector """ z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_shape(z_mean)[1] # by default, random_normal has mean = 0 and std = 1.0 epsilon = K.random_normal(shape=(batch, dim)) return z_mean + K.exp(0.5 * z_log_var) * epsilon def plot_results(models, data, batch_size=128, model_name="vae_mnist"): """Plots labels and MNIST digits as a function of the 2D latent vector # Arguments models (tuple): encoder and decoder models data (tuple): test data and label batch_size (int): prediction batch size model_name (string): which model is using this function """ encoder, decoder = models x_test, y_test = data # display a 2D plot of the digit classes in the latent space z_mean, _, _ = encoder.predict(x_test, batch_size=batch_size) plt.figure(figsize=(12, 10)) plt.scatter(z_mean[:, 0], z_mean[:, 1], c=y_test) plt.colorbar() plt.xlabel("z[0]") plt.ylabel("z[1]") plt.savefig(filename) #print(len(z_mean)) nb_elem_per_class = dataset_size*test_size #to_decode = np.array([[0.5, 0], [1.8, 1]], dtype=np.float32) #final = decoder.predict(to_decode) #print(final ) annotate=False if annotate: for i, txt in enumerate(file_shuffle[ :int(dataset_size*2 * test_size)]): txt = txt.replace('.mid', '') txt =txt.replace('enerated', '') txt =txt.replace('andom', '') txt = txt.replace('_', '') plt.annotate(txt,(z_mean[i,0], z_mean[i,1])) plt.show() def load_data(path, class_label, index_filename ): path, dirs, files = next(os.walk(path)) num_size = len(dirs) current_folder = 0 num_files = 0 for subdir, dirs, files in os.walk(path): for file in files: if num_files < dataset_size: if file != ".DS_Store": # print(os.path.join(subdir, file)) # try: midi_data = pretty_midi.PrettyMIDI(subdir + "/" + file) for instrument in midi_data.instruments: instrument.is_drum = False if len(midi_data.instruments) > 0: data = midi_data.get_piano_roll(fs=res)[35:51, 0:number_of_data_to_extract].astype(dtype=bool) data =data.flatten() if data.size>=16*number_of_data_to_extract: features.append([data, class_label]) list_files_name.insert(index_filename+num_files, file) num_files += 1 # except: # print("An exception occurred") current_folder += 1 print("Done ", num_files, " from ", current_folder, " folders on ", num_size) return True print("LOADING DATA FOR TRAINING...") features = [] path_to_load = "/home/kyrillos/CODE/VAEMIDI/quantized_rythm_dataset_v2_temperature/0" load_data(path_to_load, 0, 0) path_to_load = "/home/kyrillos/CODE/VAEMIDI/quantized_rythm_dataset_v2_temperature/100" load_data(path_to_load,1, dataset_size) # Convert into a Panda dataframe featuresdf = pd.DataFrame(features, columns=['feature', 'class_label']) print('Finished feature extraction from ', len(featuresdf), ' files') # Convert features & labels into numpy arrays listed_feature = featuresdf.feature.tolist() X = np.array(featuresdf.feature.tolist()) y = np.array(featuresdf.class_label.tolist()) print(X.shape, y.shape) # split the dataset x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=random_state) X_shuffle = shuffle(X, random_state=random_state) y_shuffle = shuffle(y, random_state=random_state) file_shuffle = shuffle(list_files_name, random_state=random_state) x_train = np.reshape(x_train, [-1, number_of_data_to_extract, range_of_notes_to_extract, 1]) x_test = np.reshape(x_test, [-1,number_of_data_to_extract, range_of_notes_to_extract, 1]) #x_train = np.reshape(x_train, [-1, original_dim]) #x_test = np.reshape(x_test, [-1, original_dim]) #x_train = x_train.astype('float64') / 100 #x_test = x_test.astype('float64') / 100 # network parameters input_shape = (number_of_data_to_extract,) #Convolutional VAE #ENCODER input_shape = (number_of_data_to_extract, range_of_notes_to_extract, 1) #datasize inputs = Input(shape=input_shape, name='encoder_input') x = inputs for i in range(2): filters *= 2 x = Conv2D(filters=filters, kernel_size=kernel_size, activation='relu', strides=2, padding='same')(x) # shape info needed to build decoder model shape = K.int_shape(x) # generate latent vector Q(z|X) x = Flatten()(x) x = Dense(16, activation='relu')(x) z_mean = Dense(latent_dim, name='z_mean')(x) z_log_var = Dense(latent_dim, name='z_log_var')(x) # use reparameterization trick to push the sampling out as input # note that "output_shape" isn't necessary with the TensorFlow backend z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var]) # instantiate encoder model encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder') # encoder.summary() #DECODER latent_inputs = Input(shape=(latent_dim,), name='z_sampling') x = Dense(shape[1] * shape[2] * shape[3], activation='relu')(latent_inputs) x = Reshape((shape[1], shape[2], shape[3]))(x) # use Conv2DTranspose to reverse the conv layers from the encoder for i in range(2): x = Conv2DTranspose(filters=filters, kernel_size=kernel_size, activation='relu', strides=2, padding='same')(x) filters //= 2 outputs = Conv2DTranspose(filters=1, kernel_size=kernel_size, activation='sigmoid', padding='same', name='decoder_output')(x) # instantiate decoder model decoder = Model(latent_inputs, outputs, name='decoder') # decoder.summary() #Building the VAE outputs = decoder(encoder(inputs)[2]) vae = Model(inputs, outputs, name='vae') #LOSS use_mse=True if use_mse: reconstruction_loss = mse(K.flatten(inputs), K.flatten(outputs)) else: reconstruction_loss = binary_crossentropy(K.flatten(inputs), K.flatten(outputs)) reconstruction_loss *= range_of_notes_to_extract * number_of_data_to_extract kl_loss = 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var) kl_loss = K.sum(kl_loss, axis=-1) kl_loss *= -0.5 vae_loss = K.mean(reconstruction_loss + kl_loss) vae.add_loss(vae_loss) #Compile the VAE vae.compile(optimizer='rmsprop') # vae.summary() if __name__ == '__main__': parser = argparse.ArgumentParser() help_ = "Load h5 model trained weights" parser.add_argument("-w", "--weights", help=help_) help_ = "Use mse loss instead of binary cross entropy (default)" parser.add_argument("-m", "--mse", help=help_, action='store_true') args = parser.parse_args() models = (encoder, decoder) data = (x_test, y_test) if args.weights: print("LOADING WEIGHTS") vae.load_weights(args.weights) else: es = EarlyStopping(monitor='val_loss', mode='min', verbose=1) # train the autoencoder score=vae.fit(x_train, epochs=epochs, verbose=1, batch_size=batch_size, validation_data=(x_test, None), callbacks=[es]) vae.save_weights('vae_mlp_mnist.h5') score2 = vae.evaluate(x_test, None, verbose=1) print('Score', score.history) print('Score', score2) plot_results(models, data, batch_size=batch_size, model_name="vae_mlp")
UTF-8
Python
false
false
9,819
py
36
cvae_train.py
31
0.620837
0.606172
0
323
29.396285
118
sctveb/django-n-flask
1,692,217,127,141
68e680b58152d06cbb37c445efac28fa328eb47f
54dc8c32adf9188bbc0c493a12d1525dc0e38322
/test_project/app.py
9698011c9f275f3f6ec9121e4939ea8b4fc390b3
[]
no_license
https://github.com/sctveb/django-n-flask
f8b34fa0386a6bd96c446ac107b9726991243ff8
8927fb100655175eff135007872af441f3ccdc13
refs/heads/master
2022-12-13T05:28:39.946182
2019-09-21T06:55:36
2019-09-21T06:55:36
209,937,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask import Flask, render_template, request, redirect, jsonify from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from models import * app = Flask(__name__) # DB 설정 app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql:///todos' app.config["SQLALCHEMY_TRACK_MODIFICATION"] = False db.init_app(app) migrate = Migrate(app,db) @app.route('/') def index(): todos = Todo.query.all() # todos = Todo.query.filter(Todo.deadline > datetime.datetime.now()).order_by(Todo.deadline.asc()).all() # todo = todos_1.query.order_by(Todo.deadline.asc()).all() return render_template('index.html',todos=todos) @app.route('/todos/new') def new(): return render_template('new.html') @app.route('/todos/create', methods=['POST']) def create(): title = request.form.get('title') content = request.form.get('content') deadline = request.form.get('deadline') todo = Todo(title=title, content=content, deadline=deadline) db.session.add(todo) db.session.commit() return render_template('create.html', todo=todo) @app.route('/todos/<int:id>') def read(id): todo = Todo.query.get(id) return render_template('read.html',todo=todo) @app.route('/todos/<int:id>/edit') def edit(id): todo = Todo.query.get(id) return render_template('edit.html', todo = todo) @app.route('/todos/<int:id>/update', methods=['POST']) def update(id): todo = Todo.query.get(id) todo.title = request.form.get('title') todo.content = request.form.get('content') todo.deadline = request.form.get('deadline') db.session.commit() return redirect('/todos/{}'.format(todo.id)) @app.route('/todos/<int:id>/delete') def delete(id): todo = Todo.query.get(id) db.session.delete(todo) db.session.commit() return redirect('/') @app.route('/todos/keyboard') def keyboard(): keyboard = { "type":"buttons", "buttons":["긴급","투두"] } return jsonify(keyboard) @app.route('/todos/message', methods=['POST']) def message(): user_msg = request.json['content'] if user_msg == "긴급": todo_now = Todo.query.filter(Todo.deadline >= datetime.datetime.now().strftime('%Y-%m-%d')).order_by(Todo.deadline.asc()).first() msg = todo_now.title + " | " + str(todo_now.content) + " | " + str(todo_now.deadline) return_dict = {'message':{'text':msg}, 'keyboard':{"type":"buttons","buttons":["긴급","투두"]}} return jsonify(return_dict) elif user_msg == "투두": return_dict = {'message':{'text':'인덱스입니다', 'message_button':{'label':'링크입니다','url':'http://flask001-sctveb.c9users.io:8080/'}}, 'keyboard':{"type":"buttons","buttons":["긴급","투두"]}} return jsonify(return_dict) # - "긴급" : deadline이 가장 가까운 todo 응답 # - "투두" : 해야 할 일 목록 인덱스 페이지 링크 버튼 전송
UTF-8
Python
false
false
2,931
py
64
app.py
25
0.634554
0.631354
0
84
32.5
137
luanjinlu/test
6,511,170,459,642
03e85c89aa4cba8a3b877c8464c749fb12a958ce
352819e919db7f6c8c1d050d5dd4e41b1416af0a
/hello.py
df9624a1d8d668c45f7048a6197f7140a79d5cf3
[]
no_license
https://github.com/luanjinlu/test
a560d0dfd0badb4921456bef59ce4cf3f3d7d645
3e8d7453219c8cda3f60193e3cba6f96961d4b6b
refs/heads/master
2020-03-29T22:13:12.069257
2018-09-26T10:31:50
2018-09-26T10:31:50
150,409,343
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python print('hello jinlu')
UTF-8
Python
false
false
44
py
1
hello.py
1
0.681818
0.681818
0
3
13.666667
21
newtasion/raas_cp
15,161,234,581,235
58a9cd344b640cb3822e626f199dcaf2444e0da8
ff2f3bcb4932d36998988af7f9b0741cb0b587bd
/match_engine/common/datafile_utils.py
2957a0e6ae650f8e82204d0235d41c4114947c96
[]
no_license
https://github.com/newtasion/raas_cp
fb54aaad1b8dc7aaa30b4bec9f2d820ca9805185
df437f83446a9a46a515074c95653a2e29303a5e
refs/heads/main
2021-01-10T22:08:55.102856
2014-11-20T06:58:50
2014-11-20T06:58:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" utilities for dealing with data files in the system. Created on Jul 12, 2013 @author: zul110 """ import os INDEX = 'domain_index' MATCHES = 'domain_matches' TVREC = 'domain_tvrec' PROFILE = 'domain_profile' CANDIDATE = "candidate" TRAININGDIR = "training" def getTrainningDir(domainDir): return os.path.join(domainDir, TRAININGDIR) def getIndexFile(domainDir): return os.path.join(domainDir, INDEX) def getMatchesFile(domainDir): return os.path.join(domainDir, MATCHES) def getTvrecFile(domainDir): return os.path.join(domainDir, TVREC) def getProfileFile(domainDir): return os.path.join(domainDir, PROFILE) def getCandidateFile(domainDir): return os.path.join(domainDir, CANDIDATE) def getTrainningDirFromDD(domainDescriptor): domainDir = domainDescriptor.get_data_path() return getTrainningDir(domainDir) def getIndexFileFromDD(domainDescriptor): domainDir = domainDescriptor.get_data_path() return getIndexFile(domainDir) def getMatchesFileFromDD(domainDescriptor): domainDir = domainDescriptor.get_data_path() return getMatchesFile(domainDir) def getTvrecFileFromDD(domainDescriptor): domainDir = domainDescriptor.get_data_path() return getTvrecFile(domainDir) def getProfileFileFromDD(domainDescriptor): domainDir = domainDescriptor.get_data_path() return getProfileFile(domainDir) def getCandidateFileFromDD(domainDescriptor): domainDir = domainDescriptor.get_data_path() return getCandidateFile(domainDir) def isIndexFile(fileName): if str(fileName).find(INDEX) > 0: return True else: return False def isTvrecFile(fileName): if str(fileName).find(TVREC) > 0: return True else: return False def isMatchesFile(fileName): if str(fileName).find(MATCHES) > 0: return True else: return False def isProfileFile(fileName): if str(fileName).find(PROFILE) > 0: return True else: return False def isCandidateFile(fileName): if str(fileName).find(CANDIDATE) > 0: return True else: return False def get_base_dir(filepath): dirname = os.path.dirname(filepath) return dirname.split('/')[-1]
UTF-8
Python
false
false
2,228
py
44
datafile_utils.py
42
0.715889
0.709156
0
110
19.254545
53
faustfu/hello_python
13,829,794,705,207
20b68724196d289a954bb02d2d8756675816fed9
f7d2114152ec5c8e283b6bfbb9feeb5a4337eb71
/file06.py
c96679b536a7bc2874e7b92437b7af94cd753210
[]
no_license
https://github.com/faustfu/hello_python
f5759ff6bf87694e6ba472349f4263bc8ad479b0
1487e60e2d9307e1a0ebffbf26d8e075da806a39
refs/heads/master
2021-02-10T18:01:50.450295
2020-11-20T02:17:18
2020-11-20T02:17:18
244,406,161
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 1. Module:configparser is for process configurations. import configparser filename = 'a.cfg' cfg = configparser.ConfigParser() cfg.add_section('a') cfg.add_section('b') for section in cfg.sections(): cfg[section]['greeting'] = 'hi' with open(filename, 'wt') as fout: cfg.write(fout) with open(filename, 'rt') as fin: cfg.read(fin) for section in cfg.sections(): print('%s greeting = %s' % (section, cfg[section]['greeting']))
UTF-8
Python
false
false
458
py
132
file06.py
132
0.665939
0.663755
0
20
21.9
71
safebutler/django-sendgrid-parse
15,461,882,296,999
b60aeaa33c9da5ff111894e56959ac5198ee26ab
4ad757d5a03db8ce7b1c123bbea30ddef2a6d89b
/django_sendgrid_parse/migrations/0004_auto_20160816_1704.py
0560848caa70ea82aef76308eaee73910d09d1de
[ "MIT" ]
permissive
https://github.com/safebutler/django-sendgrid-parse
b253c47a39d040457064d16ec7e500a8fa0b2c97
37448e78b4dcaa0b42197d5fb2071492d8b7cc77
refs/heads/master
2020-04-18T15:48:25.231111
2019-01-25T22:15:31
2019-01-25T22:15:31
167,620,137
0
0
MIT
true
2019-01-25T22:04:23
2019-01-25T22:04:23
2017-02-15T12:34:45
2017-02-21T17:27:27
52
0
0
0
null
false
null
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-08-16 17:04 from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('django_sendgrid_parse', '0003_auto_20160730_0019'), ] operations = [ migrations.AlterField( model_name='email', name='SPF', field=jsonfield.fields.JSONField(blank=True, null=True, verbose_name='Sender Policy Framework'), ), migrations.AlterField( model_name='email', name='cc', field=models.TextField(blank=True, null=True, verbose_name='Hidden'), ), migrations.AlterField( model_name='email', name='charsets', field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Charsets'), ), migrations.AlterField( model_name='email', name='dkim', field=jsonfield.fields.JSONField(blank=True, null=True, verbose_name='DomainKeys Identified Mail'), ), migrations.AlterField( model_name='email', name='envelope', field=jsonfield.fields.JSONField(blank=True, null=True, verbose_name='Envelope'), ), migrations.AlterField( model_name='email', name='from_mailbox', field=models.TextField(verbose_name='From'), ), migrations.AlterField( model_name='email', name='headers', field=models.TextField(blank=True, null=True, verbose_name='Headers'), ), migrations.AlterField( model_name='email', name='html', field=models.TextField(blank=True, null=True, verbose_name='HTML'), ), migrations.AlterField( model_name='email', name='spam_report', field=models.TextField(blank=True, null=True, verbose_name='Spam report'), ), migrations.AlterField( model_name='email', name='spam_score', field=models.FloatField(blank=True, null=True, verbose_name='Spam score'), ), migrations.AlterField( model_name='email', name='subject', field=models.TextField(blank=True, null=True, verbose_name='Carbon Copy'), ), migrations.AlterField( model_name='email', name='text', field=models.TextField(blank=True, null=True, verbose_name='Text'), ), migrations.AlterField( model_name='email', name='to_mailbox', field=models.TextField(verbose_name='To'), ), ]
UTF-8
Python
false
false
2,773
py
20
0004_auto_20160816_1704.py
16
0.559322
0.5467
0
81
33.234568
111
manuelcortez/Audio-Game-Kit-for-Python-AGK-
11,776,800,354,189
90b7d9729a7dbd45f721d06d162417c34e8f4642
76ef27d0669b6cedd31540c0b98168cc2584f7ae
/AGK/misc/menu.py
ed384ad8fa202876f25c1381ef8c4266f87d2ace
[]
no_license
https://github.com/manuelcortez/Audio-Game-Kit-for-Python-AGK-
3a779560e0b3987b2cb52b59f9c0b659f842597d
88b5e44345bb536b29995966beaed883ccd0438e
refs/heads/master
2020-07-22T15:19:32.261164
2016-11-15T14:40:49
2016-11-15T14:40:49
73,828,145
1
0
null
true
2016-11-15T15:38:03
2016-11-15T15:38:03
2016-11-10T18:57:39
2016-11-15T14:41:03
3,119
0
0
0
null
null
null
from ..speech import SAPI, auto from ..mainframe import keyboard import pygame class menu_item(object): def __init__(self,text,name,is_tts): self.text=text self.name=name self.is_tts=is_tts class menu(object): def __init__(self, sapi=False): self.position=0 self.items=[] self.sapi=sapi def add_item_tts(self,text,name): self.items.append(menu_item(text,name,True)) def run(self,intro): self.speak(intro) self.position=-1 while 1: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key==pygame.K_UP: if self.position<=0: self.position=0 else: self.position-=1 self.speak(self.items[self.position].text) if event.key==pygame.K_DOWN: if self.position<len(self.items)-1: self.position+=1 self.speak(self.items[self.position].text) if event.key==pygame.K_RETURN: return self.items[self.position] if event.key==pygame.K_ESCAPE: return -1 #internal funcs def speak(self,text): if self.sapi==False: auto.speak(text) else: SAPI.speak(text)
UTF-8
Python
false
false
1,134
py
10
menu.py
9
0.631393
0.623457
0
48
21.666667
48
KodairaTomonori/NLP100knock2015
7,086,696,055,370
fe0f0a2c1aae2be491fea83cba507c82324f647b
d19c17d12e99f3064a21d336a450ffaf91d5626b
/Python/04set/part36.py
c4e06b178dcd6c6285a6a921b3c409cbcdd60941
[]
no_license
https://github.com/KodairaTomonori/NLP100knock2015
913c4bd8de526e347344684f8db40df8a47fe3a5
f4d0319816a7e068a29e7a724f85829215088cfa
refs/heads/master
2021-01-21T12:50:06.428173
2016-04-30T13:26:43
2016-04-30T13:26:43
35,171,120
6
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding: utf-8 from part30 import * from collections import defaultdict from collections import OrderedDict def getWordFreqDict(mecab_file): line_list = makeLineList(mecab_file) base = 'base' word_frequency = defaultdict(lambda:0) for morpheme_list in line_list: for morpheme_dict in morpheme_list: word_frequency[morpheme_dict[base] ] += 1 return word_frequency if __name__ == "__main__": import sys mecab_file = open(sys.argv[1], 'r') freq_words = getWordFreqDict(mecab_file) for i, j in freq_words.items(): print i, j
UTF-8
Python
false
false
600
py
150
part36.py
102
0.65
0.64
0
26
21.346154
47
aarongilman/pysftp
16,930,761,083,139
4dcb1e7e471a9629d9682c7e5c319e3dbdb9f299
06484873314a9beaf9f2b03a0438bb82d0471465
/docwatch.py
efa8827189080670a3bcd3ba7ca532e54c8c70af
[]
permissive
https://github.com/aarongilman/pysftp
9a174fa337e593ebe90c88bdf61746d09920e5b0
b80cddee27451a2071fc71a101e025d14d125910
refs/heads/master
2022-07-02T15:03:52.805368
2020-05-14T19:35:40
2020-05-14T19:35:40
264,007,637
0
0
BSD-3-Clause
true
2020-05-14T19:34:48
2020-05-14T19:34:48
2019-08-28T12:22:26
2019-08-28T09:56:42
1,126
0
0
0
null
false
false
#!/usr/bin/env python """A small utility to live build and reload in a webbrowser when a source or config file changes. Very helpful for writing documentation.""" import platform import webbrowser from livereload import Server, shell def main(): """main routine""" make_cmd = 'make html' if platform.system() == 'FreeBSD': make_cmd = 'gmake html' server = Server() server.watch('docs/*.rst', shell(make_cmd, cwd='docs')) server.watch('pysftp/*.py', shell(make_cmd, cwd='docs')) webbrowser.open_new_tab('http://localhost:5500') server.serve(root='docs/_build/html', host='0.0.0.0') if __name__ == '__main__': main()
UTF-8
Python
false
false
665
py
41
docwatch.py
31
0.649624
0.637594
0
24
26.708333
76
stefandebruyn/Oenpelli
18,691,697,676,288
53ca8dad823cffd644638f6dc84ac42aaa4f04a0
f17effc25b24823572c34de671ed5bde1482accb
/oenpelli/__init__.py
6e0f386f472ed07c0ca5eecbe184f07dcd5ba315
[ "MIT" ]
permissive
https://github.com/stefandebruyn/Oenpelli
df9284a90caa08e2f09e5b8466f2742bff8ceb79
e7e86d45c4ef44f3019ab7d211977feb8a813a7b
refs/heads/master
2018-12-09T20:24:53.308910
2018-10-03T17:15:13
2018-10-03T17:15:13
148,065,540
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Small library for robot control engineering. """ name = "oenpelli"
UTF-8
Python
false
false
72
py
8
__init__.py
7
0.694444
0.694444
0
5
13.4
44
isg-hi/osaka_metropolis
8,478,265,472,443
f9e8b63222df440df516c84d5224f9be13c71407
ae43ba5cbbe4149f86366260d91a6639c239729e
/seeds_test.py
745c76d9b1d040582017266cc4fe142fd0743b68
[]
no_license
https://github.com/isg-hi/osaka_metropolis
e7642b783d84e85f7d09cea260dc3698a3f459dc
e8491f12076045a38e7fe7d711c875975ac4f093
refs/heads/master
2023-02-03T11:47:49.062773
2020-12-25T16:01:17
2020-12-25T16:01:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from xgb_param_tuning import XGBRegressorTuning from xgb_validation import XGBRegressorValidation import pandas as pd from datetime import datetime import os from sklearn.metrics import r2_score from sklearn.model_selection import KFold import numpy as np # 結果出力先 OUTPUT_DIR = f"{os.getenv('HOMEDRIVE')}{os.getenv('HOMEPATH')}\Desktop" # 最適化で最大化する評価指標('r2', 'neg_mean_squared_error', 'neg_mean_squared_log_error') SCORING = 'r2' # パラメータ最適化の手法(Grid, Random, Bayes, Optuna) PARAM_TUNING_METHODS = ['Bayes'] # 最適化で使用する乱数シード一覧 SEEDS = [42, 43, 44, 45, 46, 47, 48, 49, 50, 51] #使用するフィールド KEY_VALUE = 'ward_before'#キー列 OBJECTIVE_VARIALBLE = 'approval_rate'#目的変数 EXPLANATORY_VALIABLES = ['1_over60','2_between_30to60','3_male_ratio','4_required_time','5_household_member','6_income']#説明変数 USE_EXPLANATORY = ['2_between_30to60','3_male_ratio','5_household_member','latitude']#使用する説明変数 # 現在時刻 dt_now = datetime.now().strftime('%Y%m%d%H%M%S') #データ読込 df = pd.read_csv(f'./osaka_metropolis_english.csv') #目的変数と説明変数を取得(pandasではなくndarrayに変換) y = df[[OBJECTIVE_VARIALBLE]].values X = df[USE_EXPLANATORY].values # パラメータ最適化クラス xgb_tuning = XGBRegressorTuning(X, y, USE_EXPLANATORY, y_colname=OBJECTIVE_VARIALBLE) # 検証用クラス xgb_validation = XGBRegressorValidation(X, y, USE_EXPLANATORY, y_colname=OBJECTIVE_VARIALBLE) # 全乱数シードで算出したパラメータの平均値使用(基本的にはこのメソッドは不使用) def calc_params_mean(df_params): # int型、float型、それ以外に分けて平均値算出 df_int = df_params.select_dtypes(include=[int, 'int64', 'int32']) df_float = df_params.select_dtypes(include=float) df_str = df_params.select_dtypes(exclude=[int, 'int64', 'int32', float]) df_int = df_int.mean().apply(lambda x: int(x)) df_float = df_float.mean() df_str = df_str.iloc[0, :] df_params = pd.concat([df_int, df_float, df_str]) # dict化 return df_params.to_dict() # 乱数シードごとに別々のパラメータを使用 def convert_params_list(df_params): params_list = [] for i in range(len(df_params)): params_list.append(df_params.iloc[i, :].to_dict()) return params_list # 手法を変えて最適化 for method in PARAM_TUNING_METHODS: # 乱数を変えて最適化をループ実行 df_result_seeds, param_range = xgb_tuning.multiple_seeds_tuning(method, seeds=SEEDS, scoring=SCORING) # 結果出力 df_result_seeds.to_csv(f"{OUTPUT_DIR}\{method}_seed{'-'.join([str(s) for s in SEEDS])}_tuning_{dt_now}.csv", index=False) param_range_path = f"{OUTPUT_DIR}\{method}_seed{'-'.join([str(s) for s in SEEDS])}_param_range_{dt_now}.txt" with open(param_range_path, mode='w') as f: f.write('{') for k, v in param_range.items(): f.write(str(k) + ':' + str(v) + ',\n') f.write('}') # パラメータ記載列('best_'で始まる列)のみ抽出 extractcols = df_result_seeds.columns.str.startswith('best_') df_params = df_result_seeds.iloc[:, extractcols] # 列名から'best_'を削除 for colname in df_params.columns: df_params = df_params.rename(columns={colname:colname.replace('best_', '')}) # 全乱数シードで算出したパラメータの平均値使用 #params = calc_param_mean(df_params) params = convert_params_list(df_params) # 最適化したモデルを検証 validation_score, validation_detail = xgb_validation.multiple_seeds_validation(params, seeds=SEEDS, method='leave_one_out') validation_score.to_csv(f"{OUTPUT_DIR}\{method}_seed{'-'.join([str(s) for s in SEEDS])}_valid_score_{dt_now}.csv", index=False) validation_detail.to_csv(f"{OUTPUT_DIR}\{method}_seed{'-'.join([str(s) for s in SEEDS])}_valid_detail_{dt_now}.csv", index=False)
UTF-8
Python
false
false
4,018
py
7
seeds_test.py
4
0.689127
0.674378
0
86
39.22093
133
prazors/Python
652,835,045,124
11eb6ca17254f8b771b10c9e30daf435f3b419a5
26bfc7931e42885ded3c36cd12129867e952552a
/num_digits_success.py
09448b500130fa69cd51e2062a4b75f19219e05c
[]
no_license
https://github.com/prazors/Python
fa90b70716df54fbfa681a875ab35912c54c80ef
fa33e50684fdee2d9194d840fc816a6c3bfd8f1d
refs/heads/master
2021-01-10T20:19:03.594788
2013-10-22T21:38:48
2013-10-22T21:38:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def num_digits(n): count = 0 if n>0: while n: count = count + 1 n = n / 10 print count else: count = 1 print count
UTF-8
Python
false
false
193
py
55
num_digits_success.py
55
0.38342
0.352332
0
10
17.3
29
Jaycoobs/hat
12,945,031,444,046
1bd36d739109740dca9bd977b18def2c9db9edeb
bb2d392464b8acbb618210b34fa6c4352a264e19
/hat.py
52bd007ab1a846225015d476569fd450aa4c9305
[]
no_license
https://github.com/Jaycoobs/hat
c4fdb2bccbc1b11fd31752174d7b3c22800eb4d3
1ef514083898035feae0c19992b9a5e248ed4603
refs/heads/main
2023-06-30T12:43:22.253113
2021-08-01T19:19:55
2021-08-01T19:19:55
390,521,057
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import random import sched from fastapi import Body, FastAPI, HTTPException from fastapi.staticfiles import StaticFiles from fastapi.responses import RedirectResponse hats = {} nextSaveEvent = None scheduler = sched.scheduler() app = FastAPI() api = FastAPI(); app.mount("/web", StaticFiles(directory="web"), name="static") app.mount("/api", api) def loadHats(): try: with open("hats.json") as f: hats = json.loads(f.read()) return hats except FileNotFoundError: return {} def saveHats(hats): with open("hats.json", "w") as f: f.write(json.dumps(hats)) def saveHatsAndSchedule(hats, s): global nextSaveEvent print("Saving hats.") saveHats(hats) nextSaveEvent = s.enter(3600, 1, saveHatsAndSchedule, (hats, s)) return nextSaveEvent @app.on_event("startup") async def startup_event(): global hats global nextSaveEvent hats = loadHats() nextSaveEvent = saveHatsAndSchedule(hats, scheduler) @app.on_event("shutdown") async def shutdown_event(): saveHats(hats) @app.get("/", response_class=RedirectResponse) async def redirect(): return "/web/page.html" @api.post("/create-hat") def create_hat(name: str = Body(...)): if (name in hats): raise HTTPException(status_code=409, detail=f"Already a hat called {name}"); hats[name] = []; @api.get("/hats") def get_hats(): return list(hats.keys()) @api.post("/submit") def submit(hat: str = Body(...), entry: str = Body(...)): if (not hat in hats): raise HTTPException(status_code=404, detail=f"No hat named {hat}") hats[hat].append(entry) @api.get("/draw/{hat}") def draw(hat: str): hat = hats[hat] if (len(hat) == 0): raise HTTPException(status_code=400, detail="This hat is empty!") entry = random.choice(hat) hat.remove(entry) return { "entry": entry }
UTF-8
Python
false
false
1,883
py
6
hat.py
2
0.654275
0.646309
0
75
24.106667
84
Chandler-Song/pi
6,820,408,099,212
866a3b58394d45aca24185503a3c3f20effcf958
7cd8ee14711eaf33cee0d9e06e78a974fc579242
/flask/Linkedin/Linkedin/spiders/linkedin_excelsheet_parsing.py
fab96236a4ff2135db1607001497d3c969680704
[]
no_license
https://github.com/Chandler-Song/pi
c618117dfdd9a7496a57c69f029851e94787f591
aebc6d65b79ed43c66e7e1bf16d6d9f31b470372
refs/heads/master
2022-03-13T02:44:30.452673
2019-02-19T09:38:45
2019-02-19T09:38:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from linkedin_voyager_functions import * import glob import openpyxl as px class Linkedinparsing(object): def __init__(self): self.con, self.cur = get_mysql_connection(DB_HOST, DB_NAME_REQ, '') current_path = os.path.dirname(os.path.abspath(__file__)) self.social_processing_path = os.path.join(current_path, 'excelfiles') self.query = 'insert into linkedin_crawl(sk, url, content_type ,crawl_status, meta_data,created_at, modified_at) values(%s, %s, %s, %s, %s,now(), now()) on duplicate key update modified_at=now(), content_type=%s, crawl_status=0,meta_data=%s' def __del__(self): close_mysql_connection(self.con, self.cur) def main(self): files_list = glob.glob(self.social_processing_path+'/*.xlsx') if files_list: for _file in files_list: ws_ = px.load_workbook(_file, use_iterators=True) sheet_list = ws_.get_sheet_names() for xl_ in sheet_list: sheet_ = ws_.get_sheet_by_name(name=xl_) row_check = 0 email_address = linkedin_profile = ida = firstname = lastname = key_ = 0 for row in sheet_.iter_rows(): if row_check > 0: row_check += 1 continue counter = 0 for i in row: if not i.value: continue lower_head = i.value.lower() if 'key' in lower_head: key_ = counter elif 'linkedin' in lower_head: linkedin_profile = counter elif 'email' in lower_head: email_address = counter counter += 1 break m = 0 final_indents = [] _indents = {} for row in sheet_.iter_rows(): temp_rows = [] for i in row: temp_rows.append(i.value) final_indents.append(temp_rows) empty_dic = {} counter_ = 70 for row in final_indents: email_addressf = normalize(row[email_address]) linkedin_profilef = '' try: linkedin_profilef = normalize(row[linkedin_profile]) except: pass if not linkedin_profilef: continue if linkedin_profilef.strip() == 'linkedin': continue meta_date_from_browse = {} meta_date_from_browse.update({"linkedin_url":linkedin_profilef}) meta_date_from_browse.update({"email_address":email_addressf}) crawl_status = 0 rows_ = [] if linkedin_profilef.count('http') > 1: inner_results = [i.replace('s://','https://').replace(', ht','').replace('LI Inmail Sent','').strip().strip(',') for i in filter(None,re.split('http*',linkedin_profilef))] for inr in inner_results: if (inr != 'https://de.linkedin.com/pub') and ('philippe-nieuwjaer') not in inr: rows_.append(inr) else: rows_.append(linkedin_profilef) for rs in rows_: linkedin_profilef = rs if 'linkedin.com' not in normalize(linkedin_profilef): crawl_status = 10 if 'http:' in linkedin_profilef: linkedin_profilef = linkedin_profilef.replace('http:','https:') if 'id.www' in linkedin_profilef: linkedin_profilef = linkedin_profilef.replace('id.www','https://www') if 'www.linkedin.com' and 'https:' not in linkedin_profilef: linkedin_profilef = linkedin_profilef.replace('www.','https://www') if linkedin_profilef.startswith('linkedin.com'): linkedin_profilef = linkedin_profilef.replace('linkedin.com','https://www.linkedin.com') if 'https:' not in linkedin_profilef: linkedin_profilef = re.sub('(\D+)\.linkedin.com','https://www.linkedin.com',linkedin_profilef) linkedin_profilef = re.sub('https://(.*?).linkedin.com/','https://www.linkedin.com/',linkedin_profilef) if linkedin_profilef.endswith('/en') or linkedin_profilef.endswith('/fr'): linkedin_profilef = linkedin_profilef[:-3] linkedin_profilef = linkedin_profilef.strip('"').strip().strip("'").strip().strip('/').strip() if not linkedin_profilef.startswith('https://www.linkedin.com') and crawl_status!=10: linkedin_profilef = ''.join(re.findall('.*(https://.*)', linkedin_profilef)) if '/pub/' in linkedin_profilef: cv = ''.join(filter(None,re.split('https://www.linkedin.com/pub/.*?/(.*)',linkedin_profilef))).split('/')[::-1] cv[0] = cv[0].zfill(3) cv[1] = cv[1].zfill(3) if cv[-1] == '0': del cv[-1] linkedin_profilef = ( '%s%s%s%s'%('https://www.linkedin.com/in/',''.join(re.findall('https://www.linkedin.com/pub/(.*?)/.*',linkedin_profilef)),'-',''.join(cv))) if 'linkedin.com' not in linkedin_profilef: continue counter_ += 1 sk = md5("%s%s"%(normalize(email_addressf),normalize( linkedin_profilef))) linkedin_profilef = linkedin_profilef.replace('pubwww.linkedin.comhttps:','').replace('"','') values = (sk, linkedin_profilef, 'linkedin', crawl_status, json.dumps(meta_date_from_browse),'linkedin', json.dumps(meta_date_from_browse)) recof = fetchmany(self.cur, 'select * from linkedin_crawl where sk="%s"'%sk) if not recof: self.cur.execute(self.query, values) print 'nodup' print linkedin_profilef print '>>>>>>>' else: print values print '*************************' else: for prof_url in open('linkedin_file.py'): if prof_url != '\n': prof_url = prof_url.replace('\n','') sk = md5.md5(prof_url).hexdigest() meta_date_from_browse = {} values = (sk, prof_url, 'linkedin', 0,json.dumps(meta_date_from_browse),'linkedin', json.dumps(meta_date_from_browse)) self.cur.execute(self.query, values) if __name__ == '__main__': Linkedinparsing().main()
UTF-8
Python
false
false
5,501
py
392
linkedin_excelsheet_parsing.py
367
0.619887
0.61407
0
111
48.54955
243
KatyaKalache/holbertonschool-higher_level_programming
16,355,235,468,371
451183b230288ab20f3893a8b8aa6dc79d33c39d
84bdc0fd6aaaac7c519866fef855be8eae88a80f
/0x01-python-if_else_loops_functions/100-print_tebahpla.py
54cf05d2819186e59ee1ab74561781d1e70be898
[]
no_license
https://github.com/KatyaKalache/holbertonschool-higher_level_programming
b74ca3e3c32ded6f54a40748775d0d4475e32409
e746a41ccb3f268c9d6d4578b80a0b9e7cf7d067
refs/heads/master
2021-01-20T02:29:04.972257
2017-10-11T06:24:17
2017-10-11T06:24:17
89,413,672
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 i = 122 while i > 96: copy = i if (i % 2) != 0: copy = i - 32 print('{:}'.format(chr(copy)), end='') i = i - 1
UTF-8
Python
false
false
154
py
111
100-print_tebahpla.py
82
0.428571
0.357143
0
8
18.25
42
YZqiangGithub/PWN-
10,711,648,442,268
89c613821af764ddade9d7eb6f30367791983208
0e9b6d053b5c36ed6afa67496fdfae2911a5d8ee
/JO_level6/level6.py
1267f57a2866f966723935c56073db649d4b399b
[]
no_license
https://github.com/YZqiangGithub/PWN-
30098830b65d35bf9b6ba0cb88e26ed3291a733a
d57d8269da000b8eeb9d75610bdbe5b2ede538ef
refs/heads/master
2020-08-07T23:15:12.150310
2020-05-05T13:37:11
2020-05-05T13:37:11
213,618,977
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pwn import * elf = ELF('./freenote_x86') libc = ELF('./libc-2.19.so') conn = remote('pwn2.jarvisoj.com','9885') conn.interactive()
UTF-8
Python
false
false
139
py
32
level6.py
31
0.647482
0.57554
0
9
14.555556
41
vinhho2508/BigO_Blue
652,835,061,654
c9211c54a4130daaad0d4467d278eb74c6dced20
ce8f5486e89a1ca22f326f2f5488f040cc7bb4de
/msteambot.py
211851b5d545f5577ef1d0a0377fdb10ae7bdd85
[]
no_license
https://github.com/vinhho2508/BigO_Blue
5a4da7e8ef99d9341a56a257f139fb9f54c15e36
71c1b5c416a3a5c340662f51e64f928b401096bf
refs/heads/master
2022-11-30T23:42:33.035385
2022-10-30T14:46:32
2022-10-30T14:46:32
235,124,633
0
4
null
false
2022-10-30T14:46:33
2020-01-20T14:46:52
2022-10-24T14:08:14
2022-10-30T14:46:32
11,255
0
2
0
Python
false
false
import logging import pymsteams import datetime class HermesBot: hook_url: str = None client: pymsteams.connectorcard def __init__(self): self.hook_url = "https://vngms.webhook.office.com/webhookb2/vjndskvds/mvlxcvmlxcv" self.client = pymsteams.connectorcard(self.hook_url) def sent_message(self, message: str): self.client.text(message) self.client.send() def sent_alert_logging(self, message, generated_id, type_test, project_error, dataset_error, table_error, status): current_time = datetime.datetime.now() message = f""" Status: {status} Project_id: {project_error} Dataset_id: {dataset_error} Table_id: {table_error} {message} {type_test} Datetime: {current_time} """ try: action_card = pymsteams.connectorcard(hookurl=self.hook_url, http_timeout=30) action_card.color("#4e9164") action_card.title(generated_id) action_card.text(message) url = 'https://www.goodreads.com/' action_card.addLinkButton(buttontext="Rollback table", buttonurl=url) action_card.send() except TimeoutError as e: logging.error(e) print('cannot send message')
UTF-8
Python
false
false
1,293
py
21
msteambot.py
20
0.617169
0.610982
0
37
33.945946
118
drizztSun/common_project
3,058,016,720,175
385397b81ad849dc8f7f2b624ae618b7ffe368f6
9ee51d5d6d976a4ad99704a334185f60df65f7ba
/PythonLeetcode/leetcodeM/39_CombinationSum.py
539afe7fec0924f240be6ba58526194d8b0264e9
[]
no_license
https://github.com/drizztSun/common_project
348756c2b88c485fb9d192f5a7304c2a38cf4219
cf4e1f1a96db896f1325de0283f8607bba5f55aa
refs/heads/master
2021-06-05T22:35:27.071506
2021-06-05T17:26:46
2021-06-05T17:26:46
143,934,217
0
1
null
false
2021-06-05T13:01:52
2018-08-07T22:45:56
2021-06-04T22:53:01
2021-06-05T13:01:52
95,247
0
1
11
Python
false
false
""" 39. Combination Sum Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. Example 2: Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]] Example 3: Input: candidates = [2], target = 1 Output: [] Example 4: Input: candidates = [1], target = 1 Output: [[1]] Example 5: Input: candidates = [1], target = 2 Output: [[1,1]] Constraints: 1 <= candidates.length <= 30 1 <= candidates[i] <= 200 All elements of candidates are distinct. 1 <= target <= 500 """ class CombinationSum: """ Approach 1: Backtracking Intuition As a reminder, backtracking is a general algorithm for finding all (or some) solutions to some computational problems. The idea is that it incrementally builds candidates to the solutions, and abandons a candidate ("backtrack") as soon as it determines that this candidate cannot lead to a final solution. Specifically, to our problem, we could incrementally build the combination, and once we find the current combination is not valid, we backtrack and try another option. Algorithm As one can see, the above backtracking algorithm is unfolded as a DFS (Depth-First Search) tree traversal, which is often implemented with recursion. Here we define a recursive function of backtrack(remain, comb, start) (in Python), which populates the combinations, starting from the current combination (comb), the remaining sum to fulfill (remain) and the current cursor (start) to the list of candidates. Note that, the signature of the recursive function is slightly different in Java. But the idea remains the same. For the first base case of the recursive function, if the remain==0, i.e. we fulfill the desired target sum, therefore we can add the current combination to the final list. As another base case, if remain < 0, i.e. we exceed the target value, we will cease the exploration here. Other than the above two base cases, we would then continue to explore the sublist of candidates as [start ... n]. For each of the candidate, we invoke the recursive function itself with updated parameters. Specifically, we add the current candidate into the combination. With the added candidate, we now have less sum to fulfill, i.e. remain - candidate. For the next exploration, still we start from the current cursor start. At the end of each exploration, we backtrack by popping out the candidate out of the combination. """ def doit_backtracking(self, candidates: List[int], target: int) -> List[List[int]]: results = [] def backtrack(remain, comb, start): if remain == 0: # make a deep copy of the current combination results.append(list(comb)) return elif remain < 0: # exceed the scope, stop exploration. return for i in range(start, len(candidates)): # add the number into the combination comb.append(candidates[i]) # give the current number another chance, rather than moving on backtrack(remain - candidates[i], comb, i) # backtrack, remove the number from the combination comb.pop() backtrack(target, [], 0) return results def doit(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def search(nums, i, target, cur): if target == 0: res.append(cur) return for j in range(i, len(nums)): if target - nums[j] >= 0: # next level starting from j, because we wanna same num nums[j] search(nums, j, target - nums[j], cur + [nums[j]]) res = [] search(candidates, 0, target, []) return res """ 40. Combination Sum II Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. Example 1: Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ] Example 2: Input: candidates = [2,5,2,1,2], target = 5 Output: [ [1,2,2], [5] ] Constraints: 1 <= candidates.length <= 100 1 <= candidates[i] <= 50 1 <= target <= 30 """ class CombinationSumII(object): """ Approach 2: Backtracking with Index Intuition There is another way to adapt the solution of 39. Combination Sum. Rather than building a counter table to group the numbers together explicitly, we could sort the input, which could also group all the same numbers together. Similar to the solution of 39. Combination Sum, we iterate through the sorted input array, via backtracking to build the combinations. In addition, we need to do some tricks with the index of the iteration, in order to avoid generating duplicated combinations. We demonstrate the idea with the same example in the previous approach, i.e. input = [2, 5, 2, 2]. index demo As we can see from the above graph, once we sort the input array, the occurrance of each unique number would be adjacent to each other. In the above graph, we show the moment we start to process the group of number 2, with the iteration index pointed to the beginning of the group. Next, we need to move the index forward, in order to choose the next number to be added to the combination. More importantly, we need to skip certain positions, in order to avoid the generation of duplicated combinations. We skip the position if the following two condtions are met: 1). next_curr > curr: we will pick the number at the current curr position into the combination, regardless the other conditions. This is important, since the iteration should allow us to select multiple instances of a unique number into the combination. 2). candidates[next_curr] == candidates[next_curr-1]: we will skip the occurances all repetitive numbers in-between, e.g. we skip the second and third occurance of number 2 in this round of backtracking. The combined effects of the above sorting and iterating operations are equivalent to the previous approach with counter table. Algorithm It would be clearer to see how the above tricks with index play out in the algorithm. Similiar to the previous approach, we implement the backtracking process with the function named backtrack(comb, remain, curr, results), but with less parameters, compared to the previous approach. The bulk of the function remains the same as the solution of 39. Combination Sum, except the specific conditions on the index as we discussed before. In addition, we optimize the backtracking a bit by adopting the measure of early stopping, i.e. once the sum of current combination exceeds the target, we can stop the exploration for the rest of the numbers. Because all the numbers are positve, as specified in the problem, the sum of combination will increase monotonically. It is needless to explore more combinations whose sum goes beyond the desired target. O(2^N) """ def doit(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def dfs(start, target, item): if target == 0: result.append(item[:]) return if target < 0: return for i in range(start, len(candidates)): if candidates[i] > target: break if i > start and candidates[i] == candidates[i - 1]: continue item.append(candidates[i]) dfs(i + 1, target - candidates[i], item) item.pop() if candidates is None or len(candidates) == 0: return [[]] candidates.sort() result = [] dfs(0, target, []) return result
UTF-8
Python
false
false
8,977
py
2,891
39_CombinationSum.py
2,842
0.669934
0.654673
0
237
36.881857
420
fschulze/pytest-flakes
10,136,122,850,265
f6cd28030ba77f118d2d6ad81c11fdfd78ef98b2
27178fd1cfdeb2146574724480932d0304a72454
/setup.py
452867e1dd30a7d4966ea815475a8bca6472677e
[ "MIT" ]
permissive
https://github.com/fschulze/pytest-flakes
49429ecdd661263540437bd773a3dd4ed456d6bd
7d439a08a7cd53268838e7e21bef620cec3d2475
refs/heads/master
2020-12-24T16:34:59.792806
2020-11-28T00:02:29
2020-11-28T00:02:29
8,013,163
35
14
null
null
null
null
null
null
null
null
null
null
null
null
null
from setuptools import setup setup( name='pytest-flakes', description='pytest plugin to check source code with pyflakes', long_description=open("README.rst").read(), license="MIT license", version='4.0.3', author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt', url='https://github.com/asmeurer/pytest-flakes', python_requires='>=3.5', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Pytest', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Software Development :: Testing', ], py_modules=['pytest_flakes'], entry_points={'pytest11': ['flakes = pytest_flakes']}, install_requires=['pytest>=5', 'pyflakes'])
UTF-8
Python
false
false
1,118
py
3
setup.py
2
0.61449
0.597496
0
28
38.928571
67
shoomanboy/currencybot
3,762,391,360,344
593dfd0e88a3564da8fa1088f82a783007f1f49b
e5b3cd5ec76564ff00aa3b390680224ff6cc9c85
/bot_currency.py
c2ec906cf3cd63e67c4a30c01a8e6b99b41dcaac
[]
no_license
https://github.com/shoomanboy/currencybot
bcb4bf8b2c7b3123b9b4170fbb412dda9e2ac9ba
84c1cacd7b86bcbd81828c29c939ec8bc53ad802
refs/heads/main
2023-03-08T16:20:56.010274
2021-02-21T10:01:43
2021-02-21T10:01:43
316,521,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from telegram import bot, ReplyKeyboardRemove, ReplyKeyboardMarkup, PhotoSize, ParseMode, InlineKeyboardMarkup, \ InlineKeyboardButton,KeyboardButton from telegram.ext import Updater, CallbackContext, Filters, MessageHandler, ConversationHandler, CommandHandler, \ CallbackQueryHandler from settings_bot_currency import TG_Token from settings_bot_currency import id_name, mdb import os from parcer2 import get_html, get_distance import requests import pandas as pd import json import matplotlib.pyplot as plt import pymongo from emoji import emojize MONGODB_LINK = "mongodb+srv://shoomaher:7598621zhora@telegrambot.fls8z.mongodb.net/telegrambot?retryWrites=true&w=majority" MONGODB = "telegramcurrency" URL = "https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=" # Ссылка на json доллар # URL = "https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=2&deal=buy&amount=100&_=" # Евро button_currency = "Валюты" button_help = "/help" button_end = "/end" button_menu = "/menu" spisok_currency = [] letter_code = [] # сокращенное название валюты units = [] # колличество купюр rate = [] # курс валюты value = 0 # поиск выбранной валюты для ее статистике --->в функцие) button_location = "Отправить геопозицию" button_exchange = "Обмен валюты" location=0 ind = -1 # Переменная для сохранения номера элемента в БД по валютам def dontknow(bot, update): # Если непривально введена команда,то будет отправляться пользователю данная команда bot.message.reply_text(text='Я вас не понимаю,нажмите на команду или выполните пожалуйста указанное действие') """Старт""" def message_handler(bot, update): # Обработчик сообщений после ввода команды запуска user_id=bot.message.chat.id # mdb.update_one({"_id":2},{"$set":{"user_id.853611111":3}}) # result=mdb.find_one({"_id":2,"user_id.853615265":{"$exists":True}}) result=mdb.find_one({"_id":2,"user_id.%s"%user_id:{"$exists":True}}) # print(result) if result==None: mdb.update_one({"_id": 2}, {"$set": {"user_id.%s" % user_id: 1}}) my_keyboard = ReplyKeyboardMarkup([[button_exchange], [button_currency], [button_help,button_end]],resize_keyboard=True) name = bot.message.chat.first_name bot.message.reply_text( text="Привет %s,хочешь узнать курсы валют 💵💶 и их динамику📈?\nКонечно да, тогда переходи по кнопке ниже!" % name, reply_markup=my_keyboard) return "spisok comand" """Основной список команд""" def spisok_comand(bot, update): # данная функция перенаправляет пользователя на нужное направление в зависимости его запроса my_keyboard = ReplyKeyboardMarkup([[button_exchange], [button_currency], [button_help,button_end]],resize_keyboard=True) global URL if bot.message.text == button_help: bot.message.reply_text( text="Данный бот способен показывать курсы валют 💵💶 по вашему выбору и также может анализировать ее динамику📈\nКоманда: 'Валюты' перенаправит вас в меню по валютам\nКоманда: '/end' завершит диалог с ботом ") return "spisok comand" if bot.message.text == button_end: bot.message.reply_text( text="До скорой встречи!\nЕсли захочешь узнать свежую информацию, то напиши команду '/start'!", reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END if bot.message.text == button_currency: receive = requests.get("https://www.cbr-xml-daily.ru/daily_json.js") data = json.loads(receive.text) text = "💵<b>%s</b>-<i>%s</i>\n💶<b>%s</b>-<i>%s</i>" % ( data["Valute"]["USD"]["Name"], data["Valute"]["USD"]["Value"], data["Valute"]["EUR"]["Name"], data["Valute"]["EUR"]["Value"]) currency_keyboard = ReplyKeyboardMarkup( [["Определенная валюта сегодня"], ["Курс валюты в выбранные даты"], [button_menu]],resize_keyboard=True) bot.message.reply_text(text=text, parse_mode=ParseMode.HTML) bot.message.reply_text(text="Вы находитесь в меню динамики валюты\nНажмите на нужную вам команду", reply_markup=currency_keyboard) return "currency menu" if bot.message.text == button_menu: bot.message.reply_text(text="Вы находитесь в главном меню!", reply_markup=my_keyboard) return "spisok comand" if bot.message.text == "Обмен валюты": user_id = bot.message.chat.id result = mdb.find_one({"_id": 2, "user_id.%s" % user_id: {"$exists": True}}) if result["user_id"]["%s"%user_id]==1: URL="https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=" keyboard = [[InlineKeyboardButton("€ EURO", callback_data="euro")]] else: URL="https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=2&deal=buy&amount=100&_=" keyboard = [[InlineKeyboardButton("$ DOLLAR", callback_data="dollar")]] # my_keyboard = ReplyKeyboardMarkup([["Ближайшие обменники"], [button_menu]],resize_keyboard=True) inline_keyboard=InlineKeyboardMarkup(keyboard) bot.message.reply_text(text=get_html(URL,params="text"), reply_markup=inline_keyboard, parse_mode=ParseMode.HTML, disable_web_page_preview=True) button_location=KeyboardButton("📍🏦Ближайшие обменники",request_location=True) location_keyboard=ReplyKeyboardMarkup([[button_location],[button_menu]],resize_keyboard=True) # location_keyboard = ReplyKeyboardMarkup([["📍🏦Ближайшие обменники"]],request_location=True,resize_keyboard=True) bot.message.reply_text(text="💱По нажатию кнопки '<b>Ближайшие обменники</b>' вы увидите курс покупки и продажи в обменниках рядом с вами ",reply_markup=location_keyboard, parse_mode=ParseMode.HTML) return "get location" """Основная развилка по курсу валют""" def currency_spisok_command(bot, update): # Перенаправляет по направления блока (валюта) """Удаление граифка""" chat_id = bot.message.chat_id myfile = "graph_%s.png" % chat_id ## If file exists, delete it ## if os.path.isfile(myfile): os.remove(myfile) else: ## Show an error ## print("Error: %s file not found" % myfile) global value spisok_currency.clear() letter_code.clear() units.clear() rate.clear() receive = requests.get("https://www.cbr-xml-daily.ru/daily_json.js") data = json.loads(receive.text) spisok_currency.append([data["Valute"]["USD"]["Name"]]) letter_code.append([data["Valute"]["USD"]["CharCode"]]) spisok_currency.append([data["Valute"]["EUR"]["Name"]]) letter_code.append([data["Valute"]["EUR"]["CharCode"]]) for valute in data["Valute"]: if data["Valute"]["%s" % valute]["Name"] != "Доллар США" and data["Valute"]["%s" % valute]["Name"] != "Евро": spisok_currency.append([data["Valute"]["%s" % valute]["Name"]]) letter_code.append([data["Valute"]["%s" % valute]["CharCode"]]) if bot.message.text == "Определенная валюта сегодня": my_keyboard = ReplyKeyboardMarkup(spisok_currency) bot.message.reply_text(text="Выберете валюту чтобы увидеть информацию по ней за сегодня", reply_markup=my_keyboard) return "currency statistics" if bot.message.text == "Курс валюты в выбранные даты": my_keyboard = ReplyKeyboardMarkup(spisok_currency) bot.message.reply_text(text="Выберете валюту чтобы увидеть информацию по ней за промежуток времени!", reply_markup=my_keyboard) return "date input" if bot.message.text == button_menu: my_keyboard = ReplyKeyboardMarkup([["Обмен валюты"],[button_currency], [button_help, button_end]],resize_keyboard=True) bot.message.reply_text(text="Вы находитесь в главном меню", reply_markup=my_keyboard) return "spisok comand" """Статистика за промежуток времени""" def currency_statistics(bot, update): global ind, value value = bot.message.text receive = requests.get("https://www.cbr-xml-daily.ru/daily_json.js") data = json.loads(receive.text) for valute in data["Valute"]: if value == data["Valute"]["%s" % valute]["Name"]: ind = valute continue bot.message.reply_text( text="Валюта: <b>%s</b>\nСокращенное название: <b>%s</b>\nКоличество: <b>%s</b>\nКурс: <b>%s</b> <i>рублей</i>" % ( data["Valute"]["%s" % ind]["Name"], data["Valute"]["%s" % ind]["CharCode"], data["Valute"]["%s" % ind]["Nominal"], data["Valute"]["%s" % ind]["Value"]), parse_mode=ParseMode.HTML) my_keyboard = ReplyKeyboardMarkup([["Обмен валюты"], [button_currency], [button_help, button_end]],resize_keyboard=True) bot.message.reply_text(text="Вы находитесь в главном меню", reply_markup=my_keyboard) return "spisok comand" # Создание диапазона дат def date_input(bot, update): global value value = bot.message.text bot.message.reply_text( text="Введите диапозон дат как на примере:'<b>2020-10-25 2020-11-5</b>'\n'<i>Год-месяц-число Год-месяц-число</i>'\nБез ковычек!!!", reply_markup=ReplyKeyboardRemove(), parse_mode=ParseMode.HTML) return "currency certain statistics" # Вывод статистики за заданный промежуток времени def currency_certain_statistics(bot, update): chat_id = bot.message.chat_id # сохранение id spisok = [] date = [] global ind, value for i in range(len(spisok_currency)): # Нахождение соответсвуюшего элемента в БД if spisok_currency[i] == [value]: ind = i continue code = str(letter_code[ind]).replace("['", "") # Удаление лишних символов code = code.replace("']", "") # Удаление лишних символов currency_start_date, currency_end_date = map(str, bot.message.text.split(" ")) try: currency_start_date = pd.to_datetime(currency_start_date) # Преобразование в дату currency_end_date = pd.to_datetime(currency_end_date) # Преобразование в дату except ValueError: bot.message.reply_text(text="Введенная вами дата не существует или неккоректна☹\nВведите новые даты👇") daterange = pd.date_range(currency_start_date, currency_end_date) # Создание диапазона по датам for single_date in daterange: receive = requests.get("https://www.cbr-xml-daily.ru/archive/%s/daily_json.js" % ( single_date.strftime("%Y/%m/%d"))) # Отправляем запрос к странице,где сначала год,месяц,число data = json.loads(receive.text) # Преобразование в Json файл try: # Условие при котором проверяется элемент на существование в словаре data["error"] except KeyError: # Если при проверке этого элемента возникает ошибка на его существование, то выводится курс валюты spisok.append(data["Valute"]["%s" % code]["Value"]) # Сохранение курса валюты в определенную дату date.append(single_date.strftime("%Y-%m-%d")) # Сохранение даты print(date) print(spisok) """Построение графика в питоне """ df = pd.DataFrame({"date": date, "value": spisok}) # Построение графика в pandas с помощью dataframe df["date"] = pd.to_datetime(df["date"]) # Присвоение датам значение даты plt.plot(df["date"], df["value"], lw=1, ls='-', marker='o', markersize=5) # создание осей plt.title("График изменения валюты: %s" % value) plt.ylabel("Курс валюты") plt.grid(True) plt.gcf().autofmt_xdate() # Форматирование графика чтобы не наезжал шрифт plt.savefig("graph_%s" % chat_id) # сохранение графика graph = open("graph_%s.png" % chat_id, "rb") # открытие графика в переменной update.bot.send_photo(chat_id=bot.message.chat_id, photo=graph) # Отправка графика пользователю на id пользователя plt.clf() """Вывод данных за промежуток времени""" # for i,item in enumerate(date): # date[i]+=" курс: %s рубля"%spisok[i] # bot.message.reply_text(text="\n".join(date)) my_keyboard = ReplyKeyboardMarkup([["Обмен валюты"], [button_currency], [button_menu, button_end]],resize_keyboard=True) bot.message.reply_text(text="Выбери команду", reply_markup=my_keyboard) return "spisok comand" """Обмен валюты""" """Нерабочий вариант в плане того что геолокацию запрашивает после наэатия доп кнопки""" def exchange(bot, update): my_keyboard = ReplyKeyboardMarkup([["Курс обменников"], ["Ближайшие обменники"], [button_menu]],resize_keyboard=True) if bot.message.text == "Курс обменников": bot.message.reply_text(text=get_html(URL,params="text"), reply_markup=my_keyboard, parse_mode=ParseMode.HTML) bot.message.reply_text(text="Выберите команду!") return "exchange" if bot.message.text == "Ближайшие обменники": location_button = KeyboardButton("📍Отправить геолокацию📍", request_location=True) location_keyboard = ReplyKeyboardMarkup([[location_button]], resize_keyboard=True) bot.message.reply_text( text="📍Отправьте нам свою геолокацию", reply_markup=location_keyboard, parse_mode=ParseMode.HTML) return "get location" if bot.message.text=="/menu": my_keyboard = ReplyKeyboardMarkup([["Обмен валюты"], [button_currency], [button_help, button_end]],resize_keyboard=True) bot.message.reply_text(text="Вы находитесь в главном меню", reply_markup=my_keyboard) return "spisok comand" """Получаем геопозицию пользователя""" def get_location(bot, update): global location location = bot.message.location latitude = location["latitude"] longitude = location["longitude"] print(latitude, longitude) # bot.message.reply_text(text="Сейчас подберем 📍ближайшие к вам обменники %s🏦" % bot.message.chat.first_name) bot.message.reply_text(text=get_distance(get_html(URL,"distance"), "distance", latitude, longitude), parse_mode=ParseMode.HTML,reply_markup=inline_sort(),disable_web_page_preview=True) my_keyboard=ReplyKeyboardMarkup([[button_menu]], resize_keyboard=True) bot.message.reply_text(text="Вы можете найти выгодный курс <b>покупки/продажи</b> по кнопкам под сообщением\nЕсли хотите вернуться в главное меню,то нажмите кнопку<b>'/menu'</b>",reply_markup=my_keyboard,parse_mode=ParseMode.HTML) return "sort" """кнопки с покупкой продажей inline""" def inline_sort(): if URL=="https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=": keyboard = [[InlineKeyboardButton("покупка", callback_data="покупка"), InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники"), InlineKeyboardButton("продажа", callback_data="продажа")],[InlineKeyboardButton("€ EURO", callback_data="euronear")]] else: keyboard = [[InlineKeyboardButton("покупка", callback_data="покупка"), InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники"), InlineKeyboardButton("продажа", callback_data="продажа")], [InlineKeyboardButton("$ DOLLAR", callback_data="dollarnear")]] return InlineKeyboardMarkup(keyboard) def inline_sort_callback(bot,update): global URL user_id=bot.callback_query.message.chat.id query=bot.callback_query data=query.data result = mdb.find_one({"_id": 2, "user_id.%s" % user_id: {"$exists": True}}) if data=="покупка": if result["user_id"]["%s"%user_id]==1: URL="https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=" # Ссылка на json доллар keyboard = [[InlineKeyboardButton("продажа", callback_data="продажа"),InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники")],[InlineKeyboardButton("€ EURO", callback_data="euronear")]] else: keyboard = [[InlineKeyboardButton("продажа", callback_data="продажа"),InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники")],[InlineKeyboardButton("$ DOLLAR", callback_data="dollarnear")]] query.edit_message_text(text=get_distance(get_html(URL,"distance"),"distance_buy",location["latitude"],location["longitude"]),reply_markup=InlineKeyboardMarkup(keyboard),parse_mode=ParseMode.HTML,disable_web_page_preview=True) return "sort" if data=="продажа": if result["user_id"]["%s"%user_id]==1: URL="https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=" # Ссылка на json доллар keyboard = [[InlineKeyboardButton("покупка", callback_data="покупка"),InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники")],[InlineKeyboardButton("€ EURO", callback_data="euronear")]] else: keyboard = [[InlineKeyboardButton("покупка", callback_data="покупка"),InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники")],[InlineKeyboardButton("$ DOLLAR", callback_data="dollarnear")]] query.edit_message_text(text=get_distance(get_html(URL,"distance"),"distance_sell",location["latitude"],location["longitude"]), reply_markup=InlineKeyboardMarkup(keyboard),parse_mode=ParseMode.HTML,disable_web_page_preview=True) return "sort" if data=="ближайшие обменники": if result["user_id"]["%s"%user_id]==1: URL = "https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=" # Ссылка на json доллар keyboard = [[InlineKeyboardButton("покупка", callback_data="покупка"),InlineKeyboardButton("продажа", callback_data="продажа")],[InlineKeyboardButton("€ EURO", callback_data="euronear")]] else: keyboard = [[InlineKeyboardButton("покупка", callback_data="покупка"),InlineKeyboardButton("продажа", callback_data="продажа")],[InlineKeyboardButton("$ DOLLAR", callback_data="dollarnear")]] query.edit_message_text(text=get_distance(get_html(URL,"distance"), "distance",location["latitude"],location["longitude"]),reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.HTML,disable_web_page_preview=True) return "sort" if data=="/menu": my_keyboard = ReplyKeyboardMarkup([["Курс обменников"], ["Ближайшие обменники"], [button_menu]],resize_keyboard=True) query.message_text(text="Вы находитесь в главном меню",reply_markup=my_keyboard) return "spisok comand" if data=="euro": mdb.update_one({"_id": 2}, {"$set": {"user_id.%s" % user_id: 2}}) keyboard = [[InlineKeyboardButton("$ DOLLAR", callback_data="dollar")]] URL = "https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=2&deal=buy&amount=100&_=" # Евро query.edit_message_text(text=get_html(URL,params="text"), reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.HTML,disable_web_page_preview=True) return "get location" if data=="dollar": mdb.update_one({"_id": 2}, {"$set": {"user_id.%s" % user_id: 1}}) keyboard = [[InlineKeyboardButton("€ EURO", callback_data="euro")]] URL = "https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=" # Ссылка на json доллар query.edit_message_text(text=get_html(URL,params="text"), reply_markup=InlineKeyboardMarkup(keyboard),parse_mode=ParseMode.HTML, disable_web_page_preview=True) return "get location" if data=="euronear": mdb.update_one({"_id": 2}, {"$set": {"user_id.%s" % user_id: 2}}) URL="https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=2&deal=buy&amount=100&_=" keyboard=[[InlineKeyboardButton("продажа", callback_data="продажа"),InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники")],[InlineKeyboardButton("$ DOLLAR", callback_data="dollarnear")]] query.edit_message_text( text=get_distance(get_html(URL, "distance"), "distance", location["latitude"], location["longitude"]), reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.HTML, disable_web_page_preview=True) return "sort" if data=="dollarnear": mdb.update_one({"_id": 2}, {"$set": {"user_id.%s" % user_id: 1}}) URL = "https://cash.rbc.ru/cash/json/cash_rates/?city=1&currency=3&deal=buy&amount=100&_=" keyboard = [[InlineKeyboardButton("продажа", callback_data="продажа"),InlineKeyboardButton("ближайшие обменники", callback_data="ближайшие обменники")],[InlineKeyboardButton("$ EURO", callback_data="euronear")]] query.edit_message_text( text=get_distance(get_html(URL, "distance"), "distance", location["latitude"], location["longitude"]), reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.HTML, disable_web_page_preview=True) return "sort" def main(): # Основные параметры работы бота(Токен,диалог) print("Бот с курсами валют запущен") updater = Updater(token=TG_Token, use_context=True) start_handler = updater.dispatcher.add_handler( ConversationHandler(entry_points=[CommandHandler("start", message_handler)], states={ "spisok comand": [ MessageHandler(Filters.regex("/help|/end|Валюты|/menu|Обмен валюты"),spisok_comand)], "currency menu": [MessageHandler( Filters.regex("Определенная валюта сегодня|Курс валюты в выбранные даты|/menu"),currency_spisok_command)], "currency statistics": [MessageHandler(Filters.text, currency_statistics)], "date input": [MessageHandler(Filters.text, date_input)], "currency certain statistics": [MessageHandler(Filters.text, currency_certain_statistics)], "get location": [MessageHandler(Filters.location, get_location),CallbackQueryHandler(inline_sort_callback,"покупка|продажа|ближайшие обменники|/menu|€|$"),MessageHandler(Filters.regex("/help|/end|/menu"),spisok_comand)], "sort": [CallbackQueryHandler(inline_sort_callback,"покупка|продажа|ближайшие обменники|€|$"),MessageHandler(Filters.regex("/help|/end|/menu"),spisok_comand)] }, fallbacks=[MessageHandler(Filters.text | Filters.video | Filters.document | Filters.photo,dontknow)] ) ) # inline_keyboard_handler=CallbackQueryHandler(callback=inline_sort_callback,pass_chat_data=True) # updater.dispatcher.add_handler(inline_keyboard_handler) updater.start_polling() updater.idle() print("Бот с курсами валют выключен") if __name__ == "__main__": main()
UTF-8
Python
false
false
26,835
py
7
bot_currency.py
4
0.655465
0.649972
0
385
58.054545
252
udayt-7/Data-Structures-Python
893,353,214,251
45a7ded7babdbb568b1501f66d5753e213db6d8a
a3249e6686d3e4c5b980cc5868da1115997fa4fc
/Stacks_and_Queues/s1p1.py
851a69ed7b24e0d91ef5926957587a5d3f2ca918
[]
no_license
https://github.com/udayt-7/Data-Structures-Python
caa6d19c0ef37e0d9448902b23a0f98a70b08944
d4a5fad5364f5fab231e4c02b2f21d2c0dfc7ce3
refs/heads/master
2020-05-04T01:38:09.343017
2019-04-01T17:11:08
2019-04-01T17:11:08
178,909,745
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Implement a function with signature transfer(S,T) that transfers all elements from Stack S onto Stack T, #so that that elements that starts at the top of S is the first to be inserted into T, and element at the bottom of S ends up at the top of T. import stack1 s = stack1.LimitedStack() t = stack1.LimitedStack() m = int(input("Size of stack:")) def signtransfer(s,t): for ch in range(m): t.stackpush(s.stackpop()) print(t.data) for ch in range(m): ele = int(input("enter element")) s.stackpush(ele) print(s.data) signtransfer(s,t)
UTF-8
Python
false
false
552
py
38
s1p1.py
38
0.713768
0.708333
0
25
21.08
144
coolfreex/vulTest
17,703,855,206,548
ad24420bb86ff6381301db6902fd0c388d6cda0d
22e6c7a56e56793ae1587b8876ada7cbf18ea313
/e-cology.py
9a23a027851574d1daf92c059294724a005b9ec7
[]
no_license
https://github.com/coolfreex/vulTest
931b4457f4e3f33e1c5646a5263b4c7e8e2ec325
39bd3d6ef408b5dec3434698c8bc1bd74605c2b2
refs/heads/master
2021-05-25T12:20:48.592854
2020-04-07T09:51:54
2020-04-07T09:51:54
253,752,677
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/4/7 14:02 # @Author : so:Lo # @File : e-cology.py # 泛微e-cology OA Beanshell组件远程代码执行 # usage:python3 e-cology.py http://target cmd # import sys import requests # cmd = 'ls' vulable = '/weaver/bsh.servlet.BshServlet' headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 12_10) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/12.0 Safari/1200.1.25', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Content-Type': 'application/x-www-form-urlencoded' } def expliot(url,cmd): target = url+vulable print(target) payload = 'bsh.script=exec(' + '"' + cmd + '"' + ')' print("-----------------------------------") print("paylaod is " + payload) print("-----------------------------------") r = requests.post(target,headers=headers,data=payload) s = r.text if '<h2>Script Output</h2>'in s: d = s.index('<h2>Script Output</h2>') e = s.index('</td></tr></table>') print(s[d:e]) print(r.status_code) else: print('exec fail') print(r.status_code) if __name__ == '__main__': url = sys.argv[1] cmd = sys.argv[2] expliot(url,cmd)
UTF-8
Python
false
false
1,356
py
1
e-cology.py
1
0.568114
0.532934
0
51
25.196078
137
lyx199504/MachineLearningInAction-Python3
9,766,755,652,637
c3a0b150478d617de8027b144fcfa1cd8bcacf8b
6a6f0e40d58d52a57cc3c4bcbd39ee05a5919240
/ch11_apriori/apriori.py
29e86c6c18e5f3e3f72cfdb108902139efeee092
[]
no_license
https://github.com/lyx199504/MachineLearningInAction-Python3
3e930bb98615362ba445ec86cfa91d849cde8330
1d23fac90e9aaa894445f444f8caf23fe3d24c40
refs/heads/master
2020-12-04T09:09:34.191208
2020-08-11T07:58:45
2020-08-11T07:58:45
231,706,844
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/16 21:27 # @Author : LYX-夜光 # 创建子集 def createC1(dataSet): C1 = [] for transaction in dataSet: for item in transaction: if not [item] in C1: C1.append([item]) C1.sort() return list(map(frozenset, C1)) # 计算子集出现的频率 def scanD(D, Ck, minSupport): ssCnt = {} for tid in D: for can in Ck: if can.issubset(tid): # can是tid的子集 ssCnt[can] = ssCnt.get(can, 0) + 1 # 计数 numItems = float(len(D)) # 数据组数 retList = [] supportData = {} for key in ssCnt: support = ssCnt[key]/numItems # 每个元素出现的频率 if support >= minSupport: retList.insert(0, key) # 在第0个位置插入key supportData[key] = support return retList, supportData # 合并新集合 def aprioriGen(Lk, k): retList = [] lenLk = len(Lk) for i in range(lenLk): for j in range(i+1, lenLk): L1, L2 = list(Lk[i])[:k-2], list(Lk[j])[:k-2] L1.sort() L2.sort() if L1 == L2: retList.append(Lk[i] | Lk[j]) return retList def apriori(dataSet, minSupport=0.5): C1 = createC1(dataSet) # 初始子集(每个集合元素只有1个) D = list(map(set, dataSet)) L1, supportData = scanD(D, C1, minSupport) # 根据支持度选取子集 L = [L1] k = 2 while len(L[k-2]) > 0: Ck = aprioriGen(L[k-2], k) # 两两合并子集,合并后每个集合元素增加1个 Lk, Sk = scanD(D, Ck, minSupport) # 再根据支持度选取子集 supportData.update(Sk) L.append(Lk) k += 1 return L, supportData # 计算关联 def calcConf(freqSet, H, supportData, bigRuleList, minConf=0.7): prunedH = [] for conseq in H: conf = supportData[freqSet]/supportData[freqSet-conseq] # 集合支持率除以子集的支持率 if conf >= minConf: bigRuleList.append((freqSet-conseq, conseq, conf)) # 关联集合表 prunedH.append(conseq) return prunedH def rulesFromConseq(freqSet, H, supportData, bigRuleList, minConf=0.7): m = len(H[0]) if len(freqSet) > m + 1: Hmp1 = aprioriGen(H, m+1) # 两两组合元素多一个的新集合 Hmp1 = calcConf(freqSet, Hmp1, supportData, bigRuleList, minConf) # 筛选子集 if len(Hmp1) > 1: rulesFromConseq(freqSet, Hmp1, supportData, bigRuleList, minConf) # 生成关联规则 def generateRules(L, supportData, minConf=0.7): bigRuleList = [] for i in range(1, len(L)): for freqSet in L[i]: H1 = [frozenset([item]) for item in freqSet] if i > 1: rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf) else: calcConf(freqSet, H1, supportData, bigRuleList, minConf) return bigRuleList if __name__ == "__main__": dataSet = [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]] L, supportData = apriori(dataSet) bigRuleList = generateRules(L, supportData, minConf=0.5) for bigRule in bigRuleList: print(bigRule[0], "-->", bigRule[1], "conf:", bigRule[2])
UTF-8
Python
false
false
3,266
py
26
apriori.py
25
0.567831
0.540296
0
95
30.347368
81
srinivasskc/Python-Programming-Learning
1,460,288,905,563
ddb28000c77698399ca50f202f80ca80fbb2c21d
414b21e4645117e92582fb3ad76026a10c6d00d5
/Python150Challenges/Strings/20-26 Challenges/Challenge24.py
cddd426c61eb14f38432559f61a4c15384af6911
[]
no_license
https://github.com/srinivasskc/Python-Programming-Learning
1a8caf1a4fc602ef5b819d6168377fcfe6ba7351
4d4523473521b94f76709b204251bd4ef6ab5f1e
refs/heads/master
2022-11-14T20:10:02.453767
2020-07-07T03:58:03
2020-07-07T03:58:03
272,511,628
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# 024 Ask the user to type in any word and display it in upper case. word = input("Enter any country name: ") print(word.upper())
UTF-8
Python
false
false
132
py
223
Challenge24.py
198
0.704545
0.681818
0
4
32
69
cafaray/atco.de-fights
9,131,100,494,411
f64c6b1b3cc1c1a44897bc904156db6039926056
b186830ab8e74452cb2e8ff0188d0a8fa3d15b59
/smallestMultiples.py
e1e71d9c09c31b1cd390bd0c50dcbbf8a9729467
[]
no_license
https://github.com/cafaray/atco.de-fights
e3a278bd51feb7bee05623eaf20d1ea4db535eb6
1304bcabf1f18202c14a20b38144854ef05bf776
refs/heads/master
2022-11-26T05:57:37.564504
2020-07-28T12:07:01
2020-07-28T12:07:01
124,416,047
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def smallestMultiple(left, right): n=right while True: isD=True for d in range(left,right+1): if n%d!=0: isD=False break if isD: return n n+=1 left=2 right=4 print(smallestMultiple(left,right)) left=1 right=1 print(smallestMultiple(left,right))
UTF-8
Python
false
false
338
py
334
smallestMultiples.py
332
0.547337
0.526627
0
18
17.833333
37
iredkoz/testapp
6,038,724,053,662
eaed91d55dca46d2e396dde2427c535b2448b997
11a00d33e45744203a10cb3461f409bd4ccd821c
/app/home/views.py
79fb3632cb336a77dfc3bbbc4f63ab5612282245
[]
no_license
https://github.com/iredkoz/testapp
3534a9537d8dd68015a1f553b08acb498e441a77
d0118f2e42d4e439c343da92ef3985c78fbef969
refs/heads/master
2021-05-23T05:23:07.958811
2018-07-10T14:13:45
2018-07-10T14:13:45
95,160,009
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask import redirect, render_template, url_for, flash, abort from . import home @home.route('/') def home_main(): return render_template('home/index.html')
UTF-8
Python
false
false
168
py
33
views.py
17
0.714286
0.714286
0
7
23
66
desihub/desispec
11,166,915,012,111
62ad49d50ba9cdec9539be9c30761882533e1a31
5c26d7a1f93fb30a6d36e65d5724765d3deb2894
/py/desispec/test/test_pipeline_run.py
9c1d4fb468c4d37a33a6349896dd587cb7a39f48
[ "BSD-3-Clause" ]
permissive
https://github.com/desihub/desispec
8ab21880a10c25527ce8855294e6d039c75d4e0f
d75d0540cd07df1bf46130338a33c2ced51fbead
refs/heads/main
2023-08-17T16:10:23.127096
2023-08-16T17:30:36
2023-08-16T17:30:36
26,142,080
33
31
BSD-3-Clause
false
2023-09-14T18:21:54
2014-11-03T22:34:47
2023-09-01T06:51:22
2023-09-14T18:21:52
30,375
29
23
306
Python
false
false
""" tests desispec.pipeline.core """ import os import unittest import shutil import time import numpy as np import subprocess as sp # # from desispec.pipeline.common import * # from desispec.pipeline.graph import * # from desispec.pipeline.plan import * # from desispec.pipeline.run import * # from desispec.util import option_list # # import desispec.scripts.pipe_prod as pipe_prod # # import desispec.io as io # # from desiutil.log import get_logger # # from . import pipehelpers as ph class TestPipelineRun(unittest.TestCase): def setUp(self): # self.prod = "test" # self.shifter = "docker:tskisner/desipipe:latest" # self.raw = ph.fake_raw() # self.redux = ph.fake_redux(self.prod) # # (dummy value for DESIMODEL) # self.model = ph.fake_redux(self.prod) # ph.fake_env(self.raw, self.redux, self.prod, self.model) pass def tearDown(self): # for dirname in [self.raw, self.redux, self.model]: # if os.path.exists(dirname): # shutil.rmtree(dirname) # ph.fake_env_clean() pass def test_run(self): # opts = {} # opts["spectrographs"] = "0" # opts["data"] = self.raw # opts["redux"] = self.redux # opts["prod"] = self.prod # opts["shifter"] = self.shifter # sopts = option_list(opts) # sargs = pipe_prod.parse(sopts) # pipe_prod.main(sargs) # # # modify the options to use our No-op worker # rundir = io.get_pipe_rundir() # optfile = os.path.join(rundir, "options.yaml") # # opts = {} # for step in step_types: # opts["{}_worker".format(step)] = "Noop" # opts["{}_worker_opts".format(step)] = {} # opts[step] = {} # yaml_write(optfile, opts) # # envfile = os.path.join(rundir, "env.sh") # with open(envfile, "w") as f: # f.write("export DESIMODEL={}\n".format(rundir)) # if "PATH" in os.environ: # f.write("export PATH={}\n".format(os.environ["PATH"])) # if "PYTHONPATH" in os.environ: # f.write("export PYTHONPATH={}\n".format(os.environ["PYTHONPATH"])) # if "LD_LIBRARY_PATH" in os.environ: # f.write("export LD_LIBRARY_PATH={}\n".format(os.environ["LD_LIBRARY_PATH"])) # # com = ". {}; eval {}".format(envfile, os.path.join(rundir, "scripts", "run_shell_all.sh")) # print(com) # sp.call(com, shell=True, env=os.environ.copy()) pass def test_suite(): """Allows testing of only this module with the command:: python setup.py test -m <modulename> """ return unittest.defaultTestLoader.loadTestsFromName(__name__)
UTF-8
Python
false
false
2,800
py
488
test_pipeline_run.py
414
0.57
0.569643
0
89
30.460674
100
Dimi727/python-api-test
17,471,926,960,349
68620bd118151ba42ee9e7a0311d5150bc00980f
45e25eb3c25c42c88ea2d6c7187633712cb94d73
/mongodb.py
fa466341c1d67e1a13ee1543c315d0fbd250e3be
[]
no_license
https://github.com/Dimi727/python-api-test
b16d992fb6c7c4196657abb644cc511ed77d2ecd
484563a2b09a1c85e70731ebf83e6af573800c1a
refs/heads/master
2021-09-04T11:58:16.637135
2018-01-18T13:50:33
2018-01-18T13:50:33
114,892,908
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from pymongo import MongoClient from pprint import pprint client = MongoClient() db = client.admin serverStatusResult=db.command("serverStatus") pprint(serverStatusResult)
UTF-8
Python
false
false
175
py
16
mongodb.py
12
0.817143
0.817143
0
10
16.6
45
lanlingshao/algorithm
549,755,823,468
f02a95ffabc5611ce6faf4e65fe995a36d6ea63c
960619ac02393e33ef9d6c7c1019df5ad42ae329
/sort/merge_sort.py
edd0222520ac3378420430e343a844ad70374edc
[]
no_license
https://github.com/lanlingshao/algorithm
91d1c991fd1cda6b682e2fff4bc1323ea3eefb92
ea84849e537a175b236ae303ae288312bb7c0358
refs/heads/master
2023-08-25T22:59:13.235223
2021-11-04T14:28:35
2021-11-04T14:28:35
193,303,231
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" 归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。 作为一种典型的分而治之思想的算法应用,归并排序的实现由两种方法: 自上而下的递归(所有递归的方法都可以用迭代重写,所以就有了第 2 种方法); 自下而上的迭代; 和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是 O(nlogn) 的时间复杂度。代价是需要额外的内存空间 2. 算法步骤 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列; 设定两个指针,最初位置分别为两个已经排序序列的起始位置; 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置; 重复步骤 3 直到某一指针达到序列尾; 将另一序列剩下的所有元素直接复制到合并序列尾。 归并排序可以看《算法第四版》,里面写的很详细,时间复杂度的讲解很值得学习 对于小规模的数组可以采用插入排序,因为递归会使小规模问题中的方法调用过于频繁,这样改进归并排序可以减少10%-15%的运行时间 """ # 递归法,原地合并, 只是多了temp_right_sub_nums占用的辅助空间, # 但是temp_right_sub_nums最多也就占用len(nums) / 2长度的空间 class Solution1: def merge_sort(self, left, right, nums): if left < right: mid = left + (right - left) // 2 self.merge_sort(left, mid, nums) self.merge_sort(mid + 1, right, nums) # 如果中间值比右边的小,不需要对两边的进行排序了 if nums[mid] <= nums[mid + 1]: return self.merge(left, mid, right, nums) # 这个借鉴了leetcode 88题的方法,合并两个有序数组,使用从后向前合并策略 def merge(self, left, mid, right, nums): temp_right_sub_nums = [] for i in range(mid + 1, right + 1): temp_right_sub_nums.append(nums[i]) i, j, k = mid, len(temp_right_sub_nums) - 1, right while i >= left and j >= 0: if nums[i] > temp_right_sub_nums[j]: nums[k] = nums[i] i -= 1 else: nums[k] = temp_right_sub_nums.pop() j -= 1 k -= 1 while j >= 0: nums[k] = temp_right_sub_nums.pop() j -= 1 k -= 1 # 迭代法,原地合并 # 参考《算法第四版》2.2.3 第175页方法 class Solution2: def merge_sort(self, left, right, nums): size = 1 while size < len(nums): for i in range(0, len(nums), size * 2): left = i mid = left + size - 1 right = left + 2 * size - 1 if nums[mid] <= nums[mid + 1]: continue self.merge(left, mid, right, nums) size *= 2 def merge(self, left, mid, right, nums): temp_right_sub_nums = [] for i in range(mid + 1, right + 1): temp_right_sub_nums.append(nums[i]) i, j, k = mid, len(temp_right_sub_nums) - 1, right while i >= left and j >= 0: if nums[i] > temp_right_sub_nums[j]: nums[k] = nums[i] i -= 1 else: nums[k] = temp_right_sub_nums.pop() j -= 1 k -= 1 while j >= 0: nums[k] = temp_right_sub_nums.pop() j -= 1 k -= 1 if __name__ == "__main__": s = Solution2 nums1 = [3,1,4,6,7,5,2,0] s().merge_sort(0, len(nums1) - 1, nums1) print(nums1) nums2 = [3,1,4,6,7,5,2,0] s().merge_sort(0, len(nums2) - 1, nums2) print(nums2) nums2 = [0,1,2,3,4,5,6,7] s().merge_sort(0, len(nums2) - 1, nums2) print(nums2)
UTF-8
Python
false
false
4,069
py
24
merge_sort.py
15
0.522086
0.491531
0
97
30.041237
76
TimoStroehlein/dhbw-bigdata-mtg
9,895,604,650,361
3f708b6260d23a72d5b7b4b2f3deadb7b7f0bc8a
9bda4ba9c3ae050c48fb51604f822692a23d1824
/airflow/python/pyspark_export_cards.py
542aaacab800a4e521eca6283286353793ac7663
[]
no_license
https://github.com/TimoStroehlein/dhbw-bigdata-mtg
ba5852f9a3e3a9a45b22526feba7ad2e6415254b
271eb172e3a42dd5678fe3f968dc47f79a4e425c
refs/heads/main
2023-04-02T20:26:09.779902
2021-04-04T13:34:27
2021-04-04T13:34:27
350,386,642
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pyspark import argparse import json from pyspark.sql import SparkSession from pyspark import SparkContext from pyspark.sql.functions import col, expr, explode, concat_ws from pymongo import MongoClient def get_args(): """ Parses command line args. """ parser = argparse.ArgumentParser() parser.add_argument('--year', help='Partion Year To Process', required=True, type=str) parser.add_argument('--month', help='Partion Month To Process', required=True, type=str) parser.add_argument('--day', help='Partion Day To Process', required=True, type=str) return parser.parse_args() def export_cards(): """ Export final cards to MongoDB. """ # Parse Command Line Args args = get_args() # Initialize Spark Context sc = pyspark.SparkContext() spark = SparkSession(sc) # Read final cards as json from HDFS mtg_cards_df = spark.read.json(f'/user/hadoop/mtg/final/{args.year}/{args.month}/{args.day}') # Convert dataframe to json mtg_cards_json = mtg_cards_df.toJSON().map(lambda j: json.loads(j)).collect() # Connect to MongoDB cards_collection = mongodb_cards_collection() cards_collection.remove({}) # Remove all documents from the collection cards_collection.insert_many(mtg_cards_json) def mongodb_cards_collection(): """ Connect to MongoDB. :return: Cards collection of MongoDB. """ client = MongoClient(host='mongo', port=27017, serverSelectionTimeoutMS=5000) db = client['mtg'] db.authenticate('dev', 'dev') return db['cards'] if __name__ == '__main__': export_cards()
UTF-8
Python
false
false
1,765
py
16
pyspark_export_cards.py
8
0.62153
0.616431
0
64
26.578125
97
maks-ym/python-projects-and-stuff
11,957,189,002,905
0544a1216a21da0724a5544c35f5336996d0c63c
ae365a5458e16cb717dd18388c97ff37f036215c
/generators_time_test/utils.py
ec8ee4b5f41b4f0816acea692287219e91e015d2
[]
no_license
https://github.com/maks-ym/python-projects-and-stuff
70207229d11eb7d156648ca86a89bdf6c45b3062
9aac8b841d14f3d7bba3d07462d13afea23f0421
refs/heads/master
2023-04-03T19:40:38.158342
2023-03-21T20:04:27
2023-03-21T20:04:27
224,304,547
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import time import matplotlib.pyplot as plt def timeit(func): def wrapper(*args, **kw): res_time = time.time() func_res = func(*args, **kw) res_time = time.time() - res_time return res_time, func_res, func.__name__ return wrapper def create_subplot(place, x, y, title="Figure"): plt.subplot(place) plt.plot(x, y) plt.title(title) def create_figure(dict_xy): plt.figure() for i, (k, v) in enumerate(dict_xy.items()): p = "12" + str(i+1) print(p) create_subplot(p, list(range(len(v))), v, k) plt.show()
UTF-8
Python
false
false
593
py
33
utils.py
8
0.573356
0.568297
0
25
22.76
52
ghas-results/usbinfo
9,337,258,950,877
c088a02c672811ad31cb6e62555d08af695f2a40
78352c23528f9e1f5567b777984923a3cd02d319
/usbinfo/linux.py
02470dd6e3fa56f2bbb5939241a64b313ca97330
[ "Apache-2.0" ]
permissive
https://github.com/ghas-results/usbinfo
02566421a87db9f9e6fe78765cbe27043f5b9896
6445de71313e4c5ac17d83e3d82d07dde508cb79
refs/heads/master
2023-08-23T09:23:05.761262
2021-06-24T18:12:43
2021-06-24T18:12:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of ``usbinfo`` for Linux-based systems.""" import pyudev from .posix import get_mounts def usbinfo(decode_model=False, **kwargs): """Helper for usbinfo on Linux. Args: decode_model: Due to versions <=1.0.2 incorrectly using ID_MODEL, this allows for the newer API to return the proper product name. **kwargs: Additional keyword arguments specific to platform implementation. """ info_list = [] _mounts = get_mounts() context = pyudev.Context() devices = context.list_devices().match_property('ID_BUS', 'usb') for device in devices: if decode_model: id_product = _decode(device.get('ID_MODEL_ENC', u'')) id_vendor = _decode(device.get('ID_VENDOR_ENC', u'')) else: id_product = device.get('ID_MODEL', u'') id_vendor = device.get('ID_VENDOR', u'') devinfo = { 'bInterfaceNumber': device.get('ID_USB_INTERFACE_NUM', u''), 'devname': device.get('DEVNAME', u''), 'devpath': device.get('DEVPATH', u''), 'iManufacturer': id_vendor, 'iProduct': id_product, 'iSerialNumber': device.get('ID_SERIAL_SHORT', u''), 'idProduct': device.get('ID_MODEL_ID', u''), 'idVendor': device.get('ID_VENDOR_ID', u''), } mount = _mounts.get(device.get('DEVNAME')) if mount: devinfo['mount'] = mount info_list.append(devinfo) return info_list def _decode(unicode_str): """Decode malformed unicode strings from pyudev. ID_MODEL_ENC and ID_VENDOR_ENC could return values as: u'Natural\xae\\x20Ergonomic\\x20Keyboard\\x204000' which would raise a UnicodeEncodeError. To work around this, the string is first fixed by replacing any extended-ASCII characters with an escaped character string. Args: unicode_str: Unicode string to decode. Returns: A decoded string. """ fixed_str = ''.join( [c if ord(c) < 128 else '\\x%02x' % ord(c) for c in unicode_str]) return fixed_str.decode('string_escape')
UTF-8
Python
false
false
2,753
py
1
linux.py
1
0.631311
0.621867
0.001816
83
32.168675
78
Sylux6/meltylog-analysis
6,064,493,847,375
d93cceb1e19ad32dd3f749adab89ce39b6c9569c
9a77b635e4dafdc32f061b6beb9fe30f8b3cad24
/graph.py
5e0243fa08763d1ca645bcce75fd974c70964291
[ "MIT" ]
permissive
https://github.com/Sylux6/meltylog-analysis
8e8d131fad2469721db74f6c85df2340e3797cc1
e7a89b52c701d948a2db3208ff715cd88eaeb242
refs/heads/master
2021-07-13T12:31:44.228819
2018-08-29T10:31:11
2018-08-29T10:31:11
124,910,015
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pandas as pd import numpy as np from graph_tool.all import * def session_draw(cluster_id, sessions_id, log, pages, labels): cmap = plt.cm.tab20 colormap=cmap(np.linspace(0., 1., len(labels))) colormap=np.vstack((np.array([0,0,0,1]),colormap)) for id in sessions_id: session = log[log.global_session_id==id] s_urls = session.requested_url s_urls = s_urls.append(session.referrer_url) s_urls.drop_duplicates(inplace=True) g = Graph() v = {} color = g.new_vertex_property("vector<float>") halo = g.new_vertex_property("bool") for u in s_urls: v[u] = g.add_vertex() if not u.replace('"', "").startswith("www.melty.fr"): halo[v[u]] = True else: halo[v[u]] = False idx = labels.index(pages[pages.url==u].category.values[0]) color[v[u]] = colormap[idx+1].tolist() session.apply(lambda x: g.add_edge(v[x.referrer_url], v[x.requested_url]), axis=1) graph_draw(g, vertex_halo=halo, vertex_fill_color=color, output="Latex/Graphs/session"+str(id)+".png") graph_draw(g, vertex_halo=halo, vertex_fill_color=color, output="shared/session"+str(id)+".svg") return def session_draw_topic(cluster_id, sessions_id, log, pages, labels): cmap = plt.cm.tab20 colormap = cmap(np.linspace(0., 1., len(labels))) colormap = np.vstack((np.array([0, 0, 0, 1]), colormap)) for id in sessions_id: session = log[log.global_session_id == id] s_urls = session.requested_url s_urls = s_urls.append(session.referrer_url) s_urls.drop_duplicates(inplace=True) g = Graph() v = {} color = g.new_vertex_property("vector<float>") halo = g.new_vertex_property("bool") for u in s_urls: v[u] = g.add_vertex() if not u.replace('"', "").startswith("www.melty.fr"): halo[v[u]] = True else: halo[v[u]] = False idx = labels.index(pages[pages.url == u].topic.values[0]) color[v[u]] = colormap[idx + 1].tolist() session.apply( lambda x: g.add_edge(v[x.referrer_url], v[x.requested_url]), axis=1) graph_draw( g, vertex_halo=halo, vertex_fill_color=color, output="Latex/Graphs/session" + str(id) + "_topic.png") graph_draw( g, vertex_halo=halo, vertex_fill_color=color, output="shared/session" + str(id) + "_topic.svg") return def multi_session_draw(cluster_id, sessions_id, log, pages, label_category, label_topic): cmap = plt.cm.tab20 colormap_category = cmap(np.linspace(0., 1., len(label_category))) colormap_category = np.vstack((np.array([0, 0, 0, 1]), colormap_category)) colormap_topic = cmap(np.linspace(0., 1., len(label_topic))) colormap_topic = np.vstack((np.array([0, 0, 0, 1]), colormap_topic)) for id in sessions_id: session = log[log.global_session_id == id] s_urls = session.requested_url s_urls = s_urls.append(session.referrer_url) s_urls.drop_duplicates(inplace=True) g = Graph() v = {} color_category = g.new_vertex_property("vector<float>") color_topic = g.new_vertex_property("vector<float>") halo = g.new_vertex_property("bool") for u in s_urls: v[u] = g.add_vertex() if not u.replace('"', "").startswith("www.melty.fr"): halo[v[u]] = True else: halo[v[u]] = False idx = label_category.index(pages[pages.url == u].category.values[0]) color_category[v[u]] = colormap_category[idx + 1].tolist() idx = label_topic.index( pages[pages.url == u].topic.values[0]) color_topic[v[u]] = colormap_topic[idx + 1].tolist() session.apply( lambda x: g.add_edge(v[x.referrer_url], v[x.requested_url]), axis=1) graph_draw( g, vertex_halo=halo, vertex_fill_color=color_category, output="Latex/Graphs/session" + str(id) + ".png") graph_draw( g, vertex_halo=halo, vertex_fill_color=color_category, output="shared/session" + str(id) + ".svg") graph_draw( g, vertex_halo=halo, vertex_fill_color=color_topic, output="Latex/Graphs/session" + str(id) + "_topic.png") graph_draw( g, vertex_halo=halo, vertex_fill_color=color_topic, output="shared/session" + str(id) + "_topic.svg") return def session_draw_bis(sessions_id, log): session = log[log.global_session_id==sessions_id] s_urls = session.requested_url s_urls = s_urls.append(session.referrer_url) s_urls.drop_duplicates(inplace=True) g = Graph() v = {} halo = g.new_vertex_property("bool") for u in s_urls: v[u] = g.add_vertex() if not u.replace('"', "").startswith("www.melty.fr"): halo[v[u]] = True else: halo[v[u]] = False session.apply(lambda x: g.add_edge(v[x.referrer_url], v[x.requested_url]), axis=1) graph_draw(g, vertex_halo=halo, output="Latex/Graphs/_session"+str(sessions_id)+".png") return
UTF-8
Python
false
false
5,516
py
17
graph.py
16
0.556744
0.54913
0
142
37.852113
110
merapa/untitled
2,224,793,074,549
fd62218a19c5dc72501f7beb8f382fd9da779692
e4de6c16d20e9d15241cafb87336d0da3a3f2d0b
/venv/work/test4.py
d29e6878043b683923bfd0c6226a37fdf9d51df9
[]
no_license
https://github.com/merapa/untitled
7647945f47ad30099b0ddf3be3d9da5e53a88788
0186edc765c1afc120e6464db78c9b8e05a77682
refs/heads/master
2020-05-07T22:22:02.555066
2019-04-12T08:57:51
2019-04-12T08:57:51
180,942,831
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
T = int(input()) for test_case in range(1, T + 1): N, M = map(int,input().split(" ")) wi = list(map(int, input().split())) ti = list(map(int, input().split())) carryed = 0 wi.sort() ti.sort() print(wi) print(ti) max_loop1 = len(wi) max_loop2 = len(ti) wi_max_index = len(wi) - 1 ti_max_index = len(ti) - 1 for i in range(max_loop1): for j in range(max_loop2): while wi_max_index >= 0 and ti_max_index >= 0 : if wi[wi_max_index] > ti[ti_max_index]: wi_max_index = wi_max_index-1 elif wi[wi_max_index] <= ti[ti_max_index]: carryed += wi[wi_max_index] wi_max_index = wi_max_index-1 ti_max_index=ti_max_index-1 break else: ti_max_index=ti_max_index-1 print("#"+str(test_case),carryed)
UTF-8
Python
false
false
928
py
5
test4.py
5
0.475216
0.459052
0
31
28.967742
59
anapaulamendes/validate-deploy
8,650,064,161,561
aac28d9c147b6221efd1922c225698dd0625e5bb
94452bdd10a32276aa1a29f6aedab1cdf5a2afc0
/core/tests/services/test_approvers_api.py
1aad9d498e8545110a28aa7fb7c7436087a7e1c7
[]
no_license
https://github.com/anapaulamendes/validate-deploy
b5afa345cc057d02636049116823b51b9303dfa8
c05d7937a4e356fbc997c4deb75a23cf47b1eea7
refs/heads/main
2023-06-08T19:47:02.307327
2021-03-15T20:46:41
2021-03-15T20:46:41
343,945,525
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from unittest.mock import Mock, patch from faker import Faker from rest_framework.test import APITestCase from core.services.approvers_api import ApproversAPI class ApproversAPITest(APITestCase): def setUp(self): self.fake = Faker() self.approvers_api_wrapper = ApproversAPI() self.json = {"approvers": [self.fake.email(), self.fake.email()]} @patch("requests.sessions.Session.get") def test_get_approvers(self, mock): mock.return_value = Mock(ok=True) mock.return_value.json.return_value = self.json mock.return_value.status_code = 200 resp = self.approvers_api_wrapper.get_approvers() self.assertEqual(resp.status_code, 200) self.assertEqual(resp.json(), self.json) @patch("requests.sessions.Session.get") def test_get_approvers_raise_exception(self, mock): mock.side_effect = Exception() with self.assertRaises(Exception): self.approvers_api_wrapper.get_approvers()
UTF-8
Python
false
false
995
py
22
test_approvers_api.py
15
0.683417
0.677387
0
28
34.535714
73
jaustinpage/frc_rekt
6,889,127,548,972
b23e0523f7e2d13ba2e6e08702fcc0e491ca4aa4
b536395bd2d8f173a9ee14e5b4db761db420b873
/tests/test_battery.py
2874318ba58771c88a809ac2c8bef6d0b28deb48
[ "MIT" ]
permissive
https://github.com/jaustinpage/frc_rekt
0e5adda094661cb29c65157a7b2c268ca97a393a
2b950712bc645bb39088105bd0561fa47970673b
refs/heads/master
2021-01-19T02:22:04.115853
2017-04-19T19:00:01
2017-04-19T19:00:01
86,247,544
5
0
MIT
false
2021-12-19T13:47:25
2017-03-26T16:32:42
2017-12-24T01:10:45
2019-03-06T19:07:14
127
5
0
0
Python
false
false
# -*- coding: UTF-8 -*- import pytest from frc_rekt.battery import Battery def test_init(): Battery() @pytest.fixture def battery(): return Battery() def test_voltage(battery): assert battery.voltage() == 13.2
UTF-8
Python
false
false
229
py
36
test_battery.py
21
0.659389
0.641921
0
17
12.470588
36
klowe0100/filebrowser-safe
2,654,289,812,499
fbafffbcb8bf517c8f8ac1e7350c60d7fb550baa
e4155ea1c752db8b33bae371f72e43bc05bdb232
/filebrowser_safe/compat.py
4f0f3c7a6dc643640675af8834e06fed846d9cdc
[ "BSD-2-Clause" ]
permissive
https://github.com/klowe0100/filebrowser-safe
2d811494bb1d7be0b99c3b4bbb5e9df29f54695e
1c489e67a99437a4d81f684681c4c1bae87409c0
refs/heads/master
2021-09-01T23:27:40.788763
2017-12-29T06:02:39
2017-12-29T06:02:39
115,570,491
0
0
null
true
2017-12-28T01:07:49
2017-12-28T01:07:49
2017-05-06T06:54:40
2017-12-22T18:26:03
1,058
0
0
0
null
false
null
import django django_version = django.VERSION is_gte_django2 = (django_version >= (2, 0)) if is_gte_django2: from django.urls import reverse else: from django.core.urlresolvers import reverse #noqa
UTF-8
Python
false
false
209
py
1
compat.py
1
0.732057
0.712919
0
10
19.9
54
SamKG/SNN-Edge-Detector
5,342,939,331,030
407444a60ea2c89e1141dbf3f606b9541f303741
cc16c5c7360b1c8436c2c8e42310606773248729
/vectorized/ganglion_layer.py
55f1602275f8efa2feb87c0be1485a9257c73f36
[ "MIT" ]
permissive
https://github.com/SamKG/SNN-Edge-Detector
b4d4df13c2c17042a4fbbbf49034d1fb2dc11b93
f29f21c4b207e7d84f81f451f3eb677c0be98f0c
refs/heads/master
2020-05-09T11:01:06.639979
2019-05-30T19:38:59
2019-05-30T19:38:59
181,063,743
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from parameters import * from brian2 import * from brian2tools import * GanglionLayer = NeuronGroup(NUM_NEURONS, eqs, threshold='v > 10*mV', reset='v = 0*mV', refractory=REFRACTORY_TIME, method=INTEG_METHOD) GanglionLayer.v = 0*mV # initialize voltages to 0 GanglionLayer.a = 0
UTF-8
Python
false
false
300
py
21
ganglion_layer.py
18
0.703333
0.676667
0
8
36.375
86
poleha/tatamo
4,999,341,935,888
50b0323cbc717288b36e2261cc02570ec88597b3
a24c6b538c570d875c71a0bbce2f2312be1972a0
/discount/urls.py
cca948f0a51d52f4451969042bcb19e78790b9c5
[]
no_license
https://github.com/poleha/tatamo
b0eeac227e2fdb14aa1e9fc1ff942691cb279ae0
de57199be4a1cbfa2b1f519debc4d2f742bfd63f
refs/heads/master
2021-03-12T20:41:17.918056
2015-12-30T19:58:56
2015-12-30T19:58:56
30,707,477
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url from discount import views #from django.views.decorators.cache import cache_page urlpatterns = patterns('discount.views', #cart #url(r'^cart_add/(?P<pk>\d+)/$', views.AddProductToCart.as_view(), kwargs={'action': 'add'}, name='cart-add'), #url(r'^cart_remove/(?P<pk>\d+)/$', views.AddProductToCart.as_view(), kwargs={'action': 'remove'}, name='cart-remove'), url(r'^cart/$', views.CartView.as_view(), name='cart-view'), #'discount/cart/cart_view.html' url(r'^instant_cart/$', views.CartView.as_view(), name='instant-cart-view', kwargs={'action': 'instant'}), #'discount/cart/cart_view.html' url(r'^cart_remove_from_cart/$', views.CartView.as_view(), kwargs={'action': 'remove'}, name='cart-remove-from-cart'), #!!!! url(r'^cart_clear/$', views.CartView.as_view(), kwargs={'action': 'clear'}, name='cart-clear'), #!!! url(r'^cart_remove_expired/$', views.CartView.as_view(), kwargs={'action': 'remove-expired'}, name='cart-remove-expired'), #!!! url(r'^cart_finish/$', views.CartView.as_view(), name='cart-finish', kwargs={'action': 'finish'} ), #!!! #url(r'^cart/view/(?P<link>[a-zA-Z0-9_]{1,})/$', views.CartViewLink.as_view(), name='cart-view-link'), #'discount/cart/cart_view_link.html' #url(r'^cart/list/$', views.CartList.as_view(), name='cart-list'), #'discount/cart/cart_list.html' #cart-product url(r'^coupon/(?P<pk>\d+)/$', views.ProductCartView.as_view(), name='coupon-view', kwargs={'type': 'normal'}), #'discount/product/product_cart_view.html' #!!! url(r'^c/(?P<pk>\d+)/(?P<uid>\d+)/(?P<pin>\d+)/$', views.ProductCartView.as_view(), name='qr-coupon-view', kwargs={'type': 'qr'}), #'discount/product/product_cart_view.html' #!!! #Одиночная акция, на которую мы уже подписаны. Попадаем с основной страницы акции. Выводит изменения даты, статуса, размеров и цветов с момента подписки. url(r'^product/pdf_view/(?P<pk>\d+)/$', views.SingleProductPDFView.as_view(), name='product-pdf-view'), #!!! #PDF - аналог coupon-view url(r'^qr-code/(?P<data>[a-zA-Z0-9\-\/_\:\.]{1,})/$', views.coupon_qr_code_view, name='coupon-qr-code-view'), #!!! #product url(r'^product/detail/(?P<pk>\d+)/$', views.ProductDetail.as_view(), kwargs={'type': 'pk'}, name='product-detail'), #'discount/product/product_detail.html' url(r'^product/detail/(?P<code>[a-zA-Z0-9_]{1,})/$', views.ProductDetail.as_view(), kwargs={'type': 'code'}, name='product-detail-code'), #'discount/product/product_detail.html' url(r'^product/list/(?P<alias>[a-z0-9_]{1,})/$', views.ProductList.as_view(), name='product-list'), #'discount/product/product_list.html' url(r'^product/create/$', views.ProductCreate.as_view(), name='product-create'), #'discount/product/product_create.html' url(r'^product/update/(?P<pk>\d+)/$', views.ProductCreate.as_view(), name='product-update'), #'discount/product/product_create.html' url(r'^generate_product_code/$', views.GenerateProductCode.as_view(), name='generate-product-code'), #!!! url(r'^get_product_by_code', views.GetProductByCode.as_view(), name='get-product-by-code'), #!!! url(r'^left_menu/(?P<alias>[a-z0-9_]{1,})/$', views.ProductListFilterForm.as_view(), name='product-list-filter-form'), #'discount/product/_product_list_filter_form.html' #!!! url(r'^product/shop_list/$', views.ProductList.as_view(), name='product-list-shop', kwargs={'type': 'shop'}), #'discount/product/product_list.html' #!!! url(r'^left_menu_shop/$', views.ProductListFilterForm.as_view(), name='product-list-filter-form-shop', kwargs={'type': 'shop'}), #'discount/product/_product_list_filter_form.html' #!!! url(r'^product/code_list/$', views.ProductList.as_view(), name='product-list-code', kwargs={'type': 'code'}), #'discount/product/product_list.html' #!!! url(r'^left_menu_code/$', views.ProductListFilterForm.as_view(), name='product-list-filter-form-code', kwargs={'type': 'code'}), #'discount/product/_product_list_filter_form.html' #!!! url(r'^product/finished_code_list/$', views.ProductList.as_view(), name='product-list-finished-code', kwargs={'type': 'finished-code'}), #'discount/product/product_list.html' #!!! url(r'^left_menu_finished_code/$', views.ProductListFilterForm.as_view(), name='product-list-filter-form-finished-code', kwargs={'type': 'finished-code'}), #'discount/product/_product_list_filter_form.html' #!!! url(r'^get_available_product_types_ajax', views.GetAvailableProductTypesAjax.as_view(), name='get-available-product-types-ajax'), #!!! url(r'^get_available_filters_ajax', views.GetAvailableFiltersAjax.as_view(), name='get-available-filters-ajax'), #!!! url(r'^product/banners/(?P<pk>\d+)/$', views.ProductBannersView.as_view(),name='product-banners'), #'discount/product/product_detail.html' #!!! url(r'^product/start/(?P<pk>\d+)/$', views.ProductStartView.as_view(),name='product-start'), #'discount/product/product_detail.html' #!!! url(r'^product/change/(?P<pk>\d+)/$', views.ProductChangeView.as_view(), name='product-change'), #'discount/product/product_detail.html' #!!! #url(r'^product/change/update/(?P<pk>\d+)/$', views.ProductChangeView.as_view(), kwargs={'type': 'update'}, name='product-change-existing'), #'discount/product/product_detail.html' #url(r'^banner/send_to_approve/$', views.SendBannerToApproveView.as_view(), name='send-banner-to-approve'), #'discount/product/product_detail.html' url(r'^product/export/all/$', views.ExportProductsToCsvView.as_view(), name='product-export-all'), #'discount/product/product_list.html' #!!! url(r'^subscribed_to_product/(?P<pk>\d+)/$', views.SubsribedToProductView.as_view(), kwargs={'action': 'subscribed'}, name='subscribed_to_product'), #!!! url(r'^cart_to_product/(?P<pk>\d+)/$', views.SubsribedToProductView.as_view(), kwargs={'action': 'cart'}, name='cart_to_product'), #!!! url(r'^bought_to_product/(?P<pk>\d+)/$', views.SubsribedToProductView.as_view(), kwargs={'action': 'bought'}, name='bought_to_product'), #!!! url(r'^product_stat_save/(?P<pk>\d+)/$', views.ProductStatSaveView.as_view(), name='product-stat-save'), url(r'^products_stat/$', views.ProductsStatView.as_view(), name='products-stat'), #'discount/product/product_list.html' #!!! #product_to_cart #url(r'^ptc_subscribe_view/(?P<pk>\d+)/$', views.PTCSubscribe.as_view(), name='ptc-subscribe-view'), #url(r'^cart_actions/(?P<pk>\d+)/$', views.CartActions.as_view(), name='cart-actions'), url(r'^ptc_add/(?P<pk>\d+)/$', views.PtcAdd.as_view(), name='ptc-add'), #!!! url(r'^ptc_subscribe/(?P<pk>\d+)/$', views.PtcSubscribe.as_view(), name='ptc-subscribe'), #!!! url(r'^coupon_status/(?P<pk>\d+)/$', views.CouponStatus.as_view(), name='coupon-status'), #!!! #general url(r'^$', views.MainPage.as_view(), name='main-page'), #'discount/general/main_page.html' #shop url(r'^shop/detail/(?P<pk>\d+)/$', views.ShopDetail.as_view(), name='shop-detail'), #'discount/shop/shop_detail.html' #!!! url(r'^shop/list/$', views.ShopList.as_view(), name='shop-list'), #'discount/shop/shop_list.html' url(r'^shop/create/$', views.ShopCreate.as_view(), name='shop-create'), #'discount/shop/shop_list.html' #!!! #url(r'^shop/update/(?P<pk>\d+)/$', views.ShopUpdate.as_view(), name='shop-update'), url(r'^shop/update/(?P<pk>\d+)/$', views.ShopCreate.as_view(), name='shop-update'), #'discount/product/product_create.html' #!!! #user url(r'^ajax_login/$', views.DiscountLoginView.as_view(), name='login'), #'discount/user/_login.html' #!!! url(r'^login/$', views.DiscountFullLoginView.as_view(), name='full-login'), #'discount/user/_login.html' url(r'^signup/$', views.DiscountSignupView.as_view(), name='signup'), #'discount/user/_login.html' url(r'^cart_login/$', views.DiscountCartLoginView.as_view(), name='cart-login'), url(r'^cart_signup/$', views.DiscountCartSignupView.as_view(), name='cart-signup'), url(r'^user/$', views.UserDetail.as_view(), name='user-detail'), #'discount/user/user_detail.html' #!!! url(r'^shops_to_users_confirm/$', views.ShopsToUsersConfirm.as_view(), name='shops-to-users-confirm'), #'discount/user/user_detail.html' #!!! url(r'^change_password/$', views.ChangePasswordView.as_view(), name='change-password'), #'discount/user/_login.html' #!!! #static url(r'^contacts', views.ContactsPageView.as_view(), name='contacts-page'), #'discount/user/_login.html' url(r'^help', views.HelpPageView.as_view(), name='help-page'), #'discount/user/_login.html' url(r'^shop_offer', views.ShopOfferView.as_view(), name='shop-offer'), #'discount/user/_login.html' url(r'^shop_instructions', views.ShopInstructionsView.as_view(), name='shop-instructions'), #adm url(r'^tatamo_manager/$', views.TatamoManagerPageView.as_view(), name='tatamo-manager-page'), #!!! url(r'^load_products/$', views.AdmLoadProductsView.as_view(), name='load-products'), #!!! url(r'^monitor/$', views.AdmMonitorView.as_view(), name='monitor'), #!!! url(r'^product/tatamo_list/$', views.ProductList.as_view(), name='product-list-tatamo', kwargs={'type': 'tatamo'}), #'discount/product/product_list.html' #!!! url(r'^left_menu_tatamo/$', views.ProductListFilterForm.as_view(), name='product-list-filter-form-tatamo', kwargs={'type': 'tatamo'}), #'discount/product/_product_list_filter_form.html' #!!! url(r'^product_tatamo_manager_approve/(?P<pk>\d+)/$', views.ProductTatamoManagerApproveView.as_view(), name='product-tatamo-manager-approve'), #!!! url(r'^shops_monitor/$', views.AdmShopsMonitorView.as_view(), name='shops-monitor'), #!!! url(r'^users_monitor/$', views.AdmUsersMonitorView.as_view(), name='users-monitor'), #!!! url(r'^product_doubles_monitor/$', views.AdmProductDoublesMonitorView.as_view(), name='product-doubles-monitor'), #!!! url(r'^check_products_links/$', views.AdmCheckProductsLinks.as_view(), name='check-products-links'), #!!! )
UTF-8
Python
false
false
10,162
py
138
urls.py
46
0.661051
0.659555
0
137
72.211679
215
ArunBalajiR/Python-HackerRank-Solutions
12,756,052,909,675
eae02e9016e2bc4e4e34106290eaa81b675c5118
70fa51c3a23996080d38052190b9e9ba45345027
/13. Regex and Parsing/Re.findall() & Re.finditer().py
e9afb6c62224b1063be44e4b0a1eccdf2bc2c421
[]
no_license
https://github.com/ArunBalajiR/Python-HackerRank-Solutions
8f2688986d60f6cf94531e6a5a7483647217ba08
6c3ef012f04a446a249f9e74ab5ada6b0e80770f
refs/heads/master
2022-11-17T05:20:09.339118
2020-07-14T08:58:34
2020-07-14T08:58:34
277,461,821
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re r=re.findall(r'(?<=[QWRTYPSDFGHJKLZXCVBNM])[aeiou]{2,}(?=[QWRTYPSDFGHJKLZXCVBNM])',input(),re.IGNORECASE) if len(r) == 0: print(-1) else: for i in r: print(i)
UTF-8
Python
false
false
186
py
66
Re.findall() & Re.finditer().py
65
0.612903
0.596774
0
8
22.25
105
FriskySaga/Pirates-Online-Rewritten
16,458,314,706,873
a8a5b4a4d98182a6fc3ec92cae5ef53844df92fe
e78db6dca6aac99de09a5bac2882b943b5e1586b
/pirates/teleport/DistributedFSMBase.py
07214c3d59eb03bc3a6ea7c57a66c9304714d1cf
[ "BSD-3-Clause" ]
permissive
https://github.com/FriskySaga/Pirates-Online-Rewritten
cd808aa096a60af93a6b2ed94ac384d187389948
999e52d47ae75d0f42e955910a4089d84274d020
refs/heads/main
2023-02-06T23:59:53.281112
2020-12-27T01:50:58
2020-12-27T01:50:58
324,483,700
0
0
null
true
2020-12-26T04:51:19
2020-12-26T04:51:18
2020-12-08T05:27:53
2018-09-25T00:13:30
15,226
0
0
0
null
false
false
from direct.fsm.FSM import FSM, FSMException, AlreadyInTransition, RequestDenied class DistributedFSMBase(FSM): pass class DistributedFSMErrors(): Undefined = 0 Success = Undefined Undefined += 1 InTransition = Undefined Undefined += 1 RequestDenied = Undefined Undefined += 1 AlreadyInState = Undefined Undefined += 1
UTF-8
Python
false
false
361
py
260
DistributedFSMBase.py
252
0.709141
0.695291
0
16
21.625
80
tazoe5/tda_for_python
6,622,839,594,338
1e9ef38f5c77182d935902d2e80c8e55c72b82a8
c7534f5cedfd439c9ccb0f116e6436dc3a670240
/chaos.py
2edcba1962db2d35eb035e258022733e6d014e38
[]
no_license
https://github.com/tazoe5/tda_for_python
69d13bc55979784bca6904a23640a56319a1b491
10945c635345052c9e6d09cf8c0b04c06432c91d
refs/heads/master
2020-04-09T11:56:03.241545
2018-12-04T09:24:38
2018-12-04T09:24:38
160,329,471
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding:utf-8 import wave import scipy as sp import numpy as np import matplotlib.pyplot as plt import random import os import scandir from argparse import ArgumentParser def wave_load(filename): # open wave file wf = wave.open(filename,'r') channels = wf.getnchannels() # load wave data chunk_size = wf.getnframes() amp = (2**8) ** wf.getsampwidth() / 2 data = wf.readframes(chunk_size) # バイナリ読み込み data = np.frombuffer(data,'int16') # intに変換 data = data / amp # 振幅正規化 data = data[::channels] return data def embedding_phase_space(input_path,size, delay_time, dim=2): ''' input_path = 入力信号のパス size = FFTのサンプル数(2**n) ''' _, name = os.path.split(input_path) name, _ = os.path.splitext(name) st = 10000 # サンプリングする開始位置 hammingWindow = np.hamming(size) # ハミング窓 fs = 44100 #サンプリングレート d = 1.0 / fs #サンプリングレートの逆数 freqList = np.fft.fftfreq(size, d) wave = wave_load(input_path) windowedData = hammingWindow * wave[st:st+size] # 切り出した波形データ(窓関数あり) data = np.fft.fft(windowedData) data /= max(abs(data)) chaos_vectors = [] for time in np.arange(dim-1, len(data)): p = [data[time - delay_time*i] for i in np.arange(dim)] chaos_vectors.append(p) chaos_vectors = np.array(chaos_vectors).real print("file name: {}".format(name)) print("delay time: {}".format(delay_time)) print("embedding shape: {}".format(chaos_vectors.shape)) return chaos_vectors, name def plot_embedding_points(position, delay_time, name="", is_save=False): if position.ndim == 3: _, _ , dim = position.shape if dim == 2: plot_2ds(position, delay_time, name, is_save) elif dim == 3: plot_3ds(position, delay_time, name, is_save) elif position.ndim == 2: _, dim = position.shape if dim == 2: plot_2d(position, delay_time, name, is_save) elif dim == 3: plot_3d(position, delay_time, name, is_save) plt.clf() def plot_2d(position, delay_time, name="", is_save=False): print("plot_2d") plt.xlabel("p(t)") plt.ylabel("p(t-{})".format(delay_time)) plt.title("Delay Coordinate Embedding 2D") X, Y = position[:, 0], position[:, 1] plt.scatter(X, Y, label=name) plt.legend() if is_save: dir_path = "./result_dce/2D/" if not os.path.exists(dir_path): os.makedirs(dir_path) name = dir_path + "dce{}_{}.png".format(delay_time, name) plt.savefig(name) plt.clf() else: plt.show() def plot_3d(position, delay_time, name="", is_save=False): from mpl_toolkits.mplot3d import Axes3D X, Y, Z = position[:, 0], position[:, 1], position[:, 2] fig = plt.figure() ax = Axes3D(fig) ax.set_xlabel("p(t)") ax.set_ylabel("p(t-1)") ax.set_zlabel("p(t-2)") ax.plot(X, Y, Z, "o", label=name) plt.title("Delay Coordinate Embedding 3D") plt.legend() plt.show() def plot_2ds(positions, delay_time, names="", is_save=False): #, fig=None): print("plot_2ds") plt.xlabel("p(t) {} delay time:{}".format(" "*30, delay_time)) plt.ylabel("p(t-{})".format(delay_time)) plt.title("Delay Coordinate Embedding 2D") for position, name in zip(positions, names): X, Y = position[:, 0], position[:, 1] plt.scatter(X, Y, label=name) plt.legend() if is_save: dir_path = "./result_dce/2D/" if not os.path.exists(dir_path): os.makedirs(dir_path) name = dir_path + "dce{}.png".format(delay_time) plt.savefig(name) plt.clf() else: plt.show() def plot_3ds(positions, delay_time, names="", is_save=False): from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) plt.title("Delay Coordinate Embedding 3D") ax.set_xlabel("p(t)") ax.set_ylabel("p(t-1)") ax.set_zlabel("p(t-2)") for position, name in zip(positions, names): X, Y, Z = position[:, 0], position[:, 1], position[:, 2] ax.plot(X, Y, Z, "o", label=name) plt.legend() plt.show()
UTF-8
Python
false
false
4,362
py
8
chaos.py
4
0.58417
0.568627
0
143
28.244755
75
bekk-studio/Astek-etude-tondeuse-autonome
16,174,846,874,793
a2dcadde1e6487627bc4b4681ce85f833c374bb5
dcefcd767067736bb5d343e01ded03fe67b6c0a5
/gazon.py
9b749bb4e45e33a10f0a3dbb69bdbfe5191cd381
[]
no_license
https://github.com/bekk-studio/Astek-etude-tondeuse-autonome
2c0b09f695723554653a75ab1026b17374a44242
59699ecfaa8949bb00073615e0e54ff3567af88b
refs/heads/master
2020-04-12T20:11:24.306179
2018-12-21T15:49:15
2018-12-21T15:49:15
162,728,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import sys from six import StringIO, b from gym import utils from gym.envs.toy_text import discrete FORWARD = 0 TURNRIGHT = 1 TURNLEFT = 2 """orientation 0 3 1 2 """ MAPS = { "4x4": [ "SPPP", "PPPP", "PPPP", "PPBG" ], "8x8": [ "SPPPPPPP", "PPPPPPPP", "PPPPPPPP", "PPPPPPPP", "PPPPPBPP", "PPPPPPPP", "PPPPPPPP", "PPPPPPPG" ], "8x16": [ "SPPPPPPPPPPPPPPP", "PPPPPPPPPPPPPPPP", "PPPPPPPPPPPPPPPP", "PPPPPPPPPPPPPPPP", "PPPPPBPPPPPPPPPP", "PPPPPPPPPPPPPPPP", "PPPPPPPPPPPPPPPP", "PPPPPPPPPPPPPPPG" ] } class gazonEnv(discrete.DiscreteEnv): """ Gazon à tondre S : starting point, safe P : terrain plat B: terrain pentu X: terrain interdit L'episode fini lorsque tout le gazon a été tondu """ metadata = {'render.modes': ['human', 'ansi']} def __init__(self, desc=None, map_name="4x4",is_slippery=False, orientation=0): if desc is None and map_name is None: raise ValueError('Must provide either desc or map_name') elif desc is None: desc = MAPS[map_name] self.desc = desc = np.asarray(desc,dtype='c') self.nrow, self.ncol = nrow, ncol = desc.shape row, col = np.where(np.array(self.desc == b'S'))[0][0], np.where(np.array(self.desc == b'S'))[1][0] position = row*ncol + col self.state = position, orientation self.nA = 3 self.nO = 4 self.nS = nrow * ncol * self.nO self.startstate = self.state #isd = np.array(desc == b'S').astype('float64').ravel() #isd /= isd.sum() self.mowed = np.array(desc == b'S').astype(int) + np.array(desc == b'X').astype(int) #P = {s : {a : [] for a in range(nA)} for s in range(nS)} def reset(self): self.state = self.startstate self.mowed = np.array(self.desc == b'S').astype(int) + np.array(self.desc == b'X').astype(int) return self.state def step(self, action, forward_reward=-1, turn_reward=-1, mowing_reward=2 ): reward = 0 position, orientation = self.state if action==0: # forward row, col = position//self.nrow, position%self.nrow if orientation == 0: row = max(row-1,0) elif orientation == 1: col = min(col+1,self.ncol-1) elif orientation == 2: row = min(row+1,self.nrow-1) elif orientation == 3: col = max(col-1,0) position = row*self.ncol + col reward += forward_reward elif action==1: # right orientation = (orientation + 1) % 4 reward += turn_reward elif action==2: # left orientation = (orientation - 1) % 4 reward += turn_reward next_state = position, orientation self.state = next_state position, orientation = self.state row, col = position//self.nrow, position%self.nrow if self.mowed[row][col] == 0: reward += mowing_reward self.mowed[row][col] = 1 done = False if np.sum(self.mowed) == self.nrow * self.ncol: done = True return next_state, reward, done # obtain one-step dynamics for dynamic programming setting #self.P = P super(gazonEnv, self).__init__(nS, nA, P, isd) """def _render(self, mode='human', close=False): if close: return outfile = StringIO() if mode == 'ansi' else sys.stdout row, col = self.s // self.ncol, self.s % self.ncol desc = self.desc.tolist() desc = [[c.decode('utf-8') for c in line] for line in desc] desc[row][col] = utils.colorize(desc[row][col], "red", highlight=True) if self.lastaction is not None: outfile.write(" ({})\n".format(["Left","Down","Right","Up"][self.lastaction])) else: outfile.write("\n") outfile.write("\n".join(''.join(line) for line in desc)+"\n") if mode != 'human': return outfile"""
UTF-8
Python
false
false
4,330
py
3
gazon.py
1
0.522764
0.510978
0
155
26.916129
107
binweil/Point-Cloud-Rtabmap
7,155,415,519,047
5645cd31b6f64d11b98248702ca695c170adc96d
aa9c4242e3cf45fc5ed739d80e012c44c8d9c2b9
/data/process_data.py
c3cf0c35a2b232f107c3eba837dc0ce8accbf09a
[]
no_license
https://github.com/binweil/Point-Cloud-Rtabmap
e1d767df06c80e51e0675527c8a551898362a925
e72f003dbcf6fcbed9aff3b11c0e968675198774
refs/heads/master
2020-04-30T13:30:36.375401
2019-04-05T23:39:29
2019-04-05T23:39:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import csv def write_csv_file(fname): text_file = open(fname, "r") out_file = open("out_file.csv","w") with open(fname, 'r') as f: lines = f.readlines() #print(lines) lines_red = lines[11:] for lin in lines_red: mystring = lin.replace(" ", ",") print(mystring) out_file.write(mystring) write_csv_file("rtabmap_cloud.pcd")
UTF-8
Python
false
false
354
py
12
process_data.py
5
0.644068
0.638418
0
15
22.533333
36
AronsonDan/FlaskRestAPI
1,013,612,317,374
fa32b35062f0709879b5a310aaca7e675b69acb0
905e368900ef53c65854c9771e86637dba03f675
/resources/user.py
b9efc622f6f70657d0671707a601f6bb1075fad9
[]
no_license
https://github.com/AronsonDan/FlaskRestAPI
817e95286d25c2cba1a9bbeb222da6e23bc0071a
05fa50c9cc839d4bb83cf3c60943420e5eb103db
refs/heads/master
2020-12-02T22:16:29.719149
2017-07-05T09:51:10
2017-07-05T09:51:10
96,106,727
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from flask_restful import Resource, reqparse from models.usermodel import UserModel class UserRegister(Resource): def __init__(self): self.user_roles = ["Admin", "User"] parser = reqparse.RequestParser() parser.add_argument('username', required=True, type=str, help="username was not specified in the request, the request cannot be processed" ) parser.add_argument('password', required=True, type=str, help="password was not specified in the request, the request cannot be processed" ) parser.add_argument('role', required=True, type=str, help="Role was not specified in the request, the request cannot be processed" ) def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "User already exists"}, 400 user = UserModel(**data) if user.role in self.user_roles: user.save_to_db() return {"message": "User created successfully"}, 201 else: return {"message": "{}, is not a possible role. user creation failed"}.format(data['role']), 422 # Unprocessable entity.
UTF-8
Python
false
false
1,443
py
3
user.py
2
0.53569
0.529453
0
39
36
132
mew177/vote-api
3,186,865,782,290
9966be3b36983b3b477aac190b8c469433aa1754
f7f28cfcfbea56c7000681534bfe64f23212e3e5
/vote-api/lib/python3.6/copy.py
1055a277c1986c4f04b503b7bd4514bd83178a6a
[]
no_license
https://github.com/mew177/vote-api
c26ad2b508f39418eb91cc366f1e7355176d0945
b95e29c9223636d12d34de817035f164dd71d1d4
refs/heads/master
2023-08-03T14:17:29.651960
2020-06-19T03:20:11
2020-06-19T03:20:11
273,392,080
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/Users/Rycemond/anaconda3/lib/python3.6/copy.py
UTF-8
Python
false
false
47
py
48
copy.py
45
0.829787
0.765957
0
1
47
47
junha6316/Algorithm
9,723,805,974,868
0f4023f5854e98029174ab02da9db359f98921f4
94c470dd24251e8093b0e62e2966589bbd23773b
/0807_NormalNapSack_12865.py
5c65595f0b5810f8a96ae0005c4c2ff2d9530d86
[]
no_license
https://github.com/junha6316/Algorithm
eb9f4d4c4691881eb0842c2e73a56e4265a4cd82
2181e08694b105070a88f631be54f0449a4b7c67
refs/heads/master
2023-01-15T23:34:30.855847
2020-11-25T14:19:32
2020-11-25T14:19:32
283,513,806
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
N, K = map(int, input().split()) W, V =[0], [0] for i in range(N): w,v =map(int, input().split()) W.append(w) V.append(v) dp =[[0 for i in range(K+1)] for i in range(N+1)] for i in range(1, N+1): for j in range(1, K+1): if j < W[i]: dp[i][j] =dp[i-1][j] else: dp[i][j] = max(V[i]+dp[i-1][j -W[i]], dp[i-1][j]) for i in dp: print(i)
UTF-8
Python
false
false
400
py
197
0807_NormalNapSack_12865.py
190
0.445
0.415
0
19
19.736842
61
cms-sw/cmssw-cfipython
18,287,970,751,283
07a764c19d51111f828629ec93051a0c90653b98
3996539eae965e8e3cf9bd194123989741825525
/HLTrigger/JetMET/hltMETCleanerUsingJetID_cfi.py
5c3aca46feb94359a17bb8cc89560144082d0dc7
[]
no_license
https://github.com/cms-sw/cmssw-cfipython
01990ea8fcb97a57f0b0cc44a8bf5cde59af2d98
25ee4c810103c4a507ca1b949109399a23a524c5
refs/heads/CMSSW_11_2_X
2023-09-01T16:56:00.658845
2022-06-20T22:49:19
2022-06-20T22:49:19
136,184,115
1
0
null
false
2022-10-19T14:04:01
2018-06-05T13:47:28
2022-06-20T22:49:26
2022-10-19T13:48:13
1,145
1
1
0
Python
false
false
import FWCore.ParameterSet.Config as cms hltMETCleanerUsingJetID = cms.EDProducer('HLTMETCleanerUsingJetID', minPt = cms.double(20), maxEta = cms.double(5), metLabel = cms.InputTag('hltMet'), jetsLabel = cms.InputTag('hltAntiKT4CaloJets'), goodJetsLabel = cms.InputTag('hltCaloJetIDPassed'), mightGet = cms.optional.untracked.vstring )
UTF-8
Python
false
false
349
py
838
hltMETCleanerUsingJetID_cfi.py
838
0.762178
0.750716
0
10
33.9
67
DX3906W/NLP-practice
15,633,681,004,534
7358f3a4e077ee907fcc95bdb4de1b1f67f23596
1e71d0d4d5a0f71746582515d18e83cee8daf8d5
/Competition/Interview/extract_pdf.py
c305f147665e5ea67a73098f4d44c69fef21748f
[]
no_license
https://github.com/DX3906W/NLP-practice
afbfe74223da4b7aa43d5cda4cc01c22d79215cd
2fabd63273d1b6e2b7759d3c2983413022f65104
refs/heads/master
2020-12-14T14:05:01.612242
2020-07-02T04:53:32
2020-07-02T04:53:32
242,247,010
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pdfplumber import numpy as np import appConfig import os def read_pdf(file_path): with pdfplumber.open(file_path) as pdf: print('='*10, 'Start to read pdf file, totally ', len(pdf.pages), ' pages', '='*10) pdf_text = [] page_num = len(pdf.pages) for index, page in enumerate(pdf.pages): page_text = page.extract_text() print('-'*10, 'reading ', index+1, ' page', '-'*10) pdf_text.append(page_text) return pdf_text def write_txt(file_path, file_text): with open(file_path, 'w') as f: for page_text in file_text: f.write(page_text) def get_data(): print(appConfig.file_path) get_dir = os.listdir(appConfig.file_path) data = [] print('='*10, 'totally ', len(get_dir), ' file(s)', '='*10) for index, file in enumerate(get_dir): txt_data = [] sub_dir = os.path.join(appConfig.file_path, file) #print(sub_dir) print('-'*10, 'reading ', index+1, ' now', '-'*10) with open(sub_dir, 'r') as f: for line in f.readlines(): txt_data.append(line.replace('\n', '')) data.append(' '.join(txt_data)) print(txt_data) return data if __name__ == '__main__': pdf_text1 = read_pdf("C:/Users/dell1/Downloads/take_home_task(Gekko)/take_home_task(Gekko)/example1/example1.pdf") pdf_text2 = read_pdf("C:/Users/dell1/Downloads/take_home_task(Gekko)/take_home_task(Gekko)/example2/example2.pdf") write_txt('F:/mygit/NLP-practice/Competition/Interview/data/file1.txt', pdf_text1) write_txt('F:/mygit/NLP-practice/Competition/Interview/data/file2.txt', pdf_text2)
UTF-8
Python
false
false
1,724
py
60
extract_pdf.py
33
0.581206
0.563805
0
47
34.638298
118
N140191/Hacktoberfest-JKLU
15,101,105,032,818
05dbe7d27df3eaf0cefeeb7ceead2a1dd9b4782f
ae4d258f7bd0938bffe899a5b58e51489eb529ec
/data/aman.py
ccd3d846bcf476857cd927f0776bc008203914fe
[]
no_license
https://github.com/N140191/Hacktoberfest-JKLU
6ebea50af20076aef830ef705c805ca8e9b99b74
4df737d7cb0ad72151e5fbefdfdb2579d21f9456
refs/heads/master
2023-01-03T23:07:10.730073
2020-10-22T04:36:31
2020-10-22T04:36:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
name="Aman Kumar Gupta" year="Second" Branch="Computer science" print("Hello Every one this is ",name," from ",year," year . Hacktober fest is cool")
UTF-8
Python
false
false
150
py
20
aman.py
19
0.72
0.72
0
4
36.5
85
howaitoreivun/no_blocking_io
17,669,495,480,244
127dd79bd376961500d2e5611727cc522304d041
8231b244f9ce61b7f76f6b606dfe38c2087080d8
/no_blocking_io/__init__.py
207504d454bed96ab00b9b5d0fe49107b932000d
[ "MIT" ]
permissive
https://github.com/howaitoreivun/no_blocking_io
034f4bbfd0cc49085d3cfac41649271416734b05
e3bf89379f8060fa9625802d90c96124e3a8e525
refs/heads/main
2023-03-19T19:06:14.999621
2023-03-18T11:49:57
2023-03-18T11:49:57
348,296,710
0
0
null
false
2021-03-17T10:38:13
2021-03-16T10:02:40
2021-03-17T10:37:11
2021-03-17T10:38:13
1
0
0
0
null
false
false
import asyncio import functools from typing import Callable __all__ = ["to_thread"] def to_thread(func: Callable): """Asynchronously run function `func` in a separate thread""" @functools.wraps(func) async def wrapper(*args, **kwargs): partial = functools.partial(func, *args, **kwargs) coro = asyncio.to_thread(partial) return await coro return wrapper
UTF-8
Python
false
false
399
py
3
__init__.py
1
0.666667
0.666667
0
17
22.470588
65
rayhunglu/CS534-Machine-Learning
8,143,258,037,049
66e6f14adb63020dd380351ab1934c32b0209a15
3c2baa50e08d88e861cdb8cee2c558c3c88d4dff
/Implementation 3/decisionTree/adaboost.py
972d09987e144143b4feeb0d8205db9eba1b3912
[]
no_license
https://github.com/rayhunglu/CS534-Machine-Learning
167ce4c0c2f1c6b473dd4f436b4822aca3193d38
32b86a28ad82bcbcdb21822cdb4029b177aeeac1
refs/heads/master
2020-04-02T03:18:54.708860
2019-09-02T04:17:29
2019-09-02T04:17:29
153,957,879
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import decisionTree as dt import numpy as np from node import Node import math import datetime class adaboost: def __init__(self, depth, lNum, dataNum): self.wArr = [] self.L = lNum self.dtClass = dt.decesionTree(depth=depth, dataNum=dataNum) self.alphaSet = [] self.treeSet = [] self.weightInitValue = 1 def runAdaboost(self, df): self.wArr = np.ones(df.shape[0]) * self.weightInitValue # self.wArr = np.ones(df.shape[0]) * self.weightInitValue / df.shape[0] # self.normalizeWeightArr(df.shape[0]) val = self.dtClass.getLabelFromLargeData(df) for l in range(0, self.L): self.dtClass.setDataWeight(self.wArr) cl, cr = self.dtClass.getResultInfo(df) root = cur = Node((None, None, val)) self.dtClass.dicisionTree(df, cur, 0, cl, cr) alpha, errIdxArr = self.getAlphaVal(df, root) self.updWeightArr(df, alpha, errIdxArr) self.normalizeWeightArr(df.shape[0]) self.storeImpData(root=root, alpha=alpha) def updTrainData(self, df): df = df.mul(self.wArr, axis=0) df[0] = np.sign(df[0]) # W(1) * Alpha # Weight Update Rule => W(2) = W(1)* exp(Alpha * h(Xi) * -Yi) def computeFinalAccNumRate(self, df): fAccNum, dataNum = 0, df.shape[0] for dataIdx in range(0, dataNum): weight, tmp = self.weightInitValue, 0 for l in range(0, self.L): self.dtClass.predictRec(df.iloc[dataIdx:dataIdx + 1, :], self.treeSet[l]) isCorrect = 1 if self.dtClass.getAccNum() != 0 else -1 # isCorrect = -1 if dataIdx in self.errIdxSet[l] else 1 tmp += isCorrect * self.alphaSet[l] self.dtClass.resetAccNum() if np.sign(tmp) > 0: fAccNum += 1 return fAccNum / dataNum def normalizeWeightArr(self, dataNum): self.wArr = self.wArr / np.sum(self.wArr) self.wArr = self.wArr * dataNum def compNewWeight(self, alpha, isCorrect): return math.exp(alpha * isCorrect * -1) def getAlphaVal(self, df, root): totalNum = sum(self.wArr) accNum, errIdx = self.getAccAndErrInfo(df=df, root=root) errRate = (totalNum - accNum) / totalNum print("Error Rate = {0} Alpha = {1}".format(errRate, self.compAlphaByErr(errRate))) if errRate == 0: print("Loop {0} times find error rate = 0") return self.compAlphaByErr(errRate), errIdx def updWeightArr(self, df, alpha, errIdxArr): for dataIdx in range(0, df.shape[0]): isCorrect = -1 if dataIdx in errIdxArr else 1 self.wArr[dataIdx] *= self.compNewWeight(alpha, isCorrect) def getAccNum(self, df, root): self.dtClass.resetAccNum() self.dtClass.predictRec(df, root) return self.dtClass.getAccNum() def compAlphaByErr(self, errRate): return (1 / 2) * math.log((1 - errRate) / errRate) def storeImpData(self, root, alpha): self.alphaSet.append(alpha) self.treeSet.append(root) def getAccAndErrInfo(self, df, root): errIdx, accNum = [], 0 for dataIdx in range(0, df.shape[0]): self.dtClass.predictRec(df.iloc[dataIdx:dataIdx + 1, :], root) accNum += self.dtClass.getAccNum() if self.dtClass.getAccNum() == 0: errIdx.append(dataIdx) self.dtClass.resetAccNum() return accNum, errIdx
UTF-8
Python
false
false
3,647
py
9
adaboost.py
5
0.574445
0.562106
0
97
35.597938
91
sriharimaneru/askra-repo
4,818,953,349,261
756839cc190625b7f01a215355248c239e44fbfe
cf7ccb4436b47463cae030e36d2a00581def65f1
/src/askra/tag/admin.py
4a089d0cc86af4c7dd8ad8b6e66c4559c55e1212
[]
no_license
https://github.com/sriharimaneru/askra-repo
6fb434658d2c481172f2bca93543c736244cf651
190d61926fc299a49a98bf3a6f9ddbc0a6fb409c
refs/heads/master
2021-01-19T16:55:56.193144
2013-09-03T03:58:17
2013-09-03T03:58:17
5,722,415
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from tag.models import Tag class TagAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'category') list_filter = ('category',) search_fields = ('name',) admin.site.register(Tag, TagAdmin)
UTF-8
Python
false
false
240
py
42
admin.py
18
0.6875
0.6875
0
10
23
45
pramada517/Monkey
5,540,507,856,834
96ff12fa6a794f95dd3595fcf26f510b3129a183
4edaeefe8ad43372825b9365927524f0fcb8366d
/run.py
91637b5de231bf9b917f360cf4311d8925c803ce
[]
no_license
https://github.com/pramada517/Monkey
8647719e5e0445f018ebf162dc3a66f50aa84495
421ee6f70a8af2c9ae92a186710b7f30eb7bedd0
refs/heads/master
2021-01-21T19:28:22.394737
2015-06-02T20:22:37
2015-06-02T20:22:37
35,571,671
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!flask/bin/python from monkey import app from monkey.database import init_db init_db() app.run(debug=False)
UTF-8
Python
false
false
111
py
16
run.py
5
0.765766
0.765766
0
6
17.333333
35
feleHaile/my-isc-work
2,430,951,532,879
540f5f0633a040a536660b3cc1793277c664fbdf
2ba5d6343f872bc71b0adecf70761a6eba5f9b4d
/python_work_RW/10-sets-dictionaries.py
092c721b94cfbd3a18bb75654c9a8834fd04fdb7
[]
no_license
https://github.com/feleHaile/my-isc-work
9cac7d6a8cc3c10cdec9db6db876ce0056774217
85937c07085e0bf6ceddb7e0fc27e8c77cbf149e
refs/heads/master
2020-05-17T09:22:24.573666
2017-11-17T15:35:55
2017-11-17T15:35:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print print "Scripts and Libraries Exercise" print # part 1 - sets a = set([0, 1, 2, 3, 4, 5]) # creates a set, a b = set([2, 4, 6, 8]) # creates a set, b print a.union(b) # conjoins the two, but 2 and 4 don't appear twice as its a set print a.intersection(b) # prints the numbers where the two sets are the same print # just making a space in the output # part 2 - dictionaries band = ["Mel", "Geri", "Victoria", "Mel", "Emma"] # list counts = {} # creates an empty dictionary for member in band: # for every member in the band list: if member not in counts: # if member not in counts, counts[member] = 1 # add member name with the value "1" else: # if the member is already in counts, counts[member] += 1 # increase the value of the member by 1 for member in counts: # for each member in the counts dictionary, print member, counts[member] # print the member and the value # part 3 - altering and calling dictionaries UK = {"Edinburgh" : "Scotland", "Leeds" : "England"} # new dictionary if{"Scotland"}: print "Haggis" # calls out whether there is a value or not print "The items in UK dictionary: ", UK.items() print "The keys in UK dictionary: ", UK.keys() print "The values in UK dictionary: ", UK.values() print UK.get("Edinburgh") # calls out the key and returns the value UK["Reykjavik"] = "Yceland" # adds a new key and value to the dictionary UK["Reykjavik"] = "Iceland" # changes the value of a key in the dictionary print UK print
UTF-8
Python
false
false
1,473
py
25
10-sets-dictionaries.py
20
0.690428
0.677529
0
52
27.307692
80
Ing-Josef-Klotzner/python
9,552,007,306,946
e87e80c791f02c64f801d7f3f1f4816e38b9c341
a31de016611f3b4efc7a576e7113cad1a738419b
/_get_all_divisors.py
3e57fdb4bdfd8dfa9dcb7d57b88de01f6ed78159
[]
no_license
https://github.com/Ing-Josef-Klotzner/python
9d4044d632672fff966b28ab80e1ef77763c78f5
3913729d7d6e1b7ac72b46db7b06ca0c58c8a608
refs/heads/master
2022-12-09T01:40:52.275592
2022-12-01T22:46:43
2022-12-01T22:46:43
189,040,355
0
0
null
false
2022-12-01T19:52:37
2019-05-28T14:05:16
2022-05-16T12:33:18
2022-12-01T19:52:36
14,525
0
0
0
Python
false
false
from collections import deque def getDiv (n): # get all divisors (sorted) res1 = deque ([1]) res3 = deque ([n]) d = 2 sqrtn = n ** .5 while d < sqrtn: if n % d == 0: res1.append (d) res3.appendleft (n // d) d += 1 res2 = deque ([d]) if n == d * d else deque () return res1 + res2 + res3
UTF-8
Python
false
false
355
py
1,113
_get_all_divisors.py
1,074
0.484507
0.447887
0
13
26.307692
50
Etiqa/bromine
953,482,771,163
af368fc7eb7fa9c5bed340861cb8b209d75048e5
774d16302f7f641cbb4328b5c441f8b148523226
/src/bromine/element/web_element.py
22dd1c0195bafc4a43fffe251f8ae7a2d3511538
[ "BSD-2-Clause" ]
permissive
https://github.com/Etiqa/bromine
ac4917770c6cc508d37a35d0f7ab74d70e07323d
cabf0931f5a06796c26fdc7fb9f7ecf147554fd5
refs/heads/master
2021-06-30T06:40:33.497963
2020-08-21T11:01:55
2020-08-21T11:01:55
129,254,730
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Web element model. """ import six from bromine.exceptions import (NoSuchElementException, MultipleElementsFoundError, StaleElementReferenceException) from .base import Element from .locator import Locator, XPath from ..utils.image import ScreenshotFromPngBytes from .scroll import ElementScroller from .size import Html5ElementSize from .layout import SimpleVerticalLayout class WebElement(Element): """Represents a web element inside a web page. Wraps a Selenium WebElement and adds auto-refreshing behaviour to avoid StaleElementReferenceException's """ _size = Html5ElementSize def __init__(self, browser, locator, dom_element=None): if not isinstance(locator, Locator): if not isinstance(locator, six.string_types): raise TypeError('locator must be a Locator instance or a XPath string') locator = XPath(locator) self._locator = locator self._browser = browser self._dom_element = dom_element self._size = self.__class__._size(self) # TODO: consistency check: dom_element's driver is self._browser @property def dom_element(self): """Underlying Selenium WebElement object.""" if self._dom_element is None: self._find_dom_element() return self._dom_element @property def browser(self): """Instance of Selenium WebDriver.""" return self._browser @property def scroll(self): return ElementScroller(self) @property def scroll_size(self): return self._size.scroll_size() @property def size(self): return self._size.size() @property def layout(self): return SimpleVerticalLayout(self) def _find_dom_element(self): found_elements = self._locator(self._browser) if not found_elements: raise NoSuchElementException(self._locator) elif len(found_elements) > 1: raise MultipleElementsFoundError(self._locator) else: element = found_elements[0] assert element is not None self._dom_element = element def is_present(self): """Test whether this element is attached to the DOM.""" try: self._find_dom_element() except NoSuchElementException: return False else: return True def is_displayed(self): """Test whether this element is displayed. This method invokes is_displayed() method of the underlying dom_element. If the underlying dom_element is stale, it is automatically refreshed. If dom_element is not present, this method returns False instead of raising NoSuchElementException. """ try: return self.dom_element.is_displayed() except NoSuchElementException: return False except StaleElementReferenceException: try: self._find_dom_element() return self.dom_element.is_displayed() except NoSuchElementException: return False def __getattr__(self, name): try: attr = getattr(self.dom_element, name) except StaleElementReferenceException: self._find_dom_element() attr = getattr(self.dom_element, name) if not callable(attr): # pylint: disable=no-else-return return attr else: def auto_refresh_wrapper(*args, **kwargs): try: return attr(*args, **kwargs) except StaleElementReferenceException: self._find_dom_element() return getattr(self.dom_element, name)(*args, **kwargs) return auto_refresh_wrapper def get_screenshot(self): """Return ScreenshotFromPngBytes object. """ png_bytes = self._dom_element.screenshot_as_png return ScreenshotFromPngBytes(png_bytes) # TODO: DOC: elements array must not change during iteration class ElementCollection(object): def __init__(self, browser, locator, element_factory=WebElement): if not isinstance(locator, Locator): if not isinstance(locator, six.string_types): raise TypeError('locator must be a Locator instance or a XPath string') locator = XPath(locator) self._locator = locator self._browser = browser self._element_factory = element_factory def __iter__(self): dom_elements = self._locator(self._browser) return (self._instantiate_item(i, el) for i, el in enumerate(dom_elements)) def _instantiate_item(self, index, dom_element): return self._element_factory(self._browser, self._locator.item(index), dom_element)
UTF-8
Python
false
false
4,892
py
61
web_element.py
45
0.617334
0.616517
0
147
32.278912
91
lanchaoxiang/python
2,731,599,215,470
e17d833aad40d53cc3e641f21fb412d8fb8f8edd
12d333930e82bf90a977e34d22cef04cbc045f02
/joinimg.py
b26b60d3740e186ead4c513966cd74c22a941fad
[]
no_license
https://github.com/lanchaoxiang/python
9b7c64bd4c17cb2fadf71729f457c312d02a2965
0e4fe6118a4a67164dc40d2d34bbad40d76777a9
refs/heads/master
2020-07-24T08:34:32.995663
2018-03-08T07:37:55
2018-03-08T07:37:55
73,791,548
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import os from math import sqrt from PIL import Image #path是存放好友头像图的文件夹的路径 path = path = "/home/lanroot/图片/itchat/" pathList = [] for item in os.listdir(path): imgPath = os.path.join(path,item) pathList.append(imgPath) total = len(pathList)#total是好友头像图片总数 line = int(sqrt(total))#line是拼接图片的行数(即每一行包含的图片数量) NewImage = Image.new('RGB', (128*line,128*line)) x = y = 0 for item in pathList: try: img = Image.open(item) img = img.resize((128,128),Image.ANTIALIAS) NewImage.paste(img, (x * 128 , y * 128)) x += 1 except IOError: print("第%d行,%d列文件读取失败!IOError:%s" % (y,x,item)) x -= 1 if x == line: x = 0 y += 1 if (x+line*y) == line*line: break NewImage.save(path+"final.jpg")
UTF-8
Python
false
false
880
py
5
joinimg.py
5
0.608355
0.578329
0
28
26.392857
55
Matgrb/sentiment-analysis-rebtel
5,437,428,621,347
a4c19d2430197917afffd72d9e754ec26cb3743f
78c2f97e67e7167c49743b01058ccd12188589fb
/scraper.py
43f94357c2c31d967b28d546ecd45c79c92031e5
[]
no_license
https://github.com/Matgrb/sentiment-analysis-rebtel
7108309bc2c9abbcf94ceaf5dfbf91bd8d17bf35
e88b854f38835da524d074573e3c9b1cafeadd00
refs/heads/master
2020-03-21T20:14:53.707334
2018-06-28T09:36:23
2018-06-28T09:36:23
138,995,853
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import lxml.html as html import requests import time import pandas as pd import re ''' The class scrapes the reviews from trust pilot for given link ''' class Scraper: def __init__(self,scrapingWebsite,columnNames): self.website=scrapingWebsite self.columns=columnNames self.waitTime=1 def getPageTree(self,link): page = requests.get(link) return html.fromstring(page.content) def scrapeWebsite(self,scrapingTarget): pageTree =self.getPageTree(self.website+scrapingTarget) #Find number of pages to scrape try: numOfPages=int(pageTree.xpath('//a[@class="pagination-page"]')[0].text) except: numOfPages=1 print(str(numOfPages)+' pages of reviews found for '+scrapingTarget) data=pd.DataFrame(columns=self.columns) for pageNumber in range(1,numOfPages+1): if(pageNumber%10==0): print(str(pageNumber)+'/'+str(numOfPages)+' Pages scraped.') data=data.append(self.scrapeData(self.website+scrapingTarget+'?page='+str(pageNumber),scrapingTarget),ignore_index=True) time.sleep(self.waitTime) return data def scrapeData(self,link,scrapingTarget): pageTree =self.getPageTree(link) titles=pageTree.xpath('//a[@class="link link--large link--dark"]') bodies=pageTree.xpath('//p[@class="review-info__body__text"]') datetimes=pageTree.xpath('//time/@datetime') ratingsText=pageTree.xpath('//div[@class="social-share-network social-share-network--twitter"]/@data-status') numOfReviews=len(titles) pageData=pd.DataFrame(columns=self.columns) for index in range(numOfReviews): currentTitle=titles[index].text currentBody=re.sub(' +',' ',bodies[index].text.split('\n')[1])[1:] currentDate=datetimes[index] currentRating=ratingsText[index].split(' star')[0][-1] pageData=pageData.append(pd.DataFrame([[scrapingTarget,currentTitle,currentBody,currentDate,currentRating]],columns=self.columns), ignore_index=True) return pageData
UTF-8
Python
false
false
2,359
py
12
scraper.py
7
0.603222
0.597711
0
58
38
161
Aasthaengg/IBMdataset
14,027,363,189,005
2955649c341b4031692466e6e23127ef73b412b9
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03352/s513965074.py
7a1f6127bb6e815926272ae80f59f61dd228dcc8
[]
no_license
https://github.com/Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
x=int(input()) l=[] if x==1: print(1) else: for i in range(2,x+1): for j in range(1,x+1): y=j**i if y<=x: l.append(y) elif y>x: break print(max(l))
UTF-8
Python
false
false
238
py
202,060
s513965074.py
202,055
0.365546
0.340336
0
16
13.9375
30
wlgud0402/pyfiles
17,025,250,373,209
8a75363201632e8690949fc3a455257b93d9701a
c8be7becd7466bd6639382156e0886fce3cfb386
/repeat_for.py
4a63c309bacef841bedf584516dd6d20e45b89d6
[]
no_license
https://github.com/wlgud0402/pyfiles
864db71827aba5653d53320322eb8de8b0a5fc49
0e8b96c4bbfb20e1b5667ce482abe75061662299
refs/heads/master
2021-02-28T00:42:51.321207
2020-03-09T10:48:52
2020-03-09T10:48:52
245,648,824
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#for 반복문 for i in range(10): #10번 반복 하겠다는말! 여기서 is는 반복자(불특정) print("반복") #for 반복자 in 반복할수 있는것: #코드 #리스트 요소 하나하나가 element 변수로 들ㄹ어가서 차례차례 반복후 출력 list_a = [12,45,34,78,97,34] for element in list_a: print(element) #for반복문을 문자열과 함께 사용할수도 있다 for element in list_a: print("숫자", element) for comment in "안녕하세요": print("-", comment)
UTF-8
Python
false
false
529
py
107
repeat_for.py
102
0.630252
0.585434
0
20
16.9
59
santhoshbabu4546/GUVI-9
12,189,117,204,532
ed9b402d85abf62c4c2fb40a21aacb360278a744
bfaf64c553eb43684970fb3916eedaafbecf0506
/set5/avg.py
c87933be49238b13a15afbb91cb8a93f646e5d64
[]
no_license
https://github.com/santhoshbabu4546/GUVI-9
879e65df0df6fafcc07166b2eaecf676ba9807a2
b9bfa4b0fa768e70c8d3f40b11dd1bcc23692a49
refs/heads/master
2022-01-24T15:22:34.457564
2019-07-21T14:20:35
2019-07-21T14:20:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
a1=int(input()) a2=list(map(int,input().split())) print(int(sum(a2)/len(a2))
UTF-8
Python
false
false
77
py
344
avg.py
344
0.649351
0.597403
0
3
24.666667
33
prashdevops/mypython
15,882,789,110,288
f80b056be217d6101f28e5e413e46b2867f101ef
0542bec5f7dbc22657b4e0a212b56e231e1df0ce
/intro.py
27346195f84932a751bf61a33ad78fb2336c9dd1
[]
no_license
https://github.com/prashdevops/mypython
b6b09c2038a80a34721e60ab7d75870497b9d7a2
484c8aa67cb9cd79c4d4f6a91638017e5fcb3db9
refs/heads/master
2021-01-16T19:10:46.343141
2017-08-13T04:29:12
2017-08-13T04:29:12
100,149,762
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This is my first python program and This is Intrduction # Developed by Prash.DevOps my_message = 'Hello Word' my_custom_message = 'Prash\'s Custom Message' my_custom_message_one = "Prash's Second Message" my_custom_message_multiline = """ Hi , Here is my example of custom variables which is having multilines """ print(my_message) print(my_custom_message) print(my_custom_message_one) print(my_custom_message_multiline) print(len(my_custom_message)) print(my_custom_message[0]) #print(my_custom_message[24]) print(my_custom_message[0:21]) print(my_custom_message[:22]) print(my_custom_message[0:]) print(my_custom_message.lower()) print(my_custom_message.upper()) print(my_custom_message.count('a')) print(my_custom_message.find('P')) my_replace_variable = my_custom_message.replace('Prash','DevOPS') print(my_replace_variable) greet = 'Hello' name = 'Prash DevOPS' mygreet = greet + ' warm ' + name print(mygreet) mymessage = 'Welcome {}, {} '.format (greet, name) print(mymessage) #print(dir(my_custom_message))
UTF-8
Python
false
false
1,022
py
2
intro.py
2
0.737769
0.728963
0
31
31.967742
77
Marten72/chess_stats
15,410,342,704,360
b0d3702e9ab3cd8c60e5db87ab888a0112cfacc3
2d9d4b7bfcb517641fe92214ad34b730a35be5fc
/util.py
2a93176c6e3a48b28d1c3823557c8a490e4ca629
[]
no_license
https://github.com/Marten72/chess_stats
5a2ab79227070ccf3250c86bdd54bf38d8a0c403
fa1a001f98a1a1b6636fc99caf6439d1d88abfee
refs/heads/master
2020-03-28T06:00:21.360622
2015-03-14T03:57:58
2015-03-14T03:57:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import argparse def parse_host_and_port(): parser = argparse.ArgumentParser() parser.add_argument( '--port', action='store', type=int, dest='port', default=5000, help='The port that should be listned on.', ) parser.add_argument( '--host', action='store', type=str, dest='host', default='0.0.0.0', help='The IP address on which to run the server.' ) namespace = parser.parse_args() return namespace.host, namespace.port
UTF-8
Python
false
false
452
py
46
util.py
31
0.668142
0.650442
0
23
18.652174
51
Wayne27/NCHUPrograms
1,614,907,719,919
ed09e23015f0f3055dc2288d79cfa42868ddf311
5f718a342c4d8f96021d62125cbcd7a0fdb642d5
/專題程式/Main.py
5269780e9babb65ef5e09939535839370cc10cb6
[]
no_license
https://github.com/Wayne27/NCHUPrograms
b1ea92a8d755f55577443015aa08a992a4f96d32
a2d9c23ba5ae10f507c78664a7711b714f20cbe2
refs/heads/master
2021-01-20T21:35:11.924010
2017-09-04T15:00:03
2017-09-04T15:00:03
101,770,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import jieba import MySQLdb import sys from DBcrud import DBConn from food import Food from traffic import Traffic from other import Other from news import News from entertainment import Entertainment from buy import Buy from greeting import Greeting from NchuNews import nchuNews class Talk: def __init__(self): self.dbuse=DBConn() self.dbuse.dbConnect() self.fsql = "SELECT * FROM food" self.tsql = "SELECT * FROM traffic" self.osql = "SELECT * FROM other" self.esql = "SELECT * FROM entertainment" self.bsql = "SELECT * FROM buy" self.dbuse.runQuery( self.fsql) self.food=Food( self.dbuse.results) self.dbuse.runQuery( self.tsql) self.traffic=Traffic( self.dbuse.results) self.dbuse.runQuery( self.osql) self.other=Other( self.dbuse.results) self.dbuse.runQuery( self.esql) self.entertainment=Entertainment( self.dbuse.results) self.dbuse.runQuery( self.bsql) self.buy=Buy( self.dbuse.results) self.greeting=Greeting() self.news=News() self.NchuNews=nchuNews() def getsentence(self,sentence): if self.traffic.match(sentence): return self.traffic.getAnswer() elif self.greeting.greetBack(sentence): return self.greeting.getAnswer() elif self.food.match(sentence): return self.food.getAnswer() elif self.news.match(sentence): return self.news.getAnswer() elif self.NchuNews.match(sentence): return self.NchuNews.getAnswer() elif self.entertainment.match(sentence): return self.entertainment.getAnswer() elif self.buy.match(sentence): return self.buy.getAnswer() else: self.other.match() return self.other.getAnswer() """ if __name__ == '__main__': e = Talk() s="興大新聞" print e.getsentence(s) """
UTF-8
Python
false
false
1,879
py
38
Main.py
16
0.666489
0.665954
0
63
28.68254
59
geroyromanov/phone_control
16,612,933,539,058
5f8a7eef3c44d6d4711fdcb3c36678070020c36a
f37c342712fdb1077a988500c09bb02520a22b55
/backend/api/models.py
30fac57aa0c64d30852f34822611221e888d11ea
[]
no_license
https://github.com/geroyromanov/phone_control
9dbee97a90b1873cab79747141be6f4ad71b34a2
7aa49fa8e4c0db28de5b1eb8190d1b3a11ccf47e
refs/heads/master
2020-06-24T14:34:32.979639
2019-07-31T14:17:36
2019-07-31T14:17:36
198,988,198
0
0
null
false
2020-09-12T06:25:29
2019-07-26T09:27:23
2019-07-31T14:17:52
2020-09-12T06:25:27
1,479
0
0
5
Vue
false
false
from django.db import models import datetime from django.utils import timezone from django.utils.translation import gettext as _ class Phone(models.Model): phone = models.CharField(max_length = 15) email = models.CharField(max_length = 50) fio = models.CharField(max_length = 50) date_created = models.DateField(_("Date"), default=datetime.date.today) date_add = models.DateField(_("Date"), default=datetime.date.today) is_downloaded = models.CharField(max_length = 1, choices = [('0', False), ('1', True)], default = '0') # date_created = models.DateField(default = timezone.now) # date_add = models.DateField(default = timezone.now) comment = models.CharField(max_length = 100, default = None, null = True) geo = models.CharField(max_length = 3, default = None, null = True) STATUSES = [ ('0', 'Unchecked'), ('1', 'Checked'), ('2', 'not specified') ] status = models.CharField(max_length = 1, choices = STATUSES, default = '0')
UTF-8
Python
false
false
1,008
py
14
models.py
11
0.65873
0.639881
0
23
42.826087
106
vaishnavi-rajagopal/Python_Code
3,023,656,989,602
b91aac36d30c31a5968d6a2c6db6cfa5eccd611d
5073e5b728206173cd9d0a9b842890628533be13
/Exercise/bisection_search.py
e6c857724c187d5007469a562b20c608e2a5f329
[]
no_license
https://github.com/vaishnavi-rajagopal/Python_Code
8ee6b8a38c08d83fb71c5ef52539ee9ce91819fc
dc9c9e486018d6e169eab2b96d73236197e298a4
refs/heads/master
2020-04-11T16:32:18.570687
2019-05-17T17:50:16
2019-05-17T17:50:16
161,927,630
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
epsilon=0.00001 num=input("enter a number: ") num=float(num) low=0.0 high=num x=0.0 while(high-low>=4*epsilon): x=(high+low)/2 if(x**4<num): low=x else: high=x print("square_root is",x) print("squareroot is",num**(1/4))
UTF-8
Python
false
false
229
py
31
bisection_search.py
22
0.646288
0.580786
0
17
12.529412
33
rpate136/RESA
10,986,526,360,546
32d59177c40fadf55ff5db85d63203d8e99d6e95
1c9cf15c0b873486a449924cb26d556e56bda921
/RecipeApp/RecipeExt/migrations/0007_auto_20210328_2153.py
8a0e2c299be69bafee4b3703a4ebf471a2ac655e
[]
no_license
https://github.com/rpate136/RESA
cda4ee705200f1882a84acbdd80bc2a7e49929d6
9f20e236e83ab0f5a3a9640a5ce6097012c3b932
refs/heads/master
2023-03-31T19:26:09.467493
2021-03-29T00:16:07
2021-03-29T00:16:07
354,066,965
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.1.7 on 2021-03-28 21:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('RecipeExt', '0006_auto_20210328_2028'), ] operations = [ migrations.AlterField( model_name='ingredient', name='name', field=models.CharField(max_length=50), ), ]
UTF-8
Python
false
false
390
py
16
0007_auto_20210328_2153.py
14
0.589744
0.505128
0
18
20.666667
50
GDGSNF/scrapli
18,528,488,946,849
81280207292322c8eb21d737626690e516247831
d67fa16b4680559e7f78f2568d827df0fdbaa25f
/examples/transport_options/system_ssh_args.py
efa1430934b4618e17dad0c1a363e28880eab538
[ "MIT" ]
permissive
https://github.com/GDGSNF/scrapli
c9f342d933f41b3469013aee51dfcecc2dd11281
e0170a56ce10c495ab424e81dd7ebca6450199ea
refs/heads/master
2023-08-21T04:26:33.541462
2021-10-11T23:35:36
2021-10-11T23:35:36
414,172,050
0
0
MIT
true
2021-10-11T23:35:36
2021-10-06T10:47:06
2021-10-11T22:08:11
2021-10-11T23:35:36
6,814
0
0
0
Python
false
false
"""examples.transport_options.system_ssh_args""" from scrapli.driver.core import IOSXEDriver MY_DEVICE = { "host": "172.18.0.11", "auth_username": "scrapli", "auth_password": "scrapli", "auth_strict_key": False, "transport_options": {"open_cmd": ["-o", "KexAlgorithms=+diffie-hellman-group1-sha1"]}, } def main(): """Simple example demonstrating adding transport options""" conn = IOSXEDriver(**MY_DEVICE) # with the transport options provided, we can extend the open command to include extra args print(conn.transport.open_cmd) # deleting the transport options we can see what the default open command would look like MY_DEVICE.pop("transport_options") del conn conn = IOSXEDriver(**MY_DEVICE) print(conn.transport.open_cmd) if __name__ == "__main__": main()
UTF-8
Python
false
false
826
py
112
system_ssh_args.py
74
0.674334
0.662228
0
27
29.592593
95