blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
e47dce9c9c5eed815ffa55ca6d0aed20f77b9a8f
80b2700b6f9940ee672f42124b2cb8a81836426e
/cgi/cgi.cgi
5d4924622945cb130546139be58763ec78e549d9
[ "Apache-2.0" ]
permissive
Vayne-Lover/Python
6c1ac5c0d62ecdf9e3cf68d3e659d49907bb29d4
79cfe3d6971a7901d420ba5a7f52bf4c68f6a1c1
refs/heads/master
2020-04-12T08:46:13.128989
2017-04-21T06:36:40
2017-04-21T06:36:40
63,305,306
1
0
null
null
null
null
UTF-8
Python
false
false
335
cgi
#!/usr/local/bin/python import cgi form=cgi.FieldStirage() name=form.getvalue('name','world') print ''' <html> <head> <title>Page</title> </head> <body> <h1>Hello,%s</h1> <form action='cgi.cgi'> Change name<input type='text' name='name' /> <input type='submit'/> </form> </body> </html> '''%name
[ "406378362@qq.com" ]
406378362@qq.com
6a73d876aea17be4a376a5907de6235230844d3e
1a4353a45cafed804c77bc40e843b4ad463c2a0e
/examples/homogenization/linear_homogenization.py
1682971d9827a59e1fc33d4bc53001c774b6fcc9
[ "BSD-3-Clause" ]
permissive
shrutig/sfepy
9b509866d76db5af9df9f20467aa6e4b23600534
87523c5a295e5df1dbb4a522b600c1ed9ca47dc7
refs/heads/master
2021-01-15T09:28:55.804598
2014-01-24T14:28:28
2014-01-30T16:25:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,370
py
# 04.08.2009 #! #! Homogenization: Linear Elasticity #! ================================= #$ \centerline{Example input file, \today} #! Homogenization of heterogeneous linear elastic material import sfepy.fem.periodic as per from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.homogenization.utils import define_box_regions import sfepy.homogenization.coefs_base as cb from sfepy import data_dir from sfepy.base.base import Struct from sfepy.homogenization.recovery import compute_micro_u, compute_stress_strain_u, compute_mac_stress_part def recovery_le( pb, corrs, macro ): out = {} dim = corrs['corrs_le']['u_00'].shape[1] mic_u = - compute_micro_u( corrs['corrs_le'], macro['strain'], 'u', dim ) out['u_mic'] = Struct( name = 'output_data', mode = 'vertex', data = mic_u, var_name = 'u', dofs = None ) stress_Y, strain_Y = compute_stress_strain_u( pb, 'i', 'Y', 'mat.D', 'u', mic_u ) stress_Y += compute_mac_stress_part( pb, 'i', 'Y', 'mat.D', 'u', macro['strain'] ) strain = macro['strain'] + strain_Y out['cauchy_strain'] = Struct( name = 'output_data', mode = 'cell', data = strain, dofs = None ) out['cauchy_stress'] = Struct( name = 'output_data', mode = 'cell', data = stress_Y, dofs = None ) return out #! Mesh #! ---- filename_mesh = data_dir + '/meshes/3d/matrix_fiber.mesh' dim = 3 region_lbn = (0, 0, 0) region_rtf = (1, 1, 1) #! Regions #! ------- #! Regions, edges, ... regions = { 'Y' : 'all', 'Ym' : 'cells of group 1', 'Yc' : 'cells of group 2', } regions.update( define_box_regions( dim, region_lbn, region_rtf ) ) #! Materials #! --------- materials = { 'mat' : ({'D' : {'Ym': stiffness_from_youngpoisson(dim, 7.0e9, 0.4), 'Yc': stiffness_from_youngpoisson(dim, 70.0e9, 0.2)}},), } #! Fields #! ------ #! Scalar field for corrector basis functions. fields = { 'corrector' : ('real', dim, 'Y', 1), } #! Variables #! --------- #! Unknown and corresponding test variables. Parameter fields #! used for evaluation of homogenized coefficients. variables = { 'u' : ('unknown field', 'corrector', 0), 'v' : ('test field', 'corrector', 'u'), 'Pi' : ('parameter field', 'corrector', 'u'), 'Pi1' : ('parameter field', 'corrector', '(set-to-None)'), 'Pi2' : ('parameter field', 'corrector', '(set-to-None)'), } #! Functions functions = { 'match_x_plane' : (per.match_x_plane,), 'match_y_plane' : (per.match_y_plane,), 'match_z_plane' : (per.match_z_plane,), } #! Boundary Conditions #! ------------------- #! Fixed nodes. ebcs = { 'fixed_u' : ('Corners', {'u.all' : 0.0}), } if dim == 3: epbcs = { 'periodic_x' : (['Left', 'Right'], {'u.all' : 'u.all'}, 'match_x_plane'), 'periodic_y' : (['Near', 'Far'], {'u.all' : 'u.all'}, 'match_y_plane'), 'periodic_z' : (['Top', 'Bottom'], {'u.all' : 'u.all'}, 'match_z_plane'), } else: epbcs = { 'periodic_x' : (['Left', 'Right'], {'u.all' : 'u.all'}, 'match_x_plane'), 'periodic_y' : (['Bottom', 'Top'], {'u.all' : 'u.all'}, 'match_y_plane'), } all_periodic = ['periodic_%s' % ii for ii in ['x', 'y', 'z'][:dim] ] #! Integrals #! --------- #! Define the integral type Volume/Surface and quadrature rule. integrals = { 'i' : 2, } #! Options #! ------- #! Various problem-specific options. options = { 'coefs' : 'coefs', 'requirements' : 'requirements', 'ls' : 'ls', # linear solver to use 'volume' : { 'variables' : ['u'], 'expression' : 'd_volume.i.Y( u )' }, 'output_dir' : 'output', 'coefs_filename' : 'coefs_le', 'recovery_hook' : 'recovery_le', } #! Equations #! --------- #! Equations for corrector functions. equation_corrs = { 'balance_of_forces' : """dw_lin_elastic.i.Y(mat.D, v, u ) = - dw_lin_elastic.i.Y(mat.D, v, Pi )""" } #! Expressions for homogenized linear elastic coefficients. expr_coefs = """dw_lin_elastic.i.Y(mat.D, Pi1, Pi2 )""" #! Coefficients #! ------------ #! Definition of homogenized acoustic coefficients. def set_elastic(variables, ir, ic, mode, pis, corrs_rs): mode2var = {'row' : 'Pi1', 'col' : 'Pi2'} val = pis.states[ir, ic]['u'] + corrs_rs.states[ir, ic]['u'] variables[mode2var[mode]].set_data(val) coefs = { 'D' : { 'requires' : ['pis', 'corrs_rs'], 'expression' : expr_coefs, 'set_variables' : set_elastic, 'class' : cb.CoefSymSym, }, 'filenames' : {}, } requirements = { 'pis' : { 'variables' : ['u'], 'class' : cb.ShapeDimDim, }, 'corrs_rs' : { 'requires' : ['pis'], 'ebcs' : ['fixed_u'], 'epbcs' : all_periodic, 'equations' : equation_corrs, 'set_variables' : [('Pi', 'pis', 'u')], 'class' : cb.CorrDimDim, 'save_name' : 'corrs_le', 'dump_variables' : ['u'], }, } #! Solvers #! ------- #! Define linear and nonlinear solver. solvers = { 'ls' : ('ls.umfpack', {}), 'newton' : ('nls.newton', {'i_max' : 1, 'eps_a' : 1e-4, 'problem' : 'nonlinear', }) }
[ "cimrman3@ntc.zcu.cz" ]
cimrman3@ntc.zcu.cz
7b96f4da183d09e021d9952a0dcf54bf9f5af32f
c898af4efbfaeba8fa91d86bc97f7f6ee2381564
/easy/561. Array Partition I/test.py
e9fa5a72142fdad8d3321c524413f6509e273cb4
[]
no_license
weiweiECNU/leetcode
5941300131e41614ccc043cc94ba5c03e4342165
1c817338f605f84acb9126a002c571dc5e28a4f7
refs/heads/master
2020-06-20T18:33:28.157763
2019-08-20T07:52:14
2019-08-20T07:52:14
197,209,417
0
0
null
null
null
null
UTF-8
Python
false
false
423
py
# https://leetcode.com/problems/array-partition-i/ # 比较大的数字一定要和比较大的数字在一起才行,否则括号内的小的结果是较小的数字。 # 所以先排序,排序后的结果找每个组中数据的第一个数字即可。 # 时间复杂度是O(NlogN),空间复杂度是O(1). class Solution: def arrayPairSum(self, nums: List[int]) -> int: return sum(sorted(nums)[::2])
[ "weiweiwill995@gmail.com" ]
weiweiwill995@gmail.com
e05664ff87e83f760833b263ea27a3411e4d24e3
ca446c7e21cd1fb47a787a534fe308203196ef0d
/followthemoney/types/number.py
4072e01a3017fa934f2ce8208185ed2b55969689
[ "MIT" ]
permissive
critocrito/followthemoney
1a37c277408af504a5c799714e53e0f0bd709f68
bcad19aedc3b193862018a3013a66869e115edff
refs/heads/master
2020-06-12T09:56:13.867937
2019-06-28T08:23:54
2019-06-28T08:23:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
from followthemoney.types.common import PropertyType from followthemoney.util import defer as _ class NumberType(PropertyType): name = 'number' label = _('Number') plural = _('Numbers') matchable = False
[ "friedrich@pudo.org" ]
friedrich@pudo.org
4c8f7e6ae2aeddd5c42226129d42c4cb4aab080a
3ab599127dc2fc89cfee5f3ee3a91168499cb475
/tests/notebooks/print.py
f53c6110196004fd9f0397077b033b4cca94f792
[ "BSD-3-Clause" ]
permissive
maartenbreddels/voila
17dfb39c131ffad4b3b51926214dc71a2e06a964
d3a52abdd34b68bdabdd8f0ae34071711cd16742
refs/heads/master
2022-05-11T05:47:44.843627
2020-09-28T09:58:37
2020-09-28T09:58:37
149,579,689
2
1
NOASSERTION
2020-05-27T07:59:20
2018-09-20T08:50:19
Python
UTF-8
Python
false
false
284
py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.2.1 # kernelspec: # display_name: Python 3 # language: python # name: python # --- print('Hi Voilà!')
[ "maartenbreddels@gmail.com" ]
maartenbreddels@gmail.com
bb3d8a5f150df51b5fdef25b495d0d2462c6e144
aae0461973440174afbf8e75e4ddf0f0c4dd1a9c
/gnu/gnu_slides.py
1a30f50a3ee380b604a8669eeb4d4ef8b8b97991
[]
no_license
behdad/slippy
f81eeac68df39eb0f6a7465effacd7239eb24cbf
5535fe88a785dd75c96171b989f310fcd80e479e
refs/heads/master
2023-08-29T08:48:40.919688
2016-09-27T08:02:01
2016-09-27T08:02:01
15,673,169
20
0
null
2014-01-10T08:09:47
2014-01-06T12:14:35
Python
UTF-8
Python
false
false
5,180
py
#!/usr/bin/python # -*- coding:utf8 -*- slides = [] def slide_add(f, data=None, width=800, height=400): slides.append ((f, data, width, height)) return f import pango def text_slide (l): def s (r): for i in l: yield i for i in range (30): yield '' slide_add (s, data={'align': pango.ALIGN_LEFT}) texts = {} texts['en'] = """“Free software” is a matter of liberty, not price. To understand the concept, you should think of “free” as in “free speech”, not as in “free beer.” Free software is a matter of the users' freedom to run, copy, distribute, study, change and improve the software. More precisely, it refers to four kinds of freedom, for the users of the software: ------------------------------------------------------------------------------ 0. The freedom to run the program, for any purpose. 1. The freedom to study how the program works, and adapt it to your needs. Access to the source code is a precondition for this. 2. The freedom to redistribute copies so you can help your neighbor. 3. The freedom to improve the program, and release your improvements to the public, so that the whole community benefits. Access to the source code is a precondition for this. ------------------------------------------------------------------------------ The concept of these 4 freedoms (0-3) were developed by Richard Stallman. To set a good example he started to write a completely free operating system. Today Linux based GNU systems are used by millions of people around the world.""" texts['de'] = """Bei dem Begriff „Freie Software“ geht es um Freiheit, nicht um den Preis. Um dieses Konzept richtig begreifen zu können, sollte man an „frei“ wie in „freie Rede“ denken, und nicht an „Freibier“. Bei „Freier Software“ geht es um die Freiheit des Benutzers die Software nach Belieben zu benutzen, zu kopieren, weiter zu geben, die Software zu studieren, sowie Änderungen und Verbesserungen an der Software vornehmen zu können. ------------------------------------------------------------------------------ Genauer gesagt, bezieht sich der Begriff „Freie Software“ auf vier Arten von Freiheit, die der Benutzer der Software hat: 0. Die Freiheit, das Programm für jeden Zweck zu benutzen. 1. Die Freiheit, zu verstehen, wie das Programm funktioniert und wie man es für seine Ansprüche anpassen kann. Der Zugang zum Quellcode ist dafür Voraussetzung. ------------------------------------------------------------------------------ 2. Die Freiheit, Kopien weiterzuverbreiten, so dass man seinem Nächsten weiterhelfen kann. 3. Die Freiheit, das Programm zu verbessern und die Verbesserungen der Allgemeinheit zur Verfügung zu stellen, damit die ganze Gemeinschaft davon profitieren kann. Der Zugang zum Quellcode ist dafür Voraussetzung. ------------------------------------------------------------------------------ Diese 4 Freiheiten (0-3) wurden so von Richard Stallman entworfen. Um mit gutem Beispiel voran zu gehen, hat er angefangen, ein vollständig freies Betriebssystem zu entwickeln. Heute werden Linux basierte GNU Systeme von vielen Millionen Anwendern benutzt.""" texts['he'] = """"תוכנה חופשית" זה ענײן של חירות, לא של מחיר. כדי להבין את העקרון, צריך לחשוב על "חופש" כמו ב"חופש הביטוי"...\ .effectpause .back 3 ולא כמו ב"בירה חופשי". תוכנה חופשית נוגעת לחופש של משתמשים להריץ, להפיץ הפצת-המשך, ללמוד, לשנות ולשפר את התוכנה. ליתר דיוק, זה מתײחס לארבעה סוגים של חירות למשתמשי התוכנה: ------------------------------------------------------------------------------ 0. החופש להריץ את התוכנה, לכל מטרה שהיא. 1. החופש ללמוד איך תוכנה עובדת, ולשנות אותה לצרכיהם. גישה לקוד המקור היא תנאי מקדים לכך. 2. החופש להפיץ עותקים בהפצה-חוזרת כדי שיוכלו למשל לעזור לשכנים שלהם. 3. החופש לשפר את התוכנה, ולשחרר את השיפורים שלהם לציבור, כך שכל הקהילה תרויח. גישה לקוד-המקור היא תנאי מקדים לכך. ------------------------------------------------------------------------------ The concept of these 4 freedoms (0-3) were developed by Richard Stallman. To set a good example he started to write a completely free operating system. Today Linux based GNU systems are used by millions of people around the world.""" import os, re lang = os.getenv ('LANG') i = lang.find ('_') if i > 0: lang = lang[:i] text = texts.get (lang, texts['en']) def break_on_dashlines (text): s = '' for line in text.split ('\n'): if re.match ('^----*$', line): yield s s = '' else: if s: s += '\n' s += line yield s for slide in break_on_dashlines (text): text_slide (slide) if __name__ == "__main__": import slippy import gnu_theme slippy.main (slides, gnu_theme, args = ['--slideshow', '--delay', '0.05', '--repeat'])
[ "behdad@behdad.org" ]
behdad@behdad.org
f0b3710c6bf6eebf47cd69db345fc58831d7d39c
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/308/usersdata/295/73012/submittedfiles/ex1.py
d7faface2964c55c9b074fbe6eed286761f20fc3
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
302
py
# -*- coding: utf-8 -*- from __future__ import division a = input('Digite a: ') b = input('Digite b: ') c = input('Digite c: ') #COMECE A PARTIR DAQUI! a = input('Digite a: ') b = input('Digite b: ') c = input('Digite c: ') f = a*(x**2) + b*x + c if DH>0 print("X1 e X2") else: print("SRR")
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
b8664ce8a44166d29e61a75e3ca17132ba423261
76eb17916555462a9219cb7cfea741b2281ace7b
/testbot/urls.py
8b8843e97dfa5a7526faad8d82ac7c207b0cbefc
[ "MIT" ]
permissive
luungoc2005/chatbot_test
6ecabbe507d01418282a883d6ab70eb10130c991
f8c901c9c14a50727a7b514dda1e569c8180b458
refs/heads/master
2021-08-30T13:07:20.132250
2017-11-15T03:35:47
2017-11-15T03:35:47
105,901,223
0
0
null
null
null
null
UTF-8
Python
false
false
229
py
from django.urls import path from . import views urlpatterns = [ # ex: /testbot/ path('', views.index, name='index'), path('examples/', views.examples, name='examples'), path('test/', views.test, name='test'), ]
[ "luungoc2005@gmail.com" ]
luungoc2005@gmail.com
5cac8cdc56b579d7b87c1b9d6a558ed496f54f49
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/7QPHWACcDihT3AM6b_6.py
42998e86441fe6f7df22cf74314d844cef6aab32
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
871
py
""" You are given an input array of bigrams, and an array of words. Write a function that returns `True` if **every single bigram** from this array can be found at least **once** in an array of words. ### Examples can_find(["at", "be", "th", "au"], ["beautiful", "the", "hat"]) ➞ True can_find(["ay", "be", "ta", "cu"], ["maybe", "beta", "abet", "course"]) ➞ False # "cu" does not exist in any of the words. can_find(["th", "fo", "ma", "or"], ["the", "many", "for", "forest"]) ➞ True can_find(["oo", "mi", "ki", "la"], ["milk", "chocolate", "cooks"]) ➞ False ### Notes * A **bigram** is string of two consecutive characters in the same word. * If the list of words is empty, return `False`. """ def can_find(bigrams, words): for bi in bigrams: if bi not in ''.join(words): return False return True
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
a53d180b2d0604cbcd6624d4c8f734141673ae1d
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/bob/fd662cf898124b46b21e2ca30d117042.py
6281c95b5842337f10d96aec50200b80c8cd2e1d
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
346
py
def hey(input): has_alpha = False has_num = False for i in input: if i.isalpha(): has_alpha = True elif i.isnumeric(): has_num = True if not has_alpha and not has_num: return "Fine. Be that way!" if input.upper() == input and has_alpha: return "Whoa, chill out!" if input[-1] == "?": return "Sure." return "Whatever."
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
cd9d8b0b39e0e09d7940516635e9a94f971f38fc
7f4886802e83352f37d35509b7775c93c2756105
/accounts/forms.py
db5c1f9a162a945c87a84c42d50cf009988f7614
[]
no_license
JihyeKim0923/lion10
c23a019c3725de2d9f70556993db1ed3e8d6ae2e
2b76dc9290bec6f4d827a625b2f0b1e92c85ed53
refs/heads/master
2020-06-19T02:56:24.746341
2019-07-11T15:40:17
2019-07-11T15:40:17
196,539,639
0
0
null
null
null
null
UTF-8
Python
false
false
616
py
from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms class CreateUserForm(UserCreationForm): email=forms.EmailField(required=True) nickname=forms.CharField(required=True) class Meta: model=User fields=("username","email","nickname","password1","password2") def save(self, commit=True): user=super(CreateUserForm,self).save(commit=False) user.nickname=self.cleaned_data["nickname"] user.email=self.cleaned_data["email"] if commit: user.save() return user
[ "sos13313@naver.com" ]
sos13313@naver.com
369d942517debc6f30b559509854cb06ba1ef9e5
27d0ea837489f68978287e369b60faa57eeb2497
/examples/wifiz.py
9044f15d865520323e139912c9568d0c8210365d
[]
no_license
nimdavtanke/wifi-scripts
9692a4c67d23cc1a7d076d6a41be2bdd6cf4d3ce
83576bcbf62cdfe020b5c2178f9ab177733de1dc
refs/heads/master
2016-08-06T15:20:47.206467
2015-03-28T08:37:16
2015-03-28T08:37:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,227
py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # 802.11 sniffer/wpsig/wpspin/reaver # Credits go to: # # Craig Heffner Tactical Network Solutions # https://github.com/devttys0/wps # # WPSIG [ablanco@coresecurity.com, oss@coresecurity.com] __author__ = '090h' __license__ = 'GPL' from sys import argv, exit from os import path, geteuid # import logging # logging.getLogger("scapy.runtime").setLevel(logging.ERROR) # from scapy.all import conf # conf.verb = 1 # conf.use_pcap = True # conf.use_dnet = False from scapy.layers.dot11 import * from scapy.all import * # impacket try: from impacket import dot11 from impacket.dot11 import Dot11 from impacket.dot11 import Dot11Types from impacket.dot11 import Dot11ManagementFrame from impacket.dot11 import Dot11ManagementProbeRequest from impacket.ImpactDecoder import RadioTapDecoder except ImportError: Exception("impacket") from pprint import pprint from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter if LINUX: # print('Linux detected. Trying to import PyLorcon2...') try: import PyLorcon2 except ImportError: logging.warning('PyLorcon2 import failed. Injection is not available.') if WINDOWS: logging.error('Sorry, no Windows.') exit(-1) if DARWIN: logging.warning('OS X detected. Only pasive mode will be available') #TODO: add iOS and Android detection PROBE_REQUEST_TYPE = 0 PROBE_REQUEST_SUBTYPE = 4 class WiFiWizard(object): def __init__(self, iface, output=None, whitelist=None, verbose=False): # Replace this with your phone's MAC address if not whitelist: whitelist = ['00:00:00:00:00:00', ] self.iface = iface self.whitelist = whitelist self.verbose = verbose self.aps = {} self.clients = {} # Probe requests from clients def handle_probe(self, pkt): if pkt.haslayer(Dot11ProbeReq) and '\x00' not in pkt[Dot11ProbeReq].info: essid = pkt[Dot11ProbeReq].info else: essid = 'Hidden SSID' client = pkt[Dot11].addr2 if client in self.whitelist or essid in self.whitelist: #TODO: add logging return # New client if client not in self.clients: self.clients[client] = [] print('[!] New client: %s ' % client) if essid not in self.clients[client]: self.clients[client].append(essid) print('[+] New ProbeRequest: from %s to %s' % (client, essid)) def handle_beacon(self, pkt): if not pkt.haslayer(Dot11Elt): return # Check to see if it's a hidden SSID essid = pkt[Dot11Elt].info if '\x00' not in pkt[Dot11Elt].info and pkt[Dot11Elt].info != '' else 'Hidden SSID' bssid = pkt[Dot11].addr3 client = pkt[Dot11].addr2 if client in self.whitelist or essid in self.whitelist or bssid in self.whitelist: #TODO: add logging return try: channel = int(ord(pkt[Dot11Elt:3].info)) except: channel = 0 try: extra = pkt.notdecoded rssi = -(256-ord(extra[-4:-3])) except: rssi = -100 p = pkt[Dot11Elt] capability = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}" "{Dot11ProbeResp:%Dot11ProbeResp.cap%}").split('+') # print('capability = %s' % capability) crypto = set() while isinstance(p, Dot11Elt): if p.ID == 48: crypto.add("WPA2") elif p.ID == 221 and p.info.startswith('\x00P\xf2\x01\x01\x00'): crypto.add("WPA") p = p.payload if not crypto: if 'privacy' in capability: crypto.add("WEP") else: crypto.add("OPN") enc = '/'.join(crypto) if bssid not in self.aps: self.aps[bssid] = (channel, essid, bssid, enc, rssi) print "[+] New AP {0:5}\t{1:20}\t{2:20}\t{3:5}\t{4:4}".format(channel, essid, bssid, enc, rssi) def pkt_handler(self, pkt): # wlan.fc.type == 0 Management frames # wlan.fc.type == 1 Control frames # wlan.fc.type == 2 Data frames # wlan.fc.type_subtype == 0 Association request # wlan.fc.type_subtype == 1 Association response # wlan.fc.type_subtype == 2 Reassociation request # wlan.fc.type_subtype == 3 Reassociation response # wlan.fc.type_subtype == 4 Probe request # wlan.fc.type_subtype == 5 Probe response # wlan.fc.type_subtype == 8 Beacon try: print('-->', pkt.name) except: pass #Beacon if pkt.haslayer(Dot11Beacon): self.handle_beacon(pkt) # Client ProbeReq if pkt.haslayer(Dot11ProbeReq): self.handle_request(pkt) # if pkt.type == PROBE_REQUEST_TYPE and pkt.subtype == PROBE_REQUEST_SUBTYPE: if pkt.haslayer(Dot11ProbeResp): self.handle_response(pkt) def sniff(self): ''' Sniff Beacon and Probe Requst/Response frames to extract AP info :param count: packets to capture, 0 = loop :return: ''' print('Press Ctrl-C to stop sniffing.') sniff(iface=self.iface, prn=self.pkt_handler, lfilter=lambda p: p.haslayer(Dot11)) if __name__ == '__main__': parser = ArgumentParser(description='WiFi PWN T00L', formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s 1.0') parser.add_argument('interface', help='802.11 interface to use') parser.add_argument('-c', '--channel', required=False) parser.add_argument('-w', '--wps', required=False, action='store_true', help='wps hack') parser.add_argument('-a', '--active', required=False, action='store_true', help='active mode') args = parser.parse_args() if geteuid() != 0: exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'.") WiFiWizard(args.interface).sniff()
[ "oleg.kupreev@gmail.com" ]
oleg.kupreev@gmail.com
4a5c5376aa7ce609fdb64cecfb2774f44dbc8725
cf0480eb13906bf6e2c46bfe09b864ee9bbf6776
/Functions/Calc/Calc_1.py
3b600966f2c62976f2522ee032f37f2d17a06b1c
[]
no_license
ravi4all/Python_JuneRegular_Evening
f7afb665541b88a9cb6ce89a488a32120f63dd6b
ad6e17c4acdcb2c669ba0508b12aeca8bdab8976
refs/heads/master
2020-03-20T21:20:36.763561
2018-07-06T11:26:52
2018-07-06T11:26:52
137,736,114
1
0
null
null
null
null
UTF-8
Python
false
false
355
py
print(""" 1. Add 2. Sub 3. Mul 4. Div """) user_choice = input("Enter your choice : ") num_1 = int(input("Enter first number : ")) num_2 = int(input("Enter second number : ")) if user_choice == "1": result = num_1 + num_2 print("Sum is",result) elif user_choice == "2": result = num_1 - num_2 print("Diff is", result)
[ "noreply@github.com" ]
ravi4all.noreply@github.com
a7db7a35a129dddef9b0cb830716ebca4fed85be
42366c1e36038bf879652b4f4c45c6105209a738
/snakemake/wrapper.py
52b1c95f9256a8db894ea389c38ad40fd4bec165
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
endrebak/snakemake_dev
e22989e40d475250a1f6e44421290b75dcaf6651
846cad1273de7cf43a25fc210174ce43dfd45a8a
refs/heads/master
2021-01-13T16:01:30.593695
2016-12-14T08:21:22
2016-12-14T08:21:22
76,775,780
0
0
null
null
null
null
UTF-8
Python
false
false
1,340
py
__author__ = "Johannes Köster" __copyright__ = "Copyright 2016, Johannes Köster" __email__ = "koester@jimmy.harvard.edu" __license__ = "MIT" import os import posixpath from snakemake.script import script def is_script(path): return path.endswith("wrapper.py") or path.endswith("wrapper.R") def get_path(path, prefix=None): if not (path.startswith("http") or path.startswith("file:")): if prefix is None: prefix = "https://bitbucket.org/snakemake/snakemake-wrappers/raw/" path = prefix + path return path def get_script(path, prefix=None): path = get_path(path) if not is_script(path): path += "/wrapper.py" return path def get_conda_env(path): path = get_path(path) if is_script(path): # URLs and posixpaths share the same separator. Hence use posixpath here. path = posixpath.dirname(path) return path + "/environment.yaml" def wrapper(path, input, output, params, wildcards, threads, resources, log, config, rulename, conda_env, prefix): """ Load a wrapper from https://bitbucket.org/snakemake/snakemake-wrappers under the given path + wrapper.py and execute it. """ path = get_script(path, prefix=prefix) script(path, "", input, output, params, wildcards, threads, resources, log, config, rulename, conda_env)
[ "johannes.koester@tu-dortmund.de" ]
johannes.koester@tu-dortmund.de
ca2fa5ad4997c54d0f3874f400a20a3fbfbdaf02
ccbe341f4bc5f46ce31968a1d764a87f6f6803a8
/pytheas/__init__.py
49bf2edb9ecbfe446b859aa5cdeb805ed037f51e
[ "MIT" ]
permissive
skytreader/pytheas
8ce1e23965c61aff5eb48a301e9a8e04d3c70a55
c41cf985827734a1a9be1e61a93fca2a7b14c3d9
refs/heads/master
2023-04-09T01:54:24.423483
2014-06-03T04:04:35
2014-06-03T04:04:35
17,976,330
0
0
null
2023-03-31T14:38:58
2014-03-21T10:30:38
Python
UTF-8
Python
false
false
156
py
# Copied from https://github.com/andymccurdy/redis-py/blob/master/redis/__init__.py __version__ = "0.1.2" VERSION = tuple(map(int, __version__.split(".")))
[ "chadestioco@gmail.com" ]
chadestioco@gmail.com
cc0c3f49a86cd19e0eac92eb6d9d45901dc5447e
fb5c5d50d87a6861393d31911b9fae39bdc3cc62
/Scripts/sims4communitylib/enums/common_funds_sources.py
b752318a7a87e9b2ab9fbcb9e237f428646c1ce1
[ "CC-BY-4.0" ]
permissive
ColonolNutty/Sims4CommunityLibrary
ee26126375f2f59e5567b72f6eb4fe9737a61df3
58e7beb30b9c818b294d35abd2436a0192cd3e82
refs/heads/master
2023-08-31T06:04:09.223005
2023-08-22T19:57:42
2023-08-22T19:57:42
205,197,959
183
38
null
2023-05-28T16:17:53
2019-08-29T15:48:35
Python
UTF-8
Python
false
false
2,552
py
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """ from typing import Dict from sims.funds import FundsSource from sims4communitylib.enums.enumtypes.common_int import CommonInt class CommonFundsSource(CommonInt): """Sources of funds.""" HOUSEHOLD: 'CommonFundsSource' = ... RETAIL: 'CommonFundsSource' = ... BUSINESS: 'CommonFundsSource' = ... STATISTIC: 'CommonFundsSource' = ... BUCKS: 'CommonFundsSource' = ... NO_SOURCE: 'CommonFundsSource' = ... @staticmethod def convert_to_vanilla(value: 'CommonFundsSource') -> FundsSource: """convert_to_vanilla(value) Convert a value into the vanilla FundsSource enum. :param value: An instance of the enum. :type value: CommonFundsSource :return: The specified value translated to FundsSource or HOUSEHOLD if the value could not be translated. :rtype: Union[FundsSource, None] """ mapping: Dict[CommonFundsSource, FundsSource] = { CommonFundsSource.HOUSEHOLD: FundsSource.HOUSEHOLD, CommonFundsSource.RETAIL: FundsSource.RETAIL, CommonFundsSource.BUSINESS: FundsSource.BUSINESS, CommonFundsSource.STATISTIC: FundsSource.STATISTIC, CommonFundsSource.BUCKS: FundsSource.BUCKS, CommonFundsSource.NO_SOURCE: FundsSource.NO_SOURCE, } return mapping.get(value, FundsSource.HOUSEHOLD) @staticmethod def convert_from_vanilla(value: FundsSource) -> 'CommonFundsSource': """convert_from_vanilla(value) Convert a vanilla FundsSource to value. :param value: An instance of the enum. :type value: FundsSource :return: The specified value translated to CommonFundsSource or HOUSEHOLD if the value could not be translated. :rtype: CommonFundsSource """ mapping: Dict[FundsSource, CommonFundsSource] = { FundsSource.HOUSEHOLD: CommonFundsSource.HOUSEHOLD, FundsSource.RETAIL: CommonFundsSource.RETAIL, FundsSource.BUSINESS: CommonFundsSource.BUSINESS, FundsSource.STATISTIC: CommonFundsSource.STATISTIC, FundsSource.BUCKS: CommonFundsSource.BUCKS, FundsSource.NO_SOURCE: CommonFundsSource.NO_SOURCE, } return mapping.get(value, CommonFundsSource.HOUSEHOLD)
[ "ColonolNutty@hotmail.com" ]
ColonolNutty@hotmail.com
7fd63d245dbd1ed1b3c96be002435fe20c90baf8
44bbfe1c9a7f16e632cdd27c2de058033b33ea6d
/mayan/apps/authentication/links.py
dc7385bd9ff9101a3656851017b7786194679579
[ "Apache-2.0" ]
permissive
lxny2004/open-paperless
34025c3e8ac7b4236b0d8fc5ca27fc11d50869bc
a8b45f8f0ee5d7a1b9afca5291c6bfaae3db8280
refs/heads/master
2020-04-27T04:46:25.992405
2019-03-06T03:30:15
2019-03-06T03:30:15
174,064,366
0
0
NOASSERTION
2019-03-06T03:29:20
2019-03-06T03:29:20
null
UTF-8
Python
false
false
478
py
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from navigation import Link def has_usable_password(context): return context['request'].user.has_usable_password link_logout = Link( icon='fa fa-sign-out', text=_('Logout'), view='authentication:logout_view' ) link_password_change = Link( condition=has_usable_password, icon='fa fa-key', text=_('Change password'), view='authentication:password_change_view' )
[ "littlezhoubear@gmail.com" ]
littlezhoubear@gmail.com
26f57305b55d3b30eaa55261b2928f5dc17ece1b
b8ee76250770ba628b818a26b6f894347ff2e390
/Sqlite3Module.py
f3dd02adf33ac2df83d79a9fb702b4e8d11bbb8e
[]
no_license
SimonGideon/Journey-to-Pro
77c77bd1a5de387c41bc8618100bbb3957d15706
1591310891c7699710e992fe068b8fa230ac3d56
refs/heads/master
2023-04-28T19:31:53.155384
2021-05-18T19:18:32
2021-05-18T19:18:32
358,926,411
2
0
null
null
null
null
UTF-8
Python
false
false
699
py
import sqlite3 conn = sqlite3.connect('Database1.db') c = conn.cursor() # Create a table c.execute('''CREATE TABLE stocks(date text, trans text, symbol text, qty real, price real)''') # Insert a raw of data. c.execute("INSERT INTO stock VALUES ('2006-01-05','BUY','RHAT',100,35,14)") conn.commit() conn.close() # Getting Values from the db and error handling. import sqlite3 conn = sqlite3.connect('Database1.db') c = conn.cursor() c.execute("SELECT * from table_name where id=cust_id") for row in c: print(row) # To fetch mathching. print(c.fetchone()) # For mutiple row. a=c.fetchall() for row in a: print(row) try: except sqlite3.Error as e: print("An error occured:", e.args[0])
[ "simongideon918@gmail.com" ]
simongideon918@gmail.com
77936d27233ecb6692cf71a0edc03f93a9bed8ae
50dd2a43daa8316fc11e0c176b5872738fcc5dde
/Learning/130_Fluent_Python/fp2-utf8/bloccode/example 13-14.py
98a7540674b5e587a7df1e47f5cf78c41d0e53e3
[]
no_license
FrenchBear/Python
58204d368e3e72071eef298ff00d06ff51bd7914
b41ab4b6a59ee9e145ef2cd887a5fe306973962b
refs/heads/master
2023-08-31T18:43:37.792427
2023-08-26T15:53:20
2023-08-26T15:53:20
124,466,047
0
0
null
null
null
null
UTF-8
Python
false
false
261
py
# Example 13-14. typing.SupportsComplex protocol source code @runtime_checkable class SupportsComplex(Protocol): """An ABC with one abstract method __complex__.""" __slots__ = () @abstractmethod def __complex__(self) -> complex: pass
[ "FrenchBear38@outlook.com" ]
FrenchBear38@outlook.com
c3130eff5ead53a74d10c68261d2e3559dfc4623
91ab6e48d02822bd957e210484fceff4ce0b7d61
/usim_pytest/test_usimpy/utility.py
07f6c368aa6577c5ef2802885d34f46f00ad824f
[ "MIT" ]
permissive
MaineKuehn/usim
d203c78f2f644f546b932d1da40b50f26403d053
28615825fbe23140bbf9efe63fb18410f9453441
refs/heads/master
2021-09-25T08:05:03.015523
2021-09-17T13:42:39
2021-09-17T13:42:39
177,617,781
18
3
MIT
2021-09-17T13:42:40
2019-03-25T15:50:34
Python
UTF-8
Python
false
false
1,097
py
from functools import wraps from typing import Callable, Generator from ..utility import UnfinishedTest def via_usimpy(test_case: Callable[..., Generator]): """ Mark a generator function test case to be run via a ``usim.py.Environment`` .. code:: python3 @via_usimpy def test_sleep(env): before = env.now yield env.timeout(20) after = env.now assert after - before == 20 Note that ``env`` is passed in as a keyword argument. """ @wraps(test_case) def run_test(self=None, env=None, **kwargs): test_completed = False if self is not None: kwargs['self'] = self def complete_test_case(): __tracebackhide__ = True nonlocal test_completed yield from test_case(env=env, **kwargs) test_completed = True __tracebackhide__ = True env.process(complete_test_case()) result = env.run() if not test_completed: raise UnfinishedTest(test_case) return result return run_test
[ "maxfischer2781@gmail.com" ]
maxfischer2781@gmail.com
352e1986d5a4bcac3ff903fd27c91bb9134f049b
a904e99110721719d9ca493fdb91679d09577b8d
/month04/project/day01-note/django-redis-4.10.0/tests/test_sqlite_herd.py
8a053dfdee6155fadba6c8df1a27d172aada7270
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
chaofan-zheng/tedu-python-demo
7c7c64a355e5380d1f8b6464affeddfde0d27be7
abe983ddc52690f4726cf42cc6390cba815026d8
refs/heads/main
2023-03-12T05:17:34.596664
2021-02-27T08:33:31
2021-02-27T08:33:31
323,350,480
4
1
null
null
null
null
UTF-8
Python
false
false
1,113
py
SECRET_KEY = "django_tests_secret_key" CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': [ '127.0.0.1:6379:5', ], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.HerdClient', } }, "doesnotexist": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:56379?db=1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.HerdClient", } }, 'sample': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': '127.0.0.1:6379:1,127.0.0.1:6379:1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.HerdClient', } }, "with_prefix": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379?db=1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.HerdClient", }, "KEY_PREFIX": "test-prefix", }, } # TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' INSTALLED_APPS = ( "django.contrib.sessions", )
[ "417355570@qq.com" ]
417355570@qq.com
c6a4f7fd762b8c458facb55f5b26d1bc13b3c944
e16d7d8f60145c68640b25aa7c259618be60d855
/django_by_example/myshop/orders/admin.py
f09d215605498c4504e1c955a53d7fe07aa330af
[]
no_license
zongqiqi/mypython
bbe212223002dabef773ee0dbeafbad5986b4639
b80f3ce6c30a0677869a7b49421a757c16035178
refs/heads/master
2020-04-21T07:39:59.594233
2017-12-11T00:54:44
2017-12-11T00:54:44
98,426,286
2
0
null
null
null
null
UTF-8
Python
false
false
609
py
from django.contrib import admin from .models import Order,OrderItem class OrderItemInline(admin.TabularInline): model = OrderItem raw_id_fields = ['product'] class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'email','address', 'postal_code', 'city', 'paid','created', 'updated'] list_filter = ['paid', 'created', 'updated'] inlines = [OrderItemInline]#使用OrderItemline来把OrderItem引用为OrderAdmin类的内联类 #内联类允许你在同一个编辑页面引用模型,并且将这个模型作为父模型 admin.site.register(Order, OrderAdmin)
[ "544136329@qq.com" ]
544136329@qq.com
863e45c0783451eb725d9e5182ae2b3154aabdaf
c2634ebec1d4448e372d174f459c3cbc03fd1edc
/lib/node_modules/@stdlib/math/base/special/cosm1/benchmark/python/scipy/benchmark.py
0f15a4ea4a9a905870399f1ccf3964f8e9ad5d86
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "SunPro", "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-public-domain" ]
permissive
stdlib-js/stdlib
ede11aee78f08e4f78a0bb939cb0bc244850b55b
f10c6e7db1a2b15cdd2b6237dd0927466ebd7278
refs/heads/develop
2023-09-05T03:29:36.368208
2023-09-03T22:42:11
2023-09-03T22:42:11
54,614,238
4,163
230
Apache-2.0
2023-09-13T21:26:07
2016-03-24T04:19:52
JavaScript
UTF-8
Python
false
false
2,198
py
#!/usr/bin/env python # # @license Apache-2.0 # # Copyright (c) 2018 The Stdlib Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Benchmark scipy.special.cosm1.""" from __future__ import print_function import timeit NAME = "cosm1" REPEATS = 3 ITERATIONS = 1000000 def print_version(): """Print the TAP version.""" print("TAP version 13") def print_summary(total, passing): """Print the benchmark summary. # Arguments * `total`: total number of tests * `passing`: number of passing tests """ print("#") print("1.." + str(total)) # TAP plan print("# total " + str(total)) print("# pass " + str(passing)) print("#") print("# ok") def print_results(elapsed): """Print benchmark results. # Arguments * `elapsed`: elapsed time (in seconds) # Examples ``` python python> print_results(0.131009101868) ``` """ rate = ITERATIONS / elapsed print(" ---") print(" iterations: " + str(ITERATIONS)) print(" elapsed: " + str(elapsed)) print(" rate: " + str(rate)) print(" ...") def benchmark(): """Run the benchmark and print benchmark results.""" setup = "from scipy.special import cosm1; from random import random;" stmt = "y = cosm1(4.0*random() - 2.0)" t = timeit.Timer(stmt, setup=setup) print_version() for i in range(REPEATS): print("# python::scipy::" + NAME) elapsed = t.timeit(number=ITERATIONS) print_results(elapsed) print("ok " + str(i+1) + " benchmark finished") print_summary(REPEATS, REPEATS) def main(): """Run the benchmark.""" benchmark() if __name__ == "__main__": main()
[ "kgryte@gmail.com" ]
kgryte@gmail.com
d7b781bab6353a104d0b726b33244a8255434f2b
d47cd584579452a8212a19ffee462f0c2e792a9c
/fluent_contents/utils/tagparsing.py
0267274366501f593eb3eb2a955f356a98482d1c
[ "Apache-2.0" ]
permissive
kerin/django-fluent-contents
9db6d397c3b5aeebc4691e3b8ad6f09fbbd50c41
d760e7d1648f4583bdd8ba4c3078a3f5d9f544b4
refs/heads/master
2021-01-15T17:55:28.346869
2013-02-11T14:26:04
2013-02-11T14:26:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,421
py
from django.template.base import TemplateSyntaxError, Token import re kwarg_re = re.compile('^(?P<name>\w+)=') def parse_token_kwargs(parser, token, compile_args=False, compile_kwargs=False, allowed_kwargs=None): """ Allow the template tag arguments to be like a normal Python function, with *args and **kwargs. """ if isinstance(token, Token): bits = token.split_contents() else: bits = token expect_kwarg = False args = [] kwargs = {} prev_bit = None for bit in bits[1::]: match = kwarg_re.match(bit) if match: expect_kwarg = True (name, expr) = bit.split('=', 2) kwargs[name] = parser.compile_filter(expr) if compile_args else expr else: if expect_kwarg: raise TemplateSyntaxError("{0} tag may not have a non-keyword argument ({1}) after a keyword argument ({2}).".format(bits[0], bit, prev_bit)) args.append(parser.compile_filter(bit) if compile_kwargs else bit) prev_bit = bit # Validate the allowed arguments, to make things easier for template developers if allowed_kwargs is not None: for name in kwargs: if name not in allowed_kwargs: raise AttributeError("The option %s=... cannot be used in '%s'.\nPossible options are: %s." % (name, bits[0], ", ".join(allowed_kwargs))) return args, kwargs
[ "vdboor@edoburu.nl" ]
vdboor@edoburu.nl
169eefc9524590604288b8376f8c1f4d487c5c88
fa78cd539cade5bba07e393c8d1184be58a6477a
/waste_collection/admin.py
a67fc1b7b28aa161d2dfddec85b68688bc9f5d76
[]
no_license
iLabs-Makerere-University/tilenga-crm-django
e2c3e8777f012052a8cd77af5e06b9ae2180f805
f764153e9c5877e20be1a1c1459de9fcb2b9df07
refs/heads/master
2020-04-29T22:08:04.113720
2019-04-01T08:18:15
2019-04-01T08:18:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
223
py
from django.contrib import admin from . models import WasteManagementProcedure class WasteManagementProcedureAdmin(admin.ModelAdmin): pass admin.site.register(WasteManagementProcedure, WasteManagementProcedureAdmin)
[ "ephraim.malinga@gmail.com" ]
ephraim.malinga@gmail.com
601dc711804496f547111d1d953946085dd3b498
e07da133c4efa517e716af2bdf67a46f88a65b42
/hub20/apps/ethereum_money/management/commands/load_tracked_tokens.py
5701e391f3f536030bd13c896353e2c518edd93a
[ "MIT" ]
permissive
cryptobuks1/hub20
be1da5f77a884f70068fd41edaa45d5e65b7c35e
3a4d9cf16ed9d91495ac1a28c464ffb05e9f837b
refs/heads/master
2022-04-19T21:26:15.386567
2020-04-19T07:17:47
2020-04-19T07:17:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
892
py
import logging from django.core.management.base import BaseCommand from eth_utils import to_checksum_address from hub20.apps.ethereum_money.app_settings import TRACKED_TOKENS from hub20.apps.ethereum_money.models import EthereumToken logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Loads data relevant to all tokens that are going to be used by the instance" def handle(self, *args, **options): for token_address in TRACKED_TOKENS: logger.info(f"Checking token {token_address}...") try: EthereumToken.make(to_checksum_address(token_address)) except OverflowError: logger.error(f"{token_address} is not a valid address or not ERC20-compliant") except Exception as exc: logger.exception(f"Failed to load token data for {token_address}", exc_info=exc)
[ "raphael@lullis.net" ]
raphael@lullis.net
6ef6540bd2180186c923cbd1e76bfd2414db3f1d
ec6b94f8fa4558f2156f5cdf1ab0347fb5573241
/tests/clickhouse/query_dsl/test_project_id.py
ce274c9a8930b4499e68fc3e9dba3946378cca79
[ "Apache-2.0", "BUSL-1.1" ]
permissive
pombredanne/snuba
8e9a55bf38b3ac84407d0c2755e3c0ac226688de
eb1d25bc52320bf57a40fd6efc3da3dd5e9f1612
refs/heads/master
2021-08-27T20:55:46.392979
2021-08-14T08:21:47
2021-08-14T08:21:47
171,631,594
0
0
Apache-2.0
2020-01-10T10:42:17
2019-02-20T08:26:17
Python
UTF-8
Python
false
false
4,583
py
from typing import Any, MutableMapping, Set import pytest from snuba.clickhouse.query_dsl.accessors import get_object_ids_in_query_ast from snuba.datasets.factory import get_dataset from snuba.datasets.plans.translator.query import identity_translate from snuba.query.parser import parse_query test_cases = [ ( {"selected_columns": ["column1"], "conditions": [["project_id", "=", 100]]}, {100}, ), # Simple single project condition ( { "selected_columns": ["column1"], "conditions": [["project_id", "IN", [100, 200, 300]]], }, {100, 200, 300}, ), # Multiple projects in the query ( { "selected_columns": ["column1"], "conditions": [["project_id", "IN", (100, 200, 300)]], }, {100, 200, 300}, ), # Multiple projects in the query provided as tuple ( {"selected_columns": ["column1"], "conditions": []}, None, ), # No project condition ( { "selected_columns": ["column1"], "conditions": [ ["project_id", "IN", [100, 200, 300]], ["project_id", "IN", [300, 400, 500]], ], }, {300}, ), # Multiple project conditions, intersected together ( { "selected_columns": ["column1"], "conditions": [ [ ["project_id", "IN", [100, 200, 300]], ["project_id", "IN", [300, 400, 500]], ] ], }, {100, 200, 300, 400, 500}, ), # Multiple project conditions, in union ( { "selected_columns": ["column1"], "conditions": [ ["project_id", "IN", [100, 200, 300]], ["project_id", "=", 400], ], }, set(), ), # A fairly stupid query ( { "selected_columns": ["column1"], "conditions": [ ["column1", "=", "something"], [["ifNull", ["column2", 0]], "=", 1], ["project_id", "IN", [100, 200, 300]], [("count", ["column3"]), "=", 10], ["project_id", "=", 100], ], }, {100}, ), # Multiple conditions in AND. Two project conditions ( { "selected_columns": ["column1"], "conditions": [ ["project_id", "IN", [100, 200, 300]], [["project_id", "=", 100], ["project_id", "=", 200]], ], }, {100, 200}, ), # Main project list in a conditions and multiple project conditions in OR ( { "selected_columns": ["column1"], "conditions": [ ["project_id", "IN", [100, 200, 300]], [ [["ifNull", ["project_id", 1000]], "=", 100], [("count", ["column3"]), "=", 10], [["ifNull", ["project_id", 1000]], "=", 200], ], ], }, {100, 200, 300}, ), # Main project list in a conditions and multiple project conditions within unsupported function calls ( { "selected_columns": ["column1"], "conditions": [ [ [ "and", [ ["equals", ["project_id", 100]], ["equals", ["column1", "'something'"]], ], ], "=", 1, ], [ [ "and", [ ["equals", ["project_id", 200]], ["equals", ["column3", "'something_else'"]], ], ], "=", 1, ], ], }, None, ), # project_id in unsupported functions (cannot navigate into an "and" function) # TODO: make this work as it should through the AST. ] @pytest.mark.parametrize("query_body, expected_projects", test_cases) def test_find_projects( query_body: MutableMapping[str, Any], expected_projects: Set[int] ) -> None: events = get_dataset("events") query = identity_translate(parse_query(query_body, events)) project_ids_ast = get_object_ids_in_query_ast(query, "project_id") assert project_ids_ast == expected_projects
[ "noreply@github.com" ]
pombredanne.noreply@github.com
6cec2962afd83940865d9b5121ea405fb2a72374
c5dae77bb3ec7b39dca5c5c0522e101c4cb6d5a8
/rooms/permissions.py
8e1b5f8ec4de3e3507e9a1b899d0fbe75120a6cc
[]
no_license
Parkyes90/airbnb-api
f0726018738aad8eaf4ea891bb3de076ad875a36
f80864757433d0ea0421b2f47d2daab9cf02915f
refs/heads/master
2023-04-28T21:53:31.687273
2022-12-24T01:38:24
2022-12-24T01:38:24
243,207,499
0
0
null
2023-08-17T17:23:51
2020-02-26T08:19:24
Python
UTF-8
Python
false
false
320
py
from rest_framework.permissions import BasePermission class IsOwner(BasePermission): def has_object_permission(self, request, view, obj): if not hasattr(obj, "user"): raise Exception("해당 모델이 사용자 필드를 가지고 있지 않습니다.") return obj.user == request.user
[ "parkyes90@gmail.com" ]
parkyes90@gmail.com
1cb53ce92897d65d05b8eb78e9534d4bee7e0ba5
0fd9644616b5658ea960ef86f28b94cc95ce55e0
/djangoprj/mikrotik/migrations/0005_mtusers.py
744c7b72dff4e87a2d85c4bf78cfde2cdfeb1802
[]
no_license
zdimon/time-control
f4db6f26f15a18c89b91dba3f69a696a9d3a6c28
3a212d26dcaae13d3ca5a18247a425f63938fd7c
refs/heads/master
2020-05-13T16:33:53.011992
2019-04-19T07:05:01
2019-04-19T07:05:01
181,640,210
0
0
null
null
null
null
UTF-8
Python
false
false
631
py
# Generated by Django 2.2 on 2019-04-17 07:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mikrotik', '0004_auto_20190417_0640'), ] operations = [ migrations.CreateModel( name='MTUsers', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ip', models.CharField(max_length=250)), ('host', models.CharField(max_length=250)), ('mac', models.CharField(max_length=250)), ], ), ]
[ "zdimon@example.com" ]
zdimon@example.com
9be35d2a711c8eb0700d7ddfc54912967c9d4596
ff81a9d7880f1b85a1dc19d5eba5ac72d7179c86
/pychron/options/views/flux_visualization_views.py
208b66906956dcd975359ab479acc112319b92dd
[ "Apache-2.0" ]
permissive
UManPychron/pychron
2fb7e479a9f492423c0f458c70102c499e1062c4
b84c9fd70072f9cbda30abe2c471e64fe3dd75d8
refs/heads/develop
2022-12-03T23:32:45.579326
2020-01-29T19:02:20
2020-01-29T19:02:20
36,100,637
0
0
null
2015-05-23T00:10:06
2015-05-23T00:10:05
null
UTF-8
Python
false
false
2,220
py
# =============================================================================== # Copyright 2015 Jake Ross # # 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. # =============================================================================== # ============= enthought library imports ======================= from chaco.default_colormaps import color_map_name_dict from traitsui.api import Item, HGroup, VGroup, EnumEditor from pychron.options.options import SubOptions, AppearanceSubOptions class FluxVisualizationSubOptions(SubOptions): def traits_view(self): grp = VGroup(Item('plot_kind'), Item('model_kind')) return self._make_view(grp) class FluxVisualizationAppearanceSubOptions(AppearanceSubOptions): def traits_view(self): twodgrp = VGroup(HGroup(Item('color_map_name', label='Color Map', editor=EnumEditor(values=sorted(color_map_name_dict.keys()))), Item('levels')), visible_when='plot_kind=="2D"', label='Options', show_border=True) onedgrp = VGroup(Item('marker_size'), visible_when='plot_kind=="1D"', label='Options', show_border=True) scalegrp = VGroup(Item('flux_scalar', label='Scale', tooltip='Multiple flux by Scale. FOR DISPLAY ONLY')) return self._make_view(VGroup(twodgrp, onedgrp, scalegrp)) VIEWS = {'main': FluxVisualizationSubOptions, 'appearance': FluxVisualizationAppearanceSubOptions} # ============= EOF =============================================
[ "jirhiker@gmail.com" ]
jirhiker@gmail.com
caa434acc7d304b0c285e9a771010088d560dbc5
d3efc82dfa61fb82e47c82d52c838b38b076084c
/Autocase_Result/ReverseRepo/YW_NHG_SHHG_019_GC003.py
9f23f2cae281cc74a7cff9d8df2f7abdba2b90e2
[]
no_license
nantongzyg/xtp_test
58ce9f328f62a3ea5904e6ed907a169ef2df9258
ca9ab5cee03d7a2f457a95fb0f4762013caa5f9f
refs/heads/master
2022-11-30T08:57:45.345460
2020-07-30T01:43:30
2020-07-30T01:43:30
280,388,441
0
0
null
null
null
null
UTF-8
Python
false
false
3,025
py
#!/usr/bin/python # -*- encoding: utf-8 -*- import sys sys.path.append("/home/yhl2/workspace/xtp_test/xtp/api") from xtp_test_case import * sys.path.append("/home/yhl2/workspace/xtp_test/service") from ServiceConfig import * from mainService import * from QueryStkPriceQty import * from log import * sys.path.append("/home/yhl2/workspace/xtp_test/mysql") from CaseParmInsertMysql import * sys.path.append("/home/yhl2/workspace/xtp_test/utils") from QueryOrderErrorMsg import queryOrderErrorMsg class YW_NHG_SHHG_019_GC003(xtp_test_case): # YW_NHG_SHHG_019_GC003 def test_YW_NHG_SHHG_019_GC003(self): title = '上海逆回购--数量(等于100万张)-3天' # 定义当前测试用例的期待值 # 期望状态:初始、未成交、部成、全成、部撤已报、部撤、已报待撤、已撤、废单、撤废、内部撤单 # xtp_ID和cancel_xtpID默认为0,不需要变动 case_goal = { '期望状态': '全成', 'errorID': 0, 'errorMSG': '', '是否生成报单': '是', '是否是撤废': '否', 'xtp_ID': 0, 'cancel_xtpID': 0, } logger.warning(title) # 定义委托参数信息------------------------------------------ # 参数:证券代码、市场、证券类型、证券状态、交易状态、买卖方向(B买S卖)、期望状态、Api stkparm = QueryStkPriceQty('204003', '1', '12', '2', '0', 'S', case_goal['期望状态'], Api) # 如果下单参数获取失败,则用例失败 if stkparm['返回结果'] is False: rs = { '用例测试结果': stkparm['返回结果'], '测试错误原因': '获取下单参数失败,' + stkparm['错误原因'], } self.assertEqual(rs['用例测试结果'], True) else: wt_reqs = { 'business_type': Api.const.XTP_BUSINESS_TYPE['XTP_BUSINESS_TYPE_REPO'], 'order_client_id':2, 'market': Api.const.XTP_MARKET_TYPE['XTP_MKT_SH_A'], 'ticker': stkparm['证券代码'], 'side': Api.const.XTP_SIDE_TYPE['XTP_SIDE_SELL'], 'price_type': Api.const.XTP_PRICE_TYPE['XTP_PRICE_LIMIT'], 'price': stkparm['随机中间价'], 'quantity': 1000000, 'position_effect': Api.const.XTP_POSITION_EFFECT_TYPE['XTP_POSITION_EFFECT_INIT'] } ParmIni(Api, case_goal['期望状态'], wt_reqs['price_type']) CaseParmInsertMysql(case_goal, wt_reqs) rs = serviceTest(Api, case_goal, wt_reqs) logger.warning('执行结果为' + str(rs['用例测试结果']) + ',' + str(rs['用例错误源']) + ',' + str(rs['用例错误原因'])) self.assertEqual(rs['用例测试结果'], True) # 0 if __name__ == '__main__': unittest.main()
[ "418033945@qq.com" ]
418033945@qq.com
8a2eb7cfab390a2f709d7eb3419c08fa0e6dd095
0eb599c3bbfa6e5b31516913b88cc9db3a1311ce
/ABC_6q/abc169f.py
ad9eed03c6ee61e3f204ed1ab80452f68d22e136
[]
no_license
Linus-MK/AtCoder
5b84dc88c2d2773d0f97ed18265d303290da7879
a587e89a9e0c2ab4d36b09176bcc95e901e14326
refs/heads/master
2022-11-25T05:37:12.148722
2022-11-17T16:04:10
2022-11-17T16:04:10
169,840,698
0
0
null
null
null
null
UTF-8
Python
false
false
416
py
n, s = list(map(int, input().split())) nums = list(map(int, input().split())) dp = [[0 for i in range(s+1)] for j in range(n+1)] mod = 998244353 dp[0][0] = 1 for i in range(n): for summ in range(s+1): if summ - nums[i] >= 0: dp[i+1][summ] = (2 * dp[i][summ] + dp[i][summ - nums[i]]) % mod else: dp[i+1][summ] = (2 * dp[i][summ]) % mod # print(dp) print(dp[n][s] % mod)
[ "13600386+Linus-MK@users.noreply.github.com" ]
13600386+Linus-MK@users.noreply.github.com
a13a4d56104bd687f7c9c1b4efa6c7b4fb4ee4e4
2020c9c6958d9cc338b72f62e24d9ad30c1a8cad
/python/0101.symmetric-tree/symmetric-tree.py
8cf51e4680551dbd6d293ddb24a39ee7fa4c43f7
[]
no_license
ysmintor/leetcode
b2d87db932b77e72504ffa07d7bf1b0d8c09b661
434889037fe3e405a8cbc71cd822eb1bda9aa606
refs/heads/master
2020-05-30T21:03:03.886279
2019-10-31T08:46:23
2019-10-31T09:02:24
189,963,050
0
0
null
null
null
null
UTF-8
Python
false
false
534
py
class Solution: """ recursive solution """ def isSymmetric(self, root: TreeNode) -> bool: if root == None: return True return self.isMirror(root.left, root.right) def isMirror(self, t1: TreeNode, t2:TreeNode ) -> bool: if t1 == None and t2 == None: return True if t1 == None or t2 == None: return False return (t1.val == t2.val) \ and self.isMirror(t1.right, t2.left) \ and self.isMirror(t1.left, t2.right)
[ "ysmintor@gmail.com" ]
ysmintor@gmail.com
30dea1db000cc40ea6b735e332cf15c6d2f4bace
6413fe58b04ac2a7efe1e56050ad42d0e688adc6
/tempenv/lib/python3.7/site-packages/plotly/graph_objs/layout/ternary/aaxis/__init__.py
797a36fb417fb76496384beb1c5bdf6c09acee6b
[ "MIT" ]
permissive
tytechortz/Denver_temperature
7f91e0ac649f9584147d59193568f6ec7efe3a77
9d9ea31cd7ec003e8431dcbb10a3320be272996d
refs/heads/master
2022-12-09T06:22:14.963463
2019-10-09T16:30:52
2019-10-09T16:30:52
170,581,559
1
0
MIT
2022-06-21T23:04:21
2019-02-13T21:22:53
Python
UTF-8
Python
false
false
159
py
from ._title import Title from plotly.graph_objs.layout.ternary.aaxis import title from ._tickformatstop import Tickformatstop from ._tickfont import Tickfont
[ "jmswank7@gmail.com" ]
jmswank7@gmail.com
f86011e920527fade4c0b894ea3f406f6ca86766
9b20743ec6cd28d749a4323dcbadb1a0cffb281b
/10_Imbalanced_Classification_with_Python/13/03_balanced_decision_tree.py
723ce924b4ed4330ac7a194e25defea465a60bfa
[]
no_license
jggrimesdc-zz/MachineLearningExercises
6e1c7e1f95399e69bba95cdfe17c4f8d8c90d178
ee265f1c6029c91daff172b3e7c1a96177646bc5
refs/heads/master
2023-03-07T19:30:26.691659
2021-02-19T08:00:49
2021-02-19T08:00:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
823
py
# decision tree with class weight on an imbalanced classification dataset from numpy import mean from sklearn.datasets import make_classification from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.model_selection import cross_val_score from sklearn.tree import DecisionTreeClassifier # generate dataset X, y = make_classification(n_samples=10000, n_features=2, n_redundant=0, n_clusters_per_class=1, weights=[0.99], flip_y=0, random_state=3) # define model model = DecisionTreeClassifier(class_weight='balanced') # define evaluation procedure cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) # evaluate model scores = cross_val_score(model, X, y, scoring='roc_auc', cv=cv, n_jobs=-1) # summarize performance print('Mean ROC AUC: %.3f' % mean(scores))
[ "jgrimes@jgrimes.tech" ]
jgrimes@jgrimes.tech
11b41900468b82ef7940e02e889324872ea46a3f
f44a1cbb48952ce466310859234f73cb2769ef2c
/backend/mobile_5_oct_1723/wsgi.py
b09e1b28f4e63a9fbc6f3a96c61672bb2582051a
[]
no_license
crowdbotics-apps/mobile-5-oct-1723
ea496e71e634a67dccfb39019dd50d9351247943
94ddd875afaa86d5810d24644a35e23db6b231d1
refs/heads/master
2022-12-25T10:00:21.575101
2020-10-05T05:14:39
2020-10-05T05:14:39
301,300,030
0
0
null
null
null
null
UTF-8
Python
false
false
411
py
""" WSGI config for mobile_5_oct_1723 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mobile_5_oct_1723.settings') application = get_wsgi_application()
[ "team@crowdbotics.com" ]
team@crowdbotics.com
3b43b227b7faa549f674979711bdaec0a30fe8d9
aaf7e8f9ec5856241930c98167071e424967b486
/src/lib/glfs-web/app/snmp.py
f9fa73d88593c3e76f64161535626ffe193a8b58
[]
no_license
ShenDezhou/PyCRM
e32826d143598227910c6a13bbc70140ec7f56d2
36b9411d9d5372b59fed00afdbc74607fb010df9
refs/heads/master
2022-02-10T02:29:45.876818
2018-06-17T10:09:43
2018-06-17T10:09:43
72,261,079
1
1
null
null
null
null
UTF-8
Python
false
false
250
py
import netsnmp def snmp_query(oid, dest_host, community,version=2): varbind = netsnmp.Varbind(oid) result = netsnmp.snmpwalk(varbind, Version=version, DestHost=dest_host, Community=community) return result
[ "bangtech@sina.com" ]
bangtech@sina.com
fd0a6ba9360c28449fd6b0848a7aecadab2791fb
1e998b8aa40e29dd21e97b1071fc5dc46d4746c2
/example/example/urls.py
3f3d7176338ff3f5b14369d3c51078945a69d240
[ "MIT" ]
permissive
PragmaticMates/django-templates-i18n
61786d0e3daf304316609fbf17f87f27457fdaae
0dac1b8da498dc414d4836c1cf6cb82cb1597c26
refs/heads/master
2016-09-06T15:47:46.161242
2014-09-26T12:14:02
2014-09-26T12:14:02
22,213,677
3
0
null
null
null
null
UTF-8
Python
false
false
632
py
from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns # Uncomment the next two lines to enable the admin: from django.contrib import admin from views import HomeView, MyView admin.autodiscover() urlpatterns = i18n_patterns('', # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # Examples: url(r'^my-view/$', MyView.as_view(), name='my_view'), url(r'^$', HomeView.as_view(), name='home'), )
[ "erik.telepovsky@gmail.com" ]
erik.telepovsky@gmail.com
ecae1e41c1a4dbea1e9f916e518c7a30df863ebe
bc9f66258575dd5c8f36f5ad3d9dfdcb3670897d
/lib/third_party/google/cloud/pubsublite_v1/types/topic_stats.py
1ad03e069c7d8a1f576f2e229fdb25414030148e
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
google-cloud-sdk-unofficial/google-cloud-sdk
05fbb473d629195f25887fc5bfaa712f2cbc0a24
392abf004b16203030e6efd2f0af24db7c8d669e
refs/heads/master
2023-08-31T05:40:41.317697
2023-08-23T18:23:16
2023-08-23T18:23:16
335,182,594
9
2
NOASSERTION
2022-10-29T20:49:13
2021-02-02T05:47:30
Python
UTF-8
Python
false
false
5,658
py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore from google.cloud.pubsublite_v1.types import common from cloudsdk.google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.cloud.pubsublite.v1", manifest={ "ComputeMessageStatsRequest", "ComputeMessageStatsResponse", "ComputeHeadCursorRequest", "ComputeHeadCursorResponse", "ComputeTimeCursorRequest", "ComputeTimeCursorResponse", }, ) class ComputeMessageStatsRequest(proto.Message): r"""Compute statistics about a range of messages in a given topic and partition. Attributes: topic (str): Required. The topic for which we should compute message stats. partition (int): Required. The partition for which we should compute message stats. start_cursor (google.cloud.pubsublite_v1.types.Cursor): The inclusive start of the range. end_cursor (google.cloud.pubsublite_v1.types.Cursor): The exclusive end of the range. The range is empty if end_cursor <= start_cursor. Specifying a start_cursor before the first message and an end_cursor after the last message will retrieve all messages. """ topic = proto.Field(proto.STRING, number=1,) partition = proto.Field(proto.INT64, number=2,) start_cursor = proto.Field(proto.MESSAGE, number=3, message=common.Cursor,) end_cursor = proto.Field(proto.MESSAGE, number=4, message=common.Cursor,) class ComputeMessageStatsResponse(proto.Message): r"""Response containing stats for messages in the requested topic and partition. Attributes: message_count (int): The count of messages. message_bytes (int): The number of quota bytes accounted to these messages. minimum_publish_time (google.protobuf.timestamp_pb2.Timestamp): The minimum publish timestamp across these messages. Note that publish timestamps within a partition are not guaranteed to be non-decreasing. The timestamp will be unset if there are no messages. minimum_event_time (google.protobuf.timestamp_pb2.Timestamp): The minimum event timestamp across these messages. For the purposes of this computation, if a message does not have an event time, we use the publish time. The timestamp will be unset if there are no messages. """ message_count = proto.Field(proto.INT64, number=1,) message_bytes = proto.Field(proto.INT64, number=2,) minimum_publish_time = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) minimum_event_time = proto.Field( proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, ) class ComputeHeadCursorRequest(proto.Message): r"""Compute the current head cursor for a partition. Attributes: topic (str): Required. The topic for which we should compute the head cursor. partition (int): Required. The partition for which we should compute the head cursor. """ topic = proto.Field(proto.STRING, number=1,) partition = proto.Field(proto.INT64, number=2,) class ComputeHeadCursorResponse(proto.Message): r"""Response containing the head cursor for the requested topic and partition. Attributes: head_cursor (google.cloud.pubsublite_v1.types.Cursor): The head cursor. """ head_cursor = proto.Field(proto.MESSAGE, number=1, message=common.Cursor,) class ComputeTimeCursorRequest(proto.Message): r"""Compute the corresponding cursor for a publish or event time in a topic partition. Attributes: topic (str): Required. The topic for which we should compute the cursor. partition (int): Required. The partition for which we should compute the cursor. target (google.cloud.pubsublite_v1.types.TimeTarget): Required. The target publish or event time. Specifying a future time will return an unset cursor. """ topic = proto.Field(proto.STRING, number=1,) partition = proto.Field(proto.INT64, number=2,) target = proto.Field(proto.MESSAGE, number=3, message=common.TimeTarget,) class ComputeTimeCursorResponse(proto.Message): r"""Response containing the cursor corresponding to a publish or event time in a topic partition. Attributes: cursor (google.cloud.pubsublite_v1.types.Cursor): If present, the cursor references the first message with time greater than or equal to the specified target time. If such a message cannot be found, the cursor will be unset (i.e. ``cursor`` is not present). """ cursor = proto.Field(proto.MESSAGE, number=1, message=common.Cursor,) __all__ = tuple(sorted(__protobuf__.manifest))
[ "cloudsdk.mirror@gmail.com" ]
cloudsdk.mirror@gmail.com
996e69c5148b5df26512a00ee71bb6d5b3048f9e
b805ded84cff8878ae70d772e50cface0c3aa45c
/proxy_pool/proxy_pool/settings.py
b6ecc4f6634f97f0ee761b1fd95cd587f2e5db95
[]
no_license
CNZedChou/python-web-crawl-learning
74f014fe95797d3f534e373de8451d2dfcc0600c
5edf8f53e1bb9df3661ec007bb4d7f0ba04ab013
refs/heads/master
2022-11-10T08:26:53.275547
2020-07-06T02:33:03
2020-07-06T02:33:03
275,563,035
0
0
null
null
null
null
UTF-8
Python
false
false
777
py
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ @Author : Zed @Version : V1.0.0 ------------------------------------ @File : settings.py @Description : redis的密码,如果为空则表示没有密码 @CreateTime : 2020-6-30 11:22 ------------------------------------ @ModifyTime : """ PASSWORD = '' HOST = 'localhost' PORT = '6379' # 代理池的名称 PROXYPOOL = 'proxies' TEST_API = 'https://www.baidu.com' TEST_HEADERS ={ 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36', } # 循环校验时间 CYCLE_VALID_TIME = 60 # 代理池数量的最小值 LOWER_NUM = 10 # 代理池数量的最大值 UPPER_NUM = 100 # 检查时间 CHECK_POOL_CYCLE = 60
[ "1021844583@qq.com" ]
1021844583@qq.com
15b0120a6df7223e01d2f3afa3879e7993d63438
174f848b62fb2ea0a1605e1aab70085ffd27ce50
/beginning/age.py
0540185272594c22e444e0b66ab14903a4e2d11f
[]
no_license
unet-echelon/by_of_python_lesson
cd71bd3890d42d49cc128ec1730371bf1b64dbfa
c6c5c917414ac98b6dfb582dc06c26d31ea5b30c
refs/heads/master
2021-07-11T07:16:20.243347
2020-09-14T12:39:13
2020-09-14T12:39:13
201,041,106
0
0
null
null
null
null
UTF-8
Python
false
false
191
py
#!/usr/bin/env python3 age = 26 name = 'kernel' print('Возраст {0} -- {1} лет'.format(name,age)) print('Почему {0} забаляэеться с этим Python?'.format(name))
[ "aleguk@ukr.net" ]
aleguk@ukr.net
593eff5c51f3663c6b63401945d8e42c0bd744e9
1e9de96619592ed25c3a4ff57b6a78717882a709
/app/resources/database.py
970e203f904febf5289d936283299a350e6346e4
[]
no_license
AntoineDao/example-service
503d08788f7e557ee12f72fabfa537136b927d3f
8b088ecd0a67642737a883d7f035722a8cd7a0b4
refs/heads/master
2020-04-22T07:13:59.199629
2019-02-07T17:36:17
2019-02-07T17:36:17
170,213,289
0
0
null
2019-02-11T22:32:16
2019-02-11T22:32:16
null
UTF-8
Python
false
false
988
py
import os import datetime import uuid from flask_sqlalchemy import SQLAlchemy import app db = SQLAlchemy() class Example(db.Model): """ Example Model for storing example related details """ __tablename__ = "example" id = db.Column(db.String(), primary_key=True, default=str(uuid.uuid4())) email = db.Column(db.String(255), unique=True, nullable=False) registered_on = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow()) admin = db.Column(db.Boolean, nullable=False, default=False) username = db.Column(db.String(50), unique=True) password_hash = db.Column(db.String(100)) test = db.Column(db.String(100)) def __repr__(self): return "<User '{}'>".format(self.username) @classmethod def from_dict(cls, data): new = cls( id=data.get('id'), email=data.get('email'), admin=data.get('admin'), username=data.get('username') ) return new
[ "antoinedao1@gmail.com" ]
antoinedao1@gmail.com
c58f04c352758ec38036a3158f57cde81fbbd04f
3879d1ca43c573c209f962182cd1e7f7fe978fbf
/leetcode/1973. Count Nodes Equal to Sum of Descendants/1973.py
0b8f98e6fa4a8d999bcefc23edcbc239a22b78c5
[]
no_license
DoctorLai/ACM
34a5600a5adf22660c5d81b2d8b7a358be537ecf
aefa170f74c55c1230eb6f352770512b1e3f469e
refs/heads/master
2023-09-01T02:13:01.604508
2023-08-31T15:42:07
2023-08-31T15:42:07
146,173,024
62
18
null
2020-10-11T13:19:57
2018-08-26T11:00:36
C++
UTF-8
Python
false
false
864
py
# https://helloacm.com/teaching-kids-programming-count-nodes-equal-to-sum-of-descendants-recursive-depth-first-search-algorithm/ # https://leetcode.com/problems/count-nodes-equal-to-sum-of-descendants/ # MEDIUM, DFS, RECURSION # 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 equalToDescendants(self, root: Optional[TreeNode]) -> int: self.ans = 0 def dfs(root): if not root: return 0 lsum = dfs(root.left) rsum = dfs(root.right) if lsum + rsum == root.val: self.ans += 1 return lsum + rsum + root.val dfs(root) return self.ans
[ "noreply@github.com" ]
DoctorLai.noreply@github.com
0b205c12342378f7ce7b47dbe339627f706f8e2f
dd73faa1c747089c44dbe85e081de5a089046329
/api_app/views/index_view.py
afa13a27813919ffbd4ba28140a04fb8d96188ab
[]
no_license
spaun299/api_tv_web
34aaa6da5fc0f3154a5830953ec8e9ee90d1a3b0
a19c0079e06a7c823236fda5ffe9d1e46a5e829d
refs/heads/master
2021-01-10T03:39:25.309627
2016-02-12T10:26:34
2016-02-12T10:26:34
51,149,276
0
1
null
null
null
null
UTF-8
Python
false
false
260
py
from ..urls.blueprints import index_bp from flask import render_template, g from ..constants.constants import ACTIVE_PAGES @index_bp.route('/') @index_bp.route('/index') def index(): return render_template('index.html', active_page=ACTIVE_PAGES['main'])
[ "you@example.com" ]
you@example.com
e36a279c7da1ddf582be9cd6892c444d8c89ff99
f7cf5647517d5d728a306967bf7531cc86525d5a
/sdc_scale.py
2bba7f66631bbd7661779f25b465819206148b11
[]
no_license
khokhlov/seismic_data_converter
c6b4663efcf091eb2f76f260374a94cde961accf
b904f8cfa6e846beaa1c82643638886ca2dd6baa
refs/heads/master
2021-06-08T05:22:34.945126
2020-06-19T14:05:27
2020-06-19T14:05:27
95,864,892
0
0
null
null
null
null
UTF-8
Python
false
false
634
py
#!/usr/bin/env python # (C) Nikolay Khokhlov <k_h@inbox.ru> 2017 import argparse import numpy as np import sys from binjson import load_bin, save_bin def main(): parser = argparse.ArgumentParser(description = 'Scale all values at bin file.') parser.add_argument('input', help='input file') parser.add_argument('output', help='output file') parser.add_argument('-s', '--scale', help='scale value', type=float, required = True) args = parser.parse_args() jd, data = load_bin(args.input) data *= args.scale save_bin(args.output, data, jd['bbox']) if __name__ == "__main__": main()
[ "kolya.khokhlov@gmail.com" ]
kolya.khokhlov@gmail.com
b11bdcd4a134220f51a7db78eb753012b6bf3114
b144c5142226de4e6254e0044a1ca0fcd4c8bbc6
/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/learnedrouteipv6_fdef4758ad13bb42ae07821a7635e378.py
ce66b77a40c84a94b26b3eb20ccb5a7f7182c9a5
[ "MIT" ]
permissive
iwanb/ixnetwork_restpy
fa8b885ea7a4179048ef2636c37ef7d3f6692e31
c2cb68fee9f2cc2f86660760e9e07bd06c0013c2
refs/heads/master
2021-01-02T17:27:37.096268
2020-02-11T09:28:15
2020-02-11T09:28:15
239,721,780
0
0
NOASSERTION
2020-02-11T09:20:22
2020-02-11T09:20:21
null
UTF-8
Python
false
false
6,444
py
# MIT LICENSE # # Copyright 1997 - 2019 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class LearnedRouteIpv6(Base): """NOT DEFINED The LearnedRouteIpv6 class encapsulates a list of learnedRouteIpv6 resources that is managed by the system. A list of resources can be retrieved from the server using the LearnedRouteIpv6.find() method. """ __slots__ = () _SDM_NAME = 'learnedRouteIpv6' def __init__(self, parent): super(LearnedRouteIpv6, self).__init__(parent) @property def AsPath(self): """NOT DEFINED Returns: str """ return self._get_attribute('asPath') @property def BlockOffset(self): """NOT DEFINED Returns: number """ return self._get_attribute('blockOffset') @property def BlockSize(self): """NOT DEFINED Returns: number """ return self._get_attribute('blockSize') @property def ControlWordEnabled(self): """NOT DEFINED Returns: bool """ return self._get_attribute('controlWordEnabled') @property def IpPrefix(self): """NOT DEFINED Returns: str """ return self._get_attribute('ipPrefix') @property def LabelBase(self): """NOT DEFINED Returns: number """ return self._get_attribute('labelBase') @property def LocalPreference(self): """NOT DEFINED Returns: number """ return self._get_attribute('localPreference') @property def MaxLabel(self): """NOT DEFINED Returns: number """ return self._get_attribute('maxLabel') @property def MultiExitDiscriminator(self): """NOT DEFINED Returns: number """ return self._get_attribute('multiExitDiscriminator') @property def Neighbor(self): """NOT DEFINED Returns: str """ return self._get_attribute('neighbor') @property def NextHop(self): """NOT DEFINED Returns: str """ return self._get_attribute('nextHop') @property def OriginType(self): """NOT DEFINED Returns: str """ return self._get_attribute('originType') @property def PrefixLength(self): """NOT DEFINED Returns: number """ return self._get_attribute('prefixLength') @property def RouteDistinguisher(self): """NOT DEFINED Returns: str """ return self._get_attribute('routeDistinguisher') @property def SeqDeliveryEnabled(self): """NOT DEFINED Returns: bool """ return self._get_attribute('seqDeliveryEnabled') @property def SiteId(self): """NOT DEFINED Returns: number """ return self._get_attribute('siteId') def find(self, AsPath=None, BlockOffset=None, BlockSize=None, ControlWordEnabled=None, IpPrefix=None, LabelBase=None, LocalPreference=None, MaxLabel=None, MultiExitDiscriminator=None, Neighbor=None, NextHop=None, OriginType=None, PrefixLength=None, RouteDistinguisher=None, SeqDeliveryEnabled=None, SiteId=None): """Finds and retrieves learnedRouteIpv6 data from the server. All named parameters support regex and can be used to selectively retrieve learnedRouteIpv6 data from the server. By default the find method takes no parameters and will retrieve all learnedRouteIpv6 data from the server. Args: AsPath (str): NOT DEFINED BlockOffset (number): NOT DEFINED BlockSize (number): NOT DEFINED ControlWordEnabled (bool): NOT DEFINED IpPrefix (str): NOT DEFINED LabelBase (number): NOT DEFINED LocalPreference (number): NOT DEFINED MaxLabel (number): NOT DEFINED MultiExitDiscriminator (number): NOT DEFINED Neighbor (str): NOT DEFINED NextHop (str): NOT DEFINED OriginType (str): NOT DEFINED PrefixLength (number): NOT DEFINED RouteDistinguisher (str): NOT DEFINED SeqDeliveryEnabled (bool): NOT DEFINED SiteId (number): NOT DEFINED Returns: self: This instance with matching learnedRouteIpv6 data retrieved from the server available through an iterator or index Raises: ServerError: The server has encountered an uncategorized error condition """ return self._select(locals()) def read(self, href): """Retrieves a single instance of learnedRouteIpv6 data from the server. Args: href (str): An href to the instance to be retrieved Returns: self: This instance with the learnedRouteIpv6 data from the server available through an iterator or index Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ return self._read(href)
[ "srvc_cm_packages@keysight.com" ]
srvc_cm_packages@keysight.com
fcf943c9a12f68cdbce93984752dc88ce47547dc
3fa4a77e75738d00835dcca1c47d4b99d371b2d8
/backend/telegram/models/chats/admin_log_event/admin_log_event_action_toggle_admin.py
8cc707026c5b98d6b7ea0b8a0ae05a57598b13b7
[ "Apache-2.0" ]
permissive
appheap/social-media-analyzer
1711f415fcd094bff94ac4f009a7a8546f53196f
0f9da098bfb0b4f9eb38e0244aa3a168cf97d51c
refs/heads/master
2023-06-24T02:13:45.150791
2021-07-22T07:32:40
2021-07-22T07:32:40
287,000,778
5
3
null
null
null
null
UTF-8
Python
false
false
2,080
py
from typing import Optional from django.db import models, DatabaseError from telegram import models as tg_models from core.globals import logger from ...base import BaseModel class AdminLogEventActionToggleAdminQuerySet(models.QuerySet): def update_or_create_action(self, **kwargs) -> Optional['AdminLogEventActionToggleAdmin']: try: return self.update_or_create( **kwargs )[0] except DatabaseError as e: logger.exception(e) except Exception as e: logger.exception(e) return None class AdminLogEventActionToggleAdminManager(models.Manager): def get_queryset(self) -> AdminLogEventActionToggleAdminQuerySet: return AdminLogEventActionToggleAdminQuerySet(self.model, using=self._db) def update_or_create_action( self, *, db_prev_chat_member: 'tg_models.ChatMember', db_new_chat_member: 'tg_models.ChatMember', ) -> Optional['AdminLogEventActionToggleAdmin']: if db_prev_chat_member is None or db_new_chat_member is None: return None return self.get_queryset().update_or_create_action( **{ 'prev_participant': db_prev_chat_member, 'new_participant': db_new_chat_member, } ) class AdminLogEventActionToggleAdmin(BaseModel): """ The admin rights of a user were changed """ prev_participant = models.OneToOneField( 'telegram.ChatMember', on_delete=models.CASCADE, null=True, blank=True, related_name="action_toggle_admin_prev", ) new_participant = models.OneToOneField( 'telegram.ChatMember', on_delete=models.CASCADE, null=True, blank=True, related_name="action_toggle_admin_new", ) ########################################### # `admin_log_event` : AdminLogEvent this action belongs to objects = AdminLogEventActionToggleAdminManager() class Meta: verbose_name_plural = 'Events (toggle admin)'
[ "taleb.zarhesh@gmail.com" ]
taleb.zarhesh@gmail.com
174381d9dbc5ca6653d670f4e06be4f0bf6322c7
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/atbash-cipher/b9b8b95767434aa0871b2c8be48c53bd.py
f0b099a7bd55fe14b4e43829323d85f729c01d42
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
486
py
from string import ascii_lowercase, digits, maketrans, translate, whitespace, punctuation def xcode(text, space=None): xlate = maketrans(ascii_lowercase + digits, ascii_lowercase[::-1] + digits) out = translate(text.lower(), xlate, whitespace + punctuation) if space: tmp = "" for i in range(len(out))[::space]: tmp += (out[i:i+space] + " ") out = tmp.rstrip() return out encode = lambda x: xcode(x, 5) decode = lambda x: xcode(x)
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
dc73cf6e9989804e2dc0f3c2877e0fff14501cb2
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02851/s504076203.py
4b1b8ee55fac378d844e2fa9052da7b00644e874
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
1,688
py
def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getArray(intn): return [int(input()) for i in range(intn)] def input(): return sys.stdin.readline().rstrip() def rand_N(ran1, ran2): return random.randint(ran1, ran2) def rand_List(ran1, ran2, rantime): return [random.randint(ran1, ran2) for i in range(rantime)] def rand_ints_nodup(ran1, ran2, rantime): ns = [] while len(ns) < rantime: n = random.randint(ran1, ran2) if not n in ns: ns.append(n) return sorted(ns) def rand_query(ran1, ran2, rantime): r_query = [] while len(r_query) < rantime: n_q = rand_ints_nodup(ran1, ran2, 2) if not n_q in r_query: r_query.append(n_q) return sorted(r_query) from collections import defaultdict, deque, Counter from sys import exit from decimal import * import heapq import math from fractions import gcd import random import string import copy from itertools import combinations, permutations, product from operator import mul, itemgetter from functools import reduce from bisect import bisect_left, bisect_right import sys sys.setrecursionlimit(1000000000) mod = 10 ** 9 + 7 ############# # Main Code # ############# # 余りの平均が1のもの N, K = getNM() A = getList() A = [(i % K) - 1 for i in A] for i in range(N - 1): A[i + 1] += A[i] A.insert(0, 0) A = [i % K if i >= 0 else i for i in A] num = defaultdict(list) for i in range(N + 1): num[A[i]].append(i) cnt = 0 for key, opt in num.items(): for i in range(len(opt)): index = bisect_right(opt, opt[i] + K - 1) cnt += index - i - 1 print(cnt)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
16608f71543a2fe1d5b8b46899fd4afec3deff67
4104ef21c5383458ef0005179b77f582ae87844c
/web/migrations/0009_auto_20150728_1334.py
9321d918ca4040ea4a21f263470e94b1ce9fb7e9
[]
no_license
kodiers/quests
8580d4cacd5685e08989f28fc6825117b17ea146
006bfbd354c75f6baeac020112cf36adcee9b016
refs/heads/master
2021-01-18T22:25:00.676362
2016-05-23T23:08:18
2016-05-23T23:08:18
37,993,239
0
0
null
null
null
null
UTF-8
Python
false
false
1,497
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('web', '0008_organizers_show_on_main_page'), ] operations = [ migrations.CreateModel( name='EventsPhotos', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')), ('title', models.TextField(null=True, blank=True, verbose_name='Title')), ('description', models.TextField(null=True, blank=True, verbose_name='Descrition')), ('date', models.DateField(null=True, blank=True, verbose_name='Date')), ('image', models.ImageField(upload_to='images')), ], options={ 'verbose_name_plural': 'Event photos', 'verbose_name': 'Event photo', }, ), migrations.AlterField( model_name='events', name='registered_players', field=models.ManyToManyField(null=True, related_name='regitered_players', blank=True, to=settings.AUTH_USER_MODEL, verbose_name='Registered users'), ), migrations.AddField( model_name='events', name='event_photos', field=models.ManyToManyField(null=True, to='web.EventsPhotos', blank=True, verbose_name='Event photos'), ), ]
[ "kodiers@gmail.com" ]
kodiers@gmail.com
39d76c5ac93ca62d22d8102da6ae57b798a0abc1
41b59a9c8381fa3a92f5d2c37c91261afb9c82c4
/QCDEventShape/2017/MC/test/Run_QCD_test_76x_data_cfg.py
a70d898a68603a21318aca5063817cdfeee12de7
[]
no_license
Sumankkundu/ChargedParticle
c6d4f90b55df49321df2ecd758bb1f39db896f8c
eb5bada24b37a58ded186d6e5d2d7bd00898fefe
refs/heads/master
2023-07-15T03:34:33.377203
2021-08-31T05:01:32
2021-08-31T05:01:32
231,091,587
1
0
null
null
null
null
UTF-8
Python
false
false
7,329
py
import FWCore.ParameterSet.Config as cms process = cms.Process("Test") ## switch to uncheduled mode #process.options.allowUnscheduled = cms.untracked.bool(True) #process.Tracer = cms.Service("Tracer") process.load("PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff") process.load("PhysicsTools.PatAlgos.selectionLayer1.selectedPatCandidates_cff") # source process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring(#'/store/mc/Spring14dr/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/AODSIM/PU20bx25_POSTLS170_V5-v1/00000/00B6F8B6-90F1-E311-B72C-0025905A6092.root' '/store/data/Run2017F/JetHT/MINIAOD/17Nov2017-v1/70000/FEA2ED14-5CDF-E711-ACA6-02163E012AF0.root', '/store/data/Run2017F/JetHT/MINIAOD/17Nov2017-v1/70000/FE211553-36DF-E711-BAB7-02163E019BD0.root', #'/store/data/Run2017F/JetHT/MINIAOD/17Nov2017-v1/70000/FE155D02-00DF-E711-BA34-02163E011A55.root', #'/store/data/Run2017F/JetHT/MINIAOD/17Nov2017-v1/70000/FE08F446-63DF-E711-A338-A4BF0112BCF8.root', #'/store/data/Run2015D/JetHT/MINIAOD/PromptReco-v4/000/258/750/00000/28938773-BD72-E511-A479-02163E01432A.root', #'/store/data/Run2015D/JetHT/MINIAOD/PromptReco-v4/000/258/159/00000/0075E33B-3B6C-E511-BCC8-02163E01455C.root' #'/store/data/Run2015D/JetHT/MINIAOD/PromptReco-v4/000/258/159/00000/0CE8F23E-3B6C-E511-B68A-02163E013744.root', #'/store/data/Run2015D/JetHT/MINIAOD/PromptReco-v4/000/258/159/00000/36DC8060-3B6C-E511-BC73-02163E0143DD.root', #'/store/data/Run2015D/JetHT/MINIAOD/PromptReco-v4/000/258/159/00000/50A3A073-3B6C-E511-A997-02163E0144CD.root' #'/store/data/Run2015D/JetHT/MINIAOD/16Dec2015-v1/00000/301A497D-70B0-E511-9630-002590D0AFA8.root', #'/store/data/Run2015D/JetHT/MINIAOD/16Dec2015-v1/00000/7210C351-67B0-E511-A34C-7845C4FC37AF.root' #'/store/data/Run2015D/JetHT/MINIAOD/16Dec2015-v1/00000/745E2A4F-67B0-E511-9DA3-0090FAA57620.root', #'/store/data/Run2015D/JetHT/MINIAOD/16Dec2015-v1/00000/7E46D250-67B0-E511-BB96-0025905C3E66.root' ) ) #process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) #process.load("Configuration.StandardSequences.Geometry_cff") #process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff") process.load("Configuration.Geometry.GeometryRecoDB_cff") #process.GlobalTag.globaltag = cms.string('POSTLS170_V5') process.load("Configuration.StandardSequences.MagneticField_cff") from Configuration.AlCa.GlobalTag import GlobalTag #process.GlobalTag = GlobalTag(process.GlobalTag,'GR_P_V56::All') #process.GlobalTag = GlobalTag(process.GlobalTag,'GR_R_44_V11::All') #process.GlobalTag = GlobalTag(process.GlobalTag,'74X_dataRun2_Prompt_v1') #process.GlobalTag = GlobalTag(process.GlobalTag,'94X_dataRun2_ReReco_EOY17_v6') #process.GlobalTag = GlobalTag(process.GlobalTag,'94X_dataRun2_ReReco_EOY17_v2') process.GlobalTag = GlobalTag(process.GlobalTag,'94X_dataRun2_v6') from PhysicsTools.PatAlgos.tools.coreTools import * # produce PAT Layer 1 process.load("PhysicsTools.PatAlgos.patSequences_cff") process.MessageLogger = cms.Service("MessageLogger", cout = cms.untracked.PSet( default = cms.untracked.PSet( ## kill all messages in the log limit = cms.untracked.int32(0) ), FwkJob = cms.untracked.PSet( ## but FwkJob category - those unlimitted limit = cms.untracked.int32(-1) ) ), categories = cms.untracked.vstring('FwkJob'), destinations = cms.untracked.vstring('cout') ) #process.load("HLTrigger.HLTcore.hltPrescaleRecorder_cfi") #ak5 PF & Gen Jets #from RecoJets.JetProducers.ak5PFJets_cfi import ak5PFJets #from RecoJets.JetProducers.ak5GenJets_cfi import ak5GenJets #from RecoMET.METProducers.PFMET_cfi import pfMet #process.ak5PFJets = ak5PFJets.clone(src = 'packedPFCandidates') #process.ak5GenJets = ak5GenJets.clone(src = 'packedGenParticles') # Select candidates that would pass CHS requirements #process.chs = cms.EDFilter("CandPtrSelector", src = cms.InputTag("packedPFCandidates"), cut = cms.string("fromPV")) #makes chs ak5 jets (instead of ak4 that are default in miniAOD ) #process.ak5PFJetsCHS = ak5PFJets.clone(src = 'chs') process.TFileService=cms.Service("TFileService", fileName=cms.string("Test_Data_QCD_char_2017.root") ) print "test1" process.analyzeBasicPat = cms.EDAnalyzer("QCDEventShape", # photonSrc = cms.untracked.InputTag("cleanPatPhotons"), # electronSrc = cms.untracked.InputTag("cleanPatElectrons"), # muonSrc = cms.untracked.InputTag("cleanPatMuons"), # tauSrc = cms.untracked.InputTag("cleanPatTaus"), jetSrc = cms.InputTag("slimmedJets"), metSrc = cms.InputTag("slimmedMETs"), genSrc = cms.untracked.InputTag("packedGenParticles"), pfSrc = cms.InputTag("packedPFCandidates"), bits = cms.InputTag("TriggerResults","","HLT"), prescales = cms.InputTag("patTrigger"), objects = cms.InputTag("selectedPatTrigger"), vertices = cms.InputTag("offlineSlimmedPrimaryVertices"), bsSrc = cms.InputTag("offlineBeamSpot"), genjetSrc = cms.InputTag("slimmedGenJets"), pileupSrc =cms.InputTag("slimmedAddPileupInfo"), ak5pfJetSrc = cms.InputTag("ak5PFJets"), ak5genJetSrc = cms.InputTag("ak5GenJets"), evtinfo =cms.InputTag("generator"), rho = cms.InputTag('fixedGridRhoAll'), LHEEventProductInputTag = cms.InputTag('externalLHEProducer'), LHERunInfoProductInputTag = cms.InputTag('externalLHEProducer'), PDFCTEQWeightsInputTag = cms.InputTag('pdfWeights:CT14'), PDFMMTHWeightsInputTag = cms.InputTag('pdfWeights:MMHT2014lo68cl'), PDFNNPDFWeightsInputTag = cms.InputTag('pdfWeights:NNPDF30'), #ak5PFJetCHSSrc = cms.InputTag("ak5PFJetsCHS") RootFileName = cms.untracked.string('pythia8_test_13tev.root'), GenJET = cms.untracked.bool(False), HistFill = cms.untracked.bool(True), MonteCarlo = cms.untracked.bool(False), ParticleLabel = cms.untracked.bool(False), Reconstruct =cms.untracked.bool(True), # EtaRange = cms.untracked.double(5.0), # PtThreshold = cms.untracked.double(12.0), EtaRange = cms.untracked.double(3.0), PtThreshold = cms.untracked.double(55.0), #effective is 21 LeadingPtThreshold = cms.untracked.double(150.0), #effective is 81 # scaleFactorsFile = cms.FileInPath('CondFormats/JetMETObjects/data/Summer15_V0_MC_JER_AK4PFchs.txt'), # resolutionsFile = cms.FileInPath('CondFormats/JetMETObjects/data/Summer15_V0_MC_JER_AK4PFchs.txt'), # scaleFactorsFile = cms.FileInPath('Fall15_25nsV2_MC_SF_AK4PFchs.txt'), # resolutionsFile = cms.FileInPath('Fall15_25nsV2_MC_PtResolution_AK4PFchs.txt'), # scaleFactorsFile = cms.FileInPath('Fall15_25nsV2_MC_SF_AK4PFchs.txt'), # resolutionsFile = cms.FileInPath('Fall15_25nsV2_MC_PtResolution_AK4PFchs.txt'), ) #process.ak5PFJets = ak5PFJets.clone(src = 'packedPFCandidates') #process.analyzeBasicPat.append("keep *_ak5PFJets_*_EX") #process.analyzeBasicPat.append("keep *_ak5PFJetsCHS_*_EX") process.p = cms.Path(process.analyzeBasicPat) print "test2" #process.p = cms.Path(process.ak5PFJets*process.ak5GenJets*process.analyzeBasicPat)
[ "skundu91phys@gmail.com" ]
skundu91phys@gmail.com
d5415f607dd31adae279661a33d4bee445418136
76084379c92ba50a7dd273072c828e1fb886ac66
/s3iotools/io/dataframe.py
23a9451c51516f2e9c1369c1b027ddbd284b631c
[ "MIT" ]
permissive
MacHu-GWU/s3iotools-project
19a08698b3f41fdb165a5df266860afdfe82d10e
6e8a12d30792464c6ffa13cfb105578aed9f67da
refs/heads/master
2020-04-25T18:05:13.116604
2019-05-20T13:00:02
2019-05-20T13:00:02
172,972,132
0
1
null
null
null
null
UTF-8
Python
false
false
7,796
py
# -*- coding: utf-8 -*- """ s3 IO tools. """ import attr import pandas as pd from six import string_types, StringIO, BytesIO, PY3 from ..compat import gzip_compress, gzip_decompress @attr.s class S3Dataframe(object): """ S3 object backed pandas DataFrame. """ s3_resource = attr.ib(default=None) bucket_name = attr.ib( validator=attr.validators.optional( attr.validators.instance_of(string_types) ), default=None, ) _bucket = attr.ib(default=None) key = attr.ib( validator=attr.validators.optional( attr.validators.instance_of(string_types) ), default=None, ) _object = attr.ib(default=None) df = attr.ib( validator=attr.validators.optional( attr.validators.instance_of(pd.DataFrame) ), default=None, ) @property def bucket(self): """ access the ``s3.Bucket`` instance. Ref: https://boto3.readthedocs.io/en/latest/reference/services/s3.html#bucket """ if self._bucket is None: self._bucket = self.s3_resource.Bucket(self.bucket_name) return self._bucket @property def object(self): """ access the ``s3.Object`` instance. Ref: https://boto3.readthedocs.io/en/latest/reference/services/s3.html#object """ if self._object is None: self._object = self.bucket.Object(self.key) return self._object def prepare_args(self, bucket, key, kwargs, default_kwargs): if bucket is None: bucket = self.bucket if key is None: key = self.key extra_kwargs = default_kwargs.copy() extra_kwargs.update(kwargs) return bucket, key, extra_kwargs to_csv_kwargs_default = { "encoding": "utf-8", "index": False, } def to_csv(self, bucket=None, key=None, gzip_compressed=False, **to_csv_kwargs): """ Save a dataframe to a s3 object in csv format. It will overwrite existing one. :param bucket: :class:`s3.Bucket`, optional if self.bucket_name is defined :param key: str, optional if self.key is defined :param gzip_compressed: bool :param to_csv_kwargs: key word arguments for :meth:`pandas.DataFrame.to_csv` :return: s3.Bucket.put_object() response """ bucket, key, kwargs = self.prepare_args( bucket, key, to_csv_kwargs, self.to_csv_kwargs_default) body = self.df.to_csv(**kwargs) if PY3: body = body.encode("utf-8") if gzip_compressed is True: body = gzip_compress(body) response = bucket.put_object(Body=body, Key=key) return response read_csv_kwargs_default = { "encoding": "utf-8" } def read_csv(self, bucket=None, key=None, gzip_compressed=False, **read_csv_kwargs): """ Read dataframe data from a s3 object in csv format. :param bucket: :class:`s3.Bucket`, optional if self.bucket_name is defined :param key: str, optional if self.key is defined :param gzip_compressed: bool :param read_csv_kwargs: key word arguments for :meth:`pandas.read_csv` :return: s3.Object.get() response """ bucket, key, kwargs = self.prepare_args( bucket, key, read_csv_kwargs, self.read_csv_kwargs_default) obj = bucket.Object(key) response = obj.get() body = response["Body"].read() if gzip_compressed: body = gzip_decompress(body) self.df = pd.read_csv(StringIO(body.decode("utf-8")), **kwargs) return response to_json_kwargs_default = { "force_ascii": False, } def to_json(self, bucket=None, key=None, gzip_compressed=False, **to_json_kwargs): """ Save a dataframe to a s3 object in csv format. It will overwrite existing one. :param bucket: :class:`s3.Bucket`, optional if self.bucket_name is defined :param key: str, optional if self.key is defined :param gzip_compressed: bool :param to_json_kwargs: key word arguments for :meth:`pandas.DataFrame.to_json` :return: s3.Bucket.put_object() response """ bucket, key, kwargs = self.prepare_args( bucket, key, to_json_kwargs, self.to_json_kwargs_default) body = self.df.to_json(**kwargs) if PY3: body = body.encode("utf-8") if gzip_compressed is True: body = gzip_compress(body) response = bucket.put_object(Body=body, Key=key) return response read_json_kwargs_default = { "encoding": "utf-8" } def read_json(self, bucket=None, key=None, gzip_compressed=False, **read_json_kwargs): """ Read dataframe data from a s3 object in json format. :param bucket: :class:`s3.Bucket`, optional if self.bucket_name is defined :param key: str, optional if self.key is defined :param gzip_compressed: bool :param read_json_kwargs: key word arguments for :meth:`pandas.read_json` :return: s3.Object.get() response """ bucket, key, kwargs = self.prepare_args( bucket, key, read_json_kwargs, self.read_json_kwargs_default) obj = bucket.Object(key) response = obj.get() body = response["Body"].read() if gzip_compressed: body = gzip_decompress(body) self.df = pd.read_json(StringIO(body.decode("utf-8")), **kwargs) return response write_table_kwargs_default = { } class ParquestCompression: gzip = "gzip" snappy = "snappy" brotli = "brotli" lz4 = "lz4" zstd = "zstd" none = None def to_parquet(self, bucket=None, key=None, compression=None, **write_table_kwargs): """ Save a dataframe to a s3 object in parquet format. It will overwrite existing one. :param bucket: :class:`s3.Bucket`, optional if self.bucket_name is defined :param key: str, optional if self.key is defined :param gzip_compressed: bool :param to_json_kwargs: key word arguments for :meth:`pyarrow.parquet.write_table_kwargs` :return: s3.Bucket.put_object() response """ import pyarrow from pyarrow import parquet bucket, key, kwargs = self.prepare_args( bucket, key, write_table_kwargs, self.write_table_kwargs_default) buffer = BytesIO() parquet.write_table( pyarrow.Table.from_pandas(self.df), buffer, compression=compression, **write_table_kwargs ) body = buffer.getvalue() response = bucket.put_object(Body=body, Key=key) return response read_table_kwargs_default = {} def read_parquet(self, bucket=None, key=None, **read_table_kwargs): """ Read dataframe data from a s3 object in parquet format. :param bucket: :class:`s3.Bucket`, optional if self.bucket_name is defined :param key: str, optional if self.key is defined :param read_table_kwargs: key word arguments for :meth:`pyarrow.parquet.read_table` :return: s3.Object.get() response """ from pyarrow import parquet bucket, key, kwargs = self.prepare_args( bucket, key, read_table_kwargs, self.read_table_kwargs_default) obj = bucket.Object(key) response = obj.get() # boto3 StreamingBody has not implemented closed attribute buffer = BytesIO() buffer.write(response["Body"].read()) self.df = parquet.read_table(buffer, **read_table_kwargs).to_pandas() return response
[ "husanhe@gmail.com" ]
husanhe@gmail.com
37f2a774f750224dc8e9aa45726c5e4d43d15a98
78cb6dadc7599e01b078682b175f21be673ed199
/289. Game of Life.py
8f9a3ce969e8b1a9a93adcdce1c8c56a5b245d10
[]
no_license
AlexWufan/leetcode-python
5cf5f13dbc7d1e425fde646df618e50c488fa79f
435323a9fcea6a4d09266785e88fb78735e0cc3e
refs/heads/master
2021-01-13T00:49:49.870468
2018-04-13T18:44:19
2018-04-13T18:44:19
51,347,271
0
0
null
null
null
null
UTF-8
Python
false
false
205
py
class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ tbc
[ "mengnanszw@gmail.com" ]
mengnanszw@gmail.com
716e24f833117790ab5298a92011c308a6ea8355
56be7f6b6a1243c532af9ea98310ccea165a1e66
/day18/课件/day18mysite/app01/migrations/0002_publisher.py
fe58096c46afa0d01cbc643d0689ddf1f3992ce0
[]
no_license
214031230/Python21
55b0405ec4ad186b052cde7ebfb3f4bb636a3f30
d7fc68d3d23345df5bfb09d4a84686c8b49a5ad7
refs/heads/master
2021-05-26T06:00:53.393577
2019-01-09T02:29:04
2019-01-09T02:29:04
127,778,172
0
0
null
null
null
null
UTF-8
Python
false
false
569
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-08-19 04:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app01', '0001_initial'), ] operations = [ migrations.CreateModel( name='Publisher', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=24)), ], ), ]
[ "21403123@qq.com" ]
21403123@qq.com
911dc1a4721c02884df0423246b265a52c5c38e8
b914ee0f23ddafa487e5cb35c35c3d41517a47a8
/Ornek2_7.py
8874dbd3f5b9f090d4b56a7557a26203c85a08b6
[]
no_license
suacalis/VeriBilimiPython
0dc45402b09936c82cecca9d6447873d24d1b241
85dbfa98ccf1a6a4e8916d134dc1ad41f99535ad
refs/heads/main
2023-08-24T17:03:48.627831
2021-09-28T07:28:21
2021-09-28T07:28:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
395
py
''' Örnek 2.7: Kullanıcı tarafından girilen yarıçap (r) değerine göre bir dairenin çevresini hesaplayan programı kodlayalım. ''' import math #pi için gerekli import easygui #enterbox(), msgbox() için gerekli r = easygui.enterbox("Dairenin yarıçapı.:") r = float(r) #girilen float tipine dönüştü. Cevre = 2*math.pi*r easygui.msgbox(msg=Cevre,title="Dairenin Çevresi")
[ "noreply@github.com" ]
suacalis.noreply@github.com
def7d53c45ac5636dbf465c21bd23e68f4c0277e
f2a678afb6152de57635c503ed532a205664b413
/items/migrations/0001_initial.py
a97ac753a607b444c4082ac3d4068767d265ff07
[]
no_license
phrac/onepercentgame
4d4a6247d5f587a65faef8d05a22a2522de3e6f8
113d01a3c6641d90f1ce4674ec565ed40ee7c093
refs/heads/master
2016-09-16T00:49:36.489216
2015-08-30T21:30:51
2015-08-30T21:30:51
41,644,531
0
0
null
null
null
null
UTF-8
Python
false
false
565
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=32)), ('cash_value', models.DecimalField(max_digits=11, decimal_places=2)), ], ), ]
[ "derek@disflux.com" ]
derek@disflux.com
053b4ae6bb4f8ac87dc20403abc872c543784cd4
1e65ca80032b1b5a4ab3631044c3d41a9f3dd035
/01_Jump_to_Python/Chapter03/rhombus_v1.py
2ef012fb11668bdbb5d71475d648db0bd3ffd592
[]
no_license
bj730612/Bigdata
cdd398c56023c67a2e56c36151e9f2bca067a40a
9bb38e30bb3728b4a4e75bc763fa858029414d4e
refs/heads/master
2020-03-15T09:27:23.995217
2018-10-02T00:07:38
2018-10-02T00:07:38
132,075,198
0
0
null
null
null
null
UHC
Python
false
false
473
py
#coding: cp949 while True: i = 0 base=(int)(input("홀수를 입력하세요.(0 <- 종료): ")) num=(base+1)/2 if base%2 == 1: while True: if num > i: print(" "*(int)(num-1-i),end="") print("*"*(int)((2*i)+1)) i+=1 if num <= i: break elif base == 0: break else: print("짝수를 입력하셨습니다. 다시 입력하세요")
[ "USER@test.com" ]
USER@test.com
099ec43119f2ae5e0635eb44a1dbff6c88d3ed20
4730749ce5f0f4f652b688c7594badc1c357f1d6
/LV.1/핸드폰 번호 가리기.py
4553fb1630829f20ac62717e105e0e247257c327
[]
no_license
RobertHan96/programmers_algorithm
4de015278d7242ee79cd33047a6975a9c9d63c92
776777e14e33ca99571296defd28d145d6366bef
refs/heads/master
2022-04-26T22:46:54.363542
2022-04-12T13:53:46
2022-04-12T13:53:46
233,599,487
0
0
null
null
null
null
UTF-8
Python
false
false
574
py
# 프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다. # 전화번호가 문자열 phone_number로 주어졌을 때, # 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요. # s는 길이 4 이상, 20이하인 문자열입니다. def solution(phone_number): numbers = list(phone_number) return (len(numbers)-4) * "*" + ''.join(numbers[len(numbers)-4:]) print(solution('027778888'))
[ "yshan4329@gmail.com" ]
yshan4329@gmail.com
8c205a7d4003fa5e71c1b5a52726c951d55b0033
786027545626c24486753351d6e19093b261cd7d
/ghidra9.2.1_pyi/ghidra/graph/viewer/layout/GridLocationMap.pyi
f3f8d6ccb23e3486a6d68662f4b630f36b2434c5
[ "MIT" ]
permissive
kohnakagawa/ghidra_scripts
51cede1874ef2b1fed901b802316449b4bf25661
5afed1234a7266c0624ec445133280993077c376
refs/heads/main
2023-03-25T08:25:16.842142
2021-03-18T13:31:40
2021-03-18T13:31:40
338,577,905
14
1
null
null
null
null
UTF-8
Python
false
false
2,437
pyi
from typing import List import ghidra.graph.viewer.layout import java.lang class GridLocationMap(object): """ An object that maps vertices to rows and columns and edges to their articulation points. This class is essentially a container that allows layout algorithms to store results, which can later be turned into layout positioning points. The integer point values in this class are row, column grid values, starting at 0,0. Note: the Point2D values for the edge articulations use x,y values that are row and column index values, the same values as calling #row(Object) and #col(Object). After building the grid using this class, clients can call #rows() to get high-order object that represent rows. """ def __init__(self): ... def centerRows(self) -> None: """ Updates each row within the grid such that it's x values are set to center the row in the grid. Each row will be updated so that all its columns start at zero. After that, each column will be centered in the grid. """ ... @overload def col(self, __a0: object) -> int: ... @overload def col(self, __a0: object, __a1: int) -> None: ... def dispose(self) -> None: ... def equals(self, __a0: object) -> bool: ... def getArticulations(self, __a0: object) -> List[object]: ... def getClass(self) -> java.lang.Class: ... def hashCode(self) -> int: ... def notify(self) -> None: ... def notifyAll(self) -> None: ... @overload def row(self, __a0: object) -> int: ... @overload def row(self, __a0: object, __a1: int) -> None: ... def rows(self) -> List[ghidra.graph.viewer.layout.Row]: """ Returns the rows in this grid, sorted by index (index can be negative) @return the rows in this grid """ ... def set(self, __a0: object, __a1: int, __a2: int) -> None: ... def setArticulations(self, __a0: object, __a1: List[object]) -> None: ... def toString(self) -> unicode: ... def toStringGrid(self) -> unicode: """ Creates a string representation of this grid @return a string representation of this grid """ ... @overload def wait(self) -> None: ... @overload def wait(self, __a0: long) -> None: ... @overload def wait(self, __a0: long, __a1: int) -> None: ...
[ "tsunekou1019@gmail.com" ]
tsunekou1019@gmail.com
f4ef2defc06bdd2a35f26acedd9b7bac282e0460
4e54d2199f7c601f6efc58d88447eeeb3594a637
/riselive/python_courses/datatype.3.py
f917572804f2b27081ab90ec6371e9caf2148654
[ "MIT" ]
permissive
Z3Prover/doc
4e23e40cef32cf8102bd0dda7fb76d01051f9210
f79ba59ce06e855d783508d9b6f47a8947480d12
refs/heads/master
2023-09-05T19:45:26.160516
2023-08-01T17:01:16
2023-08-01T17:01:16
151,014,945
34
20
MIT
2023-06-30T03:29:19
2018-09-30T23:09:21
HTML
UTF-8
Python
false
false
393
py
Color = Datatype('Color') Color.declare('red') Color.declare('green') Color.declare('blue') Color = Color.create() print is_expr(Color.green) print Color.green == Color.blue print simplify(Color.green == Color.blue) # Let c be a constant of sort Color c = Const('c', Color) # Then, c must be red, green or blue prove(Or(c == Color.green, c == Color.blue, c == Color.red))
[ "nbjorner@microsoft.com" ]
nbjorner@microsoft.com
3ae3022f4d02fd4850ca632a44e0205b7d1fa653
c93080264201fe6d0c84a79ae435022981d8ccf6
/panoptic/panoptic/doctype/frt_link/frt_link.py
67e8a4394dda3a574c7eb1b126c1d9f854e6c6c7
[ "MIT" ]
permissive
wisharya/panoptic
100e733e9aad33d087851fc4ea9bd064e81954f2
7c9a0eeb6bd5d9032087ccb7c805a3e65a357ba8
refs/heads/master
2023-07-09T14:20:45.377441
2021-08-25T06:58:45
2021-08-25T06:58:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
273
py
# -*- coding: utf-8 -*- # Copyright (c) 2020, Internet Freedom Foundation and contributors # For license information, please see license.txt from __future__ import unicode_literals # import frappe from frappe.model.document import Document class FRTLink(Document): pass
[ "scm.mymail@gmail.com" ]
scm.mymail@gmail.com
34a3c2e383db34435bf9f7f6871b4759c697745c
30f15a184450d6e914ac16375e674cc2f993b9ce
/game/engine/scummvm/actions.py
753eacd9cdf63940e2303b46b603fc71086fe5a4
[]
no_license
Erick-Pardus/2013
9d0dd48e19400965476480a8e6826beb865bdb2e
80943b26dbb4474f6e99f81752a0d963af565234
refs/heads/master
2021-01-18T16:57:58.233209
2012-10-30T20:35:42
2012-10-30T20:35:42
6,467,098
2
0
null
null
null
null
UTF-8
Python
false
false
1,046
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt from pisi.actionsapi import autotools from pisi.actionsapi import pisitools from pisi.actionsapi import shelltools from pisi.actionsapi import get shelltools.export("HOME", get.workDIR()) def setup(): autotools.rawConfigure("--prefix=/usr \ --enable-verbose-build \ --backend=sdl \ --enable-alsa \ --enable-flac \ --enable-mad \ --with-nasm-prefix=/usr/bin/nasm \ --enable-vorbis \ --enable-zlib") def build(): autotools.make() def install(): autotools.rawInstall("DESTDIR=%s" % get.installDIR()) pisitools.dohtml("doc/he/*.html") pisitools.dodoc("AUTHORS", "COPYING", "COPYRIGHT", "NEWS", "README", "TODO", "doc/he/*.txt")
[ "yusuf.aydemir@istanbul.com" ]
yusuf.aydemir@istanbul.com
2cd19af823e90d2a4f99f3ee7ad155f837d1bb6c
f708a01bdfd1133883ec43dc9f7fc1dd8efd655c
/backend/home/migrations/0002_load_initial_data.py
cd9ce165d6eece5be8715f7fd500ce6e879c1ef5
[]
no_license
crowdbotics-apps/cws-v2-24857
d289f5011c0c122079399365b040ccde1731282c
2bd623d18e207ddf7f048ca117eaf3f864edae7e
refs/heads/master
2023-03-12T10:33:38.218689
2021-03-05T02:19:14
2021-03-05T02:19:14
344,669,015
0
0
null
null
null
null
UTF-8
Python
false
false
1,278
py
from django.db import migrations def create_customtext(apps, schema_editor): CustomText = apps.get_model("home", "CustomText") customtext_title = "CWS v2" CustomText.objects.create(title=customtext_title) def create_homepage(apps, schema_editor): HomePage = apps.get_model("home", "HomePage") homepage_body = """ <h1 class="display-4 text-center">CWS v2</h1> <p class="lead"> This is the sample application created and deployed from the Crowdbotics app. You can view list of packages selected for this application below. </p>""" HomePage.objects.create(body=homepage_body) def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "cws-v2-24857.botics.co" site_params = { "name": "CWS v2", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration): dependencies = [ ("home", "0001_initial"), ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_customtext), migrations.RunPython(create_homepage), migrations.RunPython(create_site), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
bc125099241b8ffd9f1ccc9d93c01b6f7eaf5f23
a05550df7d8385ac8cfe2f1ac30aa438e706dd59
/src/eval/create_ranking_3models.py
18e28432ac756acbb80fa5497ee808f946b56465
[]
no_license
raosudha89/clarification_question_generation
9a537e4410d649519e662c8ddd1d776d5a891deb
f8ed75cc25622fc82c753e8f73e9c25d5e2df344
refs/heads/master
2020-03-08T10:34:33.771492
2018-06-27T18:27:54
2018-06-27T18:27:54
128,076,744
0
0
null
null
null
null
UTF-8
Python
false
false
4,741
py
import argparse import gzip import nltk import pdb import sys, os from collections import defaultdict import csv import random def parse(path): g = gzip.open(path, 'r') for l in g: yield eval(l) def read_ids(fname): return [line.strip('\n') for line in open(fname, 'r').readlines()] def read_model_outputs(model_fname, model_test_ids_fname): model_test_ids = read_ids(model_test_ids_fname) with open(model_fname, 'r') as model_file: model_outputs = [line.strip('\n') for line in model_file.readlines()] model_output_dict = defaultdict(list) for i, test_id in enumerate(model_test_ids): asin = test_id.split('_')[0] model_output_dict[asin].append(model_outputs[i]) return model_output_dict def get_subset(candidates): print len(candidates) new_candidates = [] for cand in candidates: if len(cand.split()) <= 50: new_candidates.append(cand) print len(new_candidates) if len(new_candidates) == 0: pdb.set_trace() return new_candidates def main(args): titles = {} descriptions = {} test_ids = read_ids(args.test_ids) lucene_model_outs = read_model_outputs(args.lucene_model, args.lucene_model_test_ids) context_model_outs = read_model_outputs(args.context_model, args.context_model_test_ids) candqs_model_outs = read_model_outputs(args.candqs_model, args.candqs_model_test_ids) candqs_template_model_outs = read_model_outputs(args.candqs_template_model, \ args.candqs_template_model_test_ids) for v in parse(args.metadata_fname): asin = v['asin'] if asin not in test_ids: continue if asin not in lucene_model_outs or \ asin not in context_model_outs or \ asin not in candqs_model_outs or \ asin not in candqs_template_model_outs: continue description = v['description'] length = len(description.split()) title = v['title'] if length >= 100 or length < 10 or len(title.split()) == length: continue titles[asin] = title descriptions[asin] = description if len(descriptions) >= 100: break print len(descriptions) questions = defaultdict(list) for v in parse(args.qa_data_fname): asin = v['asin'] if asin not in descriptions: continue questions[asin].append(v['question']) csv_file = open(args.csv_file, 'w') writer = csv.writer(csv_file, delimiter=',') writer.writerow(['asin', 'title', 'description', \ 'q1_model', 'q1', 'q2_model', 'q2', \ 'q3_model', 'q3', 'q4_model', 'q4', \ 'q5_model', 'q5']) all_rows = [] for asin in descriptions: title = titles[asin] description = descriptions[asin] #ques_candidates = [] #for ques in questions[asin]: # if len(ques.split()) > 30: # continue # ques_candidates.append(ques) gold_question = random.choice(questions[asin]) lucene_question = random.choice(lucene_model_outs[asin]) context_question = random.choice(context_model_outs[asin]) candqs_question = random.choice(candqs_model_outs[asin]) candqs_template_question = random.choice(candqs_template_model_outs[asin]) pairs = [('gold', gold_question), ('lucene', lucene_question), \ ('context', context_question), ('candqs', candqs_question), \ ('candqs_template', candqs_template_question)] random.shuffle(pairs) writer.writerow([asin, title, description, \ pairs[0][0], pairs[0][1], pairs[1][0], pairs[1][1], \ pairs[2][0], pairs[2][1], pairs[3][0], pairs[3][1], \ pairs[4][0], pairs[4][1]]) csv_file.close() if __name__ == "__main__": argparser = argparse.ArgumentParser(sys.argv[0]) argparser.add_argument("--qa_data_fname", type = str) argparser.add_argument("--metadata_fname", type = str) argparser.add_argument("--test_ids", type=str) argparser.add_argument("--csv_file", type=str) argparser.add_argument("--lucene_model", type=str) argparser.add_argument("--lucene_model_test_ids", type=str) argparser.add_argument("--context_model", type=str) argparser.add_argument("--context_model_test_ids", type=str) argparser.add_argument("--candqs_model", type=str) argparser.add_argument("--candqs_model_test_ids", type=str) argparser.add_argument("--candqs_template_model", type=str) argparser.add_argument("--candqs_template_model_test_ids", type=str) args = argparser.parse_args() print args print "" main(args)
[ "raosudha@umiacs.umd.edu" ]
raosudha@umiacs.umd.edu
5c45e9998b505e3bdd5403e41fd8ec79d4127387
f43418339d85ab07ec369fd8f14df6f0b1d4bcd8
/ch3/barrier/python/barrier.py
86ed375668e3f0bb72ae10219c42461b09699ee9
[]
no_license
frankieliu/little-book-semaphores
732fbb1787d826666e750c4e8c8897877631921c
9017ddceeab30090af983100729649f0f29c7c99
refs/heads/master
2021-07-14T03:40:05.503689
2020-08-15T13:55:19
2020-08-15T13:55:19
195,286,896
1
4
null
null
null
null
UTF-8
Python
false
false
967
py
from threading import Thread, Semaphore import time from random import randint class Person(Thread): def __init__(self,i,m,s,count,numthreads): self.s = s self.m = m self.count = count self.count.i = 0 self.numthreads = numthreads super().__init__(name=i) def run(self): time.sleep(1e-3*randint(1,10)) print(f"{self.name} rendez") # barrier self.m.acquire() self.count.i += 1 if self.count.i == self.numthreads: self.s.release() self.m.release() self.s.acquire() self.s.release() print(f"{self.name} critical section") class Count(): pass def main(): nthreads = 10 m = Semaphore(1) s = Semaphore(0) count = Count() thr = [] for i in range(nthreads): thr.append(Person(i+1, m, s, count, nthreads)) for t in thr: t.start() for t in thr: t.join() main()
[ "frankie.y.liu@gmail.com" ]
frankie.y.liu@gmail.com
e0b5ca9db7e40e9b5e0260f2d584aa234eb16f94
cb2a40b70bc21d0057c96ddb2c86edceffe19707
/payments/migrations/0011_auto_20180104_1301.py
259d5612830139f25d17956bd53eef9cb226afa7
[]
no_license
rebkwok/pipsevents
ceed9f420b08cd1a3fa418800c0870f5a95a4067
c997349a1b4f3995ca4bb3a897be6a73001c9810
refs/heads/main
2023-08-09T14:11:52.227086
2023-07-27T20:21:01
2023-07-27T20:21:01
29,796,344
1
1
null
2023-09-13T14:32:16
2015-01-24T23:53:34
Python
UTF-8
Python
false
false
697
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-04 13:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payments', '0010_auto_20180102_1130'), ] operations = [ migrations.AlterField( model_name='paypalblocktransaction', name='invoice_id', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AlterField( model_name='paypalblocktransaction', name='transaction_id', field=models.CharField(blank=True, max_length=255, null=True), ), ]
[ "rebkwok@gmail.com" ]
rebkwok@gmail.com
75498a2f5f3b001a45ca4069131312af6328a494
7ad19e854135977ee5b789d7c9bdd39d67ec9ea4
/members/amit/f0_experiments/model.py
05a5e529b028aa62ab646eb7176aec7490be90a4
[ "MIT" ]
permissive
Leofltt/rg_sound_generation
1b4d522507bf06247247f3ef929c8d0b93015e61
8e79b4d9dce028def43284f80521a2ec61d0066c
refs/heads/main
2023-05-02T19:53:23.645982
2021-05-22T16:09:54
2021-05-22T16:09:54
369,842,561
0
0
MIT
2021-05-22T15:27:28
2021-05-22T15:27:27
null
UTF-8
Python
false
false
1,197
py
import tensorflow as tf from tensorflow.keras.layers import Input, concatenate, RepeatVector from tensorflow.keras.layers import Dense, GRU, Dropout def create_model(): _velocity = Input(shape=(5,), name='velocity') _instrument_source = Input(shape=(3,), name='instrument_source') _qualities = Input(shape=(10,), name='qualities') _z = Input(shape=(1000, 16), name='z') categorical_inputs = concatenate( [_velocity, _instrument_source, _qualities], name='categorical_inputs' ) _input = concatenate( [_z, RepeatVector(1000, name='repeat')(categorical_inputs)], name='total_inputs' ) x = GRU(256, return_sequences=True, name='gru_1')(_input) x = Dropout(0.5, name='dropout_1')(x) x = GRU(256, return_sequences=True, name='gru_2')(x) x = Dropout(0.5, name='dropout_2')(x) _f0_categorical = Dense(49, activation='softmax', name='f0_categorical')(x) model = tf.keras.models.Model( [_velocity, _instrument_source, _qualities, _z], _f0_categorical ) model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'] ) return model
[ "amit.yadav.iitr@gmail.com" ]
amit.yadav.iitr@gmail.com
13564f1fa07291d92bd2edd1ade46fb1f410c888
e84020108a7037d8d4867d95fada1b72cbcbcd25
/django/nrega.libtech.info/src/nrega/migrations/0118_auto_20170621_1328.py
219d29cf057534d7b88f61db611446f66075c53b
[]
no_license
rajesh241/libtech
8384316051a2e8c2d4a925cd43216b855b82e4d9
0105e717357a3626106028adae9bf162a7f93fbf
refs/heads/master
2022-12-10T03:09:00.048841
2020-06-14T09:39:04
2020-06-14T09:39:04
24,629,538
1
1
null
2022-12-08T02:26:11
2014-09-30T07:57:45
Python
UTF-8
Python
false
false
3,064
py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-21 07:58 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nrega', '0117_auto_20170621_1123'), ] operations = [ migrations.AlterField( model_name='applicant', name='panchayat', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Panchayat'), ), migrations.AlterField( model_name='block', name='district', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.District'), ), migrations.AlterField( model_name='district', name='state', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.State'), ), migrations.AlterField( model_name='fpsshop', name='block', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Block'), ), migrations.AlterField( model_name='fto', name='block', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Block'), ), migrations.AlterField( model_name='muster', name='block', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Block'), ), migrations.AlterField( model_name='muster', name='panchayat', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='nrega.Panchayat'), ), migrations.AlterField( model_name='nicblockreport', name='block', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Block'), ), migrations.AlterField( model_name='panchayat', name='block', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Block'), ), migrations.AlterField( model_name='panchayatreport', name='panchayat', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Panchayat'), ), migrations.AlterField( model_name='panchayatstat', name='panchayat', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Panchayat'), ), migrations.AlterField( model_name='village', name='panchayat', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='nrega.Panchayat'), ), migrations.AlterField( model_name='wagelist', name='block', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='nrega.Block'), ), ]
[ "togoli@gmail.com" ]
togoli@gmail.com
d509eed695ce2b3e20d2b819a42172b2c95fccab
4e04db11d891f869a51adf0e0895999d425f29f6
/portalbackend/lendapi/v1/accounts/permissions.py
d03cc4c6a2749a8264b3b36768a2678d71de1192
[]
no_license
mthangaraj/ix-ec-backend
21e2d4b642c1174b53a86cd1a15564f99985d23f
11b80dbd665e3592ed862403dd8c8d65b6791b30
refs/heads/master
2022-12-12T12:21:29.237675
2018-06-20T13:10:21
2018-06-20T13:10:21
138,033,811
0
0
null
2022-06-27T16:54:14
2018-06-20T13:04:22
JavaScript
UTF-8
Python
false
false
4,807
py
import json import re from rest_framework import permissions, status from rest_framework.exceptions import APIException from portalbackend.validator.errormapping import ErrorMessage from portalbackend.validator.errorcodemapping import ErrorCode from django.utils.deprecation import MiddlewareMixin from datetime import datetime, timedelta from portalbackend.lendapi.accounts.models import UserSession,CompanyMeta from re import sub from oauth2_provider.models import AccessToken from portalbackend.lendapi.v1.accounting.utils import Utils from django.http import JsonResponse from django.utils.timezone import utc from portalbackend.lendapi.constants import SESSION_EXPIRE_MINUTES, SESSION_SAVE_URLS class IsAuthenticatedOrCreate(permissions.IsAuthenticated): def has_permission(self, request, view): if request.method == 'POST': return True return super(IsAuthenticatedOrCreate, self).has_permission(request, view) class ResourceNotFound(APIException): status_code = status.HTTP_404_NOT_FOUND default_detail = {"message": ErrorMessage.RESOURCE_NOT_FOUND, "status": "failed"} class UnauthorizedAccess(APIException): status_code = status.HTTP_401_UNAUTHORIZED default_detail = {"message": ErrorMessage.UNAUTHORIZED_ACCESS, "status": "failed"} class IsCompanyUser(permissions.IsAuthenticated): message = {"message": ErrorMessage.UNAUTHORIZED_ACCESS, "status": "failed"} def has_permission(self, request, view): try: split_url = request.META.get('PATH_INFO').split("/") if split_url[3] == "docs": return request.user.is_authenticated() if len(view.kwargs) == 0 or split_url[3] != "company": if request.user.is_superuser: return request.user and request.user.is_authenticated() else: raise UnauthorizedAccess is_valid_company, message = Utils.check_company_exists(view.kwargs["pk"]) if not is_valid_company: raise ResourceNotFound if request.user.is_superuser: return request.user and request.user.is_authenticated() else: return ((request.user.is_superuser or request.user.company.id == int( view.kwargs["pk"])) and request.user.is_authenticated()) except APIException as err: raise err class SessionValidator(MiddlewareMixin): def process_request(self, request): try: session_save_urls = SESSION_SAVE_URLS request_api_url = request.META.get('PATH_INFO') for url in session_save_urls: if re.search(url, request_api_url): return header_token = request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: token = sub('Token ', '', request.META.get('HTTP_AUTHORIZATION', None)) token = token.split(' ') token_obj = AccessToken.objects.get(token=token[1]) user = token_obj.user meta = CompanyMeta.objects.get(company = user.company) if meta is not None and meta.monthly_reporting_sync_method == 'QBD': return try: user_session = UserSession.objects.get(user=user) if user_session: if user_session.is_first_time: user_session.is_first_time = False user_session.auth_key = token_obj if user_session.auth_key == token_obj: now = datetime.utcnow().replace(tzinfo=utc) if user_session.end_time > now: user_session.end_time = now + timedelta(minutes=SESSION_EXPIRE_MINUTES) user_session.save() else: user_session.delete() return JsonResponse( {'error': ErrorMessage.SESSION_EXPRIED, 'code': ErrorCode.SESSION_EXPRIED}, status=401) else: return JsonResponse( {'error': ErrorMessage.SESSION_ALREADY_ACTIVE, 'code': ErrorCode.SESSION_ALREADY_ACTIVE}, status=401) except UserSession.DoesNotExist: return JsonResponse({'error': ErrorMessage.SESSION_EXPRIED, 'code': ErrorCode.SESSION_EXPRIED}, status=401) except Exception as e: print(e) return
[ "thangaraj.matheson@ionixxtech.com" ]
thangaraj.matheson@ionixxtech.com
a2efb56dab315b04b0175314bda7483e3137b35a
b08f5367ffd3bdd1463de2ddc05d34cbfba6796e
/search/search_missing_among_billions.py
89e090a9dfd46719bbba7f53ba780a4de22f17eb
[]
no_license
uohzxela/fundamentals
cb611fa6c820dc8643a43fd045efe96bc43ba4ed
6bbbd489c3854fa4bf2fe73e1a2dfb2efe4aeb94
refs/heads/master
2020-04-04T03:56:44.145222
2018-04-05T01:08:14
2018-04-05T01:08:14
54,199,110
0
0
null
null
null
null
UTF-8
Python
false
false
1,038
py
''' create an array of 2^16 32-bit integers for every integer in the file, take its 16 most significant bits to index into this array and increment count since the file contains less than 2^32 numbers, there must be one entry in the array that is less than 2^16 this tells us that there is at least one integer which has those upper bits and is not in the file in the second pass, we focus only on the integers whose leading 16 bits match the one we have found and use a bit array of size 2^16 to identify a missing address ''' def search(file): count = [0 for i in xrange(2^16)] for e in file: count[e >> 16] += 1 for i in xrange(len(count)): c = count[i] bitset = [False for i in xrange(2^16)] if c < 2^16: for e in file: if e >> 16 == i: ''' 2^16-1 is used to mask off the upper 16 bits so that only the lower 16 bits can be obtained why minus 1? e.g. 2^4 = 10000, 2^4-1 = 01111 ''' bitset[2^16-1 & e] = True for j in xrange(2^16): if not bitset[j]: return i << 16 | j
[ "uohzxela@gmail.com" ]
uohzxela@gmail.com
41719d1f84a14e2c8c31ca71d64fb6fe025054a3
40c6fa589a0dfe88e82f8bd969cd5ef0ed04f303
/SWEA/D2/1954.py
6f69fcd9fca262d0e6c5087f16a45514a8d6b3b2
[]
no_license
EHwooKim/Algorithms
7d8653e55a491f3bca77a197965f15792f7ebe47
5db0a22b9dc0ba9a30bb9812c54d2d5ecec1676b
refs/heads/master
2021-08-20T04:05:09.967910
2021-06-15T07:54:17
2021-06-15T07:54:17
197,136,680
0
2
null
2021-01-08T05:51:37
2019-07-16T06:46:57
Python
UTF-8
Python
false
false
751
py
T = int(input()) for t in range(1, T + 1): print(f'#{t}') N = int(input()) i = j = 0 min_num = 0 max_num = N - 1 count = 1 result = [[0]*N for i in range(N)] while count <= N**2 - 1: while j < max_num: result[i][j] = count j += 1 count += 1 while i < max_num: result[i][j] = count i += 1 count += 1 max_num -= 1 while j > min_num: result[i][j] = count j -= 1 count += 1 min_num += 1 while i > min_num: result[i][j] = count i -= 1 count +=1 result[i][j] = count for n in range(N): print(*result[n], sep = ' ')
[ "ehwoo0707@naver.com" ]
ehwoo0707@naver.com
863a9e7fabd741444ae2d183a4dac774c8e404b4
204d62b325fe5dff332a517a6bea9a3cad76371d
/django/first_project/first_project/settings.py
770e2788b153469112fe4d647d2f72998cd71d5f
[]
no_license
tedyeung/Python-
ca5b87b66df95cf3e2d68e516becc04a890bb361
f379aa48d1e2118729c422e6d48a067b70639c5f
refs/heads/master
2021-09-21T11:52:20.389770
2018-08-25T14:47:46
2018-08-25T14:47:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,274
py
""" Django settings for first_project project. Generated by 'django-admin startproject' using Django 1.11.8. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bf=qzo1f4aew!i*@^^a^_mo6l0pmh@8#^l)%2(%7(n&o&p2@%i' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'first_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'first_project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,]
[ "slavo@mimicom24.com" ]
slavo@mimicom24.com
dd503f30535313cc118f2aff0289365f7759c68e
db3a0578ef5d79cee7f9e96fa3fd291bbaaf9eb4
/Web/flask/morse/morseclient.py
51987ad7f8af39d04cbbd30327428eafbe498b75
[ "MIT" ]
permissive
otisgbangba/python-lessons
0477a766cda6bc0e2671e4cce2f95bc62c8d3c43
a29f5383b56b21e6b0bc21aa9acaec40ed4df3cc
refs/heads/master
2022-11-03T22:10:52.845204
2020-06-13T15:42:40
2020-06-13T15:42:40
261,255,751
1
0
MIT
2020-05-04T17:48:12
2020-05-04T17:48:11
null
UTF-8
Python
false
false
626
py
import requests from time import sleep from codes import PASSWORD, morse_codes, words_by_symbol URL_BASE = 'http://localhost:5000' INTER_LETTER_DELAY = 0.2 def request_secret(): response = requests.get(URL_BASE + '/secret') print(response.text) def send_unlock_request(message): for letter in message: symbols_for_letter = morse_codes[letter] for symbol in symbols_for_letter: response = requests.get(URL_BASE + '/code/' + words_by_symbol[symbol]) print(response.text) sleep(INTER_LETTER_DELAY) request_secret() send_unlock_request(PASSWORD) request_secret()
[ "daveb@davebsoft.com" ]
daveb@davebsoft.com
bc52f37436a7565189d51e912a3ff824c5577c49
d21326e0e2604431549e80cf025074624f36c6bb
/boneless/test/test_alsru.py
a8fd22835150c7e12b619be0fccb994aac84ee72
[ "0BSD", "Apache-2.0" ]
permissive
zignig/Boneless-CPU
ad9232d82e19c1035f5e10443b81f147d96c4072
10bb571b4efab015e1bf147c78f0b8b3c93443e4
refs/heads/master
2020-04-25T20:29:47.987910
2019-07-05T05:35:18
2019-07-05T05:35:18
173,051,283
0
0
NOASSERTION
2019-02-28T06:06:16
2019-02-28T06:06:15
null
UTF-8
Python
false
false
4,413
py
import unittest import contextlib import random from nmigen import * from nmigen.back.pysim import * from ..gateware.alsru import * class ALSRUTestCase: dut_cls = None def setUp(self): self.checks = 100 self.width = 16 self.dut = self.dut_cls(self.width) @contextlib.contextmanager def assertComputes(self, ctrl, ci=None, si=None): asserts = [] yield(self.dut, asserts) random.seed(0) for _ in range(self.checks): rand_a = random.randint(0, (1 << self.width) - 1) rand_b = random.randint(0, (1 << self.width) - 1) rand_r = random.randint(0, (1 << self.width) - 1) rand_ci = random.randint(0, 1) if ci is None else ci rand_si = random.randint(0, 1) if si is None else si with Simulator(self.dut) as sim: def process(): yield self.dut.ctrl.eq(ctrl) yield self.dut.a.eq(rand_a) yield self.dut.b.eq(rand_b) yield self.dut.r.eq(rand_r) yield self.dut.ci.eq(rand_ci) yield self.dut.si.eq(rand_si) yield Delay() fail = False msg = "for a={:0{}x} b={:0{}x} ci={} si={}:" \ .format(rand_a, self.width // 4, rand_b, self.width // 4, rand_ci, rand_si) for signal, expr in asserts: actual = (yield signal) expect = (yield expr) if expect != actual: fail = True msg += " {}={:0{}x} (expected {:0{}x})"\ .format(signal.name, actual, signal.nbits // 4, expect, signal.nbits // 4) if fail: self.fail(msg) sim.add_process(process) sim.run() def test_A(self): with self.assertComputes(self.dut_cls.CTRL_A, ci=0) as (dut, asserts): asserts += [(dut.o, dut.a)] def test_B(self): with self.assertComputes(self.dut_cls.CTRL_B, ci=0) as (dut, asserts): asserts += [(dut.o, dut.b)] def test_nB(self): with self.assertComputes(self.dut_cls.CTRL_nB, ci=0) as (dut, asserts): asserts += [(dut.o, ~dut.b)] def test_AaB(self): with self.assertComputes(self.dut_cls.CTRL_AaB, ci=0) as (dut, asserts): asserts += [(dut.o, dut.a & dut.b)] def test_AoB(self): with self.assertComputes(self.dut_cls.CTRL_AoB, ci=0) as (dut, asserts): asserts += [(dut.o, dut.a | dut.b)] def test_AxB(self): with self.assertComputes(self.dut_cls.CTRL_AxB, ci=0) as (dut, asserts): asserts += [(dut.o, dut.a ^ dut.b)] def test_ApB(self): with self.assertComputes(self.dut_cls.CTRL_ApB) as (dut, asserts): result = dut.a + dut.b + dut.ci asserts += [(dut.o, result[:self.width]), (dut.co, result[self.width]), (dut.vo, (dut.a[-1] == dut.b[-1]) & (dut.a[-1] != result[self.width - 1]))] def test_AmB(self): with self.assertComputes(self.dut_cls.CTRL_AmB) as (dut, asserts): result = dut.a - dut.b - ~dut.ci asserts += [(dut.o, result[:self.width]), (dut.co, ~result[self.width]), (dut.vo, (dut.a[-1] == ~dut.b[-1]) & (dut.a[-1] != result[self.width - 1]))] def test_SL(self): with self.assertComputes(self.dut_cls.CTRL_SL) as (dut, asserts): result = (dut.r << 1) | dut.si asserts += [(dut.o, result[:self.width]), (dut.so, dut.r[-1])] def test_SR(self): with self.assertComputes(self.dut_cls.CTRL_SR) as (dut, asserts): result = (dut.r >> 1) | (dut.si << (self.width - 1)) asserts += [(dut.o, result[:self.width]), (dut.so, dut.r[0])] class ALSRU_4LUT_TestCase(ALSRUTestCase, unittest.TestCase): dut_cls = ALSRU_4LUT
[ "whitequark@whitequark.org" ]
whitequark@whitequark.org
acdd334ba1e6d6b647648d7ce04d95c971a8a97c
6b9084d234c87d7597f97ec95808e13f599bf9a1
/Dataset/Utility/youtube_downloader.py
9dfc738aba4989d5f42cfc43fb334b8de60c5b2a
[]
no_license
LitingLin/ubiquitous-happiness
4b46234ce0cb29c4d27b00ec5a60d3eeb52c26fc
aae2d764e136ca4a36c054212b361dd7e8b22cba
refs/heads/main
2023-07-13T19:51:32.227633
2021-08-03T16:02:03
2021-08-03T16:02:03
316,664,903
1
0
null
null
null
null
UTF-8
Python
false
false
1,870
py
import os import subprocess import threading from tqdm import tqdm import shutil def _read_outputs_from_precess(process): def _print_stdout(process): for line_ in iter(process.stdout.readline, ""): if len(line_) > 0: print(line_.strip()) def _print_stderr(process): for line_ in iter(process.stderr.readline, ""): if len(line_) > 0: print(line_.strip()) t1 = threading.Thread(target=_print_stdout, args=(process,)) t2 = threading.Thread(target=_print_stderr, args=(process,)) t1.start() t2.start() t1.join() t2.join() def download_youtube_videos(youtube_id_list, target_path: str, cache_path: str): for youtube_id in tqdm(youtube_id_list): youtube_video_path = os.path.join(target_path, youtube_id) if os.path.exists(youtube_video_path): continue url = f'https://www.youtube.com/watch?v={youtube_id}' # downloading_cache_path = os.path.join(cache_path, youtube_id) temp_path = os.path.join(target_path, f'{youtube_id}.tmp') if os.path.exists(temp_path): shutil.rmtree(temp_path) os.mkdir(temp_path) youtube_dl_output_path = os.path.join(temp_path, '%(title)s-%(id)s.%(ext)s') process = subprocess.Popen(['youtube-dl', '--cache-dir', cache_path, '-o', youtube_dl_output_path, url], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8') _read_outputs_from_precess(process) process.wait() if process.returncode != 0: print(f'Failed to download video {youtube_id}') continue files = os.listdir(temp_path) if len(files) == 0: print(f'Youtube-dl returns 0, but nothing downloaded in video {youtube_id}') continue os.rename(temp_path, youtube_video_path)
[ "linliting06@live.com" ]
linliting06@live.com
b718955f50d1f4ad7b792f47ff62beb3938634f9
3a1fea0fdd27baa6b63941f71b29eb04061678c6
/src/ch06/instructions/math/Rem.py
cc1e03153ae35a83b62c6b568c1c156b2675f163
[]
no_license
sumerzhang/JVMByPython
56a7a896e43b7a5020559c0740ebe61d608a9f2a
1554cf62f47a2c6eb10fe09c7216518416bb65bc
refs/heads/master
2022-12-02T17:21:11.020486
2020-08-18T06:57:10
2020-08-18T06:57:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,548
py
#!/usr/bin/env python # encoding: utf-8 """ @author: HuRuiFeng @file: Rem.py @time: 2019/9/15 20:04 @desc: 求余(rem)指令 """ import math from ch06.instructions.base.Instruction import NoOperandsInstruction # double remainder class DREM(NoOperandsInstruction): def execute(self, frame): stack = frame.operand_stack v2 = stack.pop_numeric() v1 = stack.pop_numeric() if v2 == 0.0: result = math.nan else: result = math.fmod(v1, v2) stack.push_numeric(result) # float remainder class FREM(NoOperandsInstruction): def execute(self, frame): stack = frame.operand_stack v2 = stack.pop_numeric() v1 = stack.pop_numeric() if v2 == 0.0: result = math.nan else: result = math.fmod(v1, v2) stack.push_numeric(result) # int remainder class IREM(NoOperandsInstruction): def execute(self, frame): stack = frame.operand_stack v2 = stack.pop_numeric() v1 = stack.pop_numeric() if v2 == 0: raise RuntimeError("java.lang.ArithmeticException: / by zero") result = v1 % v2 stack.push_numeric(result) # long remainder class LREM(NoOperandsInstruction): def execute(self, frame): stack = frame.operand_stack v2 = stack.pop_numeric() v1 = stack.pop_numeric() if v2 == 0: raise RuntimeError("java.lang.ArithmeticException: / by zero") result = v1 % v2 stack.push_numeric(result)
[ "huruifeng1202@163.com" ]
huruifeng1202@163.com
c38baec5d263b52e5b8b07f604db735e512f235b
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/domain/KbIsvMaCode.py
fa25c52f96b6b0de55cd7ffaf33dc6023902ce7c
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
1,183
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class KbIsvMaCode(object): def __init__(self): self._code = None self._num = None @property def code(self): return self._code @code.setter def code(self, value): self._code = value @property def num(self): return self._num @num.setter def num(self, value): self._num = value def to_alipay_dict(self): params = dict() if self.code: if hasattr(self.code, 'to_alipay_dict'): params['code'] = self.code.to_alipay_dict() else: params['code'] = self.code if self.num: if hasattr(self.num, 'to_alipay_dict'): params['num'] = self.num.to_alipay_dict() else: params['num'] = self.num return params @staticmethod def from_alipay_dict(d): if not d: return None o = KbIsvMaCode() if 'code' in d: o.code = d['code'] if 'num' in d: o.num = d['num'] return o
[ "liuqun.lq@alibaba-inc.com" ]
liuqun.lq@alibaba-inc.com
ad46c5cf701393737c5af474da5fe9ea2f31a1c9
56554999cdd882b6a6701b2a09e148c1fa4465c8
/scramble.py
c9cd6805db2f8759634629df0b007e63d9a93de0
[]
no_license
theriley106/Cubuyo
a266bd97fb82a8443785b40151222f68901a4bb2
38fb8caf2cb395c3df2274fd0651b51c621a5723
refs/heads/master
2020-04-11T17:17:43.095793
2018-12-16T02:34:15
2018-12-16T02:34:15
161,955,403
2
0
null
null
null
null
UTF-8
Python
false
false
645
py
import random import re Notation = ["R", "R'", "L", "L'", "U", "U'", "F", "F'", "B", "B'"] def genNew(length): Scramble = [] while len(Scramble) < length: Move = random.choice(Notation) MoveStr = " ".join(re.findall("[a-zA-Z]+", str(Move))) PreviousMove = Scramble[-1:] PreviousMove = " ".join(re.findall("[a-zA-Z]+", str(PreviousMove))) if MoveStr != PreviousMove: Num = random.randint(1,3) if Num == 1 or Num == 3: Scramble.append(Move) else: if "'" in str(Move): Move = str(Move).replace("'", "") Scramble.append('{}2'.format(Move)) T = "" for moves in Scramble: T = T + " " + str(moves) return T
[ "christopherlambert106@gmail.com" ]
christopherlambert106@gmail.com
609d3a6c31bdda855c9cdee73943267fea809e40
9645bdfbb15742e0d94e3327f94471663f32061a
/Python/719 - Find K-th Smallest Pair Distance/719_find-k-th-smallest-pair-distance.py
8370a768504118d06936fb1274d64a87cac376a5
[]
no_license
aptend/leetcode-rua
f81c080b2260adb2da677612e5c437eda256781d
80e44f4e9d3a5b592fdebe0bf16d1df54e99991e
refs/heads/master
2023-06-22T00:40:05.533424
2021-03-17T13:51:28
2021-03-17T13:51:28
186,434,133
2
0
null
2023-06-21T22:12:51
2019-05-13T14:17:27
HTML
UTF-8
Python
false
false
609
py
from leezy import Solution, solution from heapq import heappush, heappop class Q719(Solution): @solution def smallestDistancePair(self, nums, k): # MLE A = sorted(nums) N = len(A) heap = [] def push(i, j): heappush(heap, (abs(A[i]-A[j]), i, j)) for i in range(N-1): push(i, i+1) for _ in range(k): ans, i, j = heappop(heap) if j < N-1: push(i, j+1) return ans def main(): q = Q719() q.add_args([1, 3, 1], 1) q.run() if __name__ == "__main__": main()
[ "crescentwhale@hotmail.com" ]
crescentwhale@hotmail.com
749b6395b6d8726189553c6d5d199595a4229343
f9d564f1aa83eca45872dab7fbaa26dd48210d08
/huaweicloud-sdk-gaussdbfornosql/huaweicloudsdkgaussdbfornosql/v3/model/show_pause_resume_stutus_response.py
c5684b791851a26cc2626b0be1f8ff75fd7fc5a2
[ "Apache-2.0" ]
permissive
huaweicloud/huaweicloud-sdk-python-v3
cde6d849ce5b1de05ac5ebfd6153f27803837d84
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
refs/heads/master
2023-09-01T19:29:43.013318
2023-08-31T08:28:59
2023-08-31T08:28:59
262,207,814
103
44
NOASSERTION
2023-06-22T14:50:48
2020-05-08T02:28:43
Python
UTF-8
Python
false
false
8,747
py
# coding: utf-8 import six from huaweicloudsdkcore.sdk_response import SdkResponse from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class ShowPauseResumeStutusResponse(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'master_instance_id': 'str', 'slave_instance_id': 'str', 'status': 'str', 'data_sync_indicators': 'NoSQLDrDateSyncIndicators', 'rto_and_rpo_indicators': 'list[NoSQLDrRpoAndRto]' } attribute_map = { 'master_instance_id': 'master_instance_id', 'slave_instance_id': 'slave_instance_id', 'status': 'status', 'data_sync_indicators': 'data_sync_indicators', 'rto_and_rpo_indicators': 'rto_and_rpo_indicators' } def __init__(self, master_instance_id=None, slave_instance_id=None, status=None, data_sync_indicators=None, rto_and_rpo_indicators=None): """ShowPauseResumeStutusResponse The model defined in huaweicloud sdk :param master_instance_id: 主实例id :type master_instance_id: str :param slave_instance_id: 备实例id :type slave_instance_id: str :param status: 容灾实例数据同步状态 - NA:实例尚未搭建容灾关系 - NEW:尚未启动的数据同步状态 - SYNCING:数据同步正常进行中 - SUSPENDING:正在暂停数据同步 - SUSPENDED:数据同步已暂停 - RECOVERYING:正在恢复数据同步 :type status: str :param data_sync_indicators: :type data_sync_indicators: :class:`huaweicloudsdkgaussdbfornosql.v3.NoSQLDrDateSyncIndicators` :param rto_and_rpo_indicators: 切换或倒换RPO和RTO值,仅当请求实例id为主实例时有值 :type rto_and_rpo_indicators: list[:class:`huaweicloudsdkgaussdbfornosql.v3.NoSQLDrRpoAndRto`] """ super(ShowPauseResumeStutusResponse, self).__init__() self._master_instance_id = None self._slave_instance_id = None self._status = None self._data_sync_indicators = None self._rto_and_rpo_indicators = None self.discriminator = None if master_instance_id is not None: self.master_instance_id = master_instance_id if slave_instance_id is not None: self.slave_instance_id = slave_instance_id if status is not None: self.status = status if data_sync_indicators is not None: self.data_sync_indicators = data_sync_indicators if rto_and_rpo_indicators is not None: self.rto_and_rpo_indicators = rto_and_rpo_indicators @property def master_instance_id(self): """Gets the master_instance_id of this ShowPauseResumeStutusResponse. 主实例id :return: The master_instance_id of this ShowPauseResumeStutusResponse. :rtype: str """ return self._master_instance_id @master_instance_id.setter def master_instance_id(self, master_instance_id): """Sets the master_instance_id of this ShowPauseResumeStutusResponse. 主实例id :param master_instance_id: The master_instance_id of this ShowPauseResumeStutusResponse. :type master_instance_id: str """ self._master_instance_id = master_instance_id @property def slave_instance_id(self): """Gets the slave_instance_id of this ShowPauseResumeStutusResponse. 备实例id :return: The slave_instance_id of this ShowPauseResumeStutusResponse. :rtype: str """ return self._slave_instance_id @slave_instance_id.setter def slave_instance_id(self, slave_instance_id): """Sets the slave_instance_id of this ShowPauseResumeStutusResponse. 备实例id :param slave_instance_id: The slave_instance_id of this ShowPauseResumeStutusResponse. :type slave_instance_id: str """ self._slave_instance_id = slave_instance_id @property def status(self): """Gets the status of this ShowPauseResumeStutusResponse. 容灾实例数据同步状态 - NA:实例尚未搭建容灾关系 - NEW:尚未启动的数据同步状态 - SYNCING:数据同步正常进行中 - SUSPENDING:正在暂停数据同步 - SUSPENDED:数据同步已暂停 - RECOVERYING:正在恢复数据同步 :return: The status of this ShowPauseResumeStutusResponse. :rtype: str """ return self._status @status.setter def status(self, status): """Sets the status of this ShowPauseResumeStutusResponse. 容灾实例数据同步状态 - NA:实例尚未搭建容灾关系 - NEW:尚未启动的数据同步状态 - SYNCING:数据同步正常进行中 - SUSPENDING:正在暂停数据同步 - SUSPENDED:数据同步已暂停 - RECOVERYING:正在恢复数据同步 :param status: The status of this ShowPauseResumeStutusResponse. :type status: str """ self._status = status @property def data_sync_indicators(self): """Gets the data_sync_indicators of this ShowPauseResumeStutusResponse. :return: The data_sync_indicators of this ShowPauseResumeStutusResponse. :rtype: :class:`huaweicloudsdkgaussdbfornosql.v3.NoSQLDrDateSyncIndicators` """ return self._data_sync_indicators @data_sync_indicators.setter def data_sync_indicators(self, data_sync_indicators): """Sets the data_sync_indicators of this ShowPauseResumeStutusResponse. :param data_sync_indicators: The data_sync_indicators of this ShowPauseResumeStutusResponse. :type data_sync_indicators: :class:`huaweicloudsdkgaussdbfornosql.v3.NoSQLDrDateSyncIndicators` """ self._data_sync_indicators = data_sync_indicators @property def rto_and_rpo_indicators(self): """Gets the rto_and_rpo_indicators of this ShowPauseResumeStutusResponse. 切换或倒换RPO和RTO值,仅当请求实例id为主实例时有值 :return: The rto_and_rpo_indicators of this ShowPauseResumeStutusResponse. :rtype: list[:class:`huaweicloudsdkgaussdbfornosql.v3.NoSQLDrRpoAndRto`] """ return self._rto_and_rpo_indicators @rto_and_rpo_indicators.setter def rto_and_rpo_indicators(self, rto_and_rpo_indicators): """Sets the rto_and_rpo_indicators of this ShowPauseResumeStutusResponse. 切换或倒换RPO和RTO值,仅当请求实例id为主实例时有值 :param rto_and_rpo_indicators: The rto_and_rpo_indicators of this ShowPauseResumeStutusResponse. :type rto_and_rpo_indicators: list[:class:`huaweicloudsdkgaussdbfornosql.v3.NoSQLDrRpoAndRto`] """ self._rto_and_rpo_indicators = rto_and_rpo_indicators def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ShowPauseResumeStutusResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
7f23226f64137649209c8979392ca73a776cc6ed
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5738606668808192_0/Python/xulusko/CoinJam.py
2d99d9e5c0b0750367878956b22ae6d543d493aa
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
697
py
from random import randint from pyprimes import nprimes N = 16 J = 50 jamcoins = set() somePrimes = list(nprimes(47))[1:] def findDiv(val): for p in somePrimes: if val % p == 0: return p return None def getDivisors(coin): divs = [] for base in range(2, 11): val = int(coin, base) div = findDiv(val) if not div: return None divs.append(div) return tuple(divs) while len(jamcoins) < J: coin = '' for i in range(N-2): coin += str(randint(0, 1)) coin = '1' + coin + '1' divs = getDivisors(coin) if divs: jamcoins.add((coin, divs)) print('Case #1:') for coin, divs in jamcoins: print(coin, ' '.join(map(str, divs)))
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
2a742123549ed793dd03e532042a323592171d10
a2d36e471988e0fae32e9a9d559204ebb065ab7f
/huaweicloud-sdk-meeting/huaweicloudsdkmeeting/v1/model/show_sp_res_response.py
f475eccd26c2ba4a71ea8a20576fbef3e88e9b9f
[ "Apache-2.0" ]
permissive
zhouxy666/huaweicloud-sdk-python-v3
4d878a90b8e003875fc803a61414788e5e4c2c34
cc6f10a53205be4cb111d3ecfef8135ea804fa15
refs/heads/master
2023-09-02T07:41:12.605394
2021-11-12T03:20:11
2021-11-12T03:20:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,331
py
# coding: utf-8 import re import six from huaweicloudsdkcore.sdk_response import SdkResponse from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class ShowSpResResponse(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'used_accounts_count': 'int' } attribute_map = { 'used_accounts_count': 'usedAccountsCount' } def __init__(self, used_accounts_count=None): """ShowSpResResponse - a model defined in huaweicloud sdk""" super(ShowSpResResponse, self).__init__() self._used_accounts_count = None self.discriminator = None if used_accounts_count is not None: self.used_accounts_count = used_accounts_count @property def used_accounts_count(self): """Gets the used_accounts_count of this ShowSpResResponse. 已用的企业并发数 :return: The used_accounts_count of this ShowSpResResponse. :rtype: int """ return self._used_accounts_count @used_accounts_count.setter def used_accounts_count(self, used_accounts_count): """Sets the used_accounts_count of this ShowSpResResponse. 已用的企业并发数 :param used_accounts_count: The used_accounts_count of this ShowSpResResponse. :type: int """ self._used_accounts_count = used_accounts_count def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ShowSpResResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
5e0157cbe7967799bd395e9d9038dedcf13957bb
49a167d942f19fc084da2da68fc3881d44cacdd7
/kubernetes_asyncio/test/test_v1_scale_io_persistent_volume_source.py
0ee57636f0970338a9cb0f60be03d7b2ee42a7f5
[ "Apache-2.0" ]
permissive
olitheolix/kubernetes_asyncio
fdb61323dc7fc1bade5e26e907de0fe6e0e42396
344426793e4e4b653bcd8e4a29c6fa4766e1fff7
refs/heads/master
2020-03-19T12:52:27.025399
2018-06-24T23:34:03
2018-06-24T23:34:03
136,546,270
1
0
Apache-2.0
2018-06-24T23:52:47
2018-06-08T00:39:52
Python
UTF-8
Python
false
false
1,122
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v1.10.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import kubernetes_asyncio.client from kubernetes_asyncio.client.models.v1_scale_io_persistent_volume_source import V1ScaleIOPersistentVolumeSource # noqa: E501 from kubernetes_asyncio.client.rest import ApiException class TestV1ScaleIOPersistentVolumeSource(unittest.TestCase): """V1ScaleIOPersistentVolumeSource unit test stubs""" def setUp(self): pass def tearDown(self): pass def testV1ScaleIOPersistentVolumeSource(self): """Test V1ScaleIOPersistentVolumeSource""" # FIXME: construct object with mandatory attributes with example values # model = kubernetes_asyncio.client.models.v1_scale_io_persistent_volume_source.V1ScaleIOPersistentVolumeSource() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "tomasz.prus@gmail.com" ]
tomasz.prus@gmail.com
c29e4fcb17ba98010f15b65b0383c453ae095f67
4ee2ebef215cf879aafdfa44221f52d82775176a
/Inheritance/Exercise/02-Zoo/project/reptile.py
75f13a08a48e503a16c38a736c1bf215ce43adcd
[]
no_license
Avstrian/SoftUni-Python-OOP
d2a9653863cba7bc095e647cd3f0561377f10f6d
6789f005b311039fd46ef1f55f3eb6fa9313e5a6
refs/heads/main
2023-08-01T09:31:38.099842
2021-08-24T04:21:38
2021-08-24T04:21:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
128
py
from project.animal import Animal class Reptile(Animal): def __init__(self, name): super().__init__(name)
[ "noreply@github.com" ]
Avstrian.noreply@github.com
9ca7a052e7117038353576d0ec3d66ac59d833ae
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_1_neat/16_0_1_k_alkiek_countingsheep.py
f323c616326819f23c2e79d41df1a4a52585b9c4
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
736
py
T = int(raw_input()) # read number of cases nums = [0,1,2,3,4,5,6,7,8,9] def elementsofin(L,ref): #function to compare seen with all numbers x = [i for i in ref if i in L] if x == ref: return True else: return False for i in xrange(1, T + 1): N = int(raw_input()) # read chosen N if N == 0: output = "INSOMNIA" else: seen = [] z=0 while not(elementsofin(seen,nums)): z+=1 listofN = map(int, str(N*z)) # convert product into an array for j in listofN: #add digits of product as seen numbers seen.append(j) output = N*z print "Case #{}: {}".format(i, output)
[ "[dhuo@tcd.ie]" ]
[dhuo@tcd.ie]
c79f737de7690fc52877eb13c4099495de3fe7d9
9dba277eeb0d5e9d2ac75e2e17ab5b5eda100612
/exercises/1901040051/d08/mymodule/try_except.py
2bab5904e58d40ed0977888a300dca3aa289874d
[]
no_license
shen-huang/selfteaching-python-camp
e8410bfc06eca24ee2866c5d890fd063e9d4be89
459f90c9f09bd3a3df9e776fc64dfd64ac65f976
refs/heads/master
2022-05-02T05:39:08.932008
2022-03-17T07:56:30
2022-03-17T07:56:30
201,287,222
9
6
null
2019-08-08T15:34:26
2019-08-08T15:34:25
null
UTF-8
Python
false
false
217
py
def spam(divideby): try: return 42 / divideby except ZeroDivisionError: print('error:Invalid argument.') print(int(spam(2))) print(int(spam(12))) print(spam(0)) print(spam(0.1)) print(spam(1))
[ "40155646+seven-tears@users.noreply.github.com" ]
40155646+seven-tears@users.noreply.github.com
fdf116fc0fba39809c9daedd37fdb20c0c721dc8
5115d3fd60826f2e7eb36c3467608a31e34d8cd1
/myshop/orders/urls.py
a9ba0463ffca3b9978db9ce5070203cf9675187e
[]
no_license
Dyavathrocky/e-commerce
650ca4e764723101c9f1cf456c15ab43c503d1b4
2c6368fc514c5a2102088df1427da41a8b8af34a
refs/heads/master
2022-12-10T11:31:36.052547
2020-09-06T14:27:34
2020-09-06T14:27:34
289,501,162
0
0
null
null
null
null
UTF-8
Python
false
false
244
py
from django.urls import path from . import views app_name = 'orders' urlpatterns = [ path('create/', views.order_create, name='order_create'), path('admin/order/<int:order_id>/', views.admin_order_detail, name='admin_order_detail'), ]
[ "davathrak@gmail.com" ]
davathrak@gmail.com
dd3a13b3441bdb43584cc9c9fa763ecb19c44f8e
3e8e1add88b0782bc64f8682b05f399638094729
/teacherstudent/urls.py
b239ac643a67403dbc79edb5bef2e6da441b6a22
[]
no_license
nnish09/Task2
3e154c8f61ef88034cff6e1e42fdd616d2922951
cddc23c062c81e0669b6656d7f294f61f3c05976
refs/heads/master
2023-04-29T12:04:14.565984
2019-09-23T10:52:08
2019-09-23T10:52:08
209,307,595
0
0
null
2023-04-21T20:37:36
2019-09-18T12:51:29
CSS
UTF-8
Python
false
false
1,171
py
"""teacherstudent URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('studentteacher.urls')), path('accounts/', include('django.contrib.auth.urls')), path('friendship/', include('friendship.urls')) ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
[ "nishtha0995@gmail.com" ]
nishtha0995@gmail.com
ca1612d5068d3f4480ffbc0428ee9943db2a5476
e4ec5b6cf3cfe2568ef0b5654c019e398b4ecc67
/azure-cli/2.0.18/libexec/lib/python3.6/site-packages/azure/mgmt/network/v2016_09_01/models/application_gateway_ssl_policy.py
ff1c8f6c4ca1af9b4fb15521b1d8135387e1a75f
[]
no_license
EnjoyLifeFund/macHighSierra-cellars
59051e496ed0e68d14e0d5d91367a2c92c95e1fb
49a477d42f081e52f4c5bdd39535156a2df52d09
refs/heads/master
2022-12-25T19:28:29.992466
2017-10-10T13:00:08
2017-10-10T13:00:08
96,081,471
3
1
null
2022-12-17T02:26:21
2017-07-03T07:17:34
null
UTF-8
Python
false
false
1,153
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ApplicationGatewaySslPolicy(Model): """Application gateway SSL policy. :param disabled_ssl_protocols: SSL protocols to be disabled on application gateway. Possible values are: 'TLSv1_0', 'TLSv1_1', and 'TLSv1_2'. :type disabled_ssl_protocols: list of str or :class:`ApplicationGatewaySslProtocol <azure.mgmt.network.v2016_09_01.models.ApplicationGatewaySslProtocol>` """ _attribute_map = { 'disabled_ssl_protocols': {'key': 'disabledSslProtocols', 'type': '[str]'}, } def __init__(self, disabled_ssl_protocols=None): self.disabled_ssl_protocols = disabled_ssl_protocols
[ "Raliclo@gmail.com" ]
Raliclo@gmail.com
eed8531d3cb546a055192bd95204d0d304ac460e
df9d6ecde9202bd4b73e69cd28c50b41195c0aa1
/tests/data.py
c5e249eb686ffb112d8483880a75c1c68a661d9d
[ "MIT" ]
permissive
ppinard/dataclasses-sql
8d6d18dd558537fbf40c386a11fdd75f4720fa2a
8f2eeaf090887985f8fd9853adb763883906bed6
refs/heads/master
2021-03-23T22:48:34.437619
2020-06-10T14:23:07
2020-06-10T14:23:07
247,489,847
6
3
MIT
2020-11-02T01:43:20
2020-03-15T15:06:32
Python
UTF-8
Python
false
false
858
py
"""""" # Standard library modules. import dataclasses import datetime # Third party modules. # Local modules. # Globals and constants variables. @dataclasses.dataclass class TaxonomyData: kingdom: str = dataclasses.field(metadata={"key": True}) order: str = dataclasses.field(metadata={"key": True}) family: str = dataclasses.field(metadata={"key": True}) genus: str = dataclasses.field(metadata={"key": True}) @dataclasses.dataclass class TreeData: serial_number: int = dataclasses.field(metadata={"key": True}) taxonomy: TaxonomyData = dataclasses.field(metadata={"key": True}) specie: str = dataclasses.field(metadata={"key": True}) diameter_m: float = None long_description: bytes = None has_flower: bool = None plantation_datetime: datetime.datetime = None last_pruning_date: datetime.date = None
[ "philippe.pinard@gmail.com" ]
philippe.pinard@gmail.com
17b0c3efb04efec5a6d635005649370d3c085113
3e3bf98840d133e56f0d0eb16ba85678ddd6ca45
/.history/iss_20200102103033.py
9612bd296d926015d41b8fbb1e476f1266919608
[]
no_license
Imraj423/backend-iss-location-assessment
a05d3cc229a5fc4857483ae466348c1f8c23c234
b0565c089a445ccffcb8d0aab3c0be3bb0c1d5b8
refs/heads/master
2020-12-03T17:04:58.512124
2020-06-24T16:02:02
2020-06-24T16:02:02
231,400,854
0
0
null
2020-06-24T16:02:04
2020-01-02T14:43:44
null
UTF-8
Python
false
false
273
py
#!/usr/bin/env python3 __author__ = 'Imraj423' import requests import turtle r = requests.get('http://api.open-notify.org/astros.json') print(r.text) s = requests.get('http://api.open-notify.org/iss-now.json') print(s.text) # if __name__ == '__main__': # main()
[ "dahqniss@gmail.com" ]
dahqniss@gmail.com
1d959f7ffb45e5bd71979204e4f0c6b34379fcf2
55883f5c70f634b4341b2368ad3c6eccbe13e7e5
/CEPNetworks.py
30de48a2acd99ea226f70ff8ba9a0a7fe1d56710
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
kaihami/pycsa
e93fcceb4b7fed1c0b4ae23fbebd0a5bc3e2bf44
a85594526a4d10d2e8097b6e90f5b93b44a8236f
refs/heads/master
2021-01-23T02:40:29.036635
2016-04-29T17:21:11
2016-04-29T17:21:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,029
py
""" CEPNetworks.py This module is used to control all of the pipeline flow and do the reshuffling, etc. It works with the CEPAlgorithms module which can easily be adapted to include more algorithms. The main pipeline is initialized with all of the information for the rest of the project. @author: Kevin S. Brown (University of Connecticut), Christopher A. Brown (Palomidez LLC) This source code is provided under the BSD-3 license, duplicated as follows: Copyright (c) 2014, Kevin S. Brown and Christopher A. Brown All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University of Connecticut nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys, os, unittest, scipy.stats, re, copy, networkx from numpy import array from networkx import Graph as nxGraph from pycsa.CEPLogging import LogPipeline # decorator function to be used for logging purposes log_function_call = LogPipeline.log_function_call class CEPGraph(nxGraph): """This is the main graph class (subclassed from networkx.Graph) for computing statistics on networks Note: all of the functions below assume a weighted graph (setup in __init__)""" def __init__(self,nwkFile=None): """Initialize with a network file from the pipeline""" try: # initialize the networkx.Graph class first super(CEPGraph,self).__init__() self.read_network(nwkFile) if self.is_weighted(): self.weighted = True else: raise CEPGraphWeightException except IOError: raise CEPGraphIOException(nwkFile) except TypeError: super(CEPGraph,self).__init__() def is_weighted(self): edges = {'weight':False} for v1,v2 in self.edges(): if 'weight' in self[v1][v2]: edges['weight'] = True break return edges['weight'] def read_network(self,nwkFile): """Read in a network file to the current graph object""" nwkFile = open(nwkFile,'r') network = nwkFile.readlines() nwkFile.close() # add edges to self (note: (+)int nodes, (+/-)float edges, (+)float p-values) for edge in network: link = re.search('(\d+)\t(\d+)\t(-?\d+\.\d+)\t(\d+\.\d+)',edge) self.add_edge(int(link.group(1)), int(link.group(2)), weight=float(link.group(3)),pvalue=float(link.group(4))) def compute_node_degrees(self): """Computes the node degree (weighted sum if applicable) for a graph""" degrees = {} for node in self.nodes_iter(): knode = 0.0 for neighbor in self.neighbors_iter(node): knode += self.get_edge_data(node,neighbor)['weight'] degrees[node] = knode # get half sum of node degrees as well halfDegreeSum = 0.5*(array(degrees.values()).sum()) return degrees, halfDegreeSum def prune_graph(self, threshold): """Removes all weighted edges below a certain threshold along with any nodes that have been orphaned (no neighbors) by the pruning process""" for v1,v2 in self.edges(): if self[v1][v2]['weight'] < threshold: self.remove_edge(v1,v2) for n in self.nodes(): if len(self.neighbors(n)) < 1: self.remove_node(n) def calculate_pvalue(self,number=None): """Removes edges that aren't significant given their p-values (p > 0.05) Note: all MHT corrections, etc. should be taken care of in the method and not here (see CEPAlgorithms)""" edges = self.edges() for v1,v2 in edges: if self[v1][v2]['pvalue'] > 0.05: self.remove_edge(v1,v2) def calculate_mst(self,number=None): """Calculates a maximal spanning tree mapping large weights to small weights""" graph = copy.deepcopy(self) maxWeight = max([self[v[0]][v[1]]['weight'] for v in self.edges()]) for v1,v2 in self.edges(): graph[v1][v2]['weight'] = maxWeight - self[v1][v2]['weight'] edges = self.edges() tree = networkx.minimum_spanning_tree(graph,weight='weight') for v1,v2 in edges: if (v1,v2) in tree.edges(): pass else: self.remove_edge(v1,v2) def calculate_top_n(self,number): """Removes edges except for those with the n-largest weights (n = number)""" weights = [(self[v[0]][v[1]]['weight'],v[0],v[1]) for v in self.edges()] weights.sort() weights.reverse() # only keep n-largest vertex pairs weights = [(v[1],v[2]) for v in weights[:number]] edges = self.edges() for v1,v2 in edges: if (v1,v2) in weights: pass else: self.remove_edge(v1,v2) def calculate_bottom_n(self,number): """Removes edges except for those with the n-smallest weights (n = number)""" weights = [(self[v[0]][v[1]]['weight'],v[0],v[1]) for v in self.edges()] weights.sort() # only keep n-smallest vertex pairs weights = [(v[1],v[2]) for v in weights[:number]] edges = self.edges() for v1,v2 in edges: if (v1,v2) in weights: pass else: self.remove_edge(v1,v2) def compute_jaccard_index(self,graph): """Computes the Jaccard index for edges between self and another graph. note: Jaccard index = edge intersection divided by edge union""" union = frozenset(self.edges()).union(graph.edges()) intersection = frozenset(self.edges()).intersection(graph.edges()) try: jaccard = float(len(intersection))/len(union) except ZeroDivisionError: jaccard = 0.0 return jaccard class CEPGraphIOException(IOError): @log_function_call('ERROR : Network File Input') def __init__(self,nwkFile): print "The network file you have provided, '%s', does not exist. Please check your file selection."%(nwkFile) class CEPGraphWeightException(Exception): @log_function_call('ERROR : Graph Not Weighted') def __init__(self): print "The graph you have provided is not a weighted graph. Most of the methods provided are pointless for binary graphs." class CEPNetworksTests(unittest.TestCase): def setUp(self): pass # TODO add unit tests to CEPNetworks if __name__ == '__main__': unittest.main()
[ "kevin.s.brown@uconn.edu" ]
kevin.s.brown@uconn.edu
01503584d16b7c4a0cb75a7cc758eb2adfac62e9
f07a42f652f46106dee4749277d41c302e2b7406
/Data Set/bug-fixing-5/cb96f8a25034763e9f45f371afae4ca021d26a68-<process_state>-bug.py
6773a85f0e7bd66ac286e39e30972daccc1daef3
[]
no_license
wsgan001/PyFPattern
e0fe06341cc5d51b3ad0fe29b84098d140ed54d1
cc347e32745f99c0cd95e79a18ddacc4574d7faa
refs/heads/main
2023-08-25T23:48:26.112133
2021-10-23T14:11:22
2021-10-23T14:11:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
756
py
def process_state(self): try: dvs_host_states = { 'absent': { 'present': self.state_destroy_dvs_host, 'absent': self.state_exit_unchanged, }, 'present': { 'update': self.state_update_dvs_host, 'present': self.state_exit_unchanged, 'absent': self.state_create_dvs_host, }, } dvs_host_states[self.state][self.check_dvs_host_state()]() except vmodl.RuntimeFault as runtime_fault: self.module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: self.module.fail_json(msg=method_fault.msg) except Exception as e: self.module.fail_json(msg=str(e))
[ "dg1732004@smail.nju.edu.cn" ]
dg1732004@smail.nju.edu.cn
7e5707c253c5dd0752d89832311a101d4f2ddd7f
4ae7a930ca6aa629aa57df7764665358ee70ffac
/cflearn/data/blocks/ml/__init__.py
004f79c534726862b6d1c4593e1b88dbc9ee2142
[ "MIT" ]
permissive
carefree0910/carefree-learn
0ecc7046ef0ab44a642ff0a72a181c4cb5037571
554bf15c5ce6e3b4ee6a219f348d416e71d3972f
refs/heads/dev
2023-08-23T07:09:56.712338
2023-08-23T02:49:10
2023-08-23T02:49:10
273,041,593
451
38
MIT
2021-01-05T10:49:46
2020-06-17T17:44:17
Python
UTF-8
Python
false
false
169
py
from .schema import * from .file import * from .nan_handler import * from .recognizer import * from .preprocessor import * from .splitter import * from .gather import *
[ "syameimaru.saki@gmail.com" ]
syameimaru.saki@gmail.com
8f1d7509d6740417abcd8905bddf1141f2fc7058
87b249bde7c729800f2c2530a0ee35c101e3d363
/game/models.py
0182d4d21bfdffb62927c088fda77e2b58ca7a54
[]
no_license
infsolution/prehistory
9c909230cdc114dfdbc97875df27de23262befcc
70bab6b9c8352612bd46572b63330c1187dd869e
refs/heads/master
2020-09-12T12:14:39.358521
2019-11-29T23:59:43
2019-11-29T23:59:43
222,422,083
0
0
null
null
null
null
UTF-8
Python
false
false
1,041
py
from django.contrib.auth.models import User from django.contrib.auth import * from django.db import models class Knowing(models.Model): name = models.CharField(max_length=30) force = models. IntegerField(default=0) defense = models.IntegerField(default=0) allowed_level = models.IntegerField(default=0) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=40) force = models. IntegerField(default=0) defense = models. IntegerField(default=0) allowed_level = models. IntegerField(default=0) def __str__(self): return self.name class Avatar(models.Model): owner = models.OneToOneField('auth.User', related_name='avatar_owner', on_delete=models.CASCADE) name = models.CharField(max_length=12) force = models. IntegerField(default=100) defense = models.IntegerField(default=80) life = models.IntegerField(default=1000) level = models.IntegerField(default=0) knowing = models.ManyToManyField(Knowing) item = models.ManyToManyField(Item) def __str__(self): return self.name
[ "clsinfsolution@gmail.com" ]
clsinfsolution@gmail.com
7b54810242d09c7362950443e7fb95afecc7c011
368be25e37bafa8cc795f7c9f34e4585e017091f
/.history/app_fav_books/models_20201115165700.py
0eac60d92b9d9ae7be453f6bd85a6871087bd4aa
[]
no_license
steven-halla/fav_books_proj
ebcfbfda0e7f3cdc49d592c86c633b1d331da513
512005deb84ac906c9f24d4ab0939bd0db096716
refs/heads/master
2023-03-30T09:37:38.016063
2021-04-02T20:27:22
2021-04-02T20:27:22
354,125,658
0
0
null
null
null
null
UTF-8
Python
false
false
2,666
py
from django.db import models import re class UserManager(models.Manager): def user_registration_validator(self, post_data): errors = {} EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') if len(post_data['first_name']) < 3: errors['first_name'] = "First name must be 3 characters" if post_data['first_name'].isalpha() == False: errors['first_name'] = "letters only" if len(post_data['last_name']) < 3: errors['last_name'] = "Last name must be 3 characters" if post_data['last_name'].isalpha() == False: errors['last_name'] = "letters only" if len(post_data['email']) < 8: errors['email'] = "Email must contain 8 characters" if post_data['email'].find("@") == -1: errors['email'] = "email must contain @ and .com" if post_data['email'].find(".com") == -1: errors['email'] = "email must contain @ and .com" # test whether a field matches the pattern if not EMAIL_REGEX.match(post_data['email']): errors['email'] = "Invalid email address!" if post_data['password'] != post_data['confirm_password']: errors['pass_match'] = "password must match confirm password" if len(post_data['password']) < 8: errors['pass_length'] = "password must be longer than 8 characters" return errors # Create your models here. class User(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.CharField(max_length=20) password = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() class EditManager(models.Manager): def edit class BooksManager(models.Manager): def add_book_validator(self, post_data): errors = {} if len(post_data['title']) < 1: errors['title'] = "title name must be 1 characters" if len(post_data['desc']) < 5: errors['desc'] = "Description must be 5 characters" return errors class Books(models.Model): title = models.CharField(max_length=20) desc = models.CharField(max_length=40) uploaded_by = models.ForeignKey(User, related_name="books_uploaded", on_delete=models.CASCADE) users_who_favorite = models.ManyToManyField(User, related_name="liked_books") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects=BooksManager()
[ "69405488+steven-halla@users.noreply.github.com" ]
69405488+steven-halla@users.noreply.github.com
803b42aa13d6faa1c2502eba19d4b72a915cf30b
a63264a25fe18a94d9e2cba2632d7d59262e36a1
/app/handlers/converttopopulation.py
d1a9eb7efeab1d636cec5909a9a923a2ef1a3ffd
[ "BSD-3-Clause" ]
permissive
bbbales2/stochss
4f3ac8f909f52aaba0c863ffed91c2ae70b2fe27
afddf9ad8936993a5b17d1d4130677eb42afa439
refs/heads/master
2021-01-15T23:11:40.983003
2013-11-27T19:27:23
2013-11-27T19:32:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
503
py
try: import json except ImportError: from django.utils import simplejson as json import traceback from collections import OrderedDict from stochssapp import * from stochss.model import * class ConvertToPopulationPage(BaseHandler): def authentication_required(self): return True def get(self): model_edited = self.get_session_property('model_edited') self.render_response('modeleditor/convert_modeleditor.html', modelName = model_edited.name)
[ "bbbales2@gmail.com" ]
bbbales2@gmail.com
a2305f410c636a1f73e9eb03c70036300b797b07
76938f270e6165514162856b2ed33c78e3c3bcb5
/lib/coginvasion/shop/ItemType.py
e96efa1c25c3578ab1b279372a20d21679db23fd
[]
no_license
coginvasion/src
9a5ec682845cc4c9c013fcc35e9b379bd4360b6c
2d7fcdb0cd073050250cb51292ee48300a9fe19f
refs/heads/master
2021-01-19T06:50:11.786112
2015-11-08T12:28:52
2015-11-08T12:28:52
61,545,543
1
2
null
null
null
null
UTF-8
Python
false
false
173
py
# Embedded file name: lib.coginvasion.shop.ItemType """ Filename: ItemType.py Created by: DecodedLogic (13Jul15) """ class ItemType: GAG, UPGRADE, HEAL = range(3)
[ "ttarchive@yandex.com" ]
ttarchive@yandex.com
8f37672040f9e295c8762f408ad6bd4bb41e491a
971e0efcc68b8f7cfb1040c38008426f7bcf9d2e
/tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_Lag1Trend_NoCycle_MLP.py
46db9aa8f60fd81599dfc2f183a3cf62b5ad1657
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
antoinecarme/pyaf
a105d172c2e7544f8d580d75f28b751351dd83b6
b12db77cb3fa9292e774b2b33db8ce732647c35e
refs/heads/master
2023-09-01T09:30:59.967219
2023-07-28T20:15:53
2023-07-28T20:15:53
70,790,978
457
77
BSD-3-Clause
2023-03-08T21:45:40
2016-10-13T09:30:30
Python
UTF-8
Python
false
false
149
py
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Anscombe'] , ['Lag1Trend'] , ['NoCycle'] , ['MLP'] );
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
fab339050b992558c77da577c671a699a7775d41
6ab67facf12280fedf7cc47c61ae91da0bcf7339
/service/yowsup/yowsup/layers/auth/protocolentities/failure.py
12d1d8ed0f8ee7267a59a9cbb7493f6c5c879d4d
[ "MIT", "GPL-3.0-only", "GPL-3.0-or-later" ]
permissive
PuneethReddyHC/whatsapp-rest-webservice
2f035a08a506431c40b9ff0f333953b855f9c461
822dfc46b80e7a26eb553e5a10e723dda5a9f77d
refs/heads/master
2022-09-17T14:31:17.273339
2017-11-27T11:16:43
2017-11-27T11:16:43
278,612,537
0
1
MIT
2020-07-10T11:04:42
2020-07-10T11:04:41
null
UTF-8
Python
false
false
684
py
from yowsup.structs import ProtocolEntity, ProtocolTreeNode class FailureProtocolEntity(ProtocolEntity): def __init__(self, reason): super(FailureProtocolEntity, self).__init__("failure") self.reason = reason def __str__(self): out = "Failure:\n" out += "Reason: %s\n" % self.reason return out def getReason(self): return self.reason def toProtocolTreeNode(self): reasonNode = ProtocolTreeNode(self.reason, {}) return self._createProtocolTreeNode({}, children = [reasonNode]) @staticmethod def fromProtocolTreeNode(node): return FailureProtocolEntity( node.getAllChildren()[0].tag )
[ "svub@x900.svub.net" ]
svub@x900.svub.net