blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
69
| license_type
stringclasses 2
values | repo_name
stringlengths 5
118
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
63
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 2.91k
686M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 213
values | src_encoding
stringclasses 30
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 2
10.3M
| extension
stringclasses 246
values | content
stringlengths 2
10.3M
| authors
listlengths 1
1
| author_id
stringlengths 0
212
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f5c89f98c92406fb350ff22b561bd83d81edece1
|
0ff17ee041b29edd12dbf57b26fb9a63aa710f27
|
/helpers/analytics.py
|
a2a7b96a23160d8decc745b81b6b264bf6665c0f
|
[] |
no_license
|
jorgec/project_linecare
|
b7537557970cdbeb315d93efae6aadbecc5e9e10
|
65150e69c447605dc3958505c02dad1a59bbb6db
|
refs/heads/master
| 2020-03-28T20:43:23.225165
| 2019-03-07T06:14:33
| 2019-03-07T06:14:33
| 149,096,231
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,919
|
py
|
from helpers.colors import MColors
from locations.models import Country
from profiles.models import Gender
from visits.models import VisitDay
def split_by_genders(visit_days: VisitDay) -> list:
"""
Split VisitDays queryset by gender
"""
if not visit_days:
return []
genders = Gender.objects.all()
gender_splits = []
colors = MColors()
for gender in genders:
visit_days_filtered = visit_days.filter(
visit__user__account_profiles__gender_id=gender.pk
).values('visit__user').distinct()
gender_splits.append(
{
'name': gender.name,
'slug': gender.slug,
'pk': gender.pk,
'visit_days': visit_days_filtered,
'count': visit_days_filtered.count(),
'color': colors.get_color()
}
)
return gender_splits
def split_by_origin(visit_days: VisitDay) -> list:
"""
Split VisitDays queryset by country of origin
"""
if not visit_days:
return []
colors = MColors()
countries = []
country_splits = []
for visit_day in visit_days:
if visit_day.visit.user.base_profile().country_of_origin.pk not in countries:
countries.append(visit_day.visit.user.base_profile().country_of_origin.pk)
for country in countries:
c = Country.objects.get(pk=country)
visit_days_filtered = visit_days.filter(
visit__user__account_profiles__country_of_origin_id=country
).values('visit__user').distinct()
country_splits.append(
{
'name': c.name,
'slug': c.slug,
'pk': c.pk,
'visit_days': visit_days_filtered,
'count': visit_days_filtered.count(),
'color': colors.get_color()
}
)
return country_splits
|
[
"jorge.cosgayon@gmail.com"
] |
jorge.cosgayon@gmail.com
|
9f83a714b374ee275db19b67cb608640a88d4d9b
|
f548508a97bc41a0e7262700eae5c17b34219787
|
/ex23.py
|
48dbde423778ffb36e1e1744d576c13897e67d2a
|
[
"MIT"
] |
permissive
|
YadanarWin/python-exercise
|
8079b343e7f4e0e9bd5154d8b63cb464e2c75bcf
|
6074890fa946b66cc88cf537f07e088cd16be416
|
refs/heads/master
| 2020-03-19T23:58:38.149402
| 2018-06-26T08:51:03
| 2018-06-26T08:51:03
| 136,440,664
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 571
|
py
|
import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding,errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors=errors)
cooked_string = raw_bytes.decode(encoding, errors=errors)
print(raw_bytes, "<===>", cookes_string)
languages = open("languages.txt", encoding="utf-8")
main(languages, input_encoding, error)
|
[
"yadanarw65@gmail.com"
] |
yadanarw65@gmail.com
|
2eff352a1abccec68053b7c8623141ac0ac7ae17
|
6083df5235f76ee5624f272c512b100855e2294c
|
/appwrite/services/locale.py
|
fe3ad5e988b84b490c1ce091f58c7a0ef70db93a
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
AdamMusa/sdk-for-python
|
ff1c81bfe963a7079855ba3907264e2b326c7982
|
41934736d874e39a7ca69a1cf8732803eecc4102
|
refs/heads/master
| 2023-03-11T16:08:46.138018
| 2021-02-25T22:54:14
| 2021-02-25T22:54:14
| 350,777,704
| 1
| 0
|
BSD-3-Clause
| 2021-03-23T16:14:24
| 2021-03-23T16:14:23
| null |
UTF-8
|
Python
| false
| false
| 1,766
|
py
|
from ..service import Service
class Locale(Service):
def __init__(self, client):
super(Locale, self).__init__(client)
def get(self):
"""Get User Locale"""
params = {}
path = '/locale'
return self.client.call('get', path, {
'content-type': 'application/json',
}, params)
def get_continents(self):
"""List Continents"""
params = {}
path = '/locale/continents'
return self.client.call('get', path, {
'content-type': 'application/json',
}, params)
def get_countries(self):
"""List Countries"""
params = {}
path = '/locale/countries'
return self.client.call('get', path, {
'content-type': 'application/json',
}, params)
def get_countries_e_u(self):
"""List EU Countries"""
params = {}
path = '/locale/countries/eu'
return self.client.call('get', path, {
'content-type': 'application/json',
}, params)
def get_countries_phones(self):
"""List Countries Phone Codes"""
params = {}
path = '/locale/countries/phones'
return self.client.call('get', path, {
'content-type': 'application/json',
}, params)
def get_currencies(self):
"""List Currencies"""
params = {}
path = '/locale/currencies'
return self.client.call('get', path, {
'content-type': 'application/json',
}, params)
def get_languages(self):
"""List Languages"""
params = {}
path = '/locale/languages'
return self.client.call('get', path, {
'content-type': 'application/json',
}, params)
|
[
"eldad.fux@gmail.com"
] |
eldad.fux@gmail.com
|
4112207165b9dc04877fa7205d733fd533192fb5
|
f2737e4b118789d895412b4047b510a10513e057
|
/hotelapp/miapp/urls.py
|
cae27d9639dcfbf353add6e6d6953053fc3a1106
|
[] |
no_license
|
h-yuna282/pagina2
|
72c9471f12a1bc09242e009ea3b58b315d5d4d7c
|
194119bfd1295ccea06003ce46f74d1db125bfa1
|
refs/heads/master
| 2021-06-17T11:10:13.428503
| 2019-09-18T22:49:54
| 2019-09-18T22:49:54
| 209,416,741
| 0
| 0
| null | 2021-06-10T22:08:40
| 2019-09-18T22:47:14
|
HTML
|
UTF-8
|
Python
| false
| false
| 689
|
py
|
from django.urls import path
from .views import *
urlpatterns = [
path("",index, name = "index"),
path("habitacion/", habitacionList.as_view(), name = "Listarhabitacion"),
path('habitacion/nuevo/', habitacionCreate.as_view(), name = 'nuevohabitacion'),
path('habitacion/editar/<int:pk>', habitacionUpdate.as_view(), name = 'editarhabitacion'),
path('habitacion/eliminar/<int:pk>', habitacionDelete.as_view(), name = 'eliminarhabitacion'),
path('habitacion/detalle/<int:pk>', habitacionDetalle.as_view(), name = 'detallehabitacion'),
path('pago/nuevo/', pagoCreate.as_view(), name = 'nuevo_pago'),
path('pagos/', pagoList.as_view(), name = 'lista_pago'),]
|
[
"noreply@github.com"
] |
h-yuna282.noreply@github.com
|
7f77b75bf5cd3a4d414dd17089d6242a62f4690a
|
8100f7efb10aa7234d2a41fb7b6389382d2c6ab6
|
/stddev.py
|
defd5766a5a19628684bae0177d3ada09a4100d8
|
[] |
no_license
|
Vihan226/Project105
|
a66f9400e18e50d4c119b61e2c44802487e93e7b
|
0959a49085ca9c1f878fec3d7befca674c503fec
|
refs/heads/main
| 2023-07-30T17:31:16.910618
| 2021-09-24T00:02:44
| 2021-09-24T00:02:44
| 409,777,390
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 733
|
py
|
import math
#list of elements to calculate mean
import csv
with open("data.csv",newline='') as f:
reader=csv.reader(f)
file_data=list(reader)
data=file_data[0]
#mean find
def mean(data):
n=len(data)
total=0
for x in data:
total += int(x)
mean=total/n
return mean
#squaring and getting the values
squared_list=[]
for number in data:
a=int(number)-mean(data)
a=a**2
squared_list.append(a)
#getting the sum
sum=0
for i in squared_list:
sum =sum+i
#dividing the sum by the total values
result= sum/(len(data)-1)
#getting the deviation by taking square root of the result
std_deviation= math.sqrt(result)
print(std_deviation)
|
[
"noreply@github.com"
] |
Vihan226.noreply@github.com
|
b5bb250a6f9f72b825f71ab4fcf46a36c62ae1a8
|
663d6ae74e030b8283c079ac27a1511b0e513c32
|
/G3-1/Project/tracking.py
|
76fe203da7d5fe50e9ff2d154298ccc58425cbf7
|
[] |
no_license
|
Max-Hsu/Homework-NSYSU
|
c08de1f1e69c4e1524d3c5312b6e5722b145676f
|
2a1c72c8121c52f46246d4644725d62b28c4443b
|
refs/heads/main
| 2023-01-29T16:27:31.207165
| 2020-12-16T13:24:56
| 2020-12-16T13:24:56
| 314,138,422
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,107
|
py
|
import cv2
import sys
major_ver, minor_ver, subminor_ver = ['4', '3', '0']
if __name__ == '__main__' :
# Set up tracker.
# Instead of MIL, you can also use
tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']
tracker_type = tracker_types[2]
if int(minor_ver) < 3:
tracker = cv2.Tracker_create(tracker_type)
else:
if tracker_type == 'BOOSTING':
tracker = cv2.TrackerBoosting_create()
if tracker_type == 'MIL':
tracker = cv2.TrackerMIL_create()
if tracker_type == 'KCF':
tracker = cv2.TrackerKCF_create()
if tracker_type == 'TLD':
tracker = cv2.TrackerTLD_create()
if tracker_type == 'MEDIANFLOW':
tracker = cv2.TrackerMedianFlow_create()
if tracker_type == 'GOTURN':
tracker = cv2.TrackerGOTURN_create()
if tracker_type == 'MOSSE':
tracker = cv2.TrackerMOSSE_create()
if tracker_type == "CSRT":
tracker = cv2.TrackerCSRT_create()
# Read video
video = cv2.VideoCapture("output2.mp4")
# Exit if video not opened.
if not video.isOpened():
print("Could not open video")
sys.exit()
# Read first frame.
ok, frame = video.read()
if not ok:
print('Cannot read video file')
sys.exit()
# Define an initial bounding box
#bbox = (287, 23, 86, 320)
# Uncomment the line below to select a different bounding box
#bbox = cv2.selectROI(frame, False)
# Initialize tracker with first frame and bounding box
#ok = tracker.init(frame, bbox)
while True:
# Read a new frame
ok, frame = video.read()
#frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
if not ok:
break
# Start timer
timer = cv2.getTickCount()
#print(bbox)
# Update tracker
ok, bbox = tracker.update(frame)
# Calculate Frames per second (FPS)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer);
# Draw bounding box
if ok:
# Tracking success
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)
else :
# Tracking failure
cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
# Display tracker type on frame
cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2);
# Display FPS on frame
cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2);
# Display result
cv2.imshow("Tracking", frame)
# Exit if ESC pressed
k = cv2.waitKey(1) & 0xff
if k == 27 : break
elif k == ord('i'):
cv2.destroyWindow('Tracking')
bbox = cv2.selectROI(frame, False)
ok = tracker.init(frame, bbox)
|
[
"hsuevaair3317@gmail.com"
] |
hsuevaair3317@gmail.com
|
a401885e9d3ece9d87b0ca7cb9245ca832437610
|
737d41cac129ed54e8bfe9e7c1a1f4cb9b89f428
|
/recipes/migrations/0014_note_shared.py
|
b89ab9664763e82e7da6ce70aa30ea609732483b
|
[] |
no_license
|
kar288/carmelaacevedo
|
c7e3b86fbc51bc099e8e1660d23089e99be6b4e7
|
c318dd5ad2d873dc4e7a350f69fcf4453b3ed579
|
refs/heads/master
| 2021-08-28T17:51:22.471988
| 2018-11-12T08:46:46
| 2018-11-12T08:46:46
| 25,726,966
| 0
| 0
| null | 2021-08-10T19:07:18
| 2014-10-25T09:52:38
|
HTML
|
UTF-8
|
Python
| false
| false
| 388
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0013_month'),
]
operations = [
migrations.AddField(
model_name='note',
name='shared',
field=models.BooleanField(default=False),
),
]
|
[
"kar288@gmail.com"
] |
kar288@gmail.com
|
f6563f97117cf137cb095e2ad4d9ee508356240f
|
16606ea76668aa141813cb96e4360d0113812781
|
/model.py
|
14df777e709796b0563e33284d2ed07914ed317d
|
[] |
no_license
|
Lap1n/inf8225
|
e9a051ec7717ac8921b655a00e184e888b71cd3d
|
55f0a6c038242861fb341e6eecadf246513025d8
|
refs/heads/master
| 2020-03-10T23:58:19.568995
| 2018-08-29T02:31:58
| 2018-08-29T02:31:58
| 129,652,177
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,289
|
py
|
# Le projet est inspiré de l'implémentation pytorch de A2c de ikostrikov : https://github.com/ikostrikov/pytorch-a2c-ppo-acktr
import torch
from torch import nn
import numpy as np
from distributions import get_distribution
from utils import orthogonal
class Policy(nn.Module):
def __init__(self):
super(Policy, self).__init__()
"""
All classes that inheret from Policy are expected to have
a feature exctractor for actor and critic (see examples below)
and modules called linear_critic and dist. Where linear_critic
takes critic features and maps them to value and dist
represents a distribution of actions.
"""
def forward(self, inputs, states, masks):
raise NotImplementedError
def act(self, inputs, states, masks, deterministic=False):
hidden_critic, hidden_actor, states = self(inputs, states, masks)
action = self.dist.sample(hidden_actor, deterministic=deterministic)
action_log_probs, dist_entropy = self.dist.logprobs_and_entropy(hidden_actor, action)
value = self.critic_linear(hidden_critic)
return value, action, action_log_probs, states
def get_value(self, inputs, states, masks):
hidden_critic, _, states = self(inputs, states, masks)
value = self.critic_linear(hidden_critic)
return value
def evaluate_actions(self, inputs, states, masks, actions):
hidden_critic, hidden_actor, states = self(inputs, states, masks)
action_log_probs, dist_entropy = self.dist.logprobs_and_entropy(hidden_actor, actions)
value = self.critic_linear(hidden_critic)
return value, action_log_probs, dist_entropy, states
class DirectRLModel(Policy):
def __init__(self, input_size, hidden_size, action_space, num_layers=1):
super(DirectRLModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.input_size = input_size
self.action_space = action_space
self.seq_no_dropout = nn.Sequential(
nn.Linear(input_size, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 20),
nn.ReLU(),
)
self.apply(self.weights_init)
# Initialisation de la partie rnn du réseau
self.rnn = nn.GRUCell(20, hidden_size)
# Initialisation de la critique v(s) dans A2c
self.critic_linear = nn.Linear(hidden_size, 1)
# # Initialisation de l'acteur qui décidera des actions entre Short (0), Neutral (1) ou Buy (2) dans A2c
self.dist = get_distribution(hidden_size, self.action_space)
@property
def state_size(self):
return self.hidden_size
def weights_init(self, m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
weight_shape = list(m.weight.data.size())
fan_in = np.prod(weight_shape[1:4])
fan_out = np.prod(weight_shape[2:4]) * weight_shape[0]
w_bound = np.sqrt(6. / (fan_in + fan_out))
m.weight.data.uniform_(-w_bound, w_bound)
m.bias.data.fill_(0)
elif classname.find('Linear') != -1:
weight_shape = list(m.weight.data.size())
fan_in = weight_shape[1]
fan_out = weight_shape[0]
w_bound = np.sqrt(6. / (fan_in + fan_out))
m.weight.data.uniform_(-w_bound, w_bound)
m.bias.data.fill_(0)
def reset_parameters(self):
orthogonal(self.gru.weight_ih.data)
orthogonal(self.gru.weight_hh.data)
self.gru.bias_ih.data.fill_(0)
self.gru.bias_hh.data.fill_(0)
self.critic_linear.bias.data.fill_(0)
def forward(self, inputs, states, masks):
x = self.seq_no_dropout(inputs)
if inputs.size(0) == states.size(0):
x = states = self.rnn(x, states * masks)
else:
x = x.view(-1, states.size(0), x.size(1))
masks = masks.view(-1, states.size(0), 1)
outputs = []
for i in range(x.size(0)):
hx = states = self.rnn(x[i], states * masks[i])
outputs.append(hx)
x = torch.cat(outputs, 0)
return x, x, states
|
[
"philippewlelievre@gmail.com"
] |
philippewlelievre@gmail.com
|
a2db47963339e2f7560c5299646a057c2c1c8293
|
8b82875f184038d542413ebeabb46b4bfb17a40a
|
/dataset/TestSet.py
|
8029da21a19be72db0b535cb5ffd36ca085e54d3
|
[] |
no_license
|
bobo0810/JittorDogsClass
|
5d1ec046adb7f66cc8fb26e7d8f12331aab3bc4b
|
93ae414e19eab18338ee4397042152e0a83ade1e
|
refs/heads/main
| 2023-04-13T23:55:11.321066
| 2021-04-26T08:11:11
| 2021-04-26T08:11:11
| 361,667,172
| 9
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,135
|
py
|
import cv2
import socket
import yaml
import os
from jittor import transform
from jittor.dataset import Dataset
import numpy as np
import jittor as jt
from PIL import Image
cur_path = os.path.abspath(os.path.dirname(__file__))
def default_loader(path):
try:
img = cv2.imread(path)
except:
with open('read_error.txt', 'a') as fid:
fid.write(path+'\n')
return Image.new('RGB', (224,224), 'white')
return img
class TestDataset(Dataset):
def __init__(self,img_size=None,pad=True,batch_size=None,dataloader=default_loader,crop_type=None,data_conf='data_conf.yaml'):
super().__init__()
assert crop_type in ['head', 'body']
self.crop_type = 'Head' if 'head' in crop_type else 'Body'
self.dataloader = dataloader
self.pad = pad
self.batch_size=batch_size
data_dict = self.load_params(data_conf,self.crop_type)
self.imglist = os.listdir(data_dict['Test'])
self.imgs = []
self.root_path = data_dict['Test'] + '/'
for img in self.imglist:
self.imgs.append(img)
self.transform = transform.Compose([
transform.Resize( tuple(img_size)),
# transform.RandomHorizontalFlip(p=1),
transform.ToTensor(),
transform.ImageNormalize(
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225)
)])
# 加载参数
self.set_attrs(
batch_size=self.batch_size,
total_len=len(self.imglist),
shuffle=False,
num_workers=3,
)
def __getitem__(self, index):
image_name = self.imgs[index]
image = image_name
img = self.dataloader(self.root_path + image)
# 填充为正方形
if self.pad:
rows, cols, _ = img.shape
if cols > rows:
top = int((cols - rows) / 2)
bottom = cols - top - rows
img = cv2.copyMakeBorder(img, top, bottom, 0, 0, cv2.BORDER_CONSTANT, value=(0, 0, 0))
elif rows > cols:
left = int((rows - cols) / 2)
right = rows - left - cols
img = cv2.copyMakeBorder(img, 0, 0, left, right, cv2.BORDER_CONSTANT, value=(0, 0, 0))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
img = self.transform(img)
# img = np.asarray(img)
return img, image_name
@staticmethod
def load_params(data_conf,crop_type):
'''
读取yaml,加载数据集
'''
file = open(cur_path+'/'+data_conf, 'r',encoding="utf-8")
data_conf = yaml.load(file, Loader=yaml.FullLoader)
data_dict = {}
data_dict['Test'] = data_conf['Test'][crop_type]['default']
return data_dict
# if __name__=='__main__':
# jt.flags.use_cuda = 1
# dataloader =TestDataset(img_size=[368,368],batch_size=200,crop_type='head')
# for batch_idx, [img, image_name] in enumerate(dataloader):
# print(img.shape)
# print(image_name)
# print('--------')
|
[
"1055271769@qq.com"
] |
1055271769@qq.com
|
56625f6773cb4d925e37522c5d9875d8e0ba16c6
|
9e65e409106aad6339424a1afac3e75e15b4f488
|
/0x11-python-network_1/1-hbtn_header.py
|
fef81c75af7dc5ea99a55847d66c9c42dc7d9e71
|
[] |
no_license
|
jfbm74/holbertonschool-higher_level_programming
|
63fe8e35c94454896324791585fe7b8e01e1c67d
|
609f18ef7a479fb5dcf1825333df542fc99cec7b
|
refs/heads/master
| 2023-03-05T20:44:05.700354
| 2021-02-10T00:21:54
| 2021-02-10T00:21:54
| 259,452,209
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 380
|
py
|
#!/usr/bin/python3
"""
A python script that sends a request to the URL and displays the
value of the X-Request-Id variable found in the header of the response
"""
import urllib.request
import sys
if __name__ == '__main__':
url = sys.argv[1]
with urllib.request.urlopen(url) as response:
html = response.read()
print(response.headers.get('X-Request-Id'))
|
[
"jfbm74@gmail.com"
] |
jfbm74@gmail.com
|
6af6f72a651f6e9d27302b33a6214a86ca6bea5d
|
0bdffcf8f11f895dd2861e6508805be7143c180c
|
/IrisData/ExampleIris.py
|
3b969b6c89b978c7e30085232a52ce7d70585601
|
[] |
no_license
|
furkanaygur/Python-Machine-Learning
|
872684a8b0bc4fbdd52d352c2b2b55ad10839c0d
|
e77f13cdb324c6cd5c6d6026960abf4ae2571781
|
refs/heads/main
| 2023-01-14T13:24:33.517176
| 2020-11-17T23:06:28
| 2020-11-17T23:06:28
| 306,900,959
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,833
|
py
|
# -*- coding: utf-8 -*-
"""
@author: furkan
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
datas = pd.read_excel("iris.xls")
x = datas.iloc[:,1:4].values
y = datas.iloc[:,4:].values
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.33, random_state=0)
sc = StandardScaler()
X_train = sc.fit_transform(x_train)
X_test = sc.transform(x_test)
# Logistic Regression
lr = LogisticRegression(random_state=0 )
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print("Logistic Regression Confusion Matrix: \n",cm)
# K-NN Classifier
knn = KNeighborsClassifier(n_neighbors=3, metric='minkowski')
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print("Knn Classifier Confusion Matrix: \n", cm)
# SVC (SVM Classifier)
svc = SVC(kernel='rbf' )
svc.fit(X_train, y_train)
y_pred = svc.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print("SVC Confusion Matrix: \n", cm)
# Desicion Tree Classifier
dtc = DecisionTreeClassifier(criterion='entropy')
dtc.fit(X_train, y_train)
y_pred = dtc.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print("Decision Tree Classifier Confusion Matrix: \n", cm)
# Random Forest Classifier
rfc = RandomForestClassifier(n_estimators=10, criterion='entropy')
rfc.fit(X_train, y_train)
y_pred = rfc.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print("Random Forest Classifier Confuison Matrix: \n", cm)
|
[
"32839776+furkanaygur@users.noreply.github.com"
] |
32839776+furkanaygur@users.noreply.github.com
|
c0cc554acfda74cb9fa2bfbc48b79686bddee449
|
8ef6dbdd3791dd7fbe1320483a22e0540c54359b
|
/Core Python/Dictionary/20NestedForLoop.py
|
32336e6f39860fa4e9b0b186bf2bcb36c81b0f78
|
[] |
no_license
|
kundan4U/Python
|
8095eecba088910d2068a6375c907d47f2bb9c95
|
6b3fdbe66edb52e9f612352abb9c6563547b6297
|
refs/heads/main
| 2023-06-24T06:29:43.770282
| 2021-07-21T18:40:11
| 2021-07-21T18:40:11
| 388,213,053
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 185
|
py
|
a = {'course':'python','fees':15000,1:{'course':'javaScript','fees':100000}}
for i in a:
if type(a[i]) is dict:
for k in a[i]:
print(k,"=",a[i][k])
else:
print(i,"=",a[i])
|
[
"kc946605@gmail.com"
] |
kc946605@gmail.com
|
45827ff01bb45130dc4d44ea80c943af675d7a46
|
98e4dc41e3d994dfb55a2553c79d1b61590ecca6
|
/LeetCode/Medium/Coin Change/revise/sol.py
|
c9a68902719fc47186e209a0965ca97a58528da1
|
[] |
no_license
|
krohak/Project_Euler
|
b753c4f3bbf26a5eff3203e27482599d1e089fc6
|
1d8a2326543d69457f1971af9435b3e93ab32f52
|
refs/heads/master
| 2022-09-02T10:48:59.472111
| 2022-08-18T11:11:16
| 2022-08-18T11:11:16
| 111,204,162
| 4
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 842
|
py
|
def coins_dp(coins, amount):
if not amount:
return 0
amounts_list = [ float("inf") for i in range(amount+1) ]
for coin in coins:
if coin <= amount:
amounts_list[coin] = 1
print(amounts_list)
for (target, _) in enumerate(amounts_list):
min_coins = float("inf")
for coin in coins:
if (target-coin>0):
min_coins = min(min_coins, amounts_list[target-coin] + 1)
amounts_list[target] = min(min_coins, amounts_list[target])
print(amounts_list)
if amounts_list[-1] == float("inf"):
return -1
return amounts_list[-1]
coins = [1, 2, 5]
amount = 11
coins = [2]
amount = 3
coins = [1]
amount = 0
coins = [2]
amount = 1
coins = [1]
amount = 1
min_coins = coins_dp(coins, amount)
print(min_coins)
|
[
"rohaksinghal14@gmail.com"
] |
rohaksinghal14@gmail.com
|
08a1faec57667b59fb6c06141e0e3afdb950d9e9
|
bbc2a5793c153beda223f86265622a5b21e528df
|
/models/ssd_resnet_50.py
|
c98951129cd8a2140e7d90fefa36e240b1f902aa
|
[] |
no_license
|
Jadecity/tf_ssd
|
eb12b0acd35487b2981357e93c4135e11b1b2e08
|
15407257e03bfcf05b5f06149b1be7d1c6208126
|
refs/heads/master
| 2020-03-20T01:05:49.540273
| 2018-07-03T18:48:11
| 2018-07-03T18:48:11
| 137,066,680
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,835
|
py
|
"""
Define ssd net using resnet_50 as backbone network.
"""
import tensorflow as tf
from tensorflow.contrib import slim
from nets import resnet_v2
from utils import anchorsUtil
from utils import confUtil, lossUtil
import numpy as np
def multibox_predict(input_layer, class_num, layer_name, weight_decay):
"""
Compute predictions for input layer.
:param input_layer: Input feature layer
:param class_num: number of output classes.
:param layer_name: layer name.
:param weight_decay: weight decay.
:return: prediction p, and localizatoin l.
"""
# Get anchors for each layer.
layer_anchors = anchorsUtil.get_layer_anchors(layer_name)
layer_shape = layer_anchors.shape
anchor_num = layer_shape[2]
with tf.variable_scope('pred/%s' % layer_name):
with slim.arg_scope([slim.conv2d],
activation_fn=tf.nn.relu,
weights_regularizer=slim.l2_regularizer(weight_decay)):
pred = slim.conv2d(input_layer, anchor_num * (class_num + 4), kernel_size=[3, 3])
# Reshape output tensor to extract each anchor prediction.
pred = tf.reshape(pred, [-1, layer_shape[0], layer_shape[1], anchor_num, class_num + 4])
pred_cls = tf.slice(pred, [0, 0, 0, 0, 0], [-1, layer_shape[0], layer_shape[1], anchor_num, class_num])
pred_cls = tf.reshape(pred_cls, [-1, layer_shape[0]*layer_shape[1]*anchor_num, class_num])
pred_pos = tf.slice(pred, [0, 0, 0, 0, class_num], [-1, layer_shape[0], layer_shape[1], anchor_num, 4])
pred_pos = tf.reshape(pred_pos, [-1, layer_shape[0] * layer_shape[1] * anchor_num, 4])
return pred_cls, pred_pos
def init(class_num, weight_decay, is_training):
"""
Init and build net.
:param class_num: number of class.
:return: a callable object, e.g. network.
"""
def predict(image):
"""
Do predict using image.
:param image: input image, shape [batch, w, h, c]
:return: predicted raw logits.
"""
# Load resnet50
with slim.arg_scope(resnet_v2.resnet_arg_scope(weight_decay=weight_decay,
use_batch_norm=False)):
resnet, endpoints = resnet_v2.resnet_v2_50(inputs=image,
num_classes=class_num,
is_training=is_training)
end_feats = {}
net = endpoints['resnet_v2_50/block3']
end_feats['resnet_v2_50/block3'] = net
net = endpoints['resnet_v2_50/block4']
end_feats['resnet_v2_50/block4'] = net
# Create SSD conv layers.
with tf.variable_scope('SSDNet'):
with slim.arg_scope([slim.conv2d],
activation_fn=tf.nn.relu,
weights_regularizer=slim.l2_regularizer(weight_decay)):
block = 'block-1'
with tf.variable_scope(block): # 14x14x512 -> 7x7x512
net = slim.layers.conv2d(net, 256, kernel_size=[1, 1], activation_fn=tf.nn.relu)
net = slim.layers.conv2d(net, 512, kernel_size=[3, 3], stride=2, activation_fn=tf.nn.relu)
end_feats[block] = net
block = 'block-2'
with tf.variable_scope(block): # 7x7x512 -> 4x4x256
net = slim.layers.conv2d(net, 128, kernel_size=[1, 1], activation_fn=tf.nn.relu)
net = slim.layers.conv2d(net, 256, kernel_size=[3, 3], stride=2, activation_fn=tf.nn.relu)
end_feats[block] = net
block = 'block-3'
with tf.variable_scope(block): # 4x4x256 -> 2x2x256
net = slim.layers.conv2d(net, 128, kernel_size=[1, 1], activation_fn=tf.nn.relu)
net = slim.layers.conv2d(net, 256, kernel_size=[3, 3], activation_fn=tf.nn.relu)
end_feats[block] = net
block = 'block-4'
with tf.variable_scope(block): # 2x2x256 -> 1x1x256
net = slim.layers.conv2d(net, 128, kernel_size=[1, 1], activation_fn=tf.nn.relu)
net = slim.layers.conv2d(net, 256, kernel_size=[3, 3], activation_fn=tf.nn.relu, padding='VALID')
end_feats[block] = net
"""
Add classifier conv layers to each added feature map(including the last layer of backbone network).
Prediction and localisations layers.
"""
logits = []
locations = []
for layer_name in end_feats.keys():
logit, location = multibox_predict(end_feats[layer_name], class_num, layer_name, weight_decay)
logits.append(logit)
locations.append(location)
# Concat all feature layer outputs.
logits = tf.concat(logits, axis=1)
locations = tf.concat(locations, axis=1)
return logits, locations, end_feats
return predict
def posMask(bbox, anchors):
"""
Create a boolean mask of shape [anchor_num].
:param bboxes: ground truth bbox of shape[4]
:param anchors: anchors of current layer , shape [anchor_num, 4]
:return: a boolean mask of shape [anchor_num]
"""
# Compute jaccard overlap.
overlap = lossUtil.jaccardIndex(bbox, anchors)
# Get positive and negtive mask accoding to overlap.
pos_mask = tf.greater(overlap, 0.5)
return pos_mask
def classLoss(logits, label, pos_mask):
"""
Classification loss.
:param logits: predicted logits, shape [anchor_num, class_num]
:param label: scalar
:param pos_mask: shape [anchor_num]
:return: loss
"""
neg_mask = tf.logical_not(pos_mask)
# Loss for each postition.
conf_loss = tf.log(tf.nn.softmax(logits, axis=1))
pos_loss = tf.slice(conf_loss, [0, label], [-1, 1])
pos_loss = tf.boolean_mask(pos_loss, pos_mask)
pos_loss = tf.reduce_sum(pos_loss)
neg_loss = tf.slice(conf_loss, [0, 0], [-1, 1])
neg_loss = tf.boolean_mask(neg_loss, neg_mask)
# Top-k negative loss.
pos_num = tf.reduce_sum(tf.cast(pos_mask, dtype=tf.int32))
neg_num = tf.reduce_sum(tf.cast(neg_mask, dtype=tf.int32))
neg_loss = tf.cond(tf.equal(tf.multiply(neg_num, pos_num), 0),
lambda: tf.constant(0, dtype=tf.float32),
lambda: tf.nn.top_k(neg_loss, tf.minimum(neg_num, tf.multiply(pos_num, 3)))[0])
neg_loss = tf.reduce_sum(neg_loss)
conf_loss = tf.negative(tf.add(pos_loss, neg_loss))
return conf_loss
def locationLoss(location, gbbox, pos_mask):
"""
Compute location loss.
:param location: predicted location, shape [anchor_num, 4]
:param gbbox: ground truth bbox, shape [anchor_num, 4]
:param pos_mask: shape [anchor_num]
:return: location loss
"""
diff = tf.subtract(location, gbbox)
loc_loss = lossUtil.smoothL1(diff)
loc_loss = tf.boolean_mask(loc_loss, pos_mask)
loc_loss = tf.reduce_sum(loc_loss)
return loc_loss
def ssdLoss(logits, locations, labels, alpha, batch_size):
"""
Compute SSD loss.
:param logits: a tensor of raw prediction, shape [batch, total_anchor_num, class_num]
:param locations: a tensor of location prediction, shape [batch, total_anchor_num, 4]
:param labels: a dict,
labels['bbox_num']: shape [batch, 1]
labels['labels']: shape [batch, bbox_num],
labels['bboxes']: shape [batch, bbox_num, 4]
:param alpha: weight between classification loss and location loss.
:return:
"""
anchors = tf.constant(anchorsUtil.get_all_layer_anchors(), dtype=tf.float32)
total_loss = tf.constant(0, dtype=tf.float32)
for bi in range(batch_size):
label = labels['labels'][bi]
bboxes = labels['bboxes'][bi]
"""For each ground truth box, compute loss"""
for bbox, cur_label in zip(tf.unstack(bboxes), tf.unstack(label)):
# Transform bbox.
g_bbox = lossUtil.encodeBBox(bbox, anchors)
pos_mask = posMask(bbox, anchors)
pos_num = tf.reduce_sum(tf.cast(pos_mask, dtype=tf.float32))
cls_loss = classLoss(logits[bi], cur_label, pos_mask)
loc_loss = locationLoss(locations[bi], g_bbox, pos_mask)
total_loss += (cls_loss + alpha * loc_loss) / pos_num
tf.losses.add_loss(total_loss)
return total_loss
|
[
"lvhaoexp@163.com"
] |
lvhaoexp@163.com
|
d511bc9ee5811c36bb5e897425c3ed1747e38ab8
|
87d026185cf19ad573a08a683b9afa4612314cc0
|
/Kmeans2.py
|
9a0e30aef6a27994e59245901a1f23f6806a2b58
|
[] |
no_license
|
rinchinov/epam_h
|
11488d8cd391d7c5ee20cff7b60e42308181a2da
|
834c59beea61902aaf41bd79dfb3e4a65f83eb4b
|
refs/heads/master
| 2021-08-23T04:29:37.079361
| 2017-12-03T08:23:23
| 2017-12-03T08:23:23
| 112,906,474
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,372
|
py
|
from sklearn.cluster import KMeans
import numpy as np
import pickle
import folium
import pandas as pd
from branca.colormap import linear
heat_map_image = pickle.load(open("dump/heat_map_image{}".format("[(59900,30120)-(59830,30220)]"), "rb"))
model = np.ones((10000, 1))
model = np.reshape(heat_map_image["crime"], (10000, 1)) + (1/1)*np.reshape(heat_map_image["problems"], (10000, 1)) + \
2*np.reshape(heat_map_image["amenities"], (10000, 1)) + 2*np.reshape(heat_map_image["art"], (10000, 1))
kmeans = KMeans(n_clusters=4, random_state=0).fit(model)
heat_map_image["model"] = np.reshape(kmeans.labels_, (100, 100))
heat_map_image["positive"] = 2*np.reshape(heat_map_image["amenities"], (10000, 1)) + 2*np.reshape(heat_map_image["art"], (10000, 1))
heat_map_image["negative"] = np.reshape(heat_map_image["crime"], (10000, 1)) + (1/1)*np.reshape(heat_map_image["problems"], (10000, 1))
my_dict = {3.0: 3.0,
2.0: 1.0,
0.0: 0.0,
1.0: 2.0}
heat_map_image["model"] = np.array([my_dict[i] for i in heat_map_image["model"].reshape((heat_map_image["model"].shape[0]*heat_map_image["model"].shape[1]))]).reshape((heat_map_image["model"].shape[0],heat_map_image["model"].shape[1]))
for type_ in heat_map_image.keys():
if type_ != "json":
t = np.transpose(heat_map_image[type_])
data = pd.DataFrame(np.reshape(t, (10000,)), columns=["values1"])
data['id'] = [i for i in range(10000)]
# create map
colormap = linear.RdPu.scale(
data.values1.min(),
data.values1.max())
print(np.mean(data.values1))
problems_dict = data.set_index('id')['values1']
m = folium.Map(location=[59.86, 30.17], zoom_start=12)
folium.GeoJson(
heat_map_image["json"],
name='values1',
style_function=lambda feature1: {
'fillColor': colormap(problems_dict[feature1['id']]),
'color': 'black',
'weight': 1,
'dashArray': '5, 5',
'fillOpacity': 0.5,
'opacity': 0.5
}
).add_to(m)
folium.LayerControl().add_to(m)
m.save('result/{}.html'.format(type_))
data = pd.DataFrame(np.hstack((np.reshape(heat_map_image["model"], (10000, 1)), model)), columns=['clus', 'heat'])
print(data.groupby(['clus']).describe())
|
[
"roman1001001@gmail.com"
] |
roman1001001@gmail.com
|
a8e134fe12a5789674d0793f3cc0edb3c186883d
|
558ed1e8e4519ac1d4aa0e37619cf35c7f860a9d
|
/TF/tfDemo4.py
|
a81f60774fab4505b8a25614286088cbc89d2de3
|
[] |
no_license
|
xiechuanj/AIDemo
|
d92ccde83f35221b7a29df28a8f2cbcbecf5f883
|
ac946b0cdd81da07a75a5f65fffb21098a49ec98
|
refs/heads/master
| 2020-04-28T04:03:40.998833
| 2019-03-11T09:10:23
| 2019-03-11T09:10:23
| 174,963,275
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 253
|
py
|
# -*- coding: utf-8 -*-
import tensorflow as tf
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
print(sess.run(output, feed_dict={input1:[7.], input2:[2.]}))
|
[
"12121212@qq.com"
] |
12121212@qq.com
|
a27cd5d349b420d584557c9f7302902910b78b9f
|
9187d377034825b61d4178076142bddf81478fc2
|
/marlo/envs/MobchaseTrain1/main.py
|
531a363e64fc60ac590e1e22d847f93565c066aa
|
[
"MIT"
] |
permissive
|
AndKram/marLo
|
63da777a4d747499d39cd02a6f13966a6a843df9
|
7873bde58f7fb0848ef90e62133a34254b763b72
|
refs/heads/master
| 2021-07-23T20:43:28.834131
| 2018-11-05T16:01:20
| 2018-11-05T16:01:20
| 143,423,165
| 2
| 0
|
MIT
| 2018-08-03T12:12:22
| 2018-08-03T12:12:21
| null |
UTF-8
|
Python
| false
| false
| 2,696
|
py
|
import marlo
from marlo import MarloEnvBuilderBase
from marlo import MalmoPython
import os
from pathlib import Path
class MarloEnvBuilder(MarloEnvBuilderBase):
"""
# Mob Chase
## Overview of the game
Collaborative. Two or more Minecraft agents and a mob are wandering a small meadow. The agents have two choices:
- _Catch the mob_ (i.e., the agents pinch or corner the mob(s), and no escape path is available), and receive a high reward (1 point)
- _Give up_ and leave the pen through the exits, marked by special tiles on the edge of the pen, and receive a small reward (0.2 points)
The game is inspired by the variant of the _stag hunt_ presented in [Yoshida et al. 2008]. The [stag hunt](https://en.wikipedia.org/wiki/Stag_hunt) is a classical game theoretic game formulation that captures conflicts between collaboration and individual safety.
[Yoshida et al. 2008] Yoshida, Wako, Ray J. Dolan, and Karl J. Friston. ["Game theory of mind."](http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1000254) PLoS Comput Biol 4.12 (2008): e1000254.
## How to play
* Agents can move forward/backward and turn.
* Agents move in turns and try to catch the mob (1 points if caught).
* Agents can give up on catching the mob in the current round by moving to the "exit squares" on the edge of the play area (0.2 points).
* There is a maximum number of steps available (50), and agents get -0.02 point for each step taken.
## Parameters varied for tasks
* time = [0, 3000, 6000]
* mob_types = ['Pig', 'Cow', 'Chicken']
* exit_blocks = ['diamond_block', 'brick_block', 'purpur_block', 'bone_block', 'emerald_block']
* edge_blocks = ['fence', 'spruce_fence', 'jungle_fence', 'dark_oak_fence']
* edge_ground = ['sand', 'clay', 'water']
* mob_count = [1, 2]
* grid_size = [9, 11]
* exit_block_counts = [2, 3, 4]
* obstacle_counts = [2, 4, 6]
Game design space size: 1.94E+4
"""
def __init__(self, extra_params=None):
if extra_params is None:
extra_params={}
super(MarloEnvBuilder, self).__init__(
templates_folder=os.path.join(
str(Path(__file__).parent),
"templates"
)
)
self.params = self._default_params()
# You can do something with the extra_params if you wish
def _default_params(self):
_default_params = super(MarloEnvBuilder, self).default_base_params
return _default_params
if __name__ == "__main__":
env_builder = MarloEnvBuilder()
mission_xml = env_builder.render_mission_spec()
mission_spec = MalmoPython.MissionSpec(mission_xml, True)
print(mission_spec.getSummary())
|
[
"v-andkra@microsoft.com"
] |
v-andkra@microsoft.com
|
d2998ed1e82df3495b5046b8fc9d5372a205c38e
|
7009b25f80c75532889053d82702df876a6f862c
|
/pi_calculation.py
|
0d5fe6f7c03a9d64f7d2cedb54a994a1463608e9
|
[] |
no_license
|
docent09/comp_calc_intro
|
b22ba795fe63e86e7475aa9fe474e3a9aba5e7a6
|
47b3bc9168f4609289788e1487f829539a14d883
|
refs/heads/main
| 2023-08-28T04:55:06.455004
| 2021-10-25T14:14:02
| 2021-10-25T14:14:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,387
|
py
|
# Сравнение различных способов вычисления числа ПИ
def leibniz(n):
"""
Вычисление числа ПИ с помощью ряда Лейбница
:param n: число слагаемых ряда
:return: найденное число ПИ
"""
p = 0 # приближение числа пи
for i in range(n):
p += (-1)**i / (2*i + 1)
return 4*p
def euler(n):
"""
Вычисление числа ПИ с помощью ряда Эйлера
:param n: число слагаемых ряда
:return: найденное число ПИ
"""
import math
p = 0 # приближение числа пи
for i in range(1, n+1):
p += 1 / i**2
return math.sqrt(6*p)
def wallis(n):
"""
Вычисление числа ПИ с помощью произведения Валлиса
:param n: число слагаемых ряда
:return: найденное число ПИ
"""
p = 1 # приближение числа пи
for i in range(1, n+1):
p *= (2 * i)**2 / ((2*i-1) * (2*i+1))
return 2*p
def newton1(k):
"""
Вычисление числа ПИ с помощью метода Ньютона
:param k: число слагаемых ряда
:return: найденное число ПИ
"""
n = 1/2
p = 0 # приближение числа пи
F = 1 # факториал
for i in range(k):
N = 1
for j in range(i):
N *= n - j
p += (-1)**i * N / ((2*i+1) * F)
F *= i+1
return 4*p
def newton2(k):
"""
Вычисление числа ПИ с помощью улучшенного метода Ньютона
:param k: число слагаемых ряда
:return: найденное число ПИ
"""
import math
n = 1/2
p = 0 # приближение числа пи
F = 1
for i in range(k):
N = 1
for j in range(i):
N *= n - j
p += (-1)**i * N / ((2*i+1) * F) * 0.5**(2*i+1)
F *= i+1
return 12*(p-math.sqrt(3)/8)
if __name__ == "__main__":
import math
import time
tests = [1, 2, 3, 4, 5, 6]
test = 1
while test in tests:
print('Введите номер теста (1, 2, 3, 4, 5, 6):')
print('Тест #1 - ряд Лейбница')
print('Тест #2 - ряд Эйлера')
print('Тест #3 - произведение Валлиса')
print('Тест #4 - метод Ньютона (биномиальная теорема)')
print('Тест #5 - улучшенный метод Ньютона (биномиальная теорема)')
print('Тест #6 - сравнение точности 4 методов при разных n')
test = int(input())
if test == 1:
print('-- Вычисление числа ПИ по формуле ряда Лейбница --')
print('n', 'Найденное число ПИ', 'Погрешность', sep='\t')
t1 = time.time()
for n in range(100, 1001, 100):
p = leibniz(n)
e = abs(math.pi - p)
print(n, p, e, sep='\t')
print('Время вычисления =', round(time.time()-t1, 5))
print()
if test == 2:
print('-- Вычисление числа ПИ по формуле ряда Эйлера --')
print('n', 'Найденное число ПИ', 'Погрешность', sep='\t')
t1 = time.time()
for n in range(100, 1001, 100):
p = euler(n)
e = abs(math.pi - p)
print(n, p, e, sep='\t')
print('Время вычисления =', round(time.time()-t1, 5))
print()
if test == 3:
print('-- Вычисление числа ПИ по формуле произведения Валлиса --')
print('n', 'Найденное число ПИ', 'Погрешность', sep='\t')
t1 = time.time()
for n in range(100, 1001, 100):
p = wallis(n)
e = abs(math.pi - p)
print(n, p, e, sep='\t')
print('Время вычисления =', round(time.time()-t1, 5))
print()
if test == 4:
print('-- Вычисление числа ПИ по методу Ньютона --')
print('n', 'Найденное число ПИ', 'Погрешность', sep='\t')
t1 = time.time()
for n in range(10, 101, 10):
p = newton1(n)
e = abs(math.pi - p)
print(n, p, e, sep='\t')
print('Время вычисления =', round(time.time()-t1, 5))
print()
if test == 5:
print('-- Вычисление числа ПИ по улучшенному методу Ньютона --')
print('n', 'Найденное число ПИ', 'Погрешность', sep='\t')
t1 = time.time()
for n in range(2, 11, 1):
p = newton2(n)
e = abs(math.pi - p)
print(n, p, e, sep='\t')
print('Время вычисления =', round(time.time()-t1, 5))
print()
if test == 6:
print('-- Сравнение точности методов расчета ПИ при разных n --')
print('n' ,'Ряд Лейбница', 'Ряд Эйлера', 'Произв. Валлиса', 'Метод Ньютона', 'Улучшенный метод Ньютона', sep='\t')
nn = [10, 100]
for n in nn:
e1 = round(abs(math.pi - leibniz(n)), 10)
e2 = round(abs(math.pi - euler(n)), 10)
e3 = round(abs(math.pi - wallis(n)), 10)
e4 = round(abs(math.pi - newton1(n)), 10)
e5 = round(abs(math.pi - newton2(n)), 15)
print (n, e1, e2, e3, e4, e5, sep='\t')
print()
|
[
"noreply@github.com"
] |
docent09.noreply@github.com
|
aa70d83fee4059ce3133d2e612537f106b980bd1
|
b73dd400937d30b29a9c48bdbd3e81c7a035d076
|
/Django/Skole side/Skole_side/skoleside/articles/migrations/0004_auto_20151125_1723.py
|
bb26bfae499d539377ccc7d9bdc47f4c12e50b53
|
[] |
no_license
|
Exodus111/Projects
|
772ffbc94f4396b8afded1b6b5095f4b084fdd7a
|
732853897ae0048909efba7b57ea456e6aaf9e10
|
refs/heads/master
| 2020-05-21T19:26:03.972178
| 2017-03-26T10:04:35
| 2017-03-26T10:04:35
| 61,034,978
| 1
| 0
| null | 2017-03-26T10:04:36
| 2016-06-13T12:36:00
|
Rust
|
UTF-8
|
Python
| false
| false
| 717
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0003_auto_20151124_1732'),
]
operations = [
migrations.AlterField(
model_name='article',
name='title',
field=models.CharField(max_length=200),
),
migrations.AlterField(
model_name='category',
name='title',
field=models.CharField(max_length=200),
),
migrations.AlterField(
model_name='subcategory',
name='title',
field=models.CharField(max_length=200),
),
]
|
[
"aurelioxxx@hotmail.com"
] |
aurelioxxx@hotmail.com
|
f725dae2d7b8a27817dcb5158d9a35615d312572
|
2469e5c76c0f70ac64b0f333ad20ccc84a760522
|
/scripts/cluster_scripts/run_ppo_cluster.py
|
fa9da6abf7277e43d203ee36542e44b284e738ee
|
[
"MIT"
] |
permissive
|
facebookresearch/nocturne
|
8454c10643ea4ff063e10d5f83a5a0d2d90ad1c2
|
ae0a4e361457caf6b7e397675cc86f46161405ed
|
refs/heads/main
| 2023-05-24T02:25:48.963308
| 2022-10-15T19:19:29
| 2022-10-15T19:19:29
| 503,843,020
| 216
| 21
|
MIT
| 2023-04-22T16:46:06
| 2022-06-15T16:28:46
|
Python
|
UTF-8
|
Python
| false
| false
| 3,396
|
py
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Run on-policy PPO experiments on a SLURM cluster."""
import argparse
import os
import pathlib
import shutil
from datetime import datetime
from subprocess import Popen
from cfgs.config import PROJECT_PATH
from scripts.cluster_scripts.utils import Overrides
def make_code_snap(experiment, code_path, slurm_dir='exp'):
"""Copy code to directory to ensure that the run launches with correct commit.
Args:
experiment (str): Name of experiment
code_path (str): Path to where we are saving the code.
str_time (str): Unique time identifier used to distinguish
experiments with same name.
Returns
-------
snap_dir (str): path to where the code has been copied.
"""
now = datetime.now()
if len(code_path) > 0:
snap_dir = pathlib.Path(code_path) / slurm_dir
else:
snap_dir = pathlib.Path.cwd() / slurm_dir
snap_dir /= now.strftime('%Y.%m.%d')
snap_dir /= now.strftime('%H%M%S') + f'_{experiment}'
snap_dir.mkdir(exist_ok=True, parents=True)
def copy_dir(dir, pat):
dst_dir = snap_dir / 'code' / dir
dst_dir.mkdir(exist_ok=True, parents=True)
for f in (src_dir / dir).glob(pat):
shutil.copy(f, dst_dir / f.name)
dirs_to_copy = [
'.', './cfgs/', './cfgs/algo', './algos/', './algos/ppo/',
'./algos/ppo/ppo_utils', './algos/ppo/r_mappo',
'./algos/ppo/r_mappo/algorithm', './algos/ppo/utils',
'.nocturne/envs/', './nocturne_utils/', '.nocturne/python/', './build'
]
src_dir = pathlib.Path(os.path.dirname(os.getcwd()))
for dir in dirs_to_copy:
copy_dir(dir, '*.py')
copy_dir(dir, '*.yaml')
return snap_dir
def main():
"""Launch experiments on SLURM cluster by overriding Hydra config."""
parser = argparse.ArgumentParser()
parser.add_argument('experiment', type=str)
parser.add_argument('--code_path',
default='/checkpoint/eugenevinitsky/nocturne')
parser.add_argument('--dry', action='store_true')
args = parser.parse_args()
snap_dir = make_code_snap(args.experiment, args.code_path)
print(str(snap_dir))
overrides = Overrides()
overrides.add('hydra/launcher', ['submitit_slurm'])
overrides.add('hydra.launcher.partition', ['learnlab'])
overrides.add('experiment', [args.experiment])
# experiment parameters
overrides.add('episode_length', [200])
# algo
overrides.add('algo', ['ppo'])
overrides.add('algo.entropy_coef', [-0.001, 0.0, 0.001])
overrides.add('algo.n_rollout_threads', [128])
# rewards
overrides.add('rew_cfg.goal_achieved_bonus', [10, 50])
# misc
overrides.add('scenario_path',
[PROJECT_PATH / 'scenarios/twenty_car_intersection.json'])
cmd = [
'python',
str(snap_dir / 'code' / 'algos' / 'ppo' / 'nocturne_runner.py'), '-m'
]
print(cmd)
cmd += overrides.cmd()
if args.dry:
print(' '.join(cmd))
else:
env = os.environ.copy()
env['PYTHONPATH'] = str(snap_dir / 'code')
p = Popen(cmd, env=env)
p.communicate()
if __name__ == '__main__':
main()
|
[
"vinitsky.eugene@gmail.com"
] |
vinitsky.eugene@gmail.com
|
94744bc7cc6b3ef10599997cd0a35a5ffca0b434
|
8575ccf9e7e6b2257ec7aee1539c91afa90d65a5
|
/base/_06_cv2/_11_face_detector/face_mix.py
|
45c722c2f026863e7cef65767af55857db193c2c
|
[] |
no_license
|
oaifaye/pyfirst
|
86b8765751175f0be0fe3f95850ff018eacf51d3
|
e8661b5adf53afd47fa5cb6f01cd76535d8fc8b9
|
refs/heads/master
| 2021-12-12T00:33:39.523597
| 2021-08-13T08:32:10
| 2021-08-13T08:32:10
| 160,138,715
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,036
|
py
|
# coding=utf-8
#================================================================
#
# File name : face_mix.py
# Author : Faye
# Created date: 2021/2/2 17:33
# Description : 把一张脸挪到另外一张脸,只是平移,没有任何变换
#
#================================================================
import dlib
import cv2
import numpy as np
def shape_to_np(shape, dtype="int", point_count=68): # 将包含68个特征的的shape转换为numpy array格式
coords = np.zeros((point_count, 2), dtype=dtype)
for i in range(0, point_count):
coords[i] = (shape.part(i).x, shape.part(i).y)
return coords
if __name__ == '__main__':
# img_new = cv2.imread('face_mix/0016_01_1.png')
# img = cv2.imread('face_mix/0016_01_5.png')
img = cv2.imread(r'C:\Users\Administrator\Desktop\zawu\20210208/20210208123543.jpg')
img_new = cv2.imread(r'C:\Users\Administrator\Desktop\zawu\20210208/20210208123539.jpg')
detector = dlib.get_frontal_face_detector()
pointer = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 1)
if len(rects) != 0:
rect = rects[0]
shape = pointer(gray, rect)
shape = shape_to_np(shape, point_count=68)
max_xy = np.max(shape, axis=0)
min_xy = np.min(shape, axis=0)
w = max_xy[0] - min_xy[0]
h = max_xy[1] - min_xy[1]
wh = np.max((w, h)) + 20
middle = (int(min_xy[0] + w / 2), int(min_xy[1] + h / 2))
x = int(middle[0] - wh / 2)
y = int(middle[1] - wh / 2)
face_area = []
for i in range(0, 17):
face_area.append((shape[i][0], shape[i][1]))
face_area.append((shape[24][0], shape[24][1]-4))
face_area.append((shape[18][0], shape[18][1]-4))
face_area.append((shape[0][0], shape[0][1]))
# for i in range(3, 14):
# face_area.append((shape[i][0], shape[i][1]))
# # face_area.append((shape[29][0], shape[29][1]))
# face_area.append((shape[3][0], shape[3][1]))
face_area = np.asarray(face_area)
cv2.fillConvexPoly(img[y:y + wh, x:x + wh, :], face_area - (x, y), (0, 0, 0), lineType=0)
face_preplace = img[y:y + wh, x:x + wh, :]
face_balck = np.where(np.all(face_preplace == [0, 0, 0], axis=-1))
for black_x, black_y in zip(face_balck[0], face_balck[1]):
face_preplace[black_x, black_y, :] = img_new[black_x+y, black_y+x, :]
img[y:y + wh, x:x + wh, :] = face_preplace
# Create a black image
# print('rect[1]:', rect.height)
# print('rect[1][0]-rect[0][0]:', rect[1][0]-rect[0][0])
# print('rect[1][1]-rect[0][1]:', rect[1][1]-rect[0][1])
# img = np.zeros((1024, 1024, 3), np.uint8)
# pts = np.array(shape, np.int32) # 每个点都是(x, y)
# pts = pts.reshape((-1, 1, 2))
# cv2.polylines(img, [pts], True, (0, 255, 255))
cv2.imshow('img2', img)
cv2.waitKey()
|
[
"18622819565"
] |
18622819565
|
d620a4cbac5da8341002a54b62cf0bc1168fa51b
|
c09ee8b57cd46a7fa5bc62fc09af74dbfde515b6
|
/src/generator/scripts/creator.py
|
3cb2776786e775899373550f1b37ed8c53cad3d5
|
[] |
no_license
|
zemiret/willpowercode
|
00816808e221ef3bc56add657e10b18bbe8247ae
|
f04cf54b78c9d63c92660b87777d0820a8c62583
|
refs/heads/master
| 2020-03-27T05:14:04.086630
| 2019-07-02T08:46:10
| 2019-07-02T08:46:10
| 146,003,296
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 587
|
py
|
from utils.common import tmp_file_path
def create_script(path, *args, **kwargs):
"""
Uses path as a blueprint to interpolate the script using python3 string 'format' method.
Returns the path to the newly created script.
:param path: string path to original script
:return: str: string path to generated script
"""
script_file = open(path, 'r')
content = script_file.read()
content = content.format(*args, **kwargs)
out_file_path = tmp_file_path()
out_file = open(out_file_path, 'w+')
out_file.write(content)
return out_file_path
|
[
"antos.mleczko@gmail.com"
] |
antos.mleczko@gmail.com
|
96e97d2b437e68f70ef4b8b15b58df4d30711200
|
d168927a848a55db51897ccfafe6386330673f1e
|
/instance/tika/conf.py
|
4a801ba1f8dbdacf8532e4915da54344135b1962
|
[] |
no_license
|
fish2000/tessar
|
5b63245ff529d2ae7adca5ce322af571c202334e
|
f750658e0b1539285fae26bdbab8bc654d3dcbe9
|
refs/heads/master
| 2021-01-10T11:29:14.154593
| 2016-01-19T17:39:14
| 2016-01-19T17:39:14
| 49,967,922
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,182
|
py
|
from django.conf import settings
from appconf import AppConf
from os import listdir
from os.path import join
HTML_THEMES = filter(lambda f: f.endswith('css'), listdir(join(
settings.PROJECT_ROOT,
'var', 'web', 'static', 'css', 'prism-themes')))
class TikaAppConf(AppConf):
# What the Tika app specifies as the character set
# whenever we need to -- usually, this is necessary
# for HTTP responses, either incoming or outgoing
CHARSET = 'UTF-8'
# Defaults for connecting to the local Tika service
# ... BASE_HOSTNAME is inferred at runtime below
BASE_HOSTNAME = 'localhost'
BASE_PROTOCOL = 'http'
BASE_PORT = 9998
SIMPLE_PORT = 8080
# MIME override map -- for supplementing python-magic,
# and for custom internal use (e.g. epub generation)
MIME_OVERRIDES = {
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'epub': 'application/epub+zip',
'opf': 'application/oebps-package+xml',
'ncx': 'application/x-dtbncx+xml',
}
# Default theme for HTML syntax highligter
HTML_THEME = 'coy.css'
# Namespace UUID for Epub creation
NAMESPACE_UUID = '18e3e2ca-04bd-46c4-845d-cc3a3f5ac364'
DEFAULT_BOOK_ID = 'BookId'
# Default document language code
DEFAULT_LANGUAGE = 'fr'
# Dispatch UID for document-ready signal
# (as sent by TikaDocumentFields)
DOCUMENT_READY_DISPATCH_UID = 'tika-document-ready'
class Meta:
prefix = 'tika'
def configure_base_hostname(self, value):
""" Infer the local hostname """
if value is not None:
return value
import platform
local_hostname = platform.node().lower()
return local_hostname.endswith('local') and 'localhost' \
or local_hostname
def configure_html_theme(self, value):
""" Pick an HTML theme from those installed """
import random
return value in HTML_THEMES and value \
or random.choice(HTML_THEMES)
def configure_namespace_uuid(self, value):
import uuid
return uuid.UUID(value)
|
[
"fish2000@gmail.com"
] |
fish2000@gmail.com
|
058a6c728d72285bb1e6ad85a56ed83d29c3e00f
|
7ce761781e7f5b57b2469adce459a71b4758694d
|
/env/lib/python2.7/site-packages/psclient/config.py
|
29b79c68d24b87d79139cf2a73efdcbe7dd9159c
|
[] |
no_license
|
hophamtenquang/RecSys
|
c4fa18d1ba262670a284b2fba2ca97b882ef0f4c
|
535472844a046cadd9230302da647a54afff95e8
|
refs/heads/master
| 2021-01-19T17:00:32.924064
| 2017-08-30T10:31:32
| 2017-08-30T10:31:32
| 101,031,687
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,238
|
py
|
import sys
import os
import os.path
from ConfigParser import ConfigParser, NoOptionError
import logging
_logger = logging.getLogger(__name__)
# Maps parameters to environment variable names
env_var_map = {
'manager_endpoint': 'PS_MANAGER_ENDPOINT',
'query_endpoint': 'PS_QUERY_ENDPOINT',
'admin_key': 'PS_ADMIN_KEY',
'api_key': 'PS_API_KEY',
'verify_certificate': 'PS_VERIFY_CERTIFICATE',
'query_timeout': 'PS_QUERY_TIMEOUT',
}
def _getter(section, option, type):
def getter(self):
try:
if type == 'str':
return self._cp.get(section, option)
elif type == 'int':
return self._cp.getint(section, option)
elif type == 'float':
return self._cp.getfloat(section, option)
elif type == 'bool':
return self._cp.getboolean(section, option)
else:
raise ValueError("Unrecognized type: %s" % (type,))
except NoOptionError:
return None
return getter
def _setter(section, option):
def setter(self, value):
return self._cp.set(section, option, value)
return setter
def _option_property(section, option, type, doc):
if type not in ('str', 'int', 'float', 'bool'):
raise ValueError("Unexpected 'type': %r" % type)
return property(
_getter(section, option, type),
_setter(section, option),
doc=doc)
class Config(object):
"""A wrapper around a ConfigParser that knows the parameters and types it
expects."""
_section = 'Predictive Service'
manager_endpoint = _option_property(_section, 'manager_endpoint', 'str',
"The manager endpoint URL")
query_endpoint = _option_property(_section, 'query_endpoint', 'str',
"The manager endpoint URL")
verify_certificate = _option_property(_section,
'verify_certificate','bool',
"The manager endpoint URL")
api_key = _option_property(_section, 'api_key', 'str',
"The API key, which only has access to query and feedback and limited"
" operations on the manager.")
admin_key = _option_property(_section, 'admin_key', 'str',
"The admin key, which has full access to everything.")
query_timeout = _option_property(_section, 'query_timeout', 'float',
"The timeout for query operations in seconds.")
def __init__(self, cp=None):
if cp:
self._cp = cp
else:
self._cp = ConfigParser()
self._cp.add_section(self._section)
@classmethod
def load(cls, name='psclient', config_file=None, raise_if_missing=True):
"""Given a config_file, loads the file and returns a config parser. It
will also look in config_file/psclient.conf.
config_file can also be an open file handle.
If config_file is not specified, then the following file locations are
searched.
* psclient.conf in the current working directory.
* psclient.conf in the directory of the script.
* $XDG_CONFIG_HOME/psclient.conf
* $XDG_CONFIG_DIRS/psclient.conf
* ~/.psclient.conf
"""
config_filename = name+'.conf'
def path_gen():
"""Yields up potential paths for the config file."""
if config_file is not None:
# If this is a file, then we're done.
if hasattr(config_file, 'read'):
yield config_file
return
# Otherwise, we need to look at both config_file and
# config_file/psclient.conf
else:
yield config_file
yield os.path.join(config_file, config_filename)
return
yield os.path.join(os.getcwd(), config_filename)
yield os.path.join(sys.path[0], config_filename)
try:
home = os.path.expanduser('~')
except:
raise ValueError("$HOME is not set.")
yield os.path.join(
os.environ.get(
'XDG_CONFIG_HOME',
os.path.join(home, '.local', 'share')),
config_filename)
yield os.path.join(
os.environ.get(
'XDG_CONFIG_DIRS',
os.path.join(os.sep, 'etc', 'xdg')),
config_filename)
yield os.path.join(
home,
'.'+config_filename)
cp = ConfigParser()
searched = []
for path in path_gen():
_logger.info("Trying %r", path)
if hasattr(path, 'read'):
_logger.info("Loading configuration from file object")
cp.readfp(path)
break
if os.path.isfile(path):
_logger.info("Loading configuration from %r", path)
cp.read(path)
break
searched.append(path)
else:
if raise_if_missing:
raise ValueError("Cannot find config file. Tried {}".format(
", ".join([repr(s) for s in searched])))
else:
return None
return cls(cp)
def write(self, fileobject):
self._cp.write(fileobject)
def generate_config(
config_file,
predictive_service_client=None,
**kwargs
):
"""Given a configuration, generate a config file at config_file.
Recommended values for config_file:
* psclient.conf (in current working directory)
* psclient.conf (in sys.argv[0])
* $XDG_HOME_DIR/psclient.conf. ($XDG_HOME_DIR is ~/.local/share if
missing)
See psclient.connect() for where it will look for config files by default.
Parameters
----------
config_file : str or file
The file the config will be written to.
predictive_service_client : PredictiveService, optional
This will be used to fill in missing values.
**kwargs : dict
The keys of the dict are configuration parameters.
* If the key is missing, it will be loaded from the
predictive_service_client, if any. If missing, it will not be added.
* If the value are specified, these will be used, overriding whatever
is in predictive_service_client.
* If the value is None, then the key will not be used.
The keys are:
* manager_endpoint
* query_endpoint
* admin_key
* api_key
* verify_certificate
* query_timeout
Please refer to psclient.connect() for the meaning of these
parameters.
"""
cfg = Config()
for k in (
'manager_endpoint',
'query_endpoint',
'verify_certificate',
'admin_key',
'api_key',
'query_timeout',
):
v = None
if k not in kwargs:
if predictive_service_client:
v = getattr(predictive_service_client, '_'+k)
else:
v = kwargs[k]
if v is not None:
setattr(cfg, k, v)
if hasattr(config_file, 'write'):
cfg.write(config_file)
else:
with open(os.path.expanduser(config_file), 'w') as fileobject:
cfg.write(fileobject)
def _hide_key(param, value):
"""Used to hide keys in the logging."""
if not param.endswith('_key'):
return value
if len(value) > 16:
return value[:3]+'...'+value[-3:]
else:
return '********'
def load_config(params, name=None, config_file=None):
"""Loads configuration from parameters, environment variables, and a
config file. This supports the connect() methods.
Special note: If the params include 'manager_endpoint' and
'query_endpoint', then it will not return query endpoints found after the
level that the manager endpoint was found. IE, if you specify
manager_endpoint directly but query_endpoint in a config file, it will not
load the query endpoint from the file and instead return None.
Parameters
----------
params : dict
A dict where the keys are the configuration parameters you want to get
back and the values are the specified values or None.
name : str or None
The name specified, or None
config_file : str or None
The config_file specified, or None.
Returns
-------
dict
This is the params dict modified with the values set if they were
found.
"""
# This is the value of query_endpoint if manager_endpoint is found
qe_sentinel = object()
def insert_qe_sentinel():
if 'manager_endpoint' in params and 'query_endpoint' in params \
and params['manager_endpoint'] is not None \
and params['query_endpoint'] is None:
params['query_endpoint'] = qe_sentinel
# Load the name if it is not specified.
if name is not None:
_logger.debug("name was specified directly as %r", name)
else:
try:
name = os.environ['PS_NAME']
_logger.info("Using $PS_NAME=%r for name", name)
except KeyError:
name = 'psclient'
_logger.info("Defaulting name to %r", name)
for k,v in params.items():
if v is not None:
_logger.debug("%s was directly specified as %r",
k, _hide_key(k,v))
insert_qe_sentinel()
def missing():
"""Returns a list of the missing variables we need."""
return [k
for k,v in params.items()
if v is None]
def load_from_config(config):
if config is None: return
for k, v in params.items():
if v is None and getattr(config, k) is not None:
params[k] = getattr(config, k)
_logger.debug("%s set to %r from config file",
k, _hide_key(k, params[k]))
if config_file is None:
try:
config_file = os.environ['PS_CONFIG']
_logger.debug("Using $PS_CONFIG=%r for config_file", config_file)
except KeyError:
_logger.debug("config_file and $PS_CONFIG not specified")
insert_qe_sentinel()
if missing() and config_file:
_logger.debug("config_file was specified as %r. Loading from that.",
config_file)
load_from_config(Config.load(name=name, config_file=config_file))
insert_qe_sentinel()
if missing():
_logger.debug("Examining environment variables")
for k, v in params.items():
if v is None:
env_var = env_var_map[k]
try:
params[k] = os.environ[env_var]
_logger.debug("Using $%s=%r for %s",
env_var, _hide_key(k, params[k]), k)
except KeyError:
_logger.debug("$%s not specified.", env_var)
insert_qe_sentinel()
if not config_file and missing():
load_from_config(Config.load(name=name, raise_if_missing=False))
insert_qe_sentinel()
# Replace the sentinel with None for query_endpoint
if 'query_endpoint' in params and params['query_endpoint'] is qe_sentinel:
params['query_endpoint'] = None
# TODO: The requests module allows the verify parameter to be a string which
# would be the directory containing the allowed SSL certificate. We should
# probably support this.
if 'verify_certificate' in params:
if isinstance(params['verify_certificate'], (unicode, str)):
params['verify_certificate'] = (
params['verify_certificate'].lower() in (
'y', 'yes', 'true', 't', '1', 'verify', 'enable', 'enabled',
))
elif params['verify_certificate'] is None:
# Defaults to True
params['verify_certificate'] = True
else:
params['verify_certificate'] = bool(params['verify_certificate'])
if 'query_timeout' in params and params['query_timeout'] is not None:
params['query_timeout'] = float(params['query_timeout'])
return params
|
[
"hophamtenquang@gmail.com"
] |
hophamtenquang@gmail.com
|
b10e6de4e4f2b96f2c04acb970661cf77249db04
|
34bc0a3cdcdc2e2da6da43451a1e739c52521250
|
/Dataset/pdf2.py
|
bb84fb3bf403d875c7e328922dd6c126d9e3505f
|
[] |
no_license
|
sreenathmadyastha/ExploringKafka
|
a63cd5672f08dc69950954186186c44f799eeb8c
|
32c750b5d357d4d5d58001ec99d336ac808c0a2c
|
refs/heads/master
| 2021-09-03T13:41:52.289577
| 2018-01-09T13:34:23
| 2018-01-09T13:34:23
| 116,818,836
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 334
|
py
|
from PyPDF2 import PdfFileReader
def getTextPDF (pdfFileName, password=''):
pdf_file = open(pdfFileName, 'rb')
read_pdf = PdfFileReader(pdf_file)
if password != '':
read_pdf.decrypt(password)
text = []
for i in range(-1,read_pdf.getNumPages()-1):
text.append(read_pdf.getPage(i).extractText())
return '\n'.join(text)
|
[
"smadyastha@localhost.localdomain"
] |
smadyastha@localhost.localdomain
|
d69af28215dff44d575bf284d78c0726e9552ddb
|
96915863d429d59b24a954c927df337c9d6b86aa
|
/coins.py
|
31790e8b0b8015dac54cfb1ee3e8325269fb53b9
|
[] |
no_license
|
knackojacko/coding-interview-problems
|
c8680f26d602cca9464fc00b16915743e7022bb2
|
88e31002a118754699ca30e239b9e43c6d55f69d
|
refs/heads/master
| 2021-06-02T11:27:16.358075
| 2016-06-14T07:21:50
| 2016-06-14T07:21:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 526
|
py
|
#Given an in nite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent), write code to calculate the number of ways of representing n cents.
coins = (1,5,10,25)
def getChange(amount, output=""):
suitable = [c for c in coins if c <= amount]
n = len(suitable)
if n ==0:
print(output)
else:
#all suitable
#for coin in suitable:
# getChange(amount-coin, output+str(coin)+" ")
#optimal
coin = suitable[-1]
getChange(amount-coin, output+str(coin)+" ")
getChange(6)
|
[
"k.kliavin@gmail.com"
] |
k.kliavin@gmail.com
|
5bbe770a02764292c5309ea8a9de0ed3abc8a37d
|
4e06cb82884cac7498e804ed3749e4f2391fcdfe
|
/examples/classes.py
|
1d7dc4b6b672e91d30aecc14ea2c13772f7c3855
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
brazil-data-cube/lccs.py
|
6acd6baa8792ea12f5ce3030e777f06a35591c68
|
2f9b2bccf90ecadb76d56e11293108fdd19ee21b
|
refs/heads/master
| 2022-10-16T02:44:32.179529
| 2022-02-07T12:28:40
| 2022-02-07T12:28:40
| 223,473,870
| 6
| 5
|
MIT
| 2022-09-29T19:37:16
| 2019-11-22T19:37:25
|
Python
|
UTF-8
|
Python
| false
| false
| 740
|
py
|
#
# This file is part of Python Client Library for the LCCS-WS.
# Copyright (C) 2020 INPE.
#
# Python Client Library for the LCCS-WS is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""LCCS Python Client examples."""
from lccs import LCCS
# Change to the LCCS-WS URL you want to use.
service = LCCS("https://brazildatacube.dpi.inpe.br/lccs/", access_token='change-me', language='en')
# Get a specific classification system
# Make sure the classification system is available in service
classification_system = service.classification_system('prodes-1.0')
prodes_desflorestamento = classification_system.classes('1')
print(prodes_desflorestamento.title)
|
[
"fabiana_zioti@hotmail.com"
] |
fabiana_zioti@hotmail.com
|
b8a7257f2ebe4a4ceb16eab2a567b6c2a0d4a17d
|
c790223df1e9adb18584af39fa0898188cddad9b
|
/places/urls.py
|
aee3ad667841d3513500c43bcb5540a1cd7e6394
|
[] |
no_license
|
Jash271/Django-Project-travel-
|
b3760195a01472f199736d000c07e3926b8bb23c
|
10b66807bf05f4b73c9f82f30972cb1f13ce4778
|
refs/heads/master
| 2022-01-25T23:09:22.853369
| 2019-07-19T16:46:13
| 2019-07-19T16:46:13
| 197,806,252
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 259
|
py
|
from django.urls import include, path
from . import views
urlpatterns = [
path("place",views.place,name='place'),
path("destination",views.det,name='det'),
path("user",views.register,name='register'),
path("book",views.book,name='book'),
]
|
[
"shahjash271@gmail.com"
] |
shahjash271@gmail.com
|
18f8fb86dfab857e7db5e57f28bcb07612ee5316
|
0747c4a49150f82196ddcb873eac930b5ab4c96b
|
/unit5_assignment_01.py
|
4e1cac345b1c52f83f9065c457443c9de8c57aab
|
[] |
no_license
|
umesh-thatikonda/MissionRnD_python-course
|
8a64af855f44230f5152b98802c77bb970df37fa
|
1f7c46119ccd3aa7f43456b5b43576182f0bab0f
|
refs/heads/master
| 2022-01-08T12:08:12.613980
| 2022-01-06T19:21:18
| 2022-01-06T19:21:18
| 148,032,577
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,438
|
py
|
__author__ = 'Kalyan'
notes = '''
Though it might appear as if the given tests should be able to catch all logical bugs
in de_dup_and_sort, that is not the
case as the code below shows.
So be clear that some blackbox tests alone are no substitute for
reasoning/taking care of the correctness yourself.
Now add a test that fails with the given code. You can assume that inputs are of right type.
'''
def de_dup_and_sort(input):
"""
Given an input list of strings, return a list in which the duplicates are
removed and the items are sorted.
"""
input = set(input)
input = list(input)
input.sort()
return input
# add an test input that fails with above code and then fix the above code.
def test_de_dup_and_sort_student():
pass
def test_de_dup_and_sort():
assert ["a", "b"] == de_dup_and_sort(["b", "a", "b", "a"])
assert ["a"] == de_dup_and_sort(["a", "a", "a"])
assert [] == de_dup_and_sort([])
assert ["a", "b"] == de_dup_and_sort(["a", "b"])
assert ["a", "b"] == de_dup_and_sort(["a", "b"]*10)
# assert ["A","B","a","aAasdh"] == de_dup_and_sort(["a","A","A","B","aAasdh"])
# this will run only on our runs and will be skipped on your computers.
# DO NOT EDIT
import pytest
def test_de_dup_and_sort_server():
servertests = pytest.importorskip("unit5_server_tests")
servertests.test_de_dup_and_sort(de_dup_and_sort)
|
[
"noreply@github.com"
] |
umesh-thatikonda.noreply@github.com
|
4869969a8b48a540a0b3c6e72c024e050010abf1
|
9facf141ab7c5877b84511438a540880fba78dde
|
/2-logistic-liblinear.py
|
96708c330f4d626dc09aba1c4b30a64e17f5db50
|
[
"MIT"
] |
permissive
|
Sothy2018/sothy_2019
|
ab6403cfb211d795ebe12ed060f15635b44fe7f4
|
49905703fa2c31702a99e0da2dcd71f7da151e62
|
refs/heads/master
| 2020-11-27T07:46:06.183662
| 2019-12-21T01:58:23
| 2019-12-21T01:58:23
| 229,359,336
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,062
|
py
|
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
d_train = pd.read_csv("train-0.1m.csv")
d_test = pd.read_csv("test.csv")
d_train_test = d_train.append(d_test)
vars_categ = ["Month","DayofMonth","DayOfWeek","UniqueCarrier", "Origin", "Dest"]
vars_num = ["DepTime","Distance"]
def get_dummies(d, col):
dd = pd.get_dummies(d.ix[:, col])
dd.columns = [col + "_%s" % c for c in dd.columns]
return(dd)
%time X_train_test_categ = pd.concat([get_dummies(d_train_test, col) for col in vars_categ], axis = 1)
X_train_test = pd.concat([X_train_test_categ, d_train_test.ix[:,vars_num]], axis = 1)
y_train_test = np.where(d_train_test["dep_delayed_15min"]=="Y", 1, 0)
X_train = X_train_test[0:d_train.shape[0]]
y_train = y_train_test[0:d_train.shape[0]]
X_test = X_train_test[d_train.shape[0]:]
y_test = y_train_test[d_train.shape[0]:]
md = LogisticRegression(tol=0.00001, C=1000)
%time md.fit(X_train, y_train)
phat = md.predict_proba(X_test)[:,1]
metrics.roc_auc_score(y_test, phat)
|
[
"noreply@github.com"
] |
Sothy2018.noreply@github.com
|
ef88cca81e858ff25396a88215c409057d00958d
|
a1de861f5522052b23a293d0657698f951bbb1c2
|
/models/album.py
|
a709700a6a17041c95261b937cc3c7b022cb6004
|
[] |
no_license
|
JnnyRdng/music_collection
|
85932240405d6144f7bb99149071824678cc04d1
|
356ebeac2c927a1f86205eef4b95a90dcc7588cd
|
refs/heads/master
| 2022-12-03T01:11:55.160194
| 2020-08-04T14:34:43
| 2020-08-04T14:34:43
| 285,006,475
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 177
|
py
|
class Album:
def __init__(self, title, genre, artist=None, id=None):
self.title = title
self.genre = genre
self.artist = artist
self.id = id
|
[
"jonnyreading@gmail.com"
] |
jonnyreading@gmail.com
|
57f37f19ad326a3af0fe1151ccb68e4d5d2a0f1f
|
cfe6a89a4ed1cb6ed0a9eeb640c3ef0fd36cfd2e
|
/Examples/number_occur_substr_in_str.py
|
25ec0157eb6319db99a978d8daab707a733f2d6f
|
[] |
no_license
|
ylana-mogylova/Python
|
557083715f77ca722ece8be9a9dd339f6d8a4064
|
a1e2106c0c230528342121ca06a7822b0ff4f008
|
refs/heads/master
| 2021-01-19T09:34:57.223445
| 2018-04-20T14:51:06
| 2018-04-20T14:51:06
| 87,765,964
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 710
|
py
|
"""
Write a function to count how many times the substring appears in the larger String.
"""
large_string = "abcpotqwrpot"
substring = "pot"
def count_substr_occur(input_string, input_substring):
counter = 0
start_index = 0
flag = True
while flag:
find_index = input_string.find(input_substring, start_index)
if find_index == -1:
flag = False
else:
counter += 1
start_index = find_index + len(input_substring)
return counter
if __name__ == "__main__":
print("Substring %s appears %s number(s) in the string %s" % (
substring, count_substr_occur(large_string, substring), large_string))
|
[
"Uliana_Mogylova@epam.com"
] |
Uliana_Mogylova@epam.com
|
bbbc8e227676d9a52ed5800704f825c97dbe2369
|
397793669bc76f8ee1722e5ce00d9b2c3c216582
|
/PyHFS/src/constants.py
|
b2999032a68b8377951dd07a4836b681695e7715
|
[] |
no_license
|
ecurtin2/HF-Stability
|
c301f19fc6d9ed0bbb2909f38fb6b70cd6e23e12
|
84f01c95a8f0acbe01becbf379d891bea2178b84
|
refs/heads/master
| 2022-04-18T13:42:39.172025
| 2020-03-02T22:35:28
| 2020-03-02T22:35:28
| 62,247,162
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 83
|
py
|
""" Constants - Common parameters and physical constants
"""
SMALL_NUMBER = 1e-10
|
[
"ecurtin2@illinois.edu"
] |
ecurtin2@illinois.edu
|
aeb945d3edfed9d35c6e40743958b2cff05b6438
|
349f8e1d93a2b749f0dbab0e6a2912337d5dc8b4
|
/luffy/apps/course/page.py
|
89cd612307654671b29362325d1b74bfb3eaa8e4
|
[] |
no_license
|
zoyof/zyf
|
85e14cdda54a70598496f61a1879009db6196851
|
56047dddefe0eb1da7bf031e3970bde188812288
|
refs/heads/main
| 2023-08-20T12:01:08.776820
| 2021-10-15T11:59:17
| 2021-10-15T11:59:17
| 417,122,481
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 230
|
py
|
from rest_framework.pagination import PageNumberPagination
class CommonPageNumberPagination(PageNumberPagination):
page_size = 3
page_query_param = 'page'
page_size_query_param = 'size'
max_page_size = 5
|
[
"9781610+zoyoo@user.noreply.gitee.com"
] |
9781610+zoyoo@user.noreply.gitee.com
|
5fc1462ab79feb2e662b2ffe819ce1f064dd374c
|
95d9663521bbfbabc2583f89b1526016105c9ce1
|
/myweb/myweb1/migrations/0015_auto_20201027_1921.py
|
6bcab2312d516243417ae2e322ef3a6933ab90fa
|
[] |
no_license
|
msm123456/myweb1
|
675680d3466ff5ae34021376bd3a0a69dfa7ee7e
|
5f7baf067e3b95efd0edb74412913350e3ccc392
|
refs/heads/main
| 2023-01-04T03:56:12.813601
| 2020-10-29T21:49:01
| 2020-10-29T21:49:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 560
|
py
|
# Generated by Django 3.1.1 on 2020-10-27 15:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myweb1', '0014_auto_20201027_1900'),
]
operations = [
migrations.AddField(
model_name='resume',
name='cv',
field=models.FileField(null=True, upload_to='file/'),
),
migrations.AlterField(
model_name='my_about',
name='cv',
field=models.FileField(null=True, upload_to='file/'),
),
]
|
[
"mohammad1sadra1m@gmail.com"
] |
mohammad1sadra1m@gmail.com
|
6a6c07a1bba5afd922c7765f794cf13de5e72473
|
529987c6798f3d60f74d37f13e4857f9571e8170
|
/planning/withNationAndInternational.py
|
12ccdce2f3066a474938e7cf27bd8619673a67d7
|
[] |
no_license
|
weAreAllGod/AirPort1
|
be3e32372274103d2811ac332112c26f82cda1bd
|
a675face0918f5e30d2171051b1ad14f50090b79
|
refs/heads/master
| 2022-12-14T17:31:23.427369
| 2019-12-15T09:22:03
| 2019-12-15T09:22:03
| 226,262,534
| 0
| 0
| null | 2022-12-10T11:54:28
| 2019-12-06T06:35:10
|
Python
|
UTF-8
|
Python
| false
| false
| 11,031
|
py
|
import numpy as np
from pandas.plotting import register_matplotlib_converters
import matplotlib.pyplot as plt
register_matplotlib_converters()
from tools import funcForColumn
from tools.cplexFunc import cplexSoverMain,cplexForSecondPro
from tools.dataBase import myDataBase
import pandas as pd
import datetime
from tools import printResult
import time
def showFinalResult(mydata, finllGateSort, atimList, dtimList):
for ylabel, gate in enumerate(finllGateSort):
for plane in gate:
allSeconds = int((dtimList[plane] - atimList[plane]).total_seconds())
if allSeconds > 0:
plt.plot(pd.date_range(start=atimList[plane], end=dtimList[plane], periods=allSeconds),
[ylabel for i in range(allSeconds)], linewidth=3.5)
plt.text(atimList[plane], ylabel - 0.3, mydata["aflightno"].iloc[plane], fontsize=7)
else:
print("有错数据")
plt.plot(pd.date_range(start=dtimList[plane], end=atimList[plane], periods=np.abs(allSeconds)),
[ylabel for i in range(-allSeconds)], linewidth=3.5)
plt.text(atimList[plane], ylabel - 0.3, "wrongData", fontsize=7)
def showArraftFlight(mydata, atimList, dtimList):
for i in range(len(atimList)):
allSeconds = int((dtimList[i] - atimList[i]).total_seconds())
if allSeconds > 0:
plt.plot(pd.date_range(start=atimList[i], end=dtimList[i], periods=allSeconds),
[i for j in range(allSeconds)], linewidth=2)
plt.text(atimList[i], i, mydata["aflightno"].iloc[i], fontsize=4)
def getTypeOfPosition(x):
if x=="C":
return 0
elif(x=="D"):
return 1
elif(x=="E"):
return 2
elif(x=="F"):
return 3
else:
return print("在获取机位类型的时候出现了错误")
def getTypeOfNation(x,list):
if x in list:
return 1
else:
return 0
if __name__ == '__main__':
dataId = 0#0表示所有的数据,1表示国内的数据,2表示国际的数据
# 基础数据
dataBase = myDataBase()
# data = dataBase.getDataTwo()
initialData,alldata = dataBase.getDataThree()
data=alldata.iloc[:120,:]
##对国际和国内航班进行统计
# 航班号以这几个开头的为国际[QW,EU,CF,A6, UW,O3,QV,FD,UL]
# internationalPlantData = data.loc[data["nation"].isin(internationalTitle)]
# nationalPlantData = data.loc[~data["nation"].isin(internationalTitle)]
# 国内航班停机位27,国际航班停机位38
##除了互斥时间外,还考虑了近机位数量限制,机位的类型限制,类型包括C,D,E,F四种类型的停机位
##近机位C,D,E,F数量[23,34,6,2]
##国内近机位C,D,E,F数量[20,27,4,1]
##国际近机位C,D,E,F数量[3,7,2,1]
nationalType=[22, 28, 4, 1]
internationalType=[3,7,2,1]
nationalNumber=sum(nationalType)
internationalNumber =sum(internationalType)
allNumber = nationalNumber+internationalNumber
#进行去除过夜航班的操作,过夜航班不放在近机位
minAtime=data["atime"].min()
# mydata = data
mydata = data.loc[data["dtime"]<(pd.Timestamp(str(minAtime)[:10]+" 00:00:00")+pd.Timedelta("1 days"))]
mydata=mydata.sort_values(by=["atime"]).reset_index(drop=True)
bridgeNumber = allNumber
# 人工分配结果
# dataNearByHum=mydata.loc[mydata["gate"].isin(dataBase.gateInf()[0]["gateno"].to_list())]
dataNearByHum=[]
atimList = mydata["atime"].to_list()
dtimList = mydata["dtime"].to_list()
numberOfPlan=mydata["aflightno"].to_list()
typeOfplan=mydata["mdl"].apply(lambda x:x[-1:]).to_list()
nationOfPlan=mydata["nation"].to_list()
# 机位类型CDEF分别为0,1,2,3
numberOfTypeForPlan=mydata["mdl"].apply(lambda x:getTypeOfPosition(x[-1])).to_list()
# 机位的国际国内类型国内是0,国际是1
# typeOfNation=mydata["dflightno"].apply(lambda x:getTypeOfNation(x[:-4],internationalTitle)).to_list()
time1 = datetime.datetime.now()
listNodes=[]
lenAtimeList=len(atimList)
for i in range(lenAtimeList):
thisDtime=dtimList[i]
thisList=[]
for j in range(i+1,lenAtimeList):
if atimList[j]-thisDtime>pd.Timedelta("0 days 00:20:00"):
thisList.append(j)
thisNode=funcForColumn.treeNote(i,thisList)
listNodes.append(thisNode)
possibles = funcForColumn.searcher2(listNodes)##里面存放的是所有的变量
time2 = datetime.datetime.now()
print("变量构建时间",time2-time1)
# 每个变量所属的类型以及国际国内航班属性
typeOfParas=[]
nationOfParas=[]
for everyPara in possibles:
typeOfParas.append(max([numberOfTypeForPlan[i] for i in everyPara]))
nationOfParas.append(max([nationOfPlan[i] for i in everyPara]))
# 国际F只能停国际F的飞机,国际E可以停国际E和F,国际D可以停国际E,F,D.国际C,可以停C,D,E,F。
# 国内F可以停国内F和国际F,国内E可以停国内E,F和国际E,F,国内D可以停国内D,E,F以及国际的D,E,F,国内C,可以停国内C,D,E,F和国际的C,D,E,F
reMatrix = np.zeros((len(atimList) + 8, len(possibles)))
#国际F型停机位的限制
for i in range(reMatrix.shape[1]):
reMatrix[0,i]=1 if (typeOfParas[i]==3 and nationOfParas[i]==1) else 0
#国际E型停机位的限制
for i in range(reMatrix.shape[1]):
reMatrix[1,i]=1 if (nationOfParas[i]==1 and (typeOfParas[i] in [2,3])) else 0
#国际D型停机位的限制
for i in range(reMatrix.shape[1]):
reMatrix[2, i] = 1 if (nationOfParas[i]==1 and (typeOfParas[i] in [1,2,3]) ) else 0
#国际C型停机位的限制
reMatrix[3,:]=nationOfParas
#国内F型停机位
for i in range(reMatrix.shape[1]):
reMatrix[4,i]=1 if (typeOfParas[i]==3) else 0
# 国内E型停机位
for i in range(reMatrix.shape[1]):
reMatrix[5, i] = 1 if (typeOfParas[i] in [2,3]) else 0
# 国内D型停机位
for i in range(reMatrix.shape[1]):
reMatrix[6, i] = 1 if (typeOfParas[i] in [1,2, 3]) else 0
reMatrix[7,:]=[1 for i in range(reMatrix.shape[1])]
##b的设置要与上面对应
b = [1 for i in range(reMatrix.shape[0])]
# 对应上面的近机位约束,国际约束,F,E,D型约束,共5各约束
b[0] = internationalType[3]
b[1]=sum(internationalType[-2:])
b[2]=sum(internationalType[-3:])
b[3]=sum(internationalType)
b[4]=internationalType[3]+nationalType[3]
b[5] = sum(internationalType[-2:] + nationalType[-2:])
b[6] = sum(internationalType[-3:] + nationalType[-3:])
b[7] = sum(internationalType + nationalType)
# 符号
my_sense = ""
for i in range(len(b)):
my_sense += 'L'
for i in range(len(atimList)):
for j, possible in enumerate(possibles):
if i in possible:
reMatrix[i + 8, j] = 1
# 这里是靠桥的c
c = [len(i) for i in possibles]
# 这里是靠桥人数的c
passengers = []
for flt in mydata.iterrows():
passengers.append(flt[1]["apassenger"] + flt[1]["dpassenger"])
pc = []
for fa in possibles:
totalNumer = 0
for i in fa:
totalNumer += passengers[i]
pc.append(totalNumer)
time3=datetime.datetime.now()
print("模型构建时间", time3-time2)
my_prob = cplexSoverMain(c, reMatrix, b, "I",my_sense)
my_prob.write("../state/data/problem.lp")
my_prob.solution.write("../state/data/result.lp")
x = my_prob.solution.get_values()
print("Solution value = ", my_prob.solution.get_objective_value())
print('result: ')
result = [possibles[index] for index, value in enumerate(x) if value == 1]
time4 = datetime.datetime.now()
print("Model1求解时间:",time4-time3)
indexOfResult=[index for index, value in enumerate(x) if value == 1]
print(result)
typeOfResult = [typeOfParas[item] for item in indexOfResult]
nationOfResult = [nationOfParas[item] for item in indexOfResult]
resultInf = funcForColumn.anlysisForResult(result, typeOfResult, nationOfResult)
# hamiltonRouts,notBeChoosed=getHamiltonRouts(conflictTimeList)
nationalGateInf, internationalGateInf, allGate = dataBase.gateInf()
# 这里是第一种方法,用n个哈密尔顿通路进行拼接
gatePlanDict=funcForColumn.getPlanToGate(resultInf,internationalGateInf,nationalGateInf,atimList, dtimList)
#第二种贪心分配方法
time5 = datetime.datetime.now()
printResult.gateToPlan(gatePlanDict, atimList, dtimList, numberOfPlan, nationOfPlan, typeOfplan, allGate)
gatePlanDict2=funcForColumn.gateToPlanMethodsTwo(allGate,result,resultInf,atimList,dtimList,nationOfResult,typeOfResult)
time6 = datetime.datetime.now()
print("Model2求解时间:",time6-time5)
print("------------------------贪心法计算结果--------------------->")
printResult.gateToPlan(gatePlanDict2, atimList, dtimList, numberOfPlan, nationOfPlan, typeOfplan, allGate)
printResult.analysisOfPlans(result, data, dataNearByHum, resultInf, atimList)
dataBase.putDataIntoBrowerJson(gatePlanDict2,typeOfplan,nationOfPlan,atimList,dtimList,numberOfPlan,allGate)
"""放方案1
listNodes=[]
lenAtimeList=len(atimList)
for i in range(lenAtimeList):
thisDtime=dtimList[i]
thisList=[]
for j in range(i+1,lenAtimeList):
if atimList[j]-thisDtime>pd.Timedelta("0 days 00:20:00"):
thisList.append(j)
thisNode=treeNote(i,thisList)
listNodes.append(thisNode)
possibles=searcher.getPossibles(listNodes)
存为json方便后面处理
"""
"""方案二效率更高一些
possibles=searcher2(listNodes)
"""
'''cplex精确求解,经证实该方法在可接受时间内无法给出满意解。
paraForSecond,boundForSecond=getParasAndBoundForSecondPro(result, nationOfResult, typeOfResult, conflictTimeList)
my_colnames = []
for line in range(len(paraForSecond)):
for column in range(len(paraForSecond)):
if paraForSecond[line][column] == 1:
my_colnames.append("y%s,%s" % (line, column))
secondPro=cplexForSecondPro(paraForSecond,boundForSecond,result)
'''
'''
##如果分配的结果小于65说明所有的都可以靠桥,将result补满
if len(result) < bridgeNumber:
for i in range(bridgeNumber - len(result)):
result.append([])
###结果之间的不冲突关系,用链表的方式存储
dontConflictTimeList,conflictTimeList=funcForColumn.conflictForResult(atimList,dtimList,result)
print("不冲突矩阵关系如下:")
for gateNode in dontConflictTimeList:
print(gateNode.value, gateNode.noConflicts)
print("冲突矩阵关系如下:")
for gateNode in conflictTimeList:
print(gateNode.value, gateNode.noConflicts)
'''
|
[
"2422657868@qq.com"
] |
2422657868@qq.com
|
a20d6127d4b4f1875eaca1cfbecd5e9a7d5933d4
|
1c36e0143fa0409ee1fdd2e2b7cbccdfbe64d9f9
|
/run_sa.py
|
1db590656a6648299e5a0d59b27806ff2e2b9492
|
[] |
no_license
|
shailzajolly/FSDT
|
e14dc6d7d3c4fcfead5e031bf954873d86bc492c
|
8cbd16f5c16a773d84976a3a3e8e142c72aa0b97
|
refs/heads/main
| 2023-07-18T17:11:25.009848
| 2021-05-18T09:25:08
| 2021-05-18T09:25:08
| 318,878,160
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,261
|
py
|
import json
import math
from scoring_algos import SimulatedAnnealing, HillClimbing
from editor import RobertaEditor
from generator import T5FineTuner
from args import get_model_args, get_train_args, get_sa_args
if __name__=="__main__":
model_args = get_model_args()
trainer_args = get_train_args(model_args)
sa_args = get_sa_args()
editor = RobertaEditor()
editor.cuda()
generator = T5FineTuner(model_args)
generator.load_checkpoint(model_args.output_dir)
print("Model Built")
generator.cuda()
simulated_annealing = SimulatedAnnealing(editor, generator, sa_args.t_init, sa_args.C, sa_args.fluency_weight,
sa_args.semantic_weight, sa_args.max_steps)
data = json.load(open("4perc_mr_pseudoref_HC1.json", "r"))
batch_size = 32
num_batches = math.ceil(len(data)/float(batch_size))
sa_outputs = []
for i in range(num_batches):
batch_data = data[batch_size*i:batch_size*(i+1)]
input_batch = list(zip(*[[i["mr"], i["ref"]] for i in batch_data]))
sa_outputs_batch = simulated_annealing.run(input_batch)
print([(i, j) for i, j in zip(input_batch[1], sa_outputs_batch)])
break
sa_outputs += sa_outputs_batch
|
[
"shailzajolly@gmail.com"
] |
shailzajolly@gmail.com
|
6eedb1a9dbf4e238c159cf4ad5c092dcb9ac731e
|
a026a507d5a74130542bf550e89e75cd9c3872c0
|
/clienttest.py
|
72a7f992eeb5aecce2c156f5d9b749d4e42a6594
|
[] |
no_license
|
ikale1234/SpanishProject
|
a8ca5d60409d637a9c4c3cafca0a8438334fc75c
|
525a15332c2793f804ce66f0aa1f91a4c58bcf8d
|
refs/heads/master
| 2022-11-14T07:50:14.417561
| 2020-07-12T00:57:49
| 2020-07-12T00:57:49
| 256,859,052
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 363
|
py
|
import socket
import pickle
wordlist = []
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 2004 # The port used by the server
for i in range(7):
servsend = pickle.loads(data)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.send(servsend)
data = s.recv(1024)
print('Received', repr(data))
|
[
"55333848+ikale1234@users.noreply.github.com"
] |
55333848+ikale1234@users.noreply.github.com
|
8f66f829efd621c46b43529fe71d766f4a7c3eb1
|
28247646f0d2db413426575b080653312c9ee1e0
|
/lib/repo/fixed_plate_repository.py
|
0f5714fe414a7e757b0ee0ff56b351430c60713f
|
[
"MIT"
] |
permissive
|
daotranminh/SCM
|
227fbd2688af9fd0f3d342d127ad89865fd05f42
|
6681a49999cbd089032e25a441572e9a1f166897
|
refs/heads/master
| 2021-07-05T02:33:02.780222
| 2020-09-23T15:38:51
| 2020-09-23T15:38:51
| 177,731,158
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,656
|
py
|
import logging
from flask_sqlalchemy import sqlalchemy
from init import FixedPlate, config
from utilities.scm_enums import ErrorCodes
from utilities.scm_exceptions import ScmException
from utilities.scm_logger import ScmLogger
class FixedPlateRepository:
logger = ScmLogger(__name__)
def __init__(self, db):
self.db = db
def get_fixed_plate(self, fixed_plate_id):
return FixedPlate.query.filter(FixedPlate.id == fixed_plate_id).first()
def get_fixed_plate_of_product(self, product_id):
return FixedPlate.query.filter(FixedPlate.product_id == product_id).first()
def add_fixed_plate(self,
product_id,
original_plate_id,
name,
description,
unit_count,
unit_price):
try:
fixed_plate_rec = FixedPlate(product_id=product_id,
original_plate_id=original_plate_id,
name=name,
description=description,
unit_count=unit_count,
unit_price=unit_price)
self.db.session.add(fixed_plate_rec)
self.db.session.flush()
return fixed_plate_rec.id
except sqlalchemy.exc.SQLAlchemyError as ex:
message = 'Error: failed to add fixed_plate_rec. Details: %s' % (str(ex))
FixedPlateRepository.logger.error(message)
raise ScmException(ErrorCodes.ERROR_ADD_FIXED_PLATE_FAILED, message)
|
[
"daotranminh@gmail.com"
] |
daotranminh@gmail.com
|
aafe8538fb56fe40e8876788062acfd3e17ed347
|
f6f9d99498fa4aa011df48e6a52d040c012bd952
|
/talker.py
|
c901bafead8037d7b69dd18e288a31380df8aa91
|
[] |
no_license
|
prakash77000/18BEE206-tds-ros
|
bea2c43614b9a21d5b8f7e5483b300e237367636
|
b40482fad11e86a40ad53ce2a234c3744baddafd
|
refs/heads/main
| 2023-03-17T12:16:25.696703
| 2021-03-16T18:25:03
| 2021-03-16T18:25:03
| 348,449,480
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 486
|
py
|
import rospy
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = "Prakash Ganesan %s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
|
[
"noreply@github.com"
] |
prakash77000.noreply@github.com
|
a22e8c9a0cb521beabb90256d9701721345eb483
|
fa6bf80d7bde73a8c0c752da4428f00c6d61e6b1
|
/שיעור 11/play_center/z_doron.py
|
96dccefcae24902e88150b0f405893dc2b69cc42
|
[] |
no_license
|
avichai321/hackeru-lessons-part1-python
|
846afbe171beea577d49e9027c147ba749e3e2af
|
2bbeb4ea700194c5de51e65abd1f7242d8d75393
|
refs/heads/master
| 2023-06-01T02:08:58.711310
| 2021-07-01T14:25:46
| 2021-07-01T14:25:46
| 382,058,996
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,792
|
py
|
import random
point = 0
roll_result = []
bid = 5
plus = ""
def points(x, c):
global roll_result, point, plus
point += c
if x > 0:
if point - x >= 0:
point -= x
doron(x)
else:
roll_result = "You don't have points for that bid, pls enter another bid, your points is: " + str(point)
else:
plus = "+" + str(c)
def doron(y):
global roll_result, plus, bid
roll = range(1, 101)
roll_signs = []
signs = ["+", "-", "*", "/"]
roll_signs.append(random.sample(signs, 1))
while True:
roll_num = random.sample(roll, 2)
if roll_signs[0][0] != "/":
break
elif roll_signs[0][0] == "/" and (roll_num[0] % roll_num[1]) == 0:
break
roll_result = "{0} {2} {1} = ".format(str(roll_num[0]), str(roll_num[1]), roll_signs[0][0])
while True:
try:
result = input("""
point = {0} {3} rules
enter r
{1}
stop bid start increase bid decrease bid
enter e {2} enter s enter i enter d
""".format(point, roll_result, bid, plus))
if result == "e":
print(" good by")
return
elif result == "i" or result == "d" or result == "r":
roll_result = roll_result = "{0} + {1} = solve the quest or exit".format(str(roll_num[0]), str(roll_num[1]))
result = int(result)
break
except:
roll_result = "{0} + {1} = the result must be number".format(str(roll_num[0]), str(roll_num[1]))
if roll_signs[0][0] == "+":
if result == (roll_num[0] + roll_num[1]):
roll_result = "{0} + {1} = {2} pass".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+" + str(int(5 + 5 * (y / 5)))
points(0, int(5 + 5 * (y / 5)))
return
else:
roll_result = "{0} + {1} = {2} loose".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+0"
elif roll_signs[0][0] == "-":
if result == (roll_num[0] - roll_num[1]):
roll_result = "{0} - {1} = {2} pass".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+" + str(int(5 + 5 * (y / 5)))
points(0, int(5 + 5 * (y / 5)))
return
else:
roll_result = "{0} - {1} = {2} loose".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+0"
elif roll_signs[0][0] == "*":
if result == (roll_num[0] * roll_num[1]):
roll_result = "{0} * {1} = {2} pass".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+" + str(int(5 + 5 * (y / 5)))
points(0, int(5 + 5 * (y / 5)))
return
else:
roll_result = "{0} * {1} = {2} loose".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+0"
elif roll_signs[0][0] == "/":
if result == int(roll_num[0] / roll_num[1]):
roll_result = "{0} / {1} = {2} pass".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+" + str(int(5 + 5 * (y / 5)))
points(0, int(5 + 5 * (y / 5)))
return
else:
roll_result = "{0} / {1} = {2} loose".format(str(roll_num[0]), str(roll_num[1]), str(result))
plus = "+0"
def start():
global bid, roll_result, point, plus
z = input("""
point = {0} {3} rules
enter r
{1}
stop bid start increase bid decrease bid
enter e {2} enter s enter i enter d
""".format(point, roll_result, bid, plus))
plus = ""
if point != 0 and z == "s":
points(bid, 0)
elif z == "e":
print(" good by")
return
elif point == 0:
roll_result = """your point is 0, you can't play
exit the game, good by"""
return
elif z == "i":
bid += 5
roll_result = """ your bid increased to {0}
""".format(str(bid))
elif z == "d":
if bid != 5:
bid -= 5
roll_result = """ your bid decreased to {0}
""".format(str(bid))
elif z == "r":
roll_result = """ True result = {0} points
""".format(str(int(5 + 5 * (bid / 5))))
else:
plus = ""
roll_result = " enter valid choice"
start()
|
[
"77723644+avichai321@users.noreply.github.com"
] |
77723644+avichai321@users.noreply.github.com
|
5bbdc37b8f11be6ec2c17816c516722565a8d862
|
49a046cf5e6893ab6b1024390886e81e840f189b
|
/深度遍历和广度遍历/队列广度遍历.py
|
6f853f2c35d4db714cb3069d9d292e109c78dc2e
|
[] |
no_license
|
mayHYT/class
|
741d143b4c9fea23c5bd548b240559a7ec4feb90
|
f4366ef3d0cf6d7427d8da456f6e8e32e9a95a55
|
refs/heads/master
| 2020-06-12T16:36:37.762582
| 2019-09-02T08:50:50
| 2019-09-02T08:50:50
| 194,360,419
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 477
|
py
|
import os
from collections import deque
path=r"C:\Users\ehuamay\Desktop\pm_report_tags"
queue=deque([])
queue.append(path)
while len(queue) != 0:
path=queue.popleft()#取出拉出的值
filelist=os.listdir(path)#遍历路径
for filename in filelist:
filepath=os.path.join(path, filename)
if os.path.isdir(filepath):
print("文件夹",filename)
queue.append(filepath)
else:
print("文件", filename)
|
[
"13263440344@163.com"
] |
13263440344@163.com
|
70cfa5fe2344bb7ef8b7729d7548d2d417c8d526
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/K4aKGbfmzgyNNYEcM_10.py
|
87ec075891e2b03282cefb4e726b9b2e58de5b42
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213
| 2021-04-06T20:17:44
| 2021-04-06T20:17:44
| 355,318,759
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 178
|
py
|
def is_shape_possible(n, angles):
if n<2:
return False
for i in angles:
if i>180:
return False
if(sum(angles)<360 and n!=3):
return False
return True
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
8772388edd423c89541c448fad985b03e6ef0a17
|
531a5c09ed774dca6f85f3c96827ff4d9f8fc3be
|
/AutotestWebD/apps/ui_main/services/UITestcaseService.py
|
9b083ba126b0adce4f4f8ce39d39543150ba9654
|
[
"MIT"
] |
permissive
|
xiaochaom/sosotest
|
a98db41088d9411aa7d2723894f5bdc60bfbbd52
|
a3a5ce67c3dc302cf4bca906496ec6ee26b42c33
|
refs/heads/master
| 2020-07-06T09:31:39.598616
| 2020-06-23T07:51:00
| 2020-06-23T07:51:00
| 202,971,957
| 0
| 0
|
MIT
| 2019-08-18T07:12:52
| 2019-08-18T07:12:51
| null |
UTF-8
|
Python
| false
| false
| 692
|
py
|
import apps.common.func.InitDjango
from all_models_for_ui.models import Tb3UIGlobalText
from django.db import connection
from django.forms.models import model_to_dict
from apps.common.func.CommonFunc import *
from all_models.models.A0011_version_manage import TbVersionGlobalText
class UITestcaseService(object):
@staticmethod
def delText(id):
delResult = Tb3UIGlobalText.objects.get(id=id)
delResult.state = 0
delResult.save()
if __name__ == "__main__":
# print((HTTP_test_caseService.getTestCaseForIdToDict("23")))
# print(UserService.getUserByLoginname(UserService.getUsers()[0].loginname))
# HTTP_test_caseService.testCaseAdd("")
pass
|
[
"wangjilianglong@163.com"
] |
wangjilianglong@163.com
|
2c5e33a6addbcf37d6c9155289587b1df7e90102
|
877a829ad94799e20514792d2f797369a853ff85
|
/main.py
|
e0cb1ccc1e4d9607312f334dab36698274c8e9c9
|
[] |
no_license
|
egorb2008/redirect
|
8f7e30c071a9fdf7e0bdfa506f53c960690c8e78
|
8934ce34ecfe17c415f6d1fb8bfe95718e97ebfd
|
refs/heads/master
| 2023-08-24T00:15:33.593159
| 2021-11-02T15:54:09
| 2021-11-02T15:54:09
| 421,732,379
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,520
|
py
|
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit
class Calculator(QWidget):
def __init__(self):
super(Calculator, self).__init__()
self.setWindowTitle("Calculator")
self.hbox_line = QHBoxLayout()
self.hbox1 = QHBoxLayout()
self.hbox_res = QHBoxLayout()
self.hbox_clear = QHBoxLayout()
self.vbox = QVBoxLayout()
self.vbox.addLayout(self.hbox_line)
self.vbox.addLayout(self.hbox1)
self.vbox.addLayout(self.hbox_res)
self.vbox.addLayout(self.hbox_clear)
self.line = QLineEdit(self)
# задаём кнопки цифр
self.b_1 = QPushButton("1", self)
self.b_2 = QPushButton("2", self)
self.b_3 = QPushButton("3", self)
self.b_4 = QPushButton("4", self)
self.b_5 = QPushButton("5", self)
self.b_6 = QPushButton("6", self)
self.b_7 = QPushButton("7", self)
self.b_8 = QPushButton("8", self)
self.b_9 = QPushButton("9", self)
self.b_0 = QPushButton("0", self)
# задаём кнопки операций
self.b_plus = QPushButton("+", self)
# self.b_plus.setStyleSheet('background: rgb(32,178,170);')
self.b_minus = QPushButton("-", self)
# self.b_minus.setStyleSheet('background: rgb(32,178,170);')
self.b_divide = QPushButton("/", self)
# self.b_divide.setStyleSheet('background: rgb(32,178,170);')
self.b_multiply = QPushButton("*", self)
# self.b_multiply.setStyleSheet('background: rgb(32,178,170);')
self.b_res = QPushButton("=", self)
self.clear= QPushButton("Очистить поле ввода", self)
self.clear.setStyleSheet('background: rgb(139,0,0);')
self.hbox_line.addWidget(self.line)
self.hbox1.addWidget(self.b_1)
self.hbox1.addWidget(self.b_2)
self.hbox1.addWidget(self.b_3)
self.hbox1.addWidget(self.b_4)
self.hbox1.addWidget(self.b_5)
self.hbox1.addWidget(self.b_6)
self.hbox1.addWidget(self.b_7)
self.hbox1.addWidget(self.b_8)
self.hbox1.addWidget(self.b_9)
self.hbox1.addWidget(self.b_0)
self.hbox1.addWidget(self.b_plus)
self.hbox1.addWidget(self.b_minus)
self.hbox1.addWidget(self.b_divide)
self.hbox1.addWidget(self.b_multiply)
self.hbox_res.addWidget(self.b_res)
self.hbox_clear.addWidget(self.clear)
self.setLayout(self.vbox)
self.b_1.clicked.connect(lambda: self.addText("1"))
self.b_2.clicked.connect(lambda: self.addText("2"))
self.b_3.clicked.connect(lambda: self.addText("3"))
self.b_4.clicked.connect(lambda: self.addText("4"))
self.b_5.clicked.connect(lambda: self.addText("5"))
self.b_6.clicked.connect(lambda: self.addText("6"))
self.b_7.clicked.connect(lambda: self.addText("7"))
self.b_8.clicked.connect(lambda: self.addText("8"))
self.b_9.clicked.connect(lambda: self.addText("9"))
self.b_0.clicked.connect(lambda: self.addText("0"))
self.b_plus.clicked.connect(lambda: self.operation("+"))
self.b_minus.clicked.connect(lambda: self.operation("-"))
self.b_divide.clicked.connect(lambda: self.operation("/"))
self.b_multiply.clicked.connect(lambda: self.operation("*"))
self.b_res.clicked.connect(self.result)
self.clear.clicked.connect(self.clearWidget)
def addText(self, param):
line = self.line.text()
self.line.setText(line + param)
def operation(self, param):
self.num1 = self.line.text()
self.line.setText("")
self.op = param
def result(self):
self.num2 = self.line.text()
if self.op == "+":
self.line.setText(str(int(self.num1) + int(self.num2)))
if self.op == "-":
self.line.setText(str(int(self.num1) - int(self.num2)))
if self.op == "*":
self.line.setText(str(int(self.num1) * int(self.num2)))
if self.op == "/":
if int(self.num2) == 0:
self.line.setText(str("На ноль делить нельзя."))
else:
self.line.setText(str(int(self.num1) / int(self.num2)))
def clearWidget(self):
self.line.setText("")
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Calculator()
win.show()
sys.exit(app.exec_())
|
[
"efom2006@icloud.com"
] |
efom2006@icloud.com
|
d36437973e9599bfca75bed759a61a37395f00e9
|
2048bd273b2df72cc15afe982767d5196e2ae91f
|
/backend/triplannet/travel/models.py
|
273d0225993541c2c261533f43d0b822644ce366
|
[] |
no_license
|
dreamsh19/swpp2019-team6
|
66b4d1dae7fb2c9c02e27093434c0752841f7f82
|
7dbc5ef48edefff38d04a8f1d9edfbf56a83c5a4
|
refs/heads/master
| 2022-11-28T23:48:52.114066
| 2019-12-17T14:42:04
| 2019-12-17T14:42:04
| 292,757,776
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,463
|
py
|
from django.db import models
from django.contrib.auth import get_user_model
from django.conf import settings
from django_mysql.models import ListCharField, ListTextField
import os
User = get_user_model()
def travelCommit_directory_path(instance, filename):
return 'travelCommit/{}/{}'.format(instance.id, filename)
class Travel(models.Model):
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name = 'author_of_Travel',
)
collaborators = models.ManyToManyField(
User,
blank=True,
related_name = 'collaborator_of_Travel',
)
head = models.ForeignKey(
'travel.TravelCommit',
on_delete = models.SET_NULL,
related_name = 'head_of_travel',
null = True,
)
# fork_parent == None : is_forked - False,
# fork_parent != None : is_forked - True,
fork_parent = models.ForeignKey(
"self",
on_delete=models.SET_NULL,
null=True,
default = None,
)
register_time =models.DateTimeField(auto_now_add=True)
last_modified_time = models.DateTimeField(auto_now=True)
is_public = models.BooleanField(default=True)
allow_comments = models.BooleanField(default=True)
likes = models.ManyToManyField(
User,
related_name = 'like_of_Travel',
blank=True
)
views = models.ManyToManyField(
User,
related_name = 'views_of_Travel',
blank=True
)
class Meta:
ordering = ['-last_modified_time',]
class Tag(models.Model):
word = models.CharField(max_length=50, primary_key=True)
class temp(models.Model):
block = ListTextField(base_field=models.IntegerField(), size=5)
vector = ListTextField(base_field=models.IntegerField(), size=5)
class TravelCommit(models.Model):
title = models.CharField(max_length=100)
summary = models.TextField(blank=True)
description = models.TextField(blank=True)
start_date = models.DateField()
end_date = models.DateField()
block_dist = ListTextField(base_field=models.IntegerField(), size=5, default=[1])
travel_embed_vector = ListTextField(base_field=models.IntegerField(), size=512, default=[1])
days = models.ManyToManyField(
'travel.TravelDay',
through = 'TravelDayList'
)
register_time = models.DateTimeField(auto_now_add=True)
travel = models.ForeignKey(
Travel,
on_delete = models.CASCADE,
related_name = 'travelCommits',
null=True
)
author = models.ForeignKey(
User,
on_delete = models.CASCADE,
related_name = 'author_of_TravelCommit',
# collaborators only
)
photo = models.ImageField(
upload_to=travelCommit_directory_path,blank=True, null=True
)
# Override delete
def delete(self, *args, **kargs):
os.remove(os.path.join(settings.MEDIA_ROOT, self.photo.path))
super(TravelCommit, self).delete(*args, **kargs)
tags= models.ManyToManyField(
Tag,
related_name ='travel_tags',
)
class TravelDay(models.Model):
title = models.CharField(max_length=100,blank=True)
blocks = models.ManyToManyField(
'travel.TravelBlock',
through = 'TravelBlockList',
)
day = models.DateField()
parent_day = models.ForeignKey(
"self",
on_delete = models.SET_NULL,
related_name = 'child_day',
null = True,
default = None,
)
modified = models.BooleanField(default=True)
class TravelBlock(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
time = models.TimeField(null=True, blank=True)
start_location = models.TextField()
end_location = models.TextField(null=True, blank=True)
block_type = models.CharField(
max_length=3,
choices=[
('CUS','Custom'),
('ACT', 'Activity'),
('ACM', 'Accomodation'),
('TRN','Transportation'),
('RST','Restaurant')
]
)
parent_block = models.ForeignKey(
"self",
on_delete = models.SET_NULL,
related_name = 'child_block',
null = True,
default = None,
)
modified = models.BooleanField(default=True)
class TravelDayList(models.Model):
TravelCommit = models.ForeignKey(
TravelCommit,
on_delete = models.CASCADE,
)
TravelDay = models.ForeignKey(
TravelDay,
on_delete = models.CASCADE,
)
index = models.IntegerField()
class Meta:
ordering = ['TravelCommit','TravelDay','index',]
unique_together = ['TravelCommit','TravelDay','index']
class TravelBlockList(models.Model):
TravelDay = models.ForeignKey(
TravelDay,
on_delete = models.CASCADE,
)
TravelBlock = models.ForeignKey(
TravelBlock,
on_delete = models.CASCADE,
)
index = models.IntegerField()
class Meta:
ordering = ['TravelDay','TravelBlock','index',]
unique_together = ['TravelDay','TravelBlock','index']
class Comment(models.Model):
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name = 'comments',
)
travel = models.ForeignKey(
Travel,
on_delete=models.CASCADE,
related_name = 'comments'
)
content = models.TextField()
register_time =models.DateTimeField(auto_now_add=True)
|
[
"noreply@github.com"
] |
dreamsh19.noreply@github.com
|
608670999a50bc59acccb8183f2f5722cae41e98
|
ad8d49c2b6685457c617207f0f453a19e1cf2798
|
/tier_three/migrations/0002_auto_20170720_0957.py
|
792bbdca5ce41d2448d44898ecbe6ee1c70de5e6
|
[] |
no_license
|
nikolai0045/buffalo-bank-backend
|
529b241c02e51309a6ed142e933d0c1b1ac465ee
|
4db895dfb1052ae38c1bb9f69f49212e2a67292e
|
refs/heads/master
| 2021-01-18T19:33:15.712062
| 2020-01-29T03:35:39
| 2020-01-29T03:35:39
| 100,532,292
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 613
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-20 13:57
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tier_three', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='PassGoal',
new_name='T3Goal',
),
migrations.RenameModel(
old_name='PassProfile',
new_name='T3Profile',
),
migrations.RenameModel(
old_name='PassReport',
new_name='T3Report',
),
]
|
[
"tanner.ball@campusoutreach.org"
] |
tanner.ball@campusoutreach.org
|
64fed0e75ffe53aaf8503b96e1a0af8fafec3c03
|
0990ff8e3442cc78b4c43184b55f82c6b7f4af36
|
/seasonal_events/migrations/0014_season_disable_reservations.py
|
ff47444ec5d3b8adc96d23584047776552e20439
|
[
"MIT"
] |
permissive
|
hackerspace-ntnu/website
|
5db57c59ad04c38a8571b8804589fddae7daae7f
|
d2156e691cea5737b1c80506b58424cbcb2557e6
|
refs/heads/master
| 2023-07-22T10:48:58.897407
| 2023-05-06T14:06:56
| 2023-05-06T14:06:56
| 52,109,003
| 29
| 8
|
MIT
| 2023-08-29T18:27:44
| 2016-02-19T18:49:51
|
Python
|
UTF-8
|
Python
| false
| false
| 579
|
py
|
# Generated by Django 2.2.1 on 2019-05-19 16:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('seasonal_events', '0013_auto_20190430_2023'),
]
operations = [
migrations.AddField(
model_name='season',
name='disable_reservations',
field=models.BooleanField(default=False, help_text='Skru av mulighet for reservasjoner til ikke-medlemmer når denne sesongen er aktiv.', verbose_name='Hindre reservasjoner'),
preserve_default=False,
),
]
|
[
"god@e-grotto.faith"
] |
god@e-grotto.faith
|
8d8820c077ad49b00a7e905be252bb7c928472af
|
a8a38abba1a648aaab880bc3aafdc54de692c922
|
/P1_pt1.py
|
7fe11c498535af7ba50f3da896a81562e08d0181
|
[] |
no_license
|
pedrotramos/Projeto1-RobComp2019.1
|
56bc0edf7326307a6977a97c33d49d067af5c1f7
|
712a88b45883dd5f1c61c873b0c4930daa7d3cdd
|
refs/heads/master
| 2020-04-29T18:43:02.809946
| 2019-04-18T00:00:09
| 2019-04-18T00:00:09
| 176,331,587
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,833
|
py
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import rospy
from geometry_msgs.msg import Twist, Vector3
from std_msgs.msg import UInt8
from math import pi
bump = None
bump_happened = False
def bumper(data):
global bump
global bump_happened
bump = data.data
bump_happened = True
def forward(velocidade_saida):
vel = Twist(Vector3(0,0,0), Vector3(0,0,0))
velocidade_saida.publish(vel)
rospy.sleep(.2)
vel = Twist(Vector3(.25,0,0), Vector3(0,0,0))
t0 = rospy.Time.now().to_sec()
current_distance = 0
while current_distance < .2 and vel.angular.z == 0:
rospy.sleep(.1)
velocidade_saida.publish(vel)
t1 = rospy.Time.now().to_sec()
current_distance = vel.linear.x * (t1-t0)
vel.linear.x = 0
velocidade_saida.publish(vel)
rospy.sleep(1.0)
return
def rotate_left(velocidade_saida):
vel = Twist(Vector3(0,0,0), Vector3(0,0,0))
velocidade_saida.publish(vel)
rospy.sleep(.2)
vel = Twist(Vector3(0,0,0), Vector3(0,0,pi/4))
t0 = rospy.Time.now().to_sec()
current_angle = 0
while current_angle <= pi/3 and vel.linear.x == 0:
rospy.sleep(.1)
velocidade_saida.publish(vel)
t1 = rospy.Time.now().to_sec()
current_angle = vel.angular.z * (t1-t0)
vel.angular.z = 0
velocidade_saida.publish(vel)
rospy.sleep(1.0)
return
def back(velocidade_saida):
vel = Twist(Vector3(0,0,0), Vector3(0,0,0))
velocidade_saida.publish(vel)
rospy.sleep(.2)
vel = Twist(Vector3(-.25,0,0), Vector3(0,0,0))
t0 = rospy.Time.now().to_sec()
current_distance = 0
while current_distance > -.2 and vel.angular.z == 0:
rospy.sleep(.1)
velocidade_saida.publish(vel)
t1 = rospy.Time.now().to_sec()
current_distance = vel.linear.x * (t1-t0)
vel.linear.x = 0
velocidade_saida.publish(vel)
rospy.sleep(1.0)
return
def rotate_right(velocidade_saida):
vel = Twist(Vector3(0,0,0), Vector3(0,0,0))
velocidade_saida.publish(vel)
rospy.sleep(.2)
vel = Twist(Vector3(0,0,0), Vector3(0,0,-pi/4))
t0 = rospy.Time.now().to_sec()
current_angle = 0
while current_angle >= -pi/3 and vel.linear.x == 0:
rospy.sleep(.1)
velocidade_saida.publish(vel)
t1 = rospy.Time.now().to_sec()
current_angle = vel.angular.z * (t1-t0)
vel.angular.z = 0
velocidade_saida.publish(vel)
rospy.sleep(1.0)
return
def react(velocidade_saida):
if bump == 1:
bump_happened = False
back(velocidade_saida)
rotate_right(velocidade_saida)
forward(velocidade_saida)
if bump == 2:
bump_happened = False
back(velocidade_saida)
rotate_left(velocidade_saida)
forward(velocidade_saida)
if bump == 3:
bump_happened = False
forward(velocidade_saida)
if bump == 4:
bump_happened = False
forward(velocidade_saida)
|
[
"matheuspellizzon@hotmail.com"
] |
matheuspellizzon@hotmail.com
|
15d9d23b5e8a3431dd91d434167be4061f4141ec
|
99c4d4a6592fded0e8e59652484ab226ac0bd38c
|
/code/batch-1/vse-naloge-brez-testov/DN5-M-161.py
|
fbaee3ce3a1514aa8568ac02ddc80a4483ad326d
|
[] |
no_license
|
benquick123/code-profiling
|
23e9aa5aecb91753e2f1fecdc3f6d62049a990d5
|
0d496d649247776d121683d10019ec2a7cba574c
|
refs/heads/master
| 2021-10-08T02:53:50.107036
| 2018-12-06T22:56:38
| 2018-12-06T22:56:38
| 126,011,752
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,642
|
py
|
#DN5
#Obvezna naloga(1): unikati
def unikati(s):
seznam = []
for unikat in s:
if unikat not in seznam:
seznam.append(unikat)
return seznam
#Obvezna naloga(2): avtor
def avtor(tvit):
a = tvit.split (":")
return (a[0])
#Obvezna naloga(3): vsi avtorji
def vsi_avtorji(tviti):
seznam = []
for e in tviti:
a = e.split (":")
if a[0] not in seznam:
seznam.append (a[0])
return seznam
#Obvezna naloga(4): izloci besedo
def izloci_besedo(beseda):
for e in beseda:
if e[0].isalnum () == False:
beseda = beseda[1:]
else:
break
for e in beseda:
if beseda[-1].isalnum ():
break
else:
beseda = beseda[:-1]
return beseda
###nacin:2
###imoprt re
###def izloci_besedo(beseda):
### if beseda.isalnum () == True:
### return beseda
### else:
### iskano = re.compile ('^\W+|\W+$')
### for znak in beseda:
### izloceno = iskano.sub ("", beseda)
### return izloceno
###
###
###nacin: 3
###def izloci_besedo(beseda):
### if beseda.isalnum () == True:
### return beseda
### else:
### for spredaj in enumerate (beseda):
### zacetek, iskana_beseda = spredaj
### if iskana_beseda.isalnum ():
### break
### for zadaj in enumerate (beseda[::-1]):
### konec, iskana_beseda = zadaj
### if iskana_beseda.isalnum ():
### break
### return beseda[zacetek:len (beseda) - konec]
###
###nacin:4
###import re
###def izloci_besedo(beseda):
### return re.sub("^\W+|\W+$", "", beseda)
#Obvezna naloga(5): se zacne z
def se_zacne_z(tvit, c):
spredaj_urejen = []
urejen = []
besede = tvit.split (" ")
for e in besede:
if e[0] == c:
spredaj_urejen.append (e[1:])
for e in spredaj_urejen:
if e[-1].isalnum () == False:
e = e[:-1]
urejen.append (e)
else:
urejen.append (e)
return urejen
#Obvezna naloga(6): zberi se zacne z
def zberi_se_zacne_z(tviti, c):
spredaj_urejen = []
urejen = []
sortiran = []
for e in tviti:
beseda = e.split (" ")
for znak in beseda:
if znak not in spredaj_urejen:
if znak[0] == c:
spredaj_urejen.append (znak[1:])
for znak in spredaj_urejen:
if znak[-1].isalnum () == False:
znak = znak[:-1]
urejen.append (znak)
else:
urejen.append (znak)
for d in urejen:
if d not in sortiran:
sortiran.append (d)
return sortiran
#Obvezna naloga(7): vse afne
def vse_afne(tviti):
spredaj_urejen = []
urejen = []
sortiran = []
for e in tviti:
a = e.split (" ")
for g in a:
if g not in spredaj_urejen:
if g[0] == "@":
spredaj_urejen.append (g[1:])
for g in spredaj_urejen:
if g[-1].isalnum () == False:
g = g[:-1]
urejen.append (g)
else:
urejen.append (g)
for d in urejen:
if d not in sortiran:
sortiran.append (d)
return sortiran
#Obvezna naloga(8): vsi hashtagi
def vsi_hashtagi(tviti):
spredaj_urejen = []
urejen = []
sortiran = []
for e in tviti:
a = e.split (" ")
for g in a:
if g not in spredaj_urejen:
if g[0] == "#":
spredaj_urejen.append (g[1:])
for g in spredaj_urejen:
if g[-1].isalnum () == False:
g = g[:-1]
urejen.append (g)
else:
urejen.append (g)
for d in urejen:
if d not in sortiran:
sortiran.append (d)
return sortiran
#Obvezna naloga(9): vse osebe
def vse_osebe(tviti):
spredaj_urejen = []
urejen = []
sortiran = []
for e in tviti:
a = e.split (" ")
for g in a:
if g not in spredaj_urejen:
if g[0] == "@":
spredaj_urejen.append (g[1:])
for g in spredaj_urejen:
if g[-1].isalnum () == False:
g = g[:-1]
urejen.append (g)
else:
urejen.append (g)
for d in urejen:
if d not in sortiran:
sortiran.append (d)
for avtor in tviti:
av = avtor.split (":")
if av[0] not in sortiran:
sortiran.append (av[0])
return sorted(sortiran)
|
[
"lenart.motnikar@gmail.com"
] |
lenart.motnikar@gmail.com
|
c2207a7635fe7040b4696f51b902412c32afc49b
|
22e664ebbff04588fa35e821d6c218992e49e22d
|
/parseq/tests/test_columnStrings.py
|
c613314b59be6c39e9815b864098bb4abc507e9c
|
[
"MIT"
] |
permissive
|
kklmn/ParSeq
|
2225a10948fe238688a8913e0194566b067cacea
|
141483a42828592ad2abdcb54dccbfa74a2ab236
|
refs/heads/master
| 2023-08-18T19:31:24.355626
| 2023-08-10T15:32:59
| 2023-08-10T15:32:59
| 158,081,301
| 4
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,515
|
py
|
# -*- coding: utf-8 -*-
__author__ = "Konstantin Klementiev"
__date__ = "27 Jan 2018"
"""
Test expression evaluation where the expression operates arrays defined as
d["NNN"], where d is a local dictionary with the appropriate keys; the keys can
also be integers.
"""
# !!! SEE CODERULES.TXT !!!
import numpy as np
import re
#import os, sys; sys.path.append('..') # analysis:ignore
#from parseq.gui.combineSpectra import CombineSpectraWidget
#import parseq.apps.dummy as myapp
def test(colStr, isColumn=True):
keys = re.findall(r'\[(.*?)\]', colStr)
if len(keys) == 0:
keys = colStr,
colStr = 'd["{0}"]'.format(colStr)
else:
# remove outer quotes:
keys = [k[1:-1] if k.startswith(('"', "'")) else k for k in keys]
d = {}
for k in keys:
d[k] = np.ones(3)
if isColumn:
if "col" not in k.lower():
k_ = int(k)
d[k_] = d[k]
locals()[k] = k
print(d, colStr)
res = eval(colStr)
print(res, type(res))
if __name__ == '__main__':
test('d["path1"] + d["path2"]', isColumn=False)
test("d['path1'] + d['path2']", isColumn=False)
test(' + '.join(['d["path{0}"]'.format(i) for i in range(1, 3)]),
isColumn=False)
test('path1', isColumn=False)
test('d["col1"] + d["col2"]')
test('d[col1] + d[col2]')
test('d[1] + d[2]')
test(' + '.join(['d["col{0}"]'.format(i) for i in range(1, 3)]))
test('d[1]')
test('1')
test('col1')
test('Col1')
|
[
"konstantin.klementiev@gmail.com"
] |
konstantin.klementiev@gmail.com
|
ff72e7430c41fb37fe50a1e5591858b6d3cac252
|
046db5d85389f4de1a226653b01d6b3dfd3433ff
|
/home/migrations/0051_auto_20200226_0033.py
|
f6ba3cce436cc5922c2159c1cb0d8634657f42b4
|
[] |
no_license
|
newamericafoundation/newamerica-cms
|
ef3b7900d893bc527add5ec1c85de036f6da42dd
|
7d2e9c71958d214afbd32925de4288d8276fcd33
|
refs/heads/main
| 2023-09-04T11:23:01.091701
| 2023-09-01T14:34:15
| 2023-09-01T14:34:15
| 48,380,991
| 6
| 8
| null | 2023-09-08T19:16:26
| 2015-12-21T16:04:46
|
Python
|
UTF-8
|
Python
| false
| false
| 473
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.27 on 2020-02-26 05:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0050_auto_20200225_1721'),
]
operations = [
migrations.AlterField(
model_name='post',
name='ordered_date_string',
field=models.CharField(blank=True, max_length=140),
),
]
|
[
"1051450+nmorduch@users.noreply.github.com"
] |
1051450+nmorduch@users.noreply.github.com
|
48cb57a01920308af535b6f11cd832b736836c95
|
ff5b4fb423beae96012d64c7ce538deb804ba1a4
|
/portproject/manage.py
|
858fc21fc282efe7f780ef423204cdbc1a136330
|
[] |
no_license
|
prashantthumar75/social_auth
|
37bef81b3c1db8b6841f83c612fd0227ea0f3f5c
|
a869927c2c275370fc1ff139de9dee20385d95c1
|
refs/heads/master
| 2023-01-12T20:04:58.515949
| 2020-11-18T13:21:45
| 2020-11-18T13:21:45
| 304,028,060
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 631
|
py
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'portproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
|
[
"48546055+prashantthumar75@users.noreply.github.com"
] |
48546055+prashantthumar75@users.noreply.github.com
|
9b5bdb0fc9e2533c7f9edcac5f8036013b45f24b
|
c4c0f5d742b88106053b63a0c0e710efeb867e79
|
/sequencers/apps.py
|
2350c84da68d4e880839edbfc491d8e9b44a0cc2
|
[
"MIT"
] |
permissive
|
bihealth/digestiflow-server
|
0ed49c371cd59da5c331259a65cdd75ca71fab76
|
83f94d068d8592d83254a0b4271be9523334339d
|
refs/heads/main
| 2023-02-18T05:56:13.261282
| 2022-04-21T09:43:58
| 2022-04-21T09:52:52
| 165,990,428
| 16
| 3
| null | 2023-02-16T05:17:33
| 2019-01-16T06:56:04
|
Python
|
UTF-8
|
Python
| false
| false
| 95
|
py
|
from django.apps import AppConfig
class SequencersConfig(AppConfig):
name = "sequencers"
|
[
"manuel.holtgrewe@bihealth.de"
] |
manuel.holtgrewe@bihealth.de
|
1c42308c648a55a47a6d0a9c7959f0d55d0986d7
|
16f82859b150eb25dec19218df197689c4b9dd2e
|
/manage.py
|
93c16465be100a76d2005a5c024431c693bbed49
|
[] |
no_license
|
ernertoporras/django-refugio-7-aprendiendo
|
ac067435b2f21b9c0063a11f361b3f29acbcffaa
|
e52f59936eab35504bb5ee538805de6488d58269
|
refs/heads/master
| 2020-04-10T13:32:34.185335
| 2018-12-09T15:53:41
| 2018-12-09T15:53:41
| 161,053,397
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 549
|
py
|
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proyecto_refugio7.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
|
[
"ernestoporras2006@gmail.com"
] |
ernestoporras2006@gmail.com
|
866fda79b744e59f2b811a1d416ef1f8a1affe12
|
c3a3cf534fb77a1963c172836aeff70ef1875e4b
|
/workspaces/voyage/server/src/util/scheduler.py
|
7632dd987e979eb5361b05822855b7277124d4c8
|
[
"CC0-1.0"
] |
permissive
|
raychorn/svn_hp-projects
|
dd281eb06b299e770a31bcce3d1da1769a36883d
|
d5547906354e2759a93b8030632128e8c4bf3880
|
refs/heads/main
| 2023-01-08T07:31:30.042263
| 2020-10-14T21:56:57
| 2020-10-14T21:56:57
| 304,144,844
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 11,748
|
py
|
'''
Created on Oct 16, 2013
@author: ray.c.horn@hp.com
'''
import os, sys
import time
import datetime
from datetime import timedelta
from M2Crypto import EVP
import psycopg2
from psycopg2.extras import RealDictCursor
from util.stringcrypt import str_decrypt
from logging import getLogger
log = getLogger(__name__)
from util.threadpool import ThreadQueue, threadify
__Q__ = ThreadQueue(maxsize=1)
__QQ__ = ThreadQueue(maxsize=100)
isUsingWindows = (sys.platform.lower().find('win') > -1) and (os.name.lower() == 'nt')
isNotUsingLocalTimeConversions = not isUsingWindows
isUsingLocalTimeConversions = not isNotUsingLocalTimeConversions
@threadify(__QQ__)
def job_proxy(task,*args,**kwargs):
s = '''
try:
task(%s)
except:
log.exception('Scheduled task has an issue, someone should fix something.')
''' % (', '.join(['"%s"'%(n) if (isinstance(n,str)) else str(n) for n in args[0]]))
try:
exec(s,{'task':task},{})
except:
log.exception('Scheduled task has an issue, someone should fix something.')
class Scheduler():
def __init__(self,select_stmt="SELECT * FROM scheduled_tasks WHERE scheduled_tasks.status = 'scheduled'",callback=None,interval=60,usingLocalTime=True):
self.interval = interval
self.select_stmt = select_stmt
self.callback = callback
self.usingLocalTime = usingLocalTime
def interval():
doc = "interval property"
def fget(self):
return self.interval
def fset(self, interval):
self.interval = interval
return locals()
interval = property(**interval())
def select_stmt():
doc = "select_stmt property"
def fget(self):
return self.select_stmt
def fset(self, select_stmt):
self.select_stmt = select_stmt
return locals()
select_stmt = property(**select_stmt())
def callback():
doc = "callback property"
def fget(self):
return self.callback
def fset(self, callback):
self.callback = callback
return locals()
callback = property(**callback())
def usingLocalTime():
doc = "usingLocalTime property"
def fget(self):
return self.usingLocalTime
def fset(self, usingLocalTime):
self.usingLocalTime = usingLocalTime
return locals()
usingLocalTime = property(**usingLocalTime())
def get_jobs(self):
jobs = []
_conn = db_connect()
now = datetime.datetime.utcnow()
select_stmt = self.select_stmt
cur = _conn.cursor(cursor_factory=RealDictCursor)
cur.execute(select_stmt)
for rec in cur:
taskname = rec['taskname']
sched_time = rec['scheduledtime']
#if (not self.usingLocalTime):
#sched_time = datetime.datetime.utcfromtimestamp(time.mktime(sched_time.timetuple()))
d = {'id':rec['id'],'taskname':taskname,'time':sched_time,'task':None,'rec':rec,'*args':None,'**kwargs':None}
if (callable(self.callback)):
try:
self.callback(d)
except:
log.exception('Something went wrong with the callback, programmer check your logic !!!')
jobs.append(d)
cur.close()
db_disconnect(_conn)
log.info('There are %s runnable jobs.' % (len(jobs)))
return jobs
def sort_jobs(self,jobs):
for job in jobs:
t = job.get('time',None)
if (t):
now = today_localtime()
if (not self.usingLocalTime):
now = datetime.datetime.utcfromtimestamp(time.mktime(now.timetuple()))
delta = t - now
job['delta'] = delta.total_seconds()
return sorted(jobs, key=lambda k: k['delta'])
def execute_jobs(self,jobs):
log.info('BEGIN:')
for i in xrange(len(jobs)):
job = jobs[i]
log.info('job is %s' % (job))
delta = job.get('delta',None)
if (delta) and (delta <= 0):
log.info('Execute job %s' % (job))
task = job.get('task',None)
if (callable(task)):
try:
job_proxy(task,job.get('*args',[]),job.get('**kwargs',{}))
except Exception, ex:
log.exception('Scheduler failed to execute %s.' % (job))
update_task_status(job.get('id',None), 'Exception')
finally:
update_task_status(job.get('id',None), 'Success')
log.info('END !!!')
@threadify(__Q__)
def run(self):
while (1):
jobs = self.get_jobs()
jobs = self.sort_jobs(jobs)
jobs = self.execute_jobs(jobs)
time.sleep(self.interval)
def db_connect(database='ic4vc'):
from util.config import config
cfg = config()
log.debug("config value in the kwargs values are : %s" , cfg)
try :
password = str_decrypt(cfg.uimconfig['private_config']['db']['password'])
except EVP.EVPError :
log.warning("Assuming db password is not encrypted")
log.debug("The password1 here is : %s",cfg.uimconfig['private_config']['db']['password'])
password = cfg.uimconfig['private_config']['db']['password']
except :
log.debug("The password2 here is : %s",cfg.uimconfig['private_config']['db']['password'])
password = cfg.uimconfig['private_config']['db']['password']
log.exception("Error decrypting db password")
log.warning("Assuming db password is not encrypted")
user = cfg.uimconfig['private_config'].get('db', {}).get('username', None)
host = cfg.uimconfig['private_config']['db'].get('ip',None)
port = cfg.uimconfig['private_config'].get('db', {}).get('port', 5432)
return psycopg2.connect(database=str(database), host=str(host), user=str(user), password=str(password), port=port)
def db_disconnect(conn):
'''
Disconnects from scheduler DB
'''
try:
conn.close()
except:
log.exception("Cannot close db connection.")
def update_task_status(identifier,statusStr):
'''
This function update the database entry for identifier with given status
@param identifier: An integer which is the primary key of the
scheduled task entry in DB.
@param statusStr: The new status to be updated for the task
'''
_conn = db_connect()
cur = _conn.cursor()
try:
#cur.execute("UPDATE scheduled_tasks SET status = %s WHERE id = %s ",(statusStr)(identifier,))
update_stmt = """UPDATE scheduled_tasks SET status = %s WHERE id = %s """
cur.execute(update_stmt, (statusStr,identifier))
ret = (cur.rowcount > 0)
_conn.commit()
finally:
cur.close()
db_disconnect(_conn)
return ret
def _formatTimeStr():
return '%Y-%m-%dT%H:%M:%S'
def getAsDateTimeStr(value, offset=0,fmt=_formatTimeStr()):
""" return time as 2004-01-10T00:13:50.000Z """
import sys,time
import types
from datetime import datetime
strTypes = (types.StringType, types.UnicodeType)
numTypes = (types.LongType, types.FloatType, types.IntType)
if (not isinstance(offset,strTypes)):
if isinstance(value, (types.TupleType, time.struct_time)):
return time.strftime(fmt, value)
if isinstance(value, numTypes):
secs = time.gmtime(value+offset)
return time.strftime(fmt, secs)
if isinstance(value, strTypes):
try:
value = time.strptime(value, fmt)
return time.strftime(fmt, value)
except Exception, details:
_fmt = get_format_from(value)
secs = time.gmtime(time.time()+offset)
return time.strftime(fmt, secs)
elif (isinstance(value,datetime)):
from datetime import timedelta
if (offset is not None):
value += timedelta(offset)
ts = time.strftime(fmt, value.timetuple())
return ts
def getFromDateTimeStr(ts,format=_formatTimeStr()):
from datetime import datetime
try:
return datetime.strptime(ts,format)
except ValueError:
return datetime.strptime('.'.join(ts.split('.')[0:-1]),format)
def _formatTimeStr():
return '%Y-%m-%dT%H:%M:%S'
def getFromDateStr(ts,format=_formatTimeStr()):
return getFromDateTimeStr(ts,format=format)
def formatSalesForceTimeStr():
return '%Y-%m-%dT%H:%M:%S'
def timeSeconds(month=-1,day=-1,year=-1,format=formatSalesForceTimeStr()):
""" get number of seconds """
import time, datetime
fromSecs = datetime.datetime.fromtimestamp(time.time())
s = getAsDateTimeStr(fromSecs,fmt=format)
_toks = s.split('T')
toks = _toks[0].split('-')
if (month > -1):
toks[0] = '%02d' % (month)
if (day > -1):
toks[1] = '%02d' % (day)
if (year > -1):
toks[-1] = '%04d' % (year)
_toks[0] = '-'.join(toks)
s = 'T'.join(_toks)
fromSecs = getFromDateStr(s,format=format)
return time.mktime(fromSecs.timetuple())
def getFromNativeTimeStamp(ts,format=None):
format = _formatTimeStr() if (format is None) else format
if (':' not in ts):
format = format.replace(':','')
if ('T' not in ts):
format = format.split('T')[0]
return getFromDateTimeStr(ts,format=format)
def utcDelta():
import datetime, time
_uts = datetime.datetime.utcfromtimestamp(time.time())
_ts = datetime.datetime.fromtimestamp(time.time())
# This time conversion fails under Linux for some odd reason so let's just stick with UTC when this happens.
_zero = datetime.timedelta(0)
return _zero if (isNotUsingLocalTimeConversions) else (_uts - _ts if (_uts > _ts) else _ts - _uts)
def timeStamp(tsecs=0,format=_formatTimeStr(),useLocalTime=isUsingLocalTimeConversions):
""" get standard timestamp """
useLocalTime = isUsingLocalTimeConversions if (not isinstance(useLocalTime,bool)) else useLocalTime
secs = 0 if (not useLocalTime) else -utcDelta().seconds
tsecs = tsecs if (tsecs > 0) else timeSeconds()
t = tsecs+secs
return getAsDateTimeStr(t if (tsecs > abs(secs)) else tsecs,fmt=format)
def timeStampLocalTime(tsecs=0,format=_formatTimeStr()):
""" get standard timestamp adjusted to local time """
return timeStamp(tsecs=tsecs,format=format,useLocalTime=isUsingLocalTimeConversions)
def today_localtime(_timedelta=None,begin_at_midnight=False):
dt = getFromNativeTimeStamp(timeStampLocalTime())
begin_at_midnight = False if (not isinstance(begin_at_midnight,bool)) else begin_at_midnight
if (begin_at_midnight):
dt = strip_time_drom_datetime(dt)
try:
if (_timedelta is not None):
return dt - _timedelta
except Exception, details:
info_string = formattedException(details=details)
print >>sys.stderr, info_string
return dt
if (__name__ == '__main__'):
print today_localtime()
select_stmt = "SELECT scheduled_tasks.*, firmware_jobs.* FROM scheduled_tasks INNER JOIN firmware_jobs ON scheduled_tasks.id = firmware_jobs.id WHERE scheduled_tasks.status = 'scheduled'"
scheduler = Scheduler(select_stmt=select_stmt,interval=1)
scheduler.run()
__Q__.join()
|
[
"raychorn@gmail.com"
] |
raychorn@gmail.com
|
a7b328d76b2eaedc4f255f6aadc5b2deaf0590d0
|
f9d2397644f6f746eeaddc683da0251ff40518e7
|
/scripts/india_lgd/local_government_directory_districts/preprocess_test.py
|
d619c6cf32b6f4297d5dcb68d5dae513360af2c8
|
[
"Apache-2.0"
] |
permissive
|
katherinelamb/data
|
f5a0c0e6dc1487b9c6fe356c3ad675123cc6e04c
|
cb0cdcd73bc06f13e94b4b02fbd0203cc972560e
|
refs/heads/master
| 2023-07-08T20:03:26.760133
| 2021-08-11T16:37:09
| 2021-08-11T16:37:09
| 383,898,879
| 0
| 0
|
Apache-2.0
| 2021-08-13T12:56:36
| 2021-07-07T19:00:30
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 3,083
|
py
|
# 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
#
# https://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 csv
import os
import pandas as pd
import unittest
from india_lgd.local_government_directory_districts.preprocess import LocalGovermentDirectoryDistrictsDataLoader
# module_dir_ is the path to where this test is running from.
module_dir_ = os.path.dirname(__file__)
class TestPreprocess(unittest.TestCase):
def test_create_csv(self):
lgd_csv = os.path.join(os.path.dirname(__file__),
"./test_data/lgd_allDistrictofIndia_export.csv")
wikidata_csv = os.path.join(
os.path.dirname(__file__),
"./test_data/wikidata_india_districts_export.csv")
clean_csv = os.path.join(os.path.dirname(__file__),
"./test_data/clean_csv.csv")
loader = LocalGovermentDirectoryDistrictsDataLoader(
lgd_csv, wikidata_csv, clean_csv)
loader.process()
loader.save()
clean_df = pd.read_csv(clean_csv, dtype=str)
clean_df.fillna('', inplace=True)
# `karbi anglong` should be mapped to `east karbi anglong`
row = clean_df.loc[clean_df["LGDDistrictName"] == "karbi anglong"]
self.assertEqual("east karbi anglong",
row.iloc[0]["closestDistrictLabel"])
self.assertEqual("Q29025081", row.iloc[0]["WikiDataId"])
# `west karbi anglong` should be mapped to `west karbi anglong`
row = clean_df.loc[clean_df["LGDDistrictName"] == "west karbi anglong"]
self.assertEqual("west karbi anglong",
row.iloc[0]["closestDistrictLabel"])
self.assertEqual("Q24949218", row.iloc[0]["WikiDataId"])
# `tuticorin` should be mapped to `thoothukudi`
row = clean_df.loc[clean_df["LGDDistrictName"] == "tuticorin"]
self.assertEqual("thoothukudi", row.iloc[0]["closestDistrictLabel"])
self.assertEqual("Q15198", row.iloc[0]["WikiDataId"])
# `balod` should be mapped to `balod`
row = clean_df.loc[clean_df["LGDDistrictName"] == "balod"]
self.assertEqual("balod", row.iloc[0]["closestDistrictLabel"])
self.assertEqual("Q16056266", row.iloc[0]["WikiDataId"])
# `malerkotla` should be mapped to `malerkotla`
row = clean_df.loc[clean_df["LGDDistrictName"] == "malerkotla"]
self.assertEqual("malerkotla", row.iloc[0]["closestDistrictLabel"])
self.assertEqual("Q1470987", row.iloc[0]["WikiDataId"])
os.remove(clean_csv)
if __name__ == '__main__':
unittest.main()
|
[
"noreply@github.com"
] |
katherinelamb.noreply@github.com
|
eb443efba7bb5c8623744352bf7b874747b46b9f
|
753cdd1b764a24f2a520a0d313ca032bf7d833f8
|
/app.py
|
8ab415043249c9fae39dae2bc2056703c4dfcb10
|
[] |
no_license
|
TiffanySantos/flask_schools
|
eabece88a1465dce5730bfa7c49b6cd242da8c32
|
c928e95540e4df90edb0bea6a635581e2751fb3f
|
refs/heads/master
| 2022-12-02T06:41:58.114813
| 2020-08-10T11:10:14
| 2020-08-10T11:10:14
| 286,456,937
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,816
|
py
|
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# URI is uniform resource identifier whereas URL is uniform resource locator (it is an unstance of a URI)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///schools.sqlite3'
db = SQLAlchemy(app)
# tell SQLAlchemy to reflect the columns that already exist in the table
db.Model.metadata.reflect(db.engine)
class School(db.Model):
__tablename__ = 'schools-geocoded'
__table_args__ = { 'extend_existing': True }
LOC_CODE = db.Column(db.Text, primary_key=True)
@app.route("/")
def index():
# SQLAlchemy 'translates' your python to an SQL query
school_count = School.query.count()
schools = School.query.all()
return render_template("index.html", count=school_count, schools=schools, location="New York City")
@app.route('/schools/<slug>')
def detail(slug):
school = School.query.filter_by(LOC_CODE=slug).first()
return render_template("detail.html", school=school)
@app.route('/city')
def city_list():
cities = School.query.with_entities(School.city).distinct().all()
cities =[city[0].title() for city in cities]
cities = sorted(list(set(cities)))
return render_template("city.html", cities=cities)
@app.route('/city/<cityname>')
def city(cityname):
cityname = cityname.replace("-", " ")
schools = School.query.filter_by(city=cityname.upper()).all()
return render_template("index.html", schools=schools, count=len(schools), location=cityname)
@app.route("/zip/<zipcode>")
def zip(zipcode):
schools = School.query.filter_by(ZIP=zipcode).all()
return render_template("index.html", schools=schools, count=len(schools), location=zipcode)
if __name__ == '__main__':
app.run(debug=True)
# to run the app in terminal type:
# $ python3 -m flask run
|
[
"tiffanysantos@Tiffanys-MacBook-Air.local"
] |
tiffanysantos@Tiffanys-MacBook-Air.local
|
952969f39238e6427f8f75aa439387a4bdee1f09
|
9ace2224990e9d5df81e2dcc3c91f9cedd5d49d8
|
/Hackerrank/Practice/Dynamic Programming/Nikita and the Game/main.py
|
0704768a5c45ebb6a837bd2ad095042d37142f3f
|
[] |
no_license
|
iamakshatjain/Codings
|
fe18c1dabc4e2b769eb1888f560f88f19fbbfc99
|
004b0a52e7598e2e0e922f9888b4ae499c01edfe
|
refs/heads/master
| 2021-07-17T11:10:32.842520
| 2020-05-24T18:34:30
| 2020-05-24T18:37:24
| 258,223,901
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,200
|
py
|
#https://www.hackerrank.com/challenges/array-splitting/problem?h_r=internal-search
#!/bin/python3
import os
import sys
#
# Complete the arraySplitting function below.
#
sys.setrecursionlimit(10**9)
def arraySplitting(arr, sumarr, l, r):
if((r-l+1) == 1):
return 0
if((r-l+1) == 2):
if(arr[l] == arr[r]):
return 1
else:
return 0
# ls = sum(arr)
ls = sumarr[r]-(sumarr[l]-arr[l])
rs = 0
if(ls%2 != 0):
return 0
i = r
count = 0
while(i>=l):
ls-=arr[i]
rs+=arr[i]
if(ls == rs):
return max(arraySplitting(arr, sumarr, l, i-1),arraySplitting(arr, sumarr, i, r))+1
i-=1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
arr_count = int(input())
arr = list(map(int, input().rstrip().split()))
sumarr = []
s = 0
for index, i in enumerate(arr):
s+=arr[index]
sumarr.append(s)
result = arraySplitting(arr, sumarr, 0, len(arr)-1)
fptr.write(str(result) + '\n')
fptr.close()
|
[
"jain99akshat@gmail.com"
] |
jain99akshat@gmail.com
|
7bf683142d7cffb7125eb2c80cf20a46978c1035
|
8997f25ba095269ff68bc596809e141247e2c532
|
/StockBot.py
|
7f3af96687b13e23a7fc3494a4d8a3cbe8268923
|
[] |
no_license
|
DeaDHatchi/StockBot
|
cf76529e2faddf6fbed7f092aed68ec3e60e1a08
|
2f945cee8025847df8dc3018094fc46f9a89055b
|
refs/heads/master
| 2016-08-13T01:00:57.568675
| 2015-08-27T01:02:56
| 2015-08-27T01:02:56
| 36,043,626
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 9,759
|
py
|
__author__ = 'Hatchi'
from bs4 import BeautifulSoup
from datetime import datetime
import requests
class Symbol:
def __init__(self):
# Hard Coded Values
self.stock_margin = 0.15
self.transaction_cost = 7
self.trade_shares = 100
self.max_shares = 100
self.investment_return = 0.15
# Trade Variables
self.symbol = ""
self.current_price = 0.0
self.current_shares = 0
self.stock_open = 0.0
self.range_low = 0.0
self.range_high = 0.0
self.range_52_high = 0.0
self.range_52_low = 0.0
self.market_cap = ""
self.market_shares = ""
self.range_52 = 0.0
self.buy_target = 0.0
self.bought_price = 0.0
self.sell_target = 0.0
self.sell_price = 0.0
self.stock_status = ""
# Account Variables
self.account_balance = 1000000.0
self.amount_invested = 0.0
self.gross = 0.0
self.net_profit = 0.0
self.bought_count = 0
self.sold_count = 0
# List Variables
self.bought_list = []
self.sold_list = []
'''
c_list array -- 0 = Current Price
s_list array -- 0 = Range, 1 = 52 week, 2 = Open, 3 = Vol/Avg, 4 = Mkt cap, 5 = P/E
s_list array -- 6 = Div/yield, 7 = EPS, 8 = Shares, 9 = Beta, 10 = Inst. own
'''
# Google Scrape for Stock Information
def google_scrape(self):
r = requests.get("https://www.google.com/finance?q=" + self.symbol)
data = r.text
soup = BeautifulSoup(data)
tag = soup.div
c_data = tag.find_all("span", {"class": "pr"})
t_data = tag.find_all("td", {"class": "val"})
c_list = []
s_list = []
for object_in in c_data:
stock_current_price = object_in.text.strip()
c_list.append(stock_current_price)
for object_in in t_data:
stock_table = object_in.text.strip()
s_list.append(stock_table)
week_range = s_list[0].split(" - ")
for item in week_range:
item.strip('-')
item.strip(',')
self.range_low = float(week_range[0])
self.range_high = float(week_range[1])
range_52 = s_list[1].split(" - ")
self.range_52_low = float(range_52[0])
self.range_52_high = float(range_52[1])
self.range_52 = self.range_52_high - self.range_52_low
self.current_price = float(c_list[0])
self.stock_open = float(s_list[2])
self.market_cap = s_list[4]
self.market_shares = s_list[8]
# Buy/Sell Switch based on Current Shares
def buy_or_sell_switch(self):
if self.current_shares > 0:
self.sell_shares()
else:
self.buy_shares()
# Buy Parameters Function
def buy_shares(self):
self.buy_target = self.range_52_low + (self.range_52 * self.stock_margin)
if self.current_price <= self.buy_target and self.current_shares < self.max_shares and self.account_balance > \
(self.current_price * self.trade_shares) + self.transaction_cost:
self.bought_price = self.current_price
self.account_balance -= (self.bought_price * self.trade_shares) + self.transaction_cost
self.amount_invested += (self.bought_price * self.trade_shares) + self.transaction_cost
self.current_shares += self.trade_shares
self.stock_status = "Bought"
self.bought_count += 1
self.bought_list.append(self.symbol)
self.sell_target = self.bought_price + (self.bought_price * self.investment_return) + \
(self.transaction_cost / self.trade_shares)
self.buy_transaction_log()
self.print_out()
else:
self.stock_status = "Waiting"
# Sell Parameters Function
def sell_shares(self):
self.sell_target = self.bought_price + (self.bought_price * self.investment_return) + \
(self.transaction_cost / self.trade_shares)
if self.current_price >= self.sell_target:
self.amount_invested -= (self.bought_price * self.current_shares) + self.transaction_cost
self.gross += self.current_price * self.current_shares
self.net_profit += (self.current_price * self.current_shares) - (self.bought_price * self.current_shares) \
- (self.transaction_cost * 2)
self.account_balance += (self.current_price * self.trade_shares) - self.transaction_cost
self.current_shares -= self.trade_shares
self.bought_price = 0.0
self.sold_count += 1
self.stock_status = "Sold"
self.sold_list.append(self.symbol)
self.sell_transaction_log()
self.print_out()
else:
self.stock_status = "Waiting"
# Basic printout of stock information on Buy/Sell
def print_out(self):
print("")
print("-=-=-=-=- " + str(self.symbol) + " -=-=-=-=-")
print("Current Price: " + str(self.current_price))
print("Buy Target: " + str(self.buy_target))
print("Sell Target: " + str(self.sell_target))
print("Stock Range Low: " + str(self.range_low))
print("Stock Range High: " + str(self.range_high))
print("52 Week Range low: " + str(self.range_52_low))
print("52 Week Range High: " + str(self.range_52_high))
print("Stock Open: " + str(self.stock_open))
print("Market Cap: " + str(self.market_cap))
print("Market Shares: " + str(self.market_shares))
print("Stock Status: " + str(self.stock_status))
print("-=-=-=-=-=-=-=-=-=-=-=-")
# Added for Full Account Details after run 5/26/2015
def account_printout(self):
print("")
print("-=-=-=- Hatchi Account -=-=-=-")
print("Account Balance: " + str(self.account_balance))
print("Amount Invested: " + str(self.amount_invested))
print("Net Profit: " + str(self.net_profit))
print("Gross Profit: " + str(self.gross))
print("Total Bought Count: " + str(self.bought_count))
print("Total Sold Count: " + str(self.sold_count))
print("")
print("-=-=-=- Bought List -=-=-=-")
for item in self.bought_list:
print("> " + item)
print("")
print("-=-=-=- Sold List -=-=-=-")
for item in self.sold_list:
print("> " + item)
def buy_transaction_log(self):
transaction_log = open("buy_transaction_log.txt", "a")
transaction_log.write("" + "\n")
transaction_log.write("-=-=-=-=- " + str(self.symbol) + " -=-=-=-=-" + "\n")
transaction_log.write("Transaction Time: " + str(datetime.now()) + "\n")
transaction_log.write("Current Price: " + str(self.current_price) + "\n")
transaction_log.write("Buy Target: " + str(self.buy_target) + "\n")
transaction_log.write("Sell Target: " + str(self.sell_target) + "\n")
transaction_log.write("Stock Range Low: " + str(self.range_low) + "\n")
transaction_log.write("Stock Range High: " + str(self.range_high) + "\n")
transaction_log.write("52 Week Range low: " + str(self.range_52_low) + "\n")
transaction_log.write("52 Week Range High: " + str(self.range_52_high) + "\n")
transaction_log.write("Stock Open: " + str(self.stock_open) + "\n")
transaction_log.write("Market Cap: " + str(self.market_cap) + "\n")
transaction_log.write("Market Shares: " + str(self.market_shares) + "\n")
transaction_log.write("Stock Status: " + str(self.stock_status) + "\n")
transaction_log.write("-=-=-=-=-=-=-=-=-=-=-=-" + "\n")
transaction_log.close()
def sell_transaction_log(self):
transaction_log = open("sell_transaction_log.txt", "a")
transaction_log.write("" + "\n")
transaction_log.write("-=-=-=-=- " + str(self.symbol) + " -=-=-=-=-" + "\n")
transaction_log.write("Transaction Time: " + str(datetime.now()) + "\n")
transaction_log.write("Current Price: " + str(self.current_price) + "\n")
transaction_log.write("Buy Target: " + str(self.buy_target) + "\n")
transaction_log.write("Sell Target: " + str(self.sell_target) + "\n")
transaction_log.write("Stock Range Low: " + str(self.range_low) + "\n")
transaction_log.write("Stock Range High: " + str(self.range_high) + "\n")
transaction_log.write("52 Week Range low: " + str(self.range_52_low) + "\n")
transaction_log.write("52 Week Range High: " + str(self.range_52_high) + "\n")
transaction_log.write("Stock Open: " + str(self.stock_open) + "\n")
transaction_log.write("Market Cap: " + str(self.market_cap) + "\n")
transaction_log.write("Market Shares: " + str(self.market_shares) + "\n")
transaction_log.write("Stock Status: " + str(self.stock_status) + "\n")
transaction_log.write("-=-=-=-=-=-=-=-=-=-=-=-" + "\n")
transaction_log.close()
# Added for Variable Resets after scrape - 5/22/2015
def variable_reset(self):
self.symbol = ""
self.current_price = 0
self.current_shares = 0
self.stock_open = 0
self.range_low = 0
self.range_high = 0
self.range_52_high = 0
self.range_52_low = 0
self.market_cap = ""
self.market_shares = ""
self.range_52 = 0
self.buy_target = 0
self.bought_price = 0
self.sell_target = 0
self.sell_price = 0
self.stock_status = ""
# Added for List Resets after run completion - 5/26/2015
def list_reset(self):
self.bought_list = []
self.sold_list = []
|
[
"Gerken.Travis@Gmail.com"
] |
Gerken.Travis@Gmail.com
|
2762df5579eacdb99ddb7ffeabc418bac7baea62
|
02f79bc383266c71c4bfa0eb940cb663149a7630
|
/leetcode and gfg/leetCode/isCompact integer uber.py
|
52ecddff679f64ba6e2227a6552e2fe531acb6a3
|
[] |
no_license
|
neilsxD/justCodes
|
a10febad0ac47d115310e6e06768b7a7dc63d05c
|
950ae26fce82f54341deee790e5df530f65c88d4
|
refs/heads/main
| 2023-07-17T04:38:32.703085
| 2021-08-24T10:22:23
| 2021-08-24T10:22:23
| 399,422,088
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,200
|
py
|
# from heapq import heappush
class Solution:
@classmethod
def main(self, x,y,n) :
ans= 0
def isComp(val) :
while(val) :
t = val % 10
if t != x and t != y :
return False
val= val//10
return True
def reccur(sum, pos):
nonlocal ans
if pos == n-1 :
for i in range (1,10) :
sum+= i
if isComp(sum) : ans+=1
sum-= i
return
for i in range (10) :
sum+=i
reccur(sum,pos+1)
sum-=i
reccur(0,0)
return ans
print(Solution.main(1,2,2))
# def test_func1() :
# s = [6,2,5,4,5,1,6]
# x = main(s)
# assert x == 12
# def test_func1():
# s = "aab"
# x = main(s)
# print(x)
# assert x == [["a","a","b"],["aa","b"]]
# def test_func2():
# s = "a"
# x = main(s)
# print(x)
# assert x == [["a"]]
|
[
"noreply@github.com"
] |
neilsxD.noreply@github.com
|
1b6b233c8fe0c892db0154e6b7263cc4625748a3
|
4993517af7c2019a00035778d76aff9214feb787
|
/rofi_menu/rofi_mode/rofi_mode_15.py
|
8fe03bf349125fd1a662dfa69f611306089d2f3c
|
[] |
no_license
|
miphreal/python-rofi-menu
|
4dabc63fa6e527ae6335e99910be262dd8d1075b
|
d7dd764d92da922005bf547414dd3de3f256cd0a
|
refs/heads/master
| 2022-07-04T14:08:02.391939
| 2021-04-23T12:34:31
| 2021-04-23T12:34:31
| 251,117,720
| 42
| 4
| null | 2021-09-23T03:15:52
| 2020-03-29T19:37:57
|
Python
|
UTF-8
|
Python
| false
| false
| 1,524
|
py
|
"""
Rofi script mode for version <=1.5
"""
import base64
import json
from typing import Optional
MENU_ITEM_META_DELIM = "\r!"
def render_menu(prompt: str, *items) -> str:
items = [menu_prompt(prompt), menu_enable_markup(), *items]
return "\n".join(items)
def menu_prompt(text: str) -> str:
return f"\x00prompt\x1f{text}"
def menu_enable_markup() -> str:
return "\0markup-rows\x1ftrue"
def menu_message(text: str) -> str:
return f"\0message\x1f{text}"
def menu_urgent(num: int) -> str:
return f"\0urgent\x1f{num}"
def menu_active(num: int) -> str:
return f"\0active\x1f{num}"
def menu_icon(text: str, icon: str) -> str:
return f"{text}\0icon\x1f{icon}"
def menu_no_input(val: bool = True) -> str:
return ""
##
# Extending rofi
# Add meta data along all menu items
def menu_item(
text: str,
icon: Optional[str] = None,
searchable_text: Optional[str] = None,
nonselectable: Optional[bool] = None,
meta_data: Optional[dict] = None,
) -> str:
meta = json.dumps(meta_data)
meta = base64.urlsafe_b64encode(meta.encode()).decode("utf8")
text_with_meta = f"{text}{MENU_ITEM_META_DELIM}{meta}"
if icon is not None:
return menu_icon(text_with_meta, icon)
return text_with_meta
def parse_meta(selected_item: str) -> dict:
meta = None
if isinstance(selected_item, str):
meta = selected_item.partition(MENU_ITEM_META_DELIM)[-1]
if meta:
return json.loads(base64.urlsafe_b64decode(meta))
return {}
|
[
"miphreal@gmail.com"
] |
miphreal@gmail.com
|
23c314577deec241bb34225d086c46b09a551c68
|
3da732019a135d3b1a165ef5c1bd6dd22329b91e
|
/wechat_spider.py
|
975512be971d99eb8f750b66e7708415cc93446d
|
[] |
no_license
|
HouserChiu/spider_wechat
|
7721c9aae0cd98dd6362b9f470eeb65964d737a6
|
3c85be0a8ca6d75b2b5542be4ffd84505579aa9f
|
refs/heads/master
| 2020-12-06T23:52:47.950123
| 2020-01-09T14:22:09
| 2020-01-09T14:22:09
| 232,585,495
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,531
|
py
|
import time
from selenium.webdriver.common.by import By
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class Wechat_Moment():
def __init__(self):
self.desired_caps = {}
self.desired_caps['platformName'] = 'Android'
self.desired_caps['deviceName'] = '913eea43'
self.desired_caps['platformVersion'] = '6.0.1'
self.desired_caps['appPackage'] = 'com.tencent.mm'
self.desired_caps['appActivity'] = '.ui.LauncherUI'
self.start_x = 300
self.start_y = 800
self.enf_x = 300
self.end_y = 300
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', self.desired_caps)
self.wait = WebDriverWait(self.driver,300)
print('微信启动...')
def login(self):
login_btn = self.wait.until(EC.element_to_be_clickable((By.ID,'com.tencent.mm:id/ene')))
login_btn.click()
phone = self.wait.until(EC.element_to_be_clickable((By.XPATH,"//android.widget.EditText[@resource-id='com.tencent.mm:id/m7']")))
phone.click()
phone.send_keys("your username")
next_page = self.wait.until(EC.element_to_be_clickable((By.XPATH,"//android.widget.Button[@resource-id='com.tencent.mm:id/b2f']")))
next_page.click()
password = self.wait.until(EC.presence_of_element_located((By.XPATH,"//android.widget.LinearLayout[@resource-id='com.tencent.mm:id/doa']/android.widget.EditText[1]")))
password.click()
password.send_keys("your password")
login = self.wait.until(EC.element_to_be_clickable((By.ID,'com.tencent.mm:id/b2f')))
login.click()
no_btn = self.wait.until(EC.element_to_be_clickable((By.ID,'com.tencent.mm:id/b48')))
no_btn.click()
print('登录成功')
def find(self):
search_btn = self.wait.until(EC.element_to_be_clickable((By.ID,'com.tencent.mm:id/r_')))
time.sleep(5)
search_btn.click()
serarch_input = self.wait.until(EC.presence_of_element_located((By.XPATH,"//android.widget.EditText[@resource-id='com.tencent.mm:id/m7']")))
serarch_input.set_text('houser_chiu')
print('搜索醉夜歌')
houser_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH,"//android.widget.RelativeLayout[@resource-id='com.tencent.mm:id/c6t']/android.widget.LinearLayout[2]")))
houser_btn.click()
menu_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH,"//android.widget.LinearLayout[@resource-id='com.tencent.mm:id/dl3' and @content-desc='个人相册,共3张']/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]")))
menu_btn.click()
print('进入朋友圈...')
def get_data(self):
while True:
items = self.wait.until(EC.presence_of_all_elements_located((By.ID,'com.tencent.mm:id/ezu')))
self.driver.swipe(self.start_x,self.start_y,self.enf_x,self.end_y,2000)
for item in items:
moment_text = item.find_element_by_id("com.tencent.mm:id/pi").get_attribute('text')
day_text = item.find_element_by_id("com.tencent.mm:id/f5p").get_attribute('text')
month_text = item.find_element_by_id("com.tencent.mm:id/f5q").get_attribute('text')
print('抓取到醉夜歌朋友圈数据:%s' %moment_text)
print('抓取到醉夜歌发布时间:%s月%s日' %(month_text,day_text))
if __name__ == '__main__':
wc_moment = Wechat_Moment()
wc_moment.login()
wc_moment.find()
wc_moment.get_data()
|
[
"18391726137@163.com"
] |
18391726137@163.com
|
2fe90cc06e15728b2ebd62ee61cc9383c1b054d6
|
9bb34a5a6dfb9277ff2896f053489aa0b20e5ede
|
/recipe_groups/forms.py
|
8de51e82d3a9065829ab6fe095187555feaec173
|
[] |
no_license
|
john-clark/openeats2
|
31ee86dca54041ebee5b0f5b131afd96cdd3c6ce
|
19d9e4408621bda877fa82a3e2726d618264cfac
|
refs/heads/master
| 2021-01-14T14:15:35.307357
| 2016-04-22T13:49:33
| 2016-04-22T13:49:33
| 56,856,851
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 426
|
py
|
from django.forms import ModelForm
from models import Course, Cuisine
class CoursePopForm(ModelForm):
"""form object for the popup from the recipe_form to add a new course"""
class Meta:
model = Course
exclude = ('slug')
class CuisinePopForm(ModelForm):
"""form object for the popup from the recipe_form to add a new cuisine"""
class Meta:
model = Cuisine
exclude = ('slug')
|
[
"qgriffith@gmail.com"
] |
qgriffith@gmail.com
|
2c5c1f27e63c439b6c81318d3e1448d3fed261cc
|
a7c75dbe004c929266888605c60a867a074f6b9c
|
/estimate_disparity.py
|
d022944c0ec6dccff0d6702ab4922b7ef6337960
|
[] |
no_license
|
doegan32/Light-Field-Style-Transfer
|
7e7c938db3ae979f762dae4ff0cae542afa6537c
|
e1628802042eab936634573366ee39ad354c5227
|
refs/heads/main
| 2023-08-21T15:50:31.431651
| 2021-10-20T14:36:20
| 2021-10-20T14:36:20
| 337,192,820
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,741
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 13:25:54 2020
@author: donal
Run this script to estimate disparity between the neighbouring light field viewpoints
and to also calculate the weights c_{s't'}^{s,t} defined in section 2.2.2 of the paper.
DeepFlow (http://lear.inrialpes.fr/src/deepflow/) is used for this.
The code is adapted from that found here https://github.com/manuelruder/artistic-videos
"""
import argparse
import os
import time
def parse_args():
parser = argparse.ArgumentParser()
#light field arguments
parser.add_argument('--lf_input_dir', type = str, default = './lf_input', help='directory in which input light field is saved')
parser.add_argument('--content_img_frmt', type=str, default='view_%02d_%02d.png', help='Filename format of the input content frames.')
parser.add_argument('--st_size', type = int, default = 9)
# optical flow arguments
parser.add_argument('--optic_flow_dir', type=str, default='./of_output', help='disparity/optic flow estimates will be saved here')
parser.add_argument('--optic_flow_frmt_bw', type=str, default='backward_{}_{}_{}_{}.flo', help='Filename format of the backward optical flow files.')
parser.add_argument('--optic_flow_frmt_fw', type=str, default='forward_{}_{}_{}_{}.flo', help='Filename format of the forward optical flow files')
parser.add_argument('--consistency_weights_frmt', type=str, default='reliable_{}_{}_{}_{}.txt', help='Filename format of the optical flow consistency files.')
return parser.parse_args()
def optic_flow(vp, neighbours = []):
s1, t1 = vp
for vp2 in neighbours:
s2, t2 = vp2
# read in flow file: backward_current frame_previous frame
fn = args.optic_flow_frmt_bw.format(str(s1), str(t1), str(s2), str(t2))
path = os.path.join(args.optic_flow_dir, fn)
if not os.path.exists(path):
os.system("./make-opt-flow.sh " + args.lf_input_dir + "/" + args.content_img_frmt + " " + args.optic_flow_dir +" {:d} {:d} {:d} {:d}".format(s1, t1, s2, t2))
def main():
tick = time.time() # set timer going
global args
args = parse_args()
m = args.st_size
c = int(m/2)
print("light-field has {:d}x{:d} sub-aperture images".format(m,m))
counter = 0 # keep track of number of viewpoints completed
# step 0 - central viewpoint (doesn't do anything as set of neighbours is empty)
optic_flow((c, c))
counter += 1
# step 1 - estimate disparity between central view and surrounding views
# 4 midpoints
optic_flow((c-1, c), [(c, c)])
optic_flow((c, c+1), [(c, c)])
optic_flow((c+1, c), [(c, c)])
optic_flow((c, c-1), [(c, c)])
# 4 corners
optic_flow( (c-1, c-1), [(c, c), (c-1,c), (c, c-1)])
optic_flow( (c-1, c+1), [(c, c), (c-1, c), (c,c+1)])
optic_flow( (c+1, c+1), [(c, c), (c, c+1), (c+1, c)])
optic_flow( (c+1, c-1), [(c, c), (c+1, c), (c, c-1)])
counter += 8
#step n
for i in range(2, c+1):
print("starting circle {:d}".format(i+1))
# middle of sides - 3 warps
optic_flow((c-i, c), [(c+1-i, c-1), (c+1-i, c), (c+1-i, c+1)])
optic_flow((c, c+i), [(c-1, c-1+i), (c, c-1+i), (c+1, c-1+i)])
optic_flow((c+i, c), [(c-1+i, c+1), (c-1+i, c), (c-1+i, c-1)])
optic_flow((c, c-i), [(c+1, c+1-i), (c, c+1-i), (c-1, c+1-i)])
counter += 4
# rest of sides excluding corners and adjacent to corners - 3 warps
for j in range(1,i-1):
optic_flow( (c-i, c-j), [(c+1-i, c-1-j), (c+1-i, c-j), (c+1-i, c+1-j), (c-i, c-j+1)])
optic_flow( (c-i, c+j), [(c+1-i, c-1+j), (c+1-i, c+j), (c+1-i, c+1+j), (c-i, c+j-1)])
optic_flow( (c-j, c+i), [(c-1-j, c-1+i), (c-j, c-1+i), (c+1-j, c-1+i), (c-j+1, c+i)])
optic_flow( (c+j, c+i), [(c-1+j, c-1+i), (c+j, c-1+i), (c+1+j, c-1+i), (c+j-1, c+i)])
optic_flow( (c+i, c+j), [(c-1+i, c+1+j), (c-1+i, c+j), (c-1+i, c-1+j), (c+i, c+j-1)])
optic_flow( (c+i, c-j), [(c-1+i, c+1-j), (c-1+i, c-j), (c-1+i, c-1-j), (c+i, c-j+1)])
optic_flow( (c+j, c-i), [(c+1+j, c+1-i), (c+j, c+1-i), (c-1+j, c+1-i), (c+j-1, c-i)])
optic_flow( (c-j, c-i), [(c+1-j, c+1-i), (c-j, c+1-i), (c-1-j, c+1-i), (c-j+1, c-i)])
counter += 8
# adjacent to corners - 2 warps
optic_flow( (c-i, c-i+1), [(c-i+1, c-i+1), (c-i+1, c-i+2), (c-i, c-i+2)])
optic_flow( (c-i, c+i-1), [(c-i+1, c+i-2), (c-i+1, c+i-1), (c-i, c+i-2)])
optic_flow( (c-i+1, c+i), [(c-i+1, c+i-1), (c-i+2, c+i-1), (c-i+2, c+i)])
optic_flow( (c+i-1, c+i), [(c+i-2, c+i-1), (c+i-1, c+i-1), (c+i-2, c+i)])
optic_flow( (c+i, c+i-1), [(c+i-1, c+i-1), (c+i-1, c+i-2), (c+i, c+i-2)])
optic_flow( (c+i, c-i+1), [(c+i-1, c-i+2), (c+i-1, c-i+1), (c+i, c-i+2)])
optic_flow( (c+i-1, c-i), [(c+i-1, c-i+1), (c+i-2, c-i+1), (c+i-2, c-i)])
optic_flow( (c-i+1, c-i), [(c-i+2, c-i+1), (c-i+1, c-i+1), (c-i+2, c-i)])
counter += 8
# 4 corners - one warp
optic_flow( (c-i, c-i), [(c+1-i, c+1-i), (c-i+1, c-i), (c-i, c-i+1)])
optic_flow( (c-i, c+i), [(c+1-i, c-1+i), (c-i, c+i-1), (c-i+1, c+i)])
optic_flow( (c+i, c+i), [(c-1+i, c-1+i), (c+i-1, c+i), (c+i, c+i-1)])
optic_flow( (c+i, c-i), [(c-1+i, c+1-i), (c+i, c-i+1), (c+i-1, c-i)])
counter += 4
tock = time.time()
total_time = (tock - tick) / 3600.0
print("Total time taken was {:0.4f} hours.".format(total_time))
if __name__ == '__main__':
main()
|
[
"noreply@github.com"
] |
doegan32.noreply@github.com
|
9a7f9e869ff256b94b5bff872c966ffa9a1deae3
|
0550edab7b82ea398404267e9cd9aa8fbc05a808
|
/67.py
|
bb0f7e943b9ce01b8ad139ba09b1fbd93b090523
|
[] |
no_license
|
Dritte/ProjectEuler
|
534135a9c696e6ea9611adae4fe1735b6404b2e0
|
43b78ccc67b43d10e8f2e15c2b3201765311f4bd
|
refs/heads/master
| 2016-09-10T10:08:51.481278
| 2014-10-25T16:20:31
| 2014-10-25T16:20:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 15,274
|
py
|
tri=[[59],
[73,41],
[52,40,9],
[26,53,6,34],
[10,51,87,86,81],
[61,95,66,57,25,68],
[90,81,80,38,92,67,73],
[30,28,51,76,81,18,75,44],
[84,14,95,87,62,81,17,78,58],
[21,46,71,58,2,79,62,39,31,9],
[56,34,35,53,78,31,81,18,90,93,15],
[78,53,4,21,84,93,32,13,97,11,37,51],
[45,3,81,79,5,18,78,86,13,30,63,99,95],
[39,87,96,28,3,38,42,17,82,87,58,7,22,57],
[6,17,51,17,7,93,9,7,75,97,95,78,87,8,53],
[67,66,59,60,88,99,94,65,55,77,55,34,27,53,78,28],
[76,40,41,4,87,16,9,42,75,69,23,97,30,60,10,79,87],
[12,10,44,26,21,36,32,84,98,60,13,12,36,16,63,31,91,35],
[70,39,6,5,55,27,38,48,28,22,34,35,62,62,15,14,94,89,86],
[66,56,68,84,96,21,34,34,34,81,62,40,65,54,62,5,98,3,2,60],
[38,89,46,37,99,54,34,53,36,14,70,26,2,90,45,13,31,61,83,73,47],
[36,10,63,96,60,49,41,5,37,42,14,58,84,93,96,17,9,43,5,43,6,59],
[66,57,87,57,61,28,37,51,84,73,79,15,39,95,88,87,43,39,11,86,77,74,18],
[54,42,5,79,30,49,99,73,46,37,50,2,45,9,54,52,27,95,27,65,19,45,26,45],
[71,39,17,78,76,29,52,90,18,99,78,19,35,62,71,19,23,65,93,85,49,33,75,9,2],
[33,24,47,61,60,55,32,88,57,55,91,54,46,57,7,77,98,52,80,99,24,25,46,78,79,5],
[92,9,13,55,10,67,26,78,76,82,63,49,51,31,24,68,5,57,7,54,69,21,67,43,17,63,12],
[24,59,6,8,98,74,66,26,61,60,13,3,9,9,24,30,71,8,88,70,72,70,29,90,11,82,41,34],
[66,82,67,4,36,60,92,77,91,85,62,49,59,61,30,90,29,94,26,41,89,4,53,22,83,41,9,74,90],
[48,28,26,37,28,52,77,26,51,32,18,98,79,36,62,13,17,8,19,54,89,29,73,68,42,14,8,16,70,37],
[37,60,69,70,72,71,9,59,13,60,38,13,57,36,9,30,43,89,30,39,15,2,44,73,5,73,26,63,56,86,12],
[55,55,85,50,62,99,84,77,28,85,3,21,27,22,19,26,82,69,54,4,13,7,85,14,1,15,70,59,89,95,10,19],
[4,9,31,92,91,38,92,86,98,75,21,5,64,42,62,84,36,20,73,42,21,23,22,51,51,79,25,45,85,53,3,43,22],
[75,63,2,49,14,12,89,14,60,78,92,16,44,82,38,30,72,11,46,52,90,27,8,65,78,3,85,41,57,79,39,52,33,48],
[78,27,56,56,39,13,19,43,86,72,58,95,39,7,4,34,21,98,39,15,39,84,89,69,84,46,37,57,59,35,59,50,26,15,93],
[42,89,36,27,78,91,24,11,17,41,5,94,7,69,51,96,3,96,47,90,90,45,91,20,50,56,10,32,36,49,4,53,85,92,25,65],
[52,9,61,30,61,97,66,21,96,92,98,90,6,34,96,60,32,69,68,33,75,84,18,31,71,50,84,63,3,3,19,11,28,42,75,45,45],
[61,31,61,68,96,34,49,39,5,71,76,59,62,67,6,47,96,99,34,21,32,47,52,7,71,60,42,72,94,56,82,83,84,40,94,87,82,46],
[1,20,60,14,17,38,26,78,66,81,45,95,18,51,98,81,48,16,53,88,37,52,69,95,72,93,22,34,98,20,54,27,73,61,56,63,60,34,63],
[93,42,94,83,47,61,27,51,79,79,45,1,44,73,31,70,83,42,88,25,53,51,30,15,65,94,80,44,61,84,12,77,2,62,2,65,94,42,14,94],
[32,73,9,67,68,29,74,98,10,19,85,48,38,31,85,67,53,93,93,77,47,67,39,72,94,53,18,43,77,40,78,32,29,59,24,6,2,83,50,60,66],
[32,1,44,30,16,51,15,81,98,15,10,62,86,79,50,62,45,60,70,38,31,85,65,61,64,6,69,84,14,22,56,43,9,48,66,69,83,91,60,40,36,61],
[92,48,22,99,15,95,64,43,1,16,94,2,99,19,17,69,11,58,97,56,89,31,77,45,67,96,12,73,8,20,36,47,81,44,50,64,68,85,40,81,85,52,9],
[91,35,92,45,32,84,62,15,19,64,21,66,6,1,52,80,62,59,12,25,88,28,91,50,40,16,22,99,92,79,87,51,21,77,74,77,7,42,38,42,74,83,2,5],
[46,19,77,66,24,18,5,32,2,84,31,99,92,58,96,72,91,36,62,99,55,29,53,42,12,37,26,58,89,50,66,19,82,75,12,48,24,87,91,85,2,7,3,76,86],
[99,98,84,93,7,17,33,61,92,20,66,60,24,66,40,30,67,5,37,29,24,96,3,27,70,62,13,4,45,47,59,88,43,20,66,15,46,92,30,4,71,66,78,70,53,99],
[67,60,38,6,88,4,17,72,10,99,71,7,42,25,54,5,26,64,91,50,45,71,6,30,67,48,69,82,8,56,80,67,18,46,66,63,1,20,8,80,47,7,91,16,3,79,87],
[18,54,78,49,80,48,77,40,68,23,60,88,58,80,33,57,11,69,55,53,64,2,94,49,60,92,16,35,81,21,82,96,25,24,96,18,2,5,49,3,50,77,6,32,84,27,18,38],
[68,1,50,4,3,21,42,94,53,24,89,5,92,26,52,36,68,11,85,1,4,42,2,45,15,6,50,4,53,73,25,74,81,88,98,21,67,84,79,97,99,20,95,4,40,46,2,58,87],
[94,10,2,78,88,52,21,3,88,60,6,53,49,71,20,91,12,65,7,49,21,22,11,41,58,99,36,16,9,48,17,24,52,36,23,15,72,16,84,56,2,99,43,76,81,71,29,39,49,17],
[64,39,59,84,86,16,17,66,3,9,43,6,64,18,63,29,68,6,23,7,87,14,26,35,17,12,98,41,53,64,78,18,98,27,28,84,80,67,75,62,10,11,76,90,54,10,5,54,41,39,66],
[43,83,18,37,32,31,52,29,95,47,8,76,35,11,4,53,35,43,34,10,52,57,12,36,20,39,40,55,78,44,7,31,38,26,8,15,56,88,86,1,52,62,10,24,32,5,60,65,53,28,57,99],
[3,50,3,52,7,73,49,92,66,80,1,46,8,67,25,36,73,93,7,42,25,53,13,96,76,83,87,90,54,89,78,22,78,91,73,51,69,9,79,94,83,53,9,40,69,62,10,79,49,47,3,81,30],
[71,54,73,33,51,76,59,54,79,37,56,45,84,17,62,21,98,69,41,95,65,24,39,37,62,3,24,48,54,64,46,82,71,78,33,67,9,16,96,68,52,74,79,68,32,21,13,78,96,60,9,69,20,36],
[73,26,21,44,46,38,17,83,65,98,7,23,52,46,61,97,33,13,60,31,70,15,36,77,31,58,56,93,75,68,21,36,69,53,90,75,25,82,39,50,65,94,29,30,11,33,11,13,96,2,56,47,7,49,2],
[76,46,73,30,10,20,60,70,14,56,34,26,37,39,48,24,55,76,84,91,39,86,95,61,50,14,53,93,64,67,37,31,10,84,42,70,48,20,10,72,60,61,84,79,69,65,99,73,89,25,85,48,92,56,97,16],
[3,14,80,27,22,30,44,27,67,75,79,32,51,54,81,29,65,14,19,4,13,82,4,91,43,40,12,52,29,99,7,76,60,25,1,7,61,71,37,92,40,47,99,66,57,1,43,44,22,40,53,53,9,69,26,81,7],
[49,80,56,90,93,87,47,13,75,28,87,23,72,79,32,18,27,20,28,10,37,59,21,18,70,4,79,96,3,31,45,71,81,6,14,18,17,5,31,50,92,79,23,47,9,39,47,91,43,54,69,47,42,95,62,46,32,85],
[37,18,62,85,87,28,64,5,77,51,47,26,30,65,5,70,65,75,59,80,42,52,25,20,44,10,92,17,71,95,52,14,77,13,24,55,11,65,26,91,1,30,63,15,49,48,41,17,67,47,3,68,20,90,98,32,4,40,68],
[90,51,58,60,6,55,23,68,5,19,76,94,82,36,96,43,38,90,87,28,33,83,5,17,70,83,96,93,6,4,78,47,80,6,23,84,75,23,87,72,99,14,50,98,92,38,90,64,61,58,76,94,36,66,87,80,51,35,61,38],
[57,95,64,6,53,36,82,51,40,33,47,14,7,98,78,65,39,58,53,6,50,53,4,69,40,68,36,69,75,78,75,60,3,32,39,24,74,47,26,90,13,40,44,71,90,76,51,24,36,50,25,45,70,80,61,80,61,43,90,64,11],
[18,29,86,56,68,42,79,10,42,44,30,12,96,18,23,18,52,59,2,99,67,46,60,86,43,38,55,17,44,93,42,21,55,14,47,34,55,16,49,24,23,29,96,51,55,10,46,53,27,92,27,46,63,57,30,65,43,27,21,20,24,83],
[81,72,93,19,69,52,48,1,13,83,92,69,20,48,69,59,20,62,5,42,28,89,90,99,32,72,84,17,8,87,36,3,60,31,36,36,81,26,97,36,48,54,56,56,27,16,91,8,23,11,87,99,33,47,2,14,44,73,70,99,43,35,33],
[90,56,61,86,56,12,70,59,63,32,1,15,81,47,71,76,95,32,65,80,54,70,34,51,40,45,33,4,64,55,78,68,88,47,31,47,68,87,3,84,23,44,89,72,35,8,31,76,63,26,90,85,96,67,65,91,19,14,17,86,4,71,32,95],
[37,13,4,22,64,37,37,28,56,62,86,33,7,37,10,44,52,82,52,6,19,52,57,75,90,26,91,24,6,21,14,67,76,30,46,14,35,89,89,41,3,64,56,97,87,63,22,34,3,79,17,45,11,53,25,56,96,61,23,18,63,31,37,37,47],
[77,23,26,70,72,76,77,4,28,64,71,69,14,85,96,54,95,48,6,62,99,83,86,77,97,75,71,66,30,19,57,90,33,1,60,61,14,12,90,99,32,77,56,41,18,14,87,49,10,14,90,64,18,50,21,74,14,16,88,5,45,73,82,47,74,44],
[22,97,41,13,34,31,54,61,56,94,3,24,59,27,98,77,4,9,37,40,12,26,87,9,71,70,7,18,64,57,80,21,12,71,83,94,60,39,73,79,73,19,97,32,64,29,41,7,48,84,85,67,12,74,95,20,24,52,41,67,56,61,29,93,35,72,69],
[72,23,63,66,1,11,7,30,52,56,95,16,65,26,83,90,50,74,60,18,16,48,43,77,37,11,99,98,30,94,91,26,62,73,45,12,87,73,47,27,1,88,66,99,21,41,95,80,2,53,23,32,61,48,32,43,43,83,14,66,95,91,19,81,80,67,25,88],
[8,62,32,18,92,14,83,71,37,96,11,83,39,99,5,16,23,27,10,67,2,25,44,11,55,31,46,64,41,56,44,74,26,81,51,31,45,85,87,9,81,95,22,28,76,69,46,48,64,87,67,76,27,89,31,11,74,16,62,3,60,94,42,47,9,34,94,93,72],
[56,18,90,18,42,17,42,32,14,86,6,53,33,95,99,35,29,15,44,20,49,59,25,54,34,59,84,21,23,54,35,90,78,16,93,13,37,88,54,19,86,67,68,55,66,84,65,42,98,37,87,56,33,28,58,38,28,38,66,27,52,21,81,15,8,22,97,32,85,27],
[91,53,40,28,13,34,91,25,1,63,50,37,22,49,71,58,32,28,30,18,68,94,23,83,63,62,94,76,80,41,90,22,82,52,29,12,18,56,10,8,35,14,37,57,23,65,67,40,72,39,93,39,70,89,40,34,7,46,94,22,20,5,53,64,56,30,5,56,61,88,27],
[23,95,11,12,37,69,68,24,66,10,87,70,43,50,75,7,62,41,83,58,95,93,89,79,45,39,2,22,5,22,95,43,62,11,68,29,17,40,26,44,25,71,87,16,70,85,19,25,59,94,90,41,41,80,61,70,55,60,84,33,95,76,42,63,15,9,3,40,38,12,3,32],
[9,84,56,80,61,55,85,97,16,94,82,94,98,57,84,30,84,48,93,90,71,5,95,90,73,17,30,98,40,64,65,89,7,79,9,19,56,36,42,30,23,69,73,72,7,5,27,61,24,31,43,48,71,84,21,28,26,65,65,59,65,74,77,20,10,81,61,84,95,8,52,23,70],
[47,81,28,9,98,51,67,64,35,51,59,36,92,82,77,65,80,24,72,53,22,7,27,10,21,28,30,22,48,82,80,48,56,20,14,43,18,25,50,95,90,31,77,8,9,48,44,80,90,22,93,45,82,17,13,96,25,26,8,73,34,99,6,49,24,6,83,51,40,14,15,10,25,1],
[54,25,10,81,30,64,24,74,75,80,36,75,82,60,22,69,72,91,45,67,3,62,79,54,89,74,44,83,64,96,66,73,44,30,74,50,37,5,9,97,70,1,60,46,37,91,39,75,75,18,58,52,72,78,51,81,86,52,8,97,1,46,43,66,98,62,81,18,70,93,73,8,32,46,34],
[96,80,82,7,59,71,92,53,19,20,88,66,3,26,26,10,24,27,50,82,94,73,63,8,51,33,22,45,19,13,58,33,90,15,22,50,36,13,55,6,35,47,82,52,33,61,36,27,28,46,98,14,73,20,73,32,16,26,80,53,47,66,76,38,94,45,2,1,22,52,47,96,64,58,52,39],
[88,46,23,39,74,63,81,64,20,90,33,33,76,55,58,26,10,46,42,26,74,74,12,83,32,43,9,2,73,55,86,54,85,34,28,23,29,79,91,62,47,41,82,87,99,22,48,90,20,5,96,75,95,4,43,28,81,39,81,1,28,42,78,25,39,77,90,57,58,98,17,36,73,22,63,74,51],
[29,39,74,94,95,78,64,24,38,86,63,87,93,6,70,92,22,16,80,64,29,52,20,27,23,50,14,13,87,15,72,96,81,22,8,49,72,30,70,24,79,31,16,64,59,21,89,34,96,91,48,76,43,53,88,1,57,80,23,81,90,79,58,1,80,87,17,99,86,90,72,63,32,69,14,28,88,69],
[37,17,71,95,56,93,71,35,43,45,4,98,92,94,84,96,11,30,31,27,31,60,92,3,48,5,98,91,86,94,35,90,90,8,48,19,33,28,68,37,59,26,65,96,50,68,22,7,9,49,34,31,77,49,43,6,75,17,81,87,61,79,52,26,27,72,29,50,7,98,86,1,17,10,46,64,24,18,56],
[51,30,25,94,88,85,79,91,40,33,63,84,49,67,98,92,15,26,75,19,82,5,18,78,65,93,61,48,91,43,59,41,70,51,22,15,92,81,67,91,46,98,11,11,65,31,66,10,98,65,83,21,5,56,5,98,73,67,46,74,69,34,8,30,5,52,7,98,32,95,30,94,65,50,24,63,28,81,99,57],
[19,23,61,36,9,89,71,98,65,17,30,29,89,26,79,74,94,11,44,48,97,54,81,55,39,66,69,45,28,47,13,86,15,76,74,70,84,32,36,33,79,20,78,14,41,47,89,28,81,5,99,66,81,86,38,26,6,25,13,60,54,55,23,53,27,5,89,25,23,11,13,54,59,54,56,34,16,24,53,44,6],
[13,40,57,72,21,15,60,8,4,19,11,98,34,45,9,97,86,71,3,15,56,19,15,44,97,31,90,4,87,87,76,8,12,30,24,62,84,28,12,85,82,53,99,52,13,94,6,65,97,86,9,50,94,68,69,74,30,67,87,94,63,7,78,27,80,36,69,41,6,92,32,78,37,82,30,5,18,87,99,72,19,99],
[44,20,55,77,69,91,27,31,28,81,80,27,2,7,97,23,95,98,12,25,75,29,47,71,7,47,78,39,41,59,27,76,13,15,66,61,68,35,69,86,16,53,67,63,99,85,41,56,8,28,33,40,94,76,90,85,31,70,24,65,84,65,99,82,19,25,54,37,21,46,33,2,52,99,51,33,26,4,87,2,8,18,96],
[54,42,61,45,91,6,64,79,80,82,32,16,83,63,42,49,19,78,65,97,40,42,14,61,49,34,4,18,25,98,59,30,82,72,26,88,54,36,21,75,3,88,99,53,46,51,55,78,22,94,34,40,68,87,84,25,30,76,25,8,92,84,42,61,40,38,9,99,40,23,29,39,46,55,10,90,35,84,56,70,63,23,91,39],
[52,92,3,71,89,7,9,37,68,66,58,20,44,92,51,56,13,71,79,99,26,37,2,6,16,67,36,52,58,16,79,73,56,60,59,27,44,77,94,82,20,50,98,33,9,87,94,37,40,83,64,83,58,85,17,76,53,2,83,52,22,27,39,20,48,92,45,21,9,42,24,23,12,37,52,28,50,78,79,20,86,62,73,20,59],
[54,96,80,15,91,90,99,70,10,9,58,90,93,50,81,99,54,38,36,10,30,11,35,84,16,45,82,18,11,97,36,43,96,79,97,65,40,48,23,19,17,31,64,52,65,65,37,32,65,76,99,79,34,65,79,27,55,33,3,1,33,27,61,28,66,8,4,70,49,46,48,83,1,45,19,96,13,81,14,21,31,79,93,85,50,5],
[92,92,48,84,59,98,31,53,23,27,15,22,79,95,24,76,5,79,16,93,97,89,38,89,42,83,2,88,94,95,82,21,1,97,48,39,31,78,9,65,50,56,97,61,1,7,65,27,21,23,14,15,80,97,44,78,49,35,33,45,81,74,34,5,31,57,9,38,94,7,69,54,69,32,65,68,46,68,78,90,24,28,49,51,45,86,35],
[41,63,89,76,87,31,86,9,46,14,87,82,22,29,47,16,13,10,70,72,82,95,48,64,58,43,13,75,42,69,21,12,67,13,64,85,58,23,98,9,37,76,5,22,31,12,66,50,29,99,86,72,45,25,10,28,19,6,90,43,29,31,67,79,46,25,74,14,97,35,76,37,65,46,23,82,6,22,30,76,93,66,94,17,96,13,20,72],
[63,40,78,8,52,9,90,41,70,28,36,14,46,44,85,96,24,52,58,15,87,37,5,98,99,39,13,61,76,38,44,99,83,74,90,22,53,80,56,98,30,51,63,39,44,30,91,91,4,22,27,73,17,35,53,18,35,45,54,56,27,78,48,13,69,36,44,38,71,25,30,56,15,22,73,43,32,69,59,25,93,83,45,11,34,94,44,39,92],
[12,36,56,88,13,96,16,12,55,54,11,47,19,78,17,17,68,81,77,51,42,55,99,85,66,27,81,79,93,42,65,61,69,74,14,1,18,56,12,1,58,37,91,22,42,66,83,25,19,4,96,41,25,45,18,69,96,88,36,93,10,12,98,32,44,83,83,4,72,91,4,27,73,7,34,37,71,60,59,31,1,54,54,44,96,93,83,36,4,45],
[30,18,22,20,42,96,65,79,17,41,55,69,94,81,29,80,91,31,85,25,47,26,43,49,2,99,34,67,99,76,16,14,15,93,8,32,99,44,61,77,67,50,43,55,87,55,53,72,17,46,62,25,50,99,73,5,93,48,17,31,70,80,59,9,44,59,45,13,74,66,58,94,87,73,16,14,85,38,74,99,64,23,79,28,71,42,20,37,82,31,23],
[51,96,39,65,46,71,56,13,29,68,53,86,45,33,51,49,12,91,21,21,76,85,2,17,98,15,46,12,60,21,88,30,92,83,44,59,42,50,27,88,46,86,94,73,45,54,23,24,14,10,94,21,20,34,23,51,4,83,99,75,90,63,60,16,22,33,83,70,11,32,10,50,29,30,83,46,11,5,31,17,86,42,49,1,44,63,28,60,7,78,95,40],
[44,61,89,59,4,49,51,27,69,71,46,76,44,4,9,34,56,39,15,6,94,91,75,90,65,27,56,23,74,6,23,33,36,69,14,39,5,34,35,57,33,22,76,46,56,10,61,65,98,9,16,69,4,62,65,18,99,76,49,18,72,66,73,83,82,40,76,31,89,91,27,88,17,35,41,35,32,51,32,67,52,68,74,85,80,57,7,11,62,66,47,22,67],
[65,37,19,97,26,17,16,24,24,17,50,37,64,82,24,36,32,11,68,34,69,31,32,89,79,93,96,68,49,90,14,23,4,4,67,99,81,74,70,74,36,96,68,9,64,39,88,35,54,89,96,58,66,27,88,97,32,14,6,35,78,20,71,6,85,66,57,2,58,91,72,5,29,56,73,48,86,52,9,93,22,57,79,42,12,1,31,68,17,59,63,76,7,77],
[73,81,14,13,17,20,11,9,1,83,8,85,91,70,84,63,62,77,37,7,47,1,59,95,39,69,39,21,99,9,87,2,97,16,92,36,74,71,90,66,33,73,73,75,52,91,11,12,26,53,5,26,26,48,61,50,90,65,1,87,42,47,74,35,22,73,24,26,56,70,52,5,48,41,31,18,83,27,21,39,80,85,26,8,44,2,71,7,63,22,5,52,19,8,20],
[17,25,21,11,72,93,33,49,64,23,53,82,3,13,91,65,85,2,40,5,42,31,77,42,5,36,6,54,4,58,7,76,87,83,25,57,66,12,74,33,85,37,74,32,20,69,3,97,91,68,82,44,19,14,89,28,85,85,80,53,34,87,58,98,88,78,48,65,98,40,11,57,10,67,70,81,60,79,74,72,97,59,79,47,30,20,54,80,89,91,14,5,33,36,79,39],
[60,85,59,39,60,7,57,76,77,92,6,35,15,72,23,41,45,52,95,18,64,79,86,53,56,31,69,11,91,31,84,50,44,82,22,81,41,40,30,42,30,91,48,94,74,76,64,58,74,25,96,57,14,19,3,99,28,83,15,75,99,1,89,85,79,50,3,95,32,67,44,8,7,41,62,64,29,20,14,76,26,55,48,71,69,66,19,72,44,25,14,1,48,74,12,98,7],
[64,66,84,24,18,16,27,48,20,14,47,69,30,86,48,40,23,16,61,21,51,50,26,47,35,33,91,28,78,64,43,68,4,79,51,8,19,60,52,95,6,68,46,86,35,97,27,58,4,65,30,58,99,12,12,75,91,39,50,31,42,64,70,4,46,7,98,73,98,93,37,89,77,91,64,71,64,65,66,21,78,62,81,74,42,20,83,70,73,95,78,45,92,27,34,53,71,15],
[30,11,85,31,34,71,13,48,5,14,44,3,19,67,23,73,19,57,6,90,94,72,57,69,81,62,59,68,88,57,55,69,49,13,7,87,97,80,89,5,71,5,5,26,38,40,16,62,45,99,18,38,98,24,21,26,62,74,69,4,85,57,77,35,58,67,91,79,79,57,86,28,66,34,72,51,76,78,36,95,63,90,8,78,47,63,45,31,22,70,52,48,79,94,15,77,61,67,68],
[23,33,44,81,80,92,93,75,94,88,23,61,39,76,22,3,28,94,32,6,49,65,41,34,18,23,8,47,62,60,3,63,33,13,80,52,31,54,73,43,70,26,16,69,57,87,83,31,3,93,70,81,47,95,77,44,29,68,39,51,56,59,63,7,25,70,7,77,43,53,64,3,94,42,95,39,18,1,66,21,16,97,20,50,90,16,70,10,95,69,29,6,25,61,41,26,15,59,63,35]]
nexty=[]
prevy=[tri[0][0]]
for row in tri[1:]:
nexty=[]
nexty.append(row[0]+prevy[0])
for index in xrange(1, len(row)-1):
nexty.append(row[index] + max(prevy[index], prevy[index-1]))
nexty.append(row[-1]+prevy[-1])
prevy=nexty
print max(nexty)
|
[
"erf@mit.edu"
] |
erf@mit.edu
|
2b23e8b1de5200d30eec18dbc1e4983438441aed
|
d8ac8295abaa6066d03cdcfbc964fbb02a01bc48
|
/Untitled.py
|
b8af19ee270c3313a42a8b76f686afadb023d110
|
[] |
no_license
|
Anna-Ilinichna/lesson1
|
9942a5cf3fe399ebdb93082d0ae10f4635e394af
|
e863eab753d09e1bc35c02e62ea7124a4da23e98
|
refs/heads/master
| 2020-09-16T01:00:35.373449
| 2019-11-23T14:39:33
| 2019-11-23T14:39:33
| 223,603,741
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 48
|
py
|
x = 0
while x < 10:
print(x)
x += 1
|
[
"ASavinov@its.jnj.com"
] |
ASavinov@its.jnj.com
|
2ba81ad791d971b0cab7445ff15f1d3d922e19c1
|
8fa87ceafa6ee0c521f80c205772512d7ecc482b
|
/frames/industry/variety_data_ui.py
|
201439e3ed60d81fbd33588174167a9404ae8c06
|
[] |
no_license
|
zizle/FuturesAssistantClient
|
fe7a7f457dffc9a5771abc0d4a67ce584999b052
|
3519657f5f352f137b7a7c7a51d7ca43fbdea4f9
|
refs/heads/main
| 2023-06-03T00:24:45.540553
| 2020-12-31T07:48:57
| 2020-12-31T07:48:57
| 304,493,799
| 0
| 0
| null | 2021-05-25T06:40:03
| 2020-10-16T02:01:57
|
Python
|
UTF-8
|
Python
| false
| false
| 3,351
|
py
|
# _*_ coding:utf-8 _*_
# @File : variety_data_ui.py
# @Time : 2020-09-03 8:29
# @Author: zizle
from PyQt5.QtWidgets import (QWidget, QSplitter, QHBoxLayout, QTabWidget, QTableWidget, QFrame, QPushButton, QAbstractItemView,
QHeaderView)
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QMargins, Qt
from components.variety_tree import VarietyTree
class VarietyDataUI(QWidget):
def __init__(self, *args, **kwargs):
super(VarietyDataUI, self).__init__(*args, **kwargs)
main_layout = QHBoxLayout()
main_layout.setContentsMargins(QMargins(0, 0, 0, 0))
main_splitter = QSplitter(self)
self.variety_tree = VarietyTree()
main_splitter.addWidget(self.variety_tree)
# 右侧Tab
self.tab = QTabWidget(self)
self.tab.setDocumentMode(True)
self.tab.setTabShape(QTabWidget.Triangular)
# 数据列表
self.sheet_table = QTableWidget(self)
self.sheet_table.setFrameShape(QFrame.NoFrame)
self.sheet_table.setFocusPolicy(Qt.NoFocus)
self.sheet_table.verticalHeader().hide()
self.sheet_table.setEditTriggers(QHeaderView.NoEditTriggers)
self.sheet_table.setSelectionMode(QAbstractItemView.SingleSelection)
self.sheet_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.sheet_table.setAlternatingRowColors(True)
self.sheet_table.setColumnCount(5)
self.sheet_table.setHorizontalHeaderLabels(["序号", "标题", "数据起始", "数据结束", "图形"])
self.sheet_table.verticalHeader().setDefaultSectionSize(25) # 设置行高(与下行代码同时才生效)
self.sheet_table.verticalHeader().setMinimumSectionSize(25)
self.sheet_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
self.sheet_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
self.sheet_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
# 图形列表
self.chart_container = QWebEngineView(self)
self.tab.addTab(self.chart_container, "图形库")
self.tab.addTab(self.sheet_table, "数据库")
main_splitter.addWidget(self.tab)
main_splitter.setStretchFactor(1, 4)
main_splitter.setStretchFactor(2, 6)
main_splitter.setHandleWidth(1)
main_layout.addWidget(main_splitter)
self.setLayout(main_layout)
self.tab.tabBar().setObjectName("tabBar")
self.sheet_table.setObjectName("sheetTable")
self.sheet_table.horizontalHeader().setStyleSheet(
"QHeaderView::section{background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
"stop:0 #34adf3, stop: 0.5 #ccddff,stop: 0.6 #ccddff, stop:1 #34adf3);"
"border:1px solid rgb(201,202,202);border-left:none;"
"min-height:25px;min-width:40px;font-weight:bold;font-size:13px};"
)
self.setStyleSheet(
"#tabBar::tab{min-height:20px;}"
"#sheetTable{background-color:rgb(240,240,240);"
"selection-background-color:qlineargradient(x1:0,y1:0, x2:0, y2:1,"
"stop:0 #cccccc,stop:0.5 white,stop:0.6 white,stop: 1 #cccccc);"
"alternate-background-color:rgb(245,250,248);}"
)
|
[
"462894999@qq.com"
] |
462894999@qq.com
|
65530f5fdde5c9b8f31a5c0499da3baa520894e5
|
20c20938e201a0834ccf8b5f2eb5d570d407ad15
|
/abc081/abc081_b/7051715.py
|
31ad7df4c069615864b37344e4109efbf6356623
|
[] |
no_license
|
kouhei-k/atcoder_submissions
|
8e1a1fb30c38e0d443b585a27c6d134bf1af610a
|
584b4fd842ccfabb16200998fe6652f018edbfc5
|
refs/heads/master
| 2021-07-02T21:20:05.379886
| 2021-03-01T12:52:26
| 2021-03-01T12:52:26
| 227,364,764
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 280
|
py
|
N = int(input())
A = list(map(int, input().split()))
flag = True
ans = 0
while(1):
for i in range(N):
if A[i] % 2 != 0:
flag = False
break
if flag:
A = list(map(lambda x:x/2, A))
ans += 1
else:
break
print(ans)
|
[
"kouhei.k.0116@gmail.com"
] |
kouhei.k.0116@gmail.com
|
5059b702d963a2accace356f9a82e511a68e85a1
|
9e549ee54faa8b037f90eac8ecb36f853e460e5e
|
/venv/lib/python3.6/site-packages/dominate/document.py
|
8ca9ceba218b23afe46162725b052e9e6bffc55f
|
[
"MIT"
] |
permissive
|
aitoehigie/britecore_flask
|
e8df68e71dd0eac980a7de8c0f20b5a5a16979fe
|
eef1873dbe6b2cc21f770bc6dec783007ae4493b
|
refs/heads/master
| 2022-12-09T22:07:45.930238
| 2019-05-15T04:10:37
| 2019-05-15T04:10:37
| 177,354,667
| 0
| 0
|
MIT
| 2022-12-08T04:54:09
| 2019-03-24T00:38:20
|
Python
|
UTF-8
|
Python
| false
| false
| 2,339
|
py
|
__license__ = """
This file is part of Dominate.
Dominate is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Dominate is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with Dominate. If not, see
<http://www.gnu.org/licenses/>.
"""
from . import tags
try:
basestring = basestring
except NameError: # py3
basestring = str
unicode = str
class document(tags.html):
tagname = "html"
def __init__(self, title="Dominate", doctype="<!DOCTYPE html>", request=None):
"""
Creates a new document instance. Accepts `title`, `doctype`, and `request` keyword arguments.
"""
super(document, self).__init__()
self.doctype = doctype
self.head = super(document, self).add(tags.head())
self.body = super(document, self).add(tags.body())
self.title_node = self.head.add(tags.title(title))
self._entry = self.body
def get_title(self):
return self.title_node.text
def set_title(self, title):
if isinstance(title, basestring):
self.title_node.text = title
else:
self.head.remove(self.title_node)
self.head.add(title)
self.title_node = title
title = property(get_title, set_title)
def add(self, *args):
"""
Adding tags to a document appends them to the <body>.
"""
return self._entry.add(*args)
def render(self, *args, **kwargs):
"""
Creates a <title> tag if not present and renders the DOCTYPE and tag tree.
"""
r = []
# Validates the tag tree and adds the doctype if one was set
if self.doctype:
r.append(self.doctype)
r.append("\n")
r.append(super(document, self).render(*args, **kwargs))
return u"".join(r)
__str__ = __unicode__ = render
def __repr__(self):
return '<dominate.document "%s">' % self.title
|
[
"aitoehigie@gmail.com"
] |
aitoehigie@gmail.com
|
09bc1405d9d1d362e1fc04224eed43244244b8af
|
8eae1f18b292e2a13508d2b61267b4161246245d
|
/Week1/forExe2.py
|
b2aa9c18e37363d17b316360d7ff46505e45cb12
|
[] |
no_license
|
iamieht/MITx-6.00.1x
|
1649b27edf456ec4573e0d1fb8e2c5f4efbcb20b
|
67590d12c9074a6a704aee744d23897843a4521b
|
refs/heads/master
| 2020-09-01T19:16:50.180993
| 2019-11-01T17:55:55
| 2019-11-01T17:55:55
| 219,035,441
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 85
|
py
|
#Exercise: for exercise 2
print("Hello!")
for num in range(10,0,-2):
print(num)
|
[
"iamieht@gmail.com"
] |
iamieht@gmail.com
|
670d64b2a61f2774107244120ead6a736d6b1710
|
f54716bfb0847ae03387dd30753eae054edd0fa9
|
/employee/migrations/0003_auto_20210309_0608.py
|
b2f9b0fefa6c550fcf450b6c67e5642d2ccd1c98
|
[] |
no_license
|
ankitayan96/ankitayan96-PythonDjangoJWT
|
0cbf912f7b78fad22fe03f50c136e469115e7934
|
14ba6d81e1fb2e889f6beefffd0900010aad448a
|
refs/heads/master
| 2023-03-17T16:44:09.445903
| 2021-03-09T09:45:50
| 2021-03-09T09:45:50
| 345,951,280
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 398
|
py
|
# Generated by Django 3.1.7 on 2021-03-09 06:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('employee', '0002_remove_employee_password'),
]
operations = [
migrations.AlterField(
model_name='employee',
name='mobile',
field=models.IntegerField(max_length=10),
),
]
|
[
"ak28246@gmail.com"
] |
ak28246@gmail.com
|
601643cde921bc7510b83d3bd65b87b7a35f3194
|
d780df6e068ab8a0f8007acb68bc88554a9d5b50
|
/shipyard2/rules/images/examples/build.py
|
d65f2815a5eb9d4aae8cf494dddd5844ef4efca8
|
[
"MIT"
] |
permissive
|
clchiou/garage
|
ed3d314ceea487b46568c14b51e96b990a50ed6f
|
1d72863d3a5f5d620b170f4dd36f605e6b72054f
|
refs/heads/master
| 2023-08-27T13:57:14.498182
| 2023-08-15T07:09:57
| 2023-08-15T19:53:52
| 32,647,497
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,053
|
py
|
import foreman
from g1 import scripts
import shipyard2.rules.images
shipyard2.rules.images.define_image(
name='empty',
rules=[
'//bases:build',
],
)
shipyard2.rules.images.define_xar_image(
name='reqrep-client',
rules=[
'//python/g1/messaging:reqrep-client/build',
'reqrep-client/setup',
],
)
@foreman.rule('reqrep-client/setup')
@foreman.rule.depend('//bases:build')
def reqrep_client_setup(parameters):
del parameters # Unused.
shipyard2.rules.images.generate_exec_wrapper(
'usr/local/bin/reqrep-client',
'usr/local/bin/run-reqrep-client',
)
shipyard2.rules.images.define_image(
name='web-server',
rules=[
'//third-party/cpython:build',
'web-server/setup',
],
)
@foreman.rule('web-server/setup')
@foreman.rule.depend('//bases:build')
def web_server_setup(parameters):
del parameters # Unused.
with scripts.using_sudo():
scripts.mkdir('/srv/web')
scripts.cp(foreman.to_path('web-server/index.html'), '/srv/web')
|
[
"clchiou@gmail.com"
] |
clchiou@gmail.com
|
4fc0994c7a55b303cbc9687647431b87fea6ebdd
|
39356ce7ee611d660206d5992492ae76fee459e9
|
/flaskblog/errors/handlers.py
|
27149a68bf217663714fd6593a3d8da0613cfb9d
|
[] |
no_license
|
dip333/Blog-Post
|
af88fbfbfc40f52445d8d4e9efbe133d2c0d4609
|
71460d99cb23d3e815b66838f3fffa7cb7177ed6
|
refs/heads/master
| 2022-09-01T21:09:39.715024
| 2020-05-24T05:19:36
| 2020-05-24T05:19:36
| 266,471,767
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 398
|
py
|
rom flask import Blueprint, render_template
errors = Blueprint('errors', __name__)
@errors.app_errorhandler(404)
def error_404(error):
return render_template('errors/404.html'), 404
@errors.app_errorhandler(403)
def error_403(error):
return render_template('errors/403.html'), 403
@errors.app_errorhandler(500)
def error_500(error):
return render_template('errors/500.html'), 500
|
[
"sidip333@gmail.com"
] |
sidip333@gmail.com
|
dc29c130dc681a79099259bd24bb92a195e7e5ba
|
182e9a717c6f27e34b363b5cb470c47c15ed5173
|
/venv/Scripts/pip3-script.py
|
c567c829fb07c760d90f3aebcc6f66a1095de47c
|
[] |
no_license
|
rannrann/flask-tutorial
|
7975a4b323db975e8b9e15db745e7c9b126a62d7
|
0f35363354d52a21c932f7bced042dc0f964e1da
|
refs/heads/master
| 2022-12-08T09:15:41.404790
| 2020-01-07T06:39:05
| 2020-01-07T06:39:05
| 232,253,212
| 0
| 0
| null | 2022-12-08T03:24:04
| 2020-01-07T05:55:40
|
Python
|
UTF-8
|
Python
| false
| false
| 413
|
py
|
#!E:\pycharm_professional_projects\Flask\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3'
__requires__ = 'pip==10.0.1'
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==10.0.1', 'console_scripts', 'pip3')()
)
|
[
"239124260@qq.com"
] |
239124260@qq.com
|
c932d134c670f8bfb24d23db32f2cd1545dc2b22
|
48f005a65563d23c8159355c1c09da6b5412e5ff
|
/comm.py
|
f3daae8e3c9ed583f02b14bf107956d1d18ea726
|
[] |
no_license
|
ShreyasJamadagni/Feral
|
06aad2634c00a5e91169ee18dbcd3e8b4bbec185
|
8fa620eaabdb3cf06111ee0156e1d714b256d23a
|
refs/heads/master
| 2021-09-18T11:40:25.889903
| 2018-07-13T14:10:04
| 2018-07-13T14:10:04
| 104,558,005
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 696
|
py
|
class Commands:
local = locals()
def default(options):
print(options, ", Default")
return True
# calling it 'prin' as 'print' messes with python
def output(options):
# It shouldn't request for a string if the option is invalid.
print(options, ", Output")
return True
def quit(options):
return False
def configure(options):
print(options, ", configure")
return True
def info(options):
print(options)
print("Version 0.1.0")
print("Valid commands are: configure , info , print , quit .")
return True
def load(options):
print(options)
return True
|
[
"shreygj@gmail.com"
] |
shreygj@gmail.com
|
e8c34e41273571df05ebfa8d3757ea3b860d9567
|
2e83e004d8a69a773d1e305152edd16e4ea35ed8
|
/students/tao_ye/lesson07/test_html_render.py
|
88125104f0002662179e25f7dc2330b92e4a9c5a
|
[] |
no_license
|
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
|
9b170efbab5efedaba8cf541e8fc42c5c8c0934d
|
76224d0fb871d0bf0b838f3fccf01022edd70f82
|
refs/heads/master
| 2021-06-16T20:14:29.754453
| 2021-02-25T23:03:19
| 2021-02-25T23:03:19
| 161,077,720
| 19
| 182
| null | 2021-02-25T23:03:19
| 2018-12-09T20:18:25
|
Python
|
UTF-8
|
Python
| false
| false
| 10,803
|
py
|
"""
test code for html_render.py
This is just a start -- you will need more tests!
"""
import io
import pytest
# import * is often bad form, but makes it easier to test everything in a module.
from html_render import *
# utility function for testing render methods
# needs to be used in multiple tests, so we write it once here.
def render_result(element, ind=""):
"""
calls the element's render method, and returns what got rendered as a
string
"""
# the StringIO object is a "file-like" object -- something that
# provides the methods of a file, but keeps everything in memory
# so it can be used to test code that writes to a file, without
# having to actually write to disk.
outfile = io.StringIO()
# this so the tests will work before we tackle indentation
if ind:
element.render(outfile, ind)
else:
element.render(outfile)
return outfile.getvalue()
########
# Step 1
########
def test_init():
"""
This only tests that it can be initialized with and without
some content -- but it's a start
"""
e = Element()
e = Element("this is some text")
def test_append():
"""
This tests that you can append text
It doesn't test if it works --
that will be covered by the render test later
"""
e = Element("this is some text")
e.append("some more text")
def test_render_element():
"""
Tests whether the Element can render two pieces of text
So it is also testing that the append method works correctly.
It is not testing whether indentation or line feeds are correct.
"""
e = Element("this is some text")
e.append("and this is some more text")
# This uses the render_results utility above
file_contents = render_result(e).strip()
# making sure the content got in there.
assert("this is some text") in file_contents
assert("and this is some more text") in file_contents
# make sure it's in the right order
assert file_contents.index("this is") < file_contents.index("and this")
# making sure the opening and closing tags are right.
assert file_contents.startswith("<html>")
assert file_contents.endswith("</html>")
# Uncomment this one after you get the one above to pass
# Does it pass right away?
def test_render_element2():
"""
Tests whether the Element can render two pieces of text
So it is also testing that the append method works correctly.
It is not testing whether indentation or line feeds are correct.
"""
e = Element()
e.append("this is some text")
e.append("and this is some more text")
# This uses the render_results utility above
file_contents = render_result(e).strip()
# making sure the content got in there.
assert("this is some text") in file_contents
assert("and this is some more text") in file_contents
# make sure it's in the right order
assert file_contents.index("this is") < file_contents.index("and this")
# making sure the opening and closing tags are right.
assert file_contents.startswith("<html>")
assert file_contents.endswith("</html>")
# # ########
# # # Step 2
# # ########
# # tests for the new tags
def test_html():
e = Html("this is some text")
e.append("and this is some more text")
file_contents = render_result(e).strip()
assert("this is some text") in file_contents
assert("and this is some more text") in file_contents
print(file_contents)
assert file_contents.endswith("</html>")
def test_body():
e = Body("this is some text")
e.append("and this is some more text")
file_contents = render_result(e).strip()
assert("this is some text") in file_contents
assert("and this is some more text") in file_contents
assert file_contents.startswith("<body>")
assert file_contents.endswith("</body>")
def test_p():
e = P("this is some text")
e.append("and this is some more text")
file_contents = render_result(e).strip()
assert("this is some text") in file_contents
assert("and this is some more text") in file_contents
assert file_contents.startswith("<p>")
assert file_contents.endswith("</p>")
def test_sub_element():
"""
tests that you can add another element and still render properly
"""
page = Html()
page.append("some plain text.")
page.append(P("A simple paragraph of text"))
page.append("Some more plain text.")
file_contents = render_result(page)
print(file_contents) # so we can see it if the test fails
# note: The previous tests should make sure that the tags are getting
# properly rendered, so we don't need to test that here.
assert "some plain text" in file_contents
assert "A simple paragraph of text" in file_contents
assert "Some more plain text." in file_contents
assert "some plain text" in file_contents
# but make sure the embedded element's tags get rendered!
assert "<p>" in file_contents
assert "</p>" in file_contents
########
# Step 3
########
def test_head_one_line_tag():
"""
test head, title, one line tags
"""
page = Html()
head = Head()
head.append(Title("PythonClass = Revision 1087:"))
page.append(head)
file_contents = render_result(page)
print(file_contents) # so we can see it if the test fails
assert "PythonClass = Revision 1087:" in file_contents
assert "<head>" in file_contents
assert "</head>" in file_contents
assert "<title>" in file_contents
assert "</title>" in file_contents
########
# Step 4
########
def test_kwargs_in_constructor():
"""
test the class constructor to accept a set of attributes
"""
page = Html()
body = Body()
body.append(P("Here is a paragraph of text -- there could be more of them, "
"but this is enough to show that we can do some text",
style="text-align: center; font-style: oblique;"))
page.append(body)
file_contents = render_result(page)
print(file_contents) # so we can see it if the test fails
assert "Here is a paragraph of text" in file_contents
assert '<p style="text-align: center; font-style: oblique;">' in file_contents
########
# Step 5
########
def test_self_closing_tag():
"""
test self-closing-tags, such as <hr />, <br />
"""
page = Html()
body = Body()
body.append(Hr(width=400))
page.append(body)
file_contents = render_result(page)
print(file_contents) # so we can see it if the test fails
assert '<hr width="400" />' in file_contents
########
# Step 6
########
def test_link_element():
"""
test link element, such as <a href="http://google.com">link</a>
"""
page = Html()
body = Body()
body.append("And this is a ")
body.append(A("http://google.com", "link to google"))
page.append(body)
file_contents = render_result(page)
print(file_contents) # so we can see it if the test fails
assert '<a href="http://google.com">' in file_contents
assert '</a>' in file_contents
########
# Step 7
########
def test_ul_li_header():
"""
test <ul>, <li>, and <h?> tags
"""
page = Html()
body = Body()
body.append(H(2, "PythonClass - Class 6 example"))
list = Ul(id="TheList", style="line-height:200%")
list.append(Li("The first item in a list"))
list.append(Li("This is the second item", style="color: red"))
body.append(list)
page.append(body)
file_contents = render_result(page)
print(file_contents) # so we can see it if the test fails
assert '<h2>PythonClass - Class 6 example</h2>' in file_contents
assert '<ul id="TheList" style="line-height:200%">' in file_contents
assert '<li>' in file_contents
assert "The first item in a list" in file_contents
assert '</li>' in file_contents
assert file_contents.index("<li>") < file_contents.index("The first item")
assert file_contents.index("The first item") < file_contents.index("</li>")
assert '<li style="color: red">' in file_contents
########
# Step 8
########
def test_doctype_meta():
"""
test <!DOCTYPE html> and <meta>
"""
page = Html()
head = Head()
head.append(Meta(charset="UTF-8"))
head.append(Title("PythonClass = Revision 1087:"))
page.append(head)
file_contents = render_result(page)
print(file_contents) # so we can see it if the test fails
assert '<!DOCTYPE html>' in file_contents
assert '<meta charset="UTF-8" />' in file_contents
# #####################
# # indentation testing
# # Uncomment for Step 9 -- adding indentation
# #####################
def test_indent():
"""
Tests that the indentation gets passed through to the renderer
"""
html = Html("some content")
file_contents = render_result(html, ind=" ").rstrip() #remove the end newline
print(file_contents)
lines = file_contents.split("\n")
assert lines[0].startswith(" <")
print(repr(lines[-1]))
assert lines[-1].startswith(" <")
def test_indent_contents():
"""
The contents in a element should be indented more than the tag
by the amount in the indent class attribute
"""
html = Element("some content")
file_contents = render_result(html, ind="")
print(file_contents)
lines = file_contents.split("\n")
assert lines[1].startswith(Element.indent)
def test_multiple_indent():
"""
make sure multiple levels get indented fully
"""
body = Body()
body.append(P("some text"))
html = Html(body)
file_contents = render_result(html)
print(file_contents)
lines = file_contents.split("\n")
for i in range(3): # this needed to be adapted to the <DOCTYPE> tag
assert lines[i + 1].startswith(i * Element.indent + "<")
assert lines[4].startswith(3 * Element.indent + "some")
def test_element_indent1():
"""
Tests whether the Element indents at least simple content
we are expecting to to look like this:
<html>
this is some text
<\html>
More complex indentation should be tested later.
"""
e = Element("this is some text")
# This uses the render_results utility above
file_contents = render_result(e).strip()
# making sure the content got in there.
assert("this is some text") in file_contents
# break into lines to check indentation
lines = file_contents.split('\n')
# making sure the opening and closing tags are right.
assert lines[0] == "<html>"
# this line should be indented by the amount specified
# by the class attribute: "indent"
assert lines[1].startswith(Element.indent + "thi")
assert lines[2] == "</html>"
assert file_contents.endswith("</html>")
|
[
"taoyeh@gmail.com"
] |
taoyeh@gmail.com
|
35036c906a16e6682fa6e71ce1ca7234a8214ccb
|
1ce21f7e2ba82b2e90fd0fdf808283aa1d4e1799
|
/Assignment-2-DecisionTree/helpers.py
|
dc8fadde08926388262b6a606ac5479cadccd945
|
[] |
no_license
|
T-Nawaz/Hiperdyne-Assignments
|
865627b3c2245ad507ccaeabd66fc5dcd47b91d9
|
ca6712947376ee4d363b05083968c089c7a0842a
|
refs/heads/master
| 2020-04-11T14:59:08.115473
| 2019-02-13T03:20:02
| 2019-02-13T03:20:02
| 161,874,937
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 103
|
py
|
def peek(data):
x=0
for line in data:
if x<5:
print(line)
x+=1
|
[
"tntanzim@gmail.com"
] |
tntanzim@gmail.com
|
330f0b2387476e84045dbea84d03e7cb917bba86
|
82fc697f757b7255cacd85bc7864e6c592889da7
|
/nipyapi/nifi/models/versioned_flow_entity.py
|
4846eac031ebc99a0dc08dc97f647aa67b2f0848
|
[
"Apache-2.0"
] |
permissive
|
pvillard31/nipyapi
|
1b456797fed6fff12c2ea9a417b512f200ce542d
|
9003dee5366c569fa90b6b31dc6f658063da7e88
|
refs/heads/master
| 2020-03-09T11:40:05.798820
| 2018-03-06T23:41:41
| 2018-03-06T23:41:41
| 128,766,892
| 1
| 0
| null | 2018-04-09T12:17:17
| 2018-04-09T12:17:16
| null |
UTF-8
|
Python
| false
| false
| 3,663
|
py
|
# coding: utf-8
"""
NiFi Rest Api
The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, definitions of the expected input and output, potential response codes, and the authorizations required to invoke each service.
OpenAPI spec version: 1.6.0-SNAPSHOT
Contact: dev@nifi.apache.org
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class VersionedFlowEntity(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 = {
'versioned_flow': 'VersionedFlowDTO'
}
attribute_map = {
'versioned_flow': 'versionedFlow'
}
def __init__(self, versioned_flow=None):
"""
VersionedFlowEntity - a model defined in Swagger
"""
self._versioned_flow = None
if versioned_flow is not None:
self.versioned_flow = versioned_flow
@property
def versioned_flow(self):
"""
Gets the versioned_flow of this VersionedFlowEntity.
The versioned flow
:return: The versioned_flow of this VersionedFlowEntity.
:rtype: VersionedFlowDTO
"""
return self._versioned_flow
@versioned_flow.setter
def versioned_flow(self, versioned_flow):
"""
Sets the versioned_flow of this VersionedFlowEntity.
The versioned flow
:param versioned_flow: The versioned_flow of this VersionedFlowEntity.
:type: VersionedFlowDTO
"""
self._versioned_flow = versioned_flow
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in 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
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return 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, VersionedFlowEntity):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
[
"noreply@github.com"
] |
pvillard31.noreply@github.com
|
3cc6d1ecd5da628ce95c4eba54e7ac9bbc12c139
|
474cac4c6803c00b4c75c39121867a510d8ab23d
|
/part1/buttuns.py
|
c56d9ee23e627c8d06654deff914f142c3555d22
|
[] |
no_license
|
nadavru/RL_ROS
|
00d57fe059ff2aeb2783df93a4fbdf2cb9ee878c
|
69560a48e14f62d824a307e0e83169faaa1c72c6
|
refs/heads/master
| 2023-06-06T08:35:18.487539
| 2021-07-02T17:45:29
| 2021-07-02T17:45:29
| 375,120,892
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,219
|
py
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
# Generating x and y-values
x = np.arange(0, 1, 0.02)
y = x
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.3)
p, = plt.plot(x, y, color='red')
ax.title.set_text('Graph for y = x')
# Home button
axButn1 = plt.axes([0.1, 0.1, 0.1, 0.1])
btn1 = Button(
axButn1, label="Home", color='pink', hovercolor='tomato')
# To plot a graph for y = x
def plot1(event):
p.set_xdata(x)
p.set_ydata(x)
ax.title.set_text('Graph for y = x')
plt.draw()
btn1.on_clicked(plot1)
# Previous button
axButn2 = plt.axes([0.3, 0.1, 0.1, 0.1])
btn2 = Button(
axButn2, label="Prev", color='pink', hovercolor='tomato')
# To plot a graph for y = x**2
def plot2(event):
p.set_xdata(x)
p.set_ydata(x ** 2)
ax.title.set_text('Graph for y = x**2')
plt.draw()
btn2.on_clicked(plot2)
# Next button
axButn3 = plt.axes([0.5, 0.1, 0.1, 0.1])
btn3 = Button(
axButn3, label="Next", color='pink', hovercolor='tomato')
# To plot a graph for y = 2x
def plot3(event):
p.set_xdata(x)
p.set_ydata(2 * x)
ax.title.set_text('Graph for y = 2x')
plt.draw()
btn3.on_clicked(plot3)
plt.show()
|
[
"olaniado@campus.technion.ac.il"
] |
olaniado@campus.technion.ac.il
|
07383ecdccf2473d2cd81b121f7cb783684a5740
|
843fe12039e5c837e1edb1b0df4f3826aeec99c4
|
/03_Pandas/F_iloc_loc.py
|
ea03821755d1865ba54994bcfdf24cf0c40674d4
|
[] |
no_license
|
2019-a-gr1-python/py-Aguirre-Maldonado-Carlos-Arturo
|
6e3cf89a0173ead760c985b26b7af2f730f5aaa5
|
80a58b374a13f25238941ca5ec5b60b1a1cadeea
|
refs/heads/master
| 2020-05-04T16:56:21.199940
| 2019-07-31T14:00:42
| 2019-07-31T14:00:42
| 179,292,823
| 0
| 0
| null | 2019-07-30T04:58:05
| 2019-04-03T13:11:02
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 1,395
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 07:35:28 2019
@author: carlosaguirre
"""
import pandas as pd
path_guardado = '/Users/carlosaguirre/Documents/GitHub/py-Aguirre-Maldonado-Carlos-Arturo/03_Pandas/data/csv/artwork_data.pickle'
df = pd.read_pickle(path_guardado)
primero = df.loc[1035,'artist']
segundo = df.loc[1036,'units']
df.loc[0] # Error porque no esta dentro del label indice
primero_a = df.iloc[0,1]
primero_b = df.iloc[0,:]
primero_c = df.iloc[0:100,2:4]
tres_primeros = df.head(10)['width'].sort_values(ascending=False).head(3)
tres_ultimos = df.head(10)['width'].sort_values().tail(3)
a = df['year'].sort_values(axis=0)
serie_validado = pd.to_numeric(df['width'], errors='coerce')
df.loc[:,'width'] = serie_validado
df.iloc[:,5] = serie_validado
diez_primeros = df['height'].sort_values(ascending=False).head(10)
diez_ultimos = df['width'].sort_values(ascending=False).tail(10)
serie_validado_height = pd.to_numeric(df['height'], errors='coerce')
df.loc[:,'height'] = serie_validado_height
area = df['height'] * df['width']
type(area) # Serie
df['area'] = area
df = df.assign(areados = area)
df_area = df['area'].sort_values(ascending=False).head(1)
id_max_area = df['area'].idxmax() # Label
id_min_area = df['area'].idxmin() # Label
registro_mas_area = df.loc[id_max_area]
registro_menor_area = df.loc[id_min_area]
|
[
"caguirremal11@gmail.com"
] |
caguirremal11@gmail.com
|
1241fa302866c8143de7fc38c0231383a342313e
|
97c52297eefe999a6c47089af11c3f35c9c2caa3
|
/secondpass.py
|
7c6d3062a4dd717f8668afb99fb143d72ca46103
|
[] |
no_license
|
rmopia/sic-xe-simulator
|
fce55e8c0b3845c9633e10b1a2e073a831b12c41
|
34e8a256e0847ca17561adeb9c06f6791437a91e
|
refs/heads/master
| 2020-09-05T00:18:51.821063
| 2019-11-13T04:22:44
| 2019-11-13T04:22:44
| 219,931,982
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,584
|
py
|
import numpy as np
format1_list = ["FIX", "FLOAT", "HIO", "NORM", "SIO", "TIO"]
format2_list = ["ADDR", "COMPR", "DIVR", "MULR", "RMO", "SHIFTL", "SHIFTR", "SUBR", "SVC", "TIXR"]
assignments = ["RESW", "WORD", "RESB", "BYTE"]
OPTAB = {"ADD": "18", "LDA": "00", "LDS": "6C", "LDX": "04", "STA": "0C", "COMPR": "A0", "JLT": "38", "SUB": "1C",
"MULR": "98", "FIX": "C4", "FLOAT": "C0", "HIO": "F4", "TIO": "F8", "NORM": "C8", "SIO": "F0"}
registers = {"A": "0", "X": "1", "L": "2", "B": "3", "S": "4", "T": "5"}
base_dict = {"BASE": None}
index_dict = {"X": 0} # if it isn't specified ala LDX, by default X is 0
sp_dict = {}
sp_list = []
def pass2(new_content, fp_dict, pc_dict):
# TODO distinguish format, opcode, nixbpe (flags), disp/addr
obj_code_dict = {}
print(new_content)
print(fp_dict)
print(pc_dict)
for item in new_content:
if "BASE" in item:
base_dict["BASE"] = item[-1]
for item in new_content:
# TODO find format 1-4, START, ENDS, ASSIGNMENTS & BASE
if "+" in item[0] or "+" in item[1]:
print("format 4")
obj_code_dict[' '.join(item)] = format4(item, fp_dict)
elif bool(set(item).intersection(format2_list)):
# print("format 2")
obj_code_dict[' '.join(item)] = format2(item)
elif bool(set(item).intersection(format1_list)):
# print("format 1")
obj_code_dict[' '.join(item)] = OPTAB[item[-1]]
elif bool(set(item).intersection(assignments)): # we don't want object code for assignments
pass
elif "START" in item or "END" in item: # we also don't want object code for START & END
pass
else:
obj_code = format3(item, fp_dict, pc_dict)
obj_code_dict[' '.join(item)] = obj_code
print(obj_code_dict)
def format2(item):
result_list = []
if len(item) == 3:
op_code = OPTAB[item[1]]
else:
op_code = OPTAB[item[0]]
regs = str(item[-1]).split(',')
for r in regs:
if r in registers:
result_list.append(registers[r])
new_op = np.binary_repr(int(op_code, 16), 8)
r1and2 = np.binary_repr(int(''.join(result_list), 16), 8)
return hex(int(new_op + r1and2, 2))
def format3(item, fp_dict, pc_dict):
if len(item) == 3:
op_code = OPTAB[item[1]]
else: # len(item) = 2
op_code = OPTAB[item[0]]
flags = {"n": 0, "i": 0, "x": 0, "b": 0, "p": 0, "e": 0}
if "#" in item[-1]:
flags["n"], flags["i"] = 0, 1
elif "@" in item[-1]:
flags["n"], flags["i"] = 1, 0
else:
flags["n"], flags["i"] = 1, 1 # we're ruling out that we don't want sic instances (ni = 00)
if ",x" in item[-1] or ",X" in item[-1]: # not sure if capitalization matters - yet
flags["x"] = 1
flags["b"], flags["p"], flags["e"] = 0, 1, 0
if bool(base_dict["BASE"]): # if not empty # TODO fix this so if the 12+ bits in disp, base is applied
flags["b"], flags["p"], flags["e"] = 1, 0, 0
# since this is format 3, can never have e = 1
# TODO make a base flag and/or base dictionary to remember what variable is a base: thus if their is a
# base and if our disp/addr doesn't fit in 12 bits then use base
flags["b"], flags["p"], flags["e"] = 0, 1, 0
st = [str(i) for i in list(flags.values())]
flag_string = ''.join(st)
s = ' '.join(item)
disp = ''
if flag_string == '110000':
# disp = TA
TA = int(fp_dict[item[-1]], 16)
disp = np.binary_repr(TA, 12)
elif flag_string == '110010': # JLT LOOP tests 2's compliment!
# disp = TA - PC
# print("TA: " + fp_dict[item[-1]])
# print("PC: " + pc_dict[s])
TA = int(fp_dict[item[-1]], 16)
PC = int(pc_dict[s], 16)
res = TA - PC
# print(hex(res))
# print(np.binary_repr(res, 12))
disp = np.binary_repr(res, 12)
elif flag_string == '110100':
# disp = TA - BASE
print("op m")
elif flag_string == '111000':
# disp = TA - X
print("op c,x")
elif flag_string == '111010':
# disp = TA - PC - X
print("op m,x")
elif flag_string == '111100':
# disp = TA - BASE - X
print("op m,x")
elif flag_string == '100000':
# disp = TA
addr = str(item[-1]).replace("@", "")
TA = int(addr, 16)
# print(np.binary_repr(TA, 12))
disp = np.binary_repr(TA, 12)
print("op @c")
elif flag_string == '100010':
# disp = TA - PC
addr = str(item[-1]).replace("@", "")
TA = int(addr, 16)
PC = int(pc_dict[s], 16)
res = TA - PC
# print(np.binary_repr(res, 12))
disp = np.binary_repr(res, 12)
print("op @m")
elif flag_string == '100100':
# disp = TA - BASE
print("op @m")
elif flag_string == '010000':
# disp = TA
val = str(item[-1]).replace("#", "")
TA = int(val, 16)
# print(np.binary_repr(TA, 12))
disp = np.binary_repr(TA, 12)
print("op #c")
elif flag_string == '010010':
# disp = TA - PC
value = str(item[-1]).replace("#", "")
TA = int(value, 16)
PC = int(pc_dict[s], 16)
# print(TA)
# print(PC)
res = TA - PC
# print(hex(res))
# print(np.binary_repr(res, 12))
disp = np.binary_repr(res, 12)
print("op #m")
elif flag_string == '010100':
# disp = TA - BASE
print("op #m")
new_op = np.binary_repr(int(op_code, 16), 8)[:-2]
# print(new_op)
combined_bin = new_op + flag_string + disp
# print(combined_bin)
# print(hex(int(combined_bin, 2)))
return hex(int(combined_bin, 2))
def format4(item, fp_dict):
flags = {"n": 0, "i": 0, "x": 0, "b": 0, "p": 0, "e": 1} # e will always be 1 under format 4
print(item)
if "+" in item[0] or "+" in item[1]:
if len(item) == 3:
op_code = str(item[1]).replace("+", "")
else:
op_code = str(item[0]).replace("+", "")
hex_opr = OPTAB[op_code]
new_op = np.binary_repr(int(hex_opr, 16), 8)[:-2]
if "#" in item[-1]:
flags["n"], flags["i"] = 0, 1
operand = str(item[-1]).replace("#", "")
if operand.isdecimal():
address = np.binary_repr(int(operand, 16), 20)
else:
opr = fp_dict[operand]
address = np.binary_repr(int(opr, 16), 20)
elif "@" in item[-1]:
flags["n"], flags["i"] = 1, 0
operand = str(item[-1]).replace("@", "")
hex_opr = fp_dict[operand]
address = np.binary_repr(int(hex_opr, 16), 20)
elif ",x" in item[-1] or ",X" in item[-1]:
# addr = TA - X
flags["n"], flags["i"], flags["x"] = 1, 1, 1
if ",x" in item[-1]:
operand = str(item[-1]).replace(",x", "")
else:
operand = str(item[-1]).replace(",X", "")
hex_opr = fp_dict[operand]
TA = int(hex_opr, 16)
index = int(str(index_dict["X"]), 16)
res = TA - index
hex_res = hex(res)[2:]
address = np.binary_repr(int(hex_res, 16), 20)
else:
flags["n"], flags["i"] = 1, 1
operand = fp_dict[item[-1]]
address = np.binary_repr(int(operand, 16), 20)
st = [str(i) for i in list(flags.values())]
flag_string = ''.join(st)
print(new_op)
print(flag_string)
print(address)
inst4 = new_op + flag_string + address # 32 bits in total
return hex(int(inst4, 2))
|
[
"robert.mopia@gmail.com"
] |
robert.mopia@gmail.com
|
a211e0ec4f9643b7909a6cd7763ecd93c3a1f7bf
|
0a35a0a7acdfc01f1c53fd21394676c7e523197b
|
/Door_Lock_2019_12_02.py
|
811259f5fb809f82b8433adc77fc9897e9b72862
|
[] |
no_license
|
budtaylor/Door_lock.sql
|
bf8b0467564b2fa8b999a1ef9fa0e1c90e5e10de
|
aa586c3c411c5052415f2eb87e26b2dbfb299fcf
|
refs/heads/master
| 2020-09-07T16:33:46.649489
| 2019-12-02T14:07:11
| 2019-12-02T14:07:11
| 220,845,347
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,686
|
py
|
def main():
import RPi.GPIO as GPIO
import time
import mysql.connector
from datetime import datetime
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()
try:
id, text = reader.read()
#print(id)
finally:
GPIO.cleanup()
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="PI",
database="Club_door"
)
#print(mydb)
mycursor = mydb.cursor()
mycursor.execute("select rfid_code from access_list")
myresult = mycursor.fetchall()
for row in myresult:
# print(row)
#from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
a = now.strftime("%Y-%m-%d")
b = now.strftime("%H:%M:%S")
#print(a)
RFID_ID = id
if (RFID_ID in row):
print ("access granted")
mycursor = mydb.cursor()
sql = "INSERT INTO access_log (rfid_presented, rfid_presented_date,rfid_presented_time, rfid_granted) VALUES (%s,%s,%s,%s)"
val = (RFID_ID, a , b , "granted")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
time.sleep(2)
main()
else:
print("access denied")
mycursor = mydb.cursor()
sql = "INSERT INTO access_log (rfid_presented, rfid_presented_date,rfid_presented_time, rfid_granted) VALUES (%s,%s,%s,%s)"
val = (RFID_ID, a , b , "denied")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
time.sleep(2)
main()
if __name__ == "__main__":
main()
|
[
"noreply@github.com"
] |
budtaylor.noreply@github.com
|
146d57450fd4b1ac0ad71288b146483a0841dac5
|
2d94b0be7dbd5f1e0a2bfb349742033d7bd66c87
|
/functional_tests/base.py
|
0afc115c1446d3d77c70b55db25f0fe6ac478f87
|
[] |
no_license
|
r-perez/tdd-project
|
759228200ef3a938c22f4fed035970b63c933549
|
dc21f30d768b4725ad2bbb64335df76fa07a22b7
|
refs/heads/master
| 2023-01-05T15:18:46.154487
| 2020-10-25T16:14:06
| 2020-10-25T16:14:06
| 247,837,313
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,251
|
py
|
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException
import time
MAX_WAIT = 10 # 5
class FunctionalTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
self.browser.quit()
def wait_for_row_in_list_table(self, row_text):
start_time = time.time()
while True:
try:
table = self.browser.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
self.assertIn(row_text, [row.text for row in rows])
return
except (AssertionError, WebDriverException) as e:
if time.time() - start_time > MAX_WAIT:
raise e
time.sleep(0.5)
def wait_for(self, fn):
start_time = time.time()
while True:
try:
return fn()
except (AssertionError, WebDriverException) as e:
if time.time() - start_time > MAX_WAIT:
raise e
time.sleep(0.5)
|
[
"rafael.perez@dcc.ufmg.br"
] |
rafael.perez@dcc.ufmg.br
|
83a46ccee1cfc19ab7d2eb33b3b487d05ad5fd3d
|
79898a231d0f8c341ec2e51f3bb714e134c31b0a
|
/Chapter 2 custom visualization ez.py
|
463ae91a6a2f4c77d644d876e961db7901be1cc0
|
[] |
no_license
|
tomjingang/data-science
|
4a5fdbfd3f63d973e2074856d817cf2d394d4c1f
|
67efb6225017754b9c000b0a23c30c6d06c4841c
|
refs/heads/master
| 2022-04-15T09:23:08.169587
| 2020-03-25T01:37:33
| 2020-03-25T01:37:33
| 249,858,733
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,177
|
py
|
# A challenge that users face is that, for a given y-axis value (e.g. 42,000),
# it is difficult to know which x-axis values are most likely to be representative,
# because the confidence levels overlap and their distributions are different
# (the lengths of the confidence interval bars are unequal). One of the solutions the authors propose
# for this problem (Figure 2c) is to allow users to indicate the y-axis value of interest (e.g. 42,000)
# and then draw a horizontal line and color bars based on this value. So bars might be colored red if
# they are definitely above this value
# (given the confidence interval), blue if they are definitely below this value, or white if they contain this value.
import pandas as pd
import numpy as np
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000,200000,3650),
np.random.normal(43000,100000,3650),
np.random.normal(43500,140000,3650),
np.random.normal(48000,70000,3650)],
index=[1992,1993,1994,1995])
df = df.transpose()
# 将df的行和列呼唤
# df.describe()
# 输出一个matrix,里面包含了 诸如 count数目 max最大值 等每一列数据的基本信息
import math
mean = list(df.mean())# 平均值
std = list(df.std())# 标准差
ye1 = [] # 误差
for i in range (4) :
ye1.append(1.96*(std[i]/math.sqrt(len(df))))
nearest = 100
Y = 39500
df_p = pd.DataFrame()
df_p['diff'] = nearest*((Y - df.mean())//nearest) # 输出整数部分
df_p['sign'] = df_p['diff'].abs()/df_p['diff'] # 输出符号 正负号
old_range = abs(df_p['diff']).min(), df_p['diff'].abs().max()
# 输出diff这一列中的最大值和最小值
new_range = .5,1
print(type(new_range))
df_p['shade'] = df_p['sign']*np.interp(df_p['diff'].abs(), old_range, new_range)
# 这样做的目的是
# 1. 将diff中的四个值按照线性关系插入到0.5到1之间,最小的对应0.5,最大对应1.0,等比例插入
# 2. 再乘以他们之间的符号(正负号,含0)
shade = list(df_p['shade'])
# print(shade)
from matplotlib import cm
blues = cm.Blues
reds = cm.Reds
# 当diff为正,则用蓝色
# 当diff为负,则用红色
# 当diff为0,则用白色
color = ['White' if x == 0 else reds(abs(x))
if x<0 else blues(abs(x)) for x in shade]
import matplotlib.pyplot as plt
plt.figure(num=None, figsize=(6, 6), dpi=80, facecolor='w', edgecolor='k')
plt.bar(range(len(df.columns)), height = df.values.mean(axis = 0), yerr=ye1,
error_kw={'capsize': 10, 'elinewidth': 2, 'alpha':0.7}, color = color)
plt.axhline(y=Y, color = 'black', label = 'Y')
# 绘制平行于x轴的水平参考线
plt.text(3.5, 39000, "39000")
plt.xticks(range(len(df.columns)), df.columns)
# x轴为df的列名
plt.title('Generated Data Between 1992 - 1995')
# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', right='off', labelbottom='on')
# remove the frame of the chart
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.show()
|
[
"noreply@github.com"
] |
tomjingang.noreply@github.com
|
389818fbaf4dc414c4b1c2d3833e16c7377caf99
|
cb729559a42732aba8119de998cd4a5e1bdb88b1
|
/processors/base.py
|
5715518cac2810e8fa71eae6d932b64b840c14c0
|
[] |
no_license
|
omersaraf/PyTL
|
be2f012cdc8538694f3e409218332db254e2ef1e
|
fc7ce5ee63b021522e01cb3fb1fcae2bd46ca66f
|
refs/heads/master
| 2020-11-25T12:29:37.701667
| 2019-12-17T16:54:44
| 2019-12-17T16:54:44
| 228,661,566
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 538
|
py
|
from typing import List, Iterable
from pipeline.base import END_MESSAGE
from writers.base import PipelineWriterBase
from queues.base import QueueBase
class PipelineProcessor(PipelineWriterBase):
def process(self, input_queue: QueueBase, output_queue: QueueBase):
for bulk in self._get_iterator(input_queue):
for result in self._process(bulk):
output_queue.push(result)
output_queue.push(END_MESSAGE)
def _process(self, items: List) -> Iterable:
raise NotImplementedError()
|
[
"omer@spotlightltd.com"
] |
omer@spotlightltd.com
|
71263c6e29e925e96474a695aebaa87c9567625c
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/nouns/_roadrunner.py
|
e5b9a953686d9298110d2e8cd827c00a50d91c42
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 418
|
py
|
#calss header
class _ROADRUNNER():
def __init__(self,):
self.name = "ROADRUNNER"
self.definitions = [u'a bird from the southwestern US and Mexico with a long tail and feathers that stand up on the top of its head, that runs very fast']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
3867b5452cd8755f9bb48b89a4584563de444320
|
d6c66a945fab9961dfe6e2aea8cf44ffd26e5df6
|
/Lab06/venv/Scripts/pip3-script.py
|
5dc05d4ecc9fa4a34e3d34bb7ad91e7a7784dd1e
|
[] |
no_license
|
sulleyi/CSC-120
|
f23332a9dad5b00b6c1e839b9ecaff9d28c146d6
|
77b8e42839d389af61d0f278f8eb68ad2a06b98c
|
refs/heads/master
| 2022-09-21T17:09:27.687286
| 2020-06-05T11:20:22
| 2020-06-05T11:20:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 397
|
py
|
#!C:\CSC120\Sulley_Lab06\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')()
)
|
[
"57299945+sulleyi@users.noreply.github.com"
] |
57299945+sulleyi@users.noreply.github.com
|
8e09286aad5474bfac3ea92ffaba9ffc572c4c6d
|
b41d9dbe576f925aa6550d8fc914ff5a18ca9981
|
/UkBot.py
|
efdfa0624959f9e5a329b8387879a231f5f6c6b8
|
[] |
no_license
|
inctoolsproject/4
|
7ae9ff7196938d03cf771b7f7b9d8f8215fae333
|
0ec06e18d252e73d812e98943a7ad486581e9a79
|
refs/heads/master
| 2021-05-08T20:49:53.434859
| 2018-01-28T11:17:37
| 2018-01-28T11:17:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 132,204
|
py
|
# -*- coding: utf-8 -*-
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
import time, random, sys, ast, re, os, io, json, subprocess, threading, string, codecs, requests, tweepy, ctypes, urllib, urllib2, wikipedia, goslate
import timeit
from bs4 import BeautifulSoup
from urllib import urlopen
from io import StringIO
from threading import Thread
from gtts import gTTS
from googletrans import Translator
import six
if (six.PY2):
import urllib2
import urllib
else:
import urllib.request
import urllib.parse
cl = LINETCR.LINE()
#cl.login(qr=True)
cl.login(token="Epa0J1lFMWCH4Pu2nUP5.FB71M2QkkIwofQXkk9ovDq.gSs6bMux8vmeVuT1gpaTmlWXLFrgDyMe+uZKnJ0OeRM=")
cl.loginResult()
print "==================[Login Success]==================="
reload(sys)
sys.setdefaultencoding('utf-8')
helpmsg ="""╔════════════════════════════════
=====================
==࿅ོ࿆༼UK_self༽࿅ོ࿆==
=====================
╠
╠➩ Help1-5
╠
╠➩ SelfBot Digunakan Hanya Untuk
╠ Bermain-main
╚════════════════════════════════
"""
helppro ="""╔═════════════════
=======================
==࿅ོ࿆༼Comand_protect༽࿅ོ࿆==
=======================
╠➩〘Protect on/off〙
���➩〘Qr on/off〙
╠➩〘Invit on/off〙
╠➩〘Cancel on/off〙
╚═════════════════
"""
helpself ="""╔═════════════════
=====================
==࿅ོ࿆༼Comand_self༽࿅ོ࿆==
=====================
╠➩〘Me〙
╠➩〘Myname: 〙
╠➩〘Mybio: 〙
╠➩〘Myname〙
╠➩〘Mybio〙
╠➩〘Mypict〙
╠➩〘Mycover〙
╠➩〘Mycopy @〙
╠➩〘Mybackup〙
╠➩〘Getgrup image〙
╠➩〘Getmid @〙
╠➩〘Getprofile @〙
╠➩〘Getcontact @〙
╠➩〘Getinfo @〙
╠➩〘Getname @〙
╠➩〘Getbio @〙
╠➩〘Getpict @〙
╠➩〘Getcover @〙
╠➩〘Mention〙
╠➩〘Sider on/off〙
╠➩〘Sider〙
╠➩〘Mimic on/off〙
╠➩〘Micadd @〙
╠➩〘Micdel @〙
╚═════════════════
"""
helpset ="""╔═════════════════
=====================
==࿅ོ࿆༼Comand_setting༽࿅ོ࿆==
=====================
╠➩〘Contact on/off〙
╠➩〘Autojoin on/off〙
╠➩〘Autoleave on/off〙
╠➩〘Autoadd on/off〙
╠➩〘Like me〙
╠➩〘Like friend〙
╠➩〘Like on〙
╠➩〘My respon on/off〙
╠➩〘My read on/off〙
╠➩〘My simisimi on/off〙
╚═════════════════
"""
helpgrup ="""╔═════════════════
=====================
==࿅ོ࿆༼Comand_Group༽࿅ོ࿆==
=====================
╠➩〘Link on/off〙
╠➩〘Url〙
╠➩〘Cancel〙
╠➩〘Gcreator〙
╠➩〘Kick @〙
╠➩〘Ulti @〙
╠➩〘Cancel〙
╠➩〘Gname: 〙
╠➩〘Infogrup〙
╠➩〘Gruplist〙
╠➩〘Friendlist〙
╠➩〘Blocklist〙
╠➩〘Ban @〙
╠➩〘Unban @〙
╠➩〘Clearban〙
╠➩〘Banlist〙
╠➩〘Contactban〙
╠➩〘Midban〙
╚═════════════════
"""
helpmed ="""╔═════════════════
=============================
==࿅ོ࿆༼Comand_Media_social༽࿅ོ࿆==
=============================
╠➩〘kalender〙
╠➩〘tr-id 〙
╠➩〘tr-en 〙
╠➩〘tr-jp 〙
╠➩〘tr-ko 〙
╠➩〘say-id 〙
╠➩〘say-en 〙
╠➩〘say-jp 〙
╠➩〘say-ko 〙
╠➩〘/cekig 〙
╠➩〘/postig 〙
╠➩〘checkdate 〙
╠➩〘wikipedia 〙
╠➩〘lirik 〙
╠➩〘video 〙
╠➩〘/image 〙
╠➩〘/youtube 〙
╚═════════════════
"""
mid = cl.getProfile().mid
Bots=["u7dbef59b6a8a2a258e16ac4a2bd39575"]
admin=["u7dbef59b6a8a2a258e16ac4a2bd39575"]
wait = {
"likeOn":True,
"alwayRead":False,
"detectMention":True,
"kickMention":False,
"Sambutan":True,
"steal":False,
"Sider":{},
'pap':{},
'invite':{},
"spam":{},
'contact':False,
'autoJoin':True,
'autoCancel':{"on":False,"members":1},
'leaveRoom':False,
'timeline':True,
'autoAdd':True,
'message':"Thanks for add me ^_^",
"lang":"JP",
"comment":"Haii Kaka",
"commentOn":True,
"commentBlack":{},
"wblack":False,
"dblack":False,
"clock":False,
"cNames":"ই͜✿ই͜ M O R A✿",
"cNames":"",
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"protect":False,
"cancelprotect":False,
"inviteprotect":False,
"linkprotect":False,
}
wait2 = {
"readPoint":{},
"readMember":{},
"setTime":{},
"ROM":{}
}
mimic = {
"copy":False,
"copy2":False,
"status":False,
"target":{}
}
settings = {
"simiSimi":{}
}
cctv = {
"cyduk":{},
"point":{},
"sidermem":{}
}
res = {
'num':{},
'us':{},
'au':{},
}
setTime = {}
setTime = wait2['setTime']
mulai = time.time()
contact = cl.getProfile()
backup = cl.getProfile()
backup.displayName = contact.displayName
backup.statusMessage = contact.statusMessage
backup.pictureStatus = contact.pictureStatus
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def download_page(url):
version = (3,0)
cur_version = sys.version_info
if cur_version >= version:
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
req = urllib.request.Request(url, headers = headers)
resp = urllib.request.urlopen(req)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else:
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req)
page = response.read()
return page
except:
return"Page Not found"
def _images_get_next_item(s):
start_line = s.find('rg_di')
if start_line == -1:
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_line = s.find('"class="rg_meta"')
start_content = s.find('"ou"',start_line+1)
end_content = s.find(',"ow"',start_content+1)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
def _images_get_all_items(page):
items = []
while True:
item, end_content = _images_get_next_item(page)
if item == "no_links":
break
else:
items.append(item)
time.sleep(0.1)
page = page[end_content:]
return items
def upload_tempimage(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
config = {
'album': album,
'name': 'bot auto upload',
'title': 'bot auto upload',
'description': 'bot auto upload'
}
print("Uploading image... ")
image = client.upload_from_path(image_path, config=config, anon=False)
print("Done")
print()
def summon(to, nama):
aa = ""
bb = ""
strt = int(14)
akh = int(14)
nm = nama
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "\xe2\x95\xa0 @x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.text = "\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n"+bb+"\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90"
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print "[Command] Tag All"
try:
cl.sendMessage(msg)
except Exception as error:
print error
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs)
def sendImage(self, to_, path):
M = Message(to=to_,contentType = 1)
M.contentMetadata = None
M.contentPreview = None
M_id = self._client.sendMessage(M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self._client.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
#r.content
return True
def sendImageWithURL(self, to_, url):
path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download image failure.')
try:
self.sendImage(to_, path)
except Exception as e:
raise e
def sendAudio(self, to_, path):
M = Message(to=to_, text=None, contentType = 3)
M.contentMetadata = None
M.contentPreview = None
M2 = self.Talk.client.sendMessage(0,M)
M_id = M2.id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'audio',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload audio failure.')
return True
def sendAudioWithUrl(self, to_, url):
path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download audio failure.')
try:
self.sendAudio(to_, path)
except Exception as e:
raise (e)
def cms(string, commands): #/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX...
tex = ["+","@","/",">",";","^","%","$","^","サテラ:","サテラ:","サテラ:","サテラ:"]
for texX in tex:
for command in commands:
if string ==command:
return True
return False
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def bot(op):
try:
if op.type == 0:
return
if op.type == 13:
if mid in op.param3:
G = cl.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
cl.rejectGroupInvitation(op.param1)
else:
cl.acceptGroupInvitation(op.param1)
else:
cl.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
cl.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
cl.cancelGroupInvitation(op.param1, matched_list)
if op.type == 19:
if mid in op.param3:
wait["blacklist"][op.param2] = True
if op.type == 22:
if wait["leaveRoom"] == True:
cl.leaveRoom(op.param1)
if op.type == 24:
if wait["leaveRoom"] == True:
cl.leaveRoom(op.param1)
if op.type == 26:
msg = op.message
if msg.toType == 0:
msg.to = msg.from_
if msg.from_ == mid:
if "join:" in msg.text:
list_ = msg.text.split(":")
try:
cl.acceptGroupInvitationByTicket(list_[1],list_[2])
G = cl.getGroup(list_[1])
G.preventJoinByTicket = True
cl.updateGroup(G)
except:
cl.sendText(msg.to,"error")
if msg.toType == 1:
if wait["leaveRoom"] == True:
cl.leaveRoom(msg.to)
if msg.contentType == 16:
url = msg.contentMetadata["postEndUrl"]
cl.like(url[25:58], url[66:], likeType=1001)
if op.type == 26:
msg = op.message
if msg.from_ in mimic["target"] and mimic["status"] == True and mimic["target"][msg.from_] == True:
text = msg.text
if text is not None:
cl.sendText(msg.to,text)
if op.type == 55:
try:
if cctv['cyduk'][op.param1]==True:
if op.param1 in cctv['point']:
Name = cl.getContact(op.param2).displayName
if Name in cctv['sidermem'][op.param1]:
pass
else:
cctv['sidermem'][op.param1] += "\n• " + Name
if " " in Name:
nick = Name.split(' ')
if len(nick) == 2:
cl.sendText(op.param1, "kan kan " + "☞ " + nick[0] + " ☜" + "\nYang ngintip . . .\nSering ngintip orang mandi kakak niii (-__-) ")
else:
cl.sendText(op.param1, "nah kan " + "☞ " + nick[1] + " ☜" + "\nBetah Banget Jadi tukan nyimak. . .\nHadehh kelamaan di hutan kayaknya ni kakak (-__-) ")
else:
cl.sendText(op.param1, "Woeee " + "☞ " + Name + " ☜" + "\nparah kakak ni ???\nEhhh dasar tukan ngintipp ")
else:
pass
else:
pass
except:
pass
else:
pass
if op.type == 17:
if wait["Sambutan"] == True:
if op.param2 in admin:
return
ginfo = cl.getGroup(op.param1)
contact = cl.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
cl.sendMessage(c)
cl.sendText(op.param1,"Haii " + cl.getContact(op.param2).displayName + "\nWelcome To ☞ " + str(ginfo.name) + " ☜" + "\nSelamat bergabung moga dapat nikung di mari ya kak hi hi..\nDan Salam kenal aja ya kak ^_^")
cl.sendImageWithURL(op.param1,image)
print "MEMBER JOIN TO GROUP"
if op.type == 15:
if wait["Sambutan"] == True:
if op.param2 in admin:
return
cl.sendText(op.param1,"Good Bye " + cl.getContact(op.param2).displayName + "\nSee You Next Time . . . (p′︵‵。) 🤗")
cl.inviteIntoGroup(op.param1,[op.param2])
print "MEMBER HAS LEFT THE GROUP"
if op.type == 26:
msg = op.message
if msg.to in settings["simiSimi"]:
if settings["simiSimi"][msg.to] == True:
if msg.text is not None:
text = msg.text
r = requests.get("http://api.ntcorp.us/chatbot/v1/?text=" + text.replace(" ","+") + "&key=beta1.nt")
data = r.text
data = json.loads(data)
if data['status'] == 200:
if data['result']['result'] == 100:
cl.sendText(msg.to, "[ChatBOT] " + data['result']['response'].encode('utf-8'))
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention"] == True:
contact = cl.getContact(msg.from_)
cName = contact.displayName
balas = ["Sekali lagi nge tag gw sumpahin jomblo seumur hidup!","Dont Tag!! Lagi Sibuk",cName + " Ngapain Ngetag?",cName + " Nggak Usah Tag-Tag! Kalo Penting Langsung Pc Aja","Tag Mulu Lo Anjirr!","Dia Lagi Off", cName + " Kenapa Tag? Kangen?","Dia Lagi Tidur\nJangan Di Tag " + cName, "Jangan Suka Tag Gua " + cName, "Kamu Siapa " + cName + "?", "Ada Perlu Apa " + cName + "?","Woii " + cName + " Jangan Ngetag, Riibut!"]
ret_ = random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in admin:
cl.sendText(msg.to,ret_)
break
if mention['M'] in Bots:
cl.sendText(msg.to,ret_)
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["kickMention"] == True:
contact = cl.getContact(msg.from_)
cName = contact.displayName
balas = ["Dont Tag Me!! Im Busy",cName + " Ngapain Ngetag?",cName + " Nggak Usah Tag-Tag! Kalo Penting Langsung Pc Aja","Fahmi Nya lagi off", cName + " Kenapa Tag saya?","SPAM PC aja " + cName, "Jangan Suka Tag gua " + cName, "Kamu siapa " + cName + "?", "Ada Perlu apa " + cName + "?","Tenggelamkan tuh yang suka tag pake BOT","Tersummon -_-"]
ret_ = "[Auto Respond] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
cl.sendText(msg.to,ret_)
cl.kickoutFromGroup(msg.to,[msg.from_])
break
if msg.contentType == 13:
if wait['invite'] == True:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = cl.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
cl.sendText(msg.to, _name + " Berada DiGrup Ini")
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
cl.findAndAddContactsByMid(target)
cl.inviteIntoGroup(msg.to,[target])
cl.sendText(msg.to,"Invite " + _name)
wait['invite'] = False
break
except:
cl.sendText(msg.to,"Error")
wait['invite'] = False
break
if msg.contentType == 13:
if wait["steal"] == True:
_name = msg.contentMetadata["displayName"]
copy = msg.contentMetadata["mid"]
groups = cl.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
print "[Target] Stealed"
break
else:
targets.append(copy)
if targets == []:
pass
else:
for target in targets:
try:
cl.findAndAddContactsByMid(target)
contact = cl.getContact(target)
cu = cl.channel.getCover(target)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + msg.contentMetadata["mid"] + "\n\nBio :\n" + contact.statusMessage)
cl.sendText(msg.to,"Profile Picture " + contact.displayName)
cl.sendImageWithURL(msg.to,image)
cl.sendText(msg.to,"Cover " + contact.displayName)
cl.sendImageWithURL(msg.to,path)
wait["steal"] = False
break
except:
pass
if wait["alwayRead"] == True:
if msg.toType == 0:
cl.sendChatChecked(msg.from_,msg.id)
else:
cl.sendChatChecked(msg.to,msg.id)
if op.type == 25:
msg = op.message
if msg.contentType == 13:
if wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
cl.sendText(msg.to,"In Blacklist")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
cl.sendText(msg.to,"Nothing")
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"Done")
wait["dblack"] = False
else:
wait["dblack"] = False
cl.sendText(msg.to,"Not in Blacklist")
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
cl.sendText(msg.to,"In Blacklist")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
cl.sendText(msg.to,"Done")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"Done")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
cl.sendText(msg.to,"Done")
elif wait["contact"] == True:
msg.contentType = 0
cl.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = cl.getContact(msg.contentMetadata["mid"])
try:
cu = cl.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
cl.sendText(msg.to,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
else:
contact = cl.getContact(msg.contentMetadata["mid"])
try:
cu = cl.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
cl.sendText(msg.to,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
elif msg.contentType == 16:
if wait["timeline"] == True:
msg.contentType = 0
if wait["lang"] == "JP":
msg.text = "menempatkan URL\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = msg.contentMetadata["postEndUrl"]
cl.sendText(msg.to,msg.text)
elif msg.text is None:
return
elif msg.text.lower() == 'selfhelp':
if wait["lang"] == "JP":
cl.sendText(msg.to,helpmsg)
else:
cl.sendText(msg.to,helpmsg)
elif msg.text.lower() == 'help5':
if wait["lang"] == "JP":
cl.sendText(msg.to,helppro)
else:
cl.sendText(msg.to,helppro)
elif msg.text.lower() == 'help4':
if wait["lang"] == "JP":
cl.sendText(msg.to,helpself)
else:
cl.sendText(msg.to,helpself)
elif msg.text.lower() == 'help3':
if wait["lang"] == "JP":
cl.sendText(msg.to,helpgrup)
else:
cl.sendText(msg.to,helpgrup)
elif msg.text.lower() == 'help2':
if wait["lang"] == "JP":
cl.sendText(msg.to,helpset)
else:
cl.sendText(msg.to,helpset)
elif msg.text.lower() == 'help1':
if wait["lang"] == "JP":
cl.sendText(msg.to,helpmed)
else:
cl.sendText(msg.to,helpmed)
elif msg.text.lower() == 'speed':
cl.sendText(msg.to, "「Speed My SelfBot」")
start = time.time()
time.sleep(0.07)
elapsed_time = time.time() - start
cl.sendText(msg.to, "☞「 Speed SelfBot 」\n☞ Type: Speed\n☞ Speed : %sseconds" % (elapsed_time))
elif msg.text.lower() == 'sp':
cl.sendText(msg.to, "「Speed My SelfBot」")
start = time.time()
time.sleep(0.07)
elapsed_time = time.time() - start
cl.sendText(msg.to, "☞「 Speed SelfBot 」\n☞ Type: Speed\n☞ Speed : %sseconds" % (elapsed_time))
elif msg.text.lower() == 'crash':
msg.contentType = 13
msg.contentMetadata = {'mid': "u6f25799ac10f71444c7b4e01ce6a1903',"}
cl.sendMessage(msg)
elif msg.text.lower() == 'me':
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendMessage(msg)
#========================== B O T ``C O M M A N D =============================#
#==============================================================================#
elif msg.text.lower() == 'contact on':
if wait["contact"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"contact set to on")
else:
cl.sendText(msg.to,"contact already on")
else:
wait["contact"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"contact set to on")
else:
cl.sendText(msg.to,"contact already on")
elif msg.text.lower() == 'contact off':
if wait["contact"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"contact set to off")
else:
cl.sendText(msg.to,"contact already off")
else:
wait["contact"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"contact set to off")
else:
cl.sendText(msg.to,"contact already off")
elif msg.text.lower() == 'protect on':
if wait["protect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection set to on")
else:
cl.sendText(msg.to,"Protection already on")
else:
wait["protect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection set to on")
else:
cl.sendText(msg.to,"Protection already on")
elif msg.text.lower() == 'qr on':
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Qr set to on")
else:
cl.sendText(msg.to,"Protection Qr already on")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Qr set to on")
else:
cl.sendText(msg.to,"Protection Qr already on")
elif msg.text.lower() == 'invit on':
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Invite set to on")
else:
cl.sendText(msg.to,"Protection Invite already on")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Invite set to on")
else:
cl.sendText(msg.to,"Protection Invite already on")
elif msg.text.lower() == 'cancel on':
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Protection set to on")
else:
cl.sendText(msg.to,"Cancel Protection already on")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Protection set to on")
else:
cl.sendText(msg.to,"Cancel Protection already on")
elif msg.text.lower() == 'autojoin on':
if wait["autoJoin"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Autojoin set to on")
else:
cl.sendText(msg.to,"Autojoin already on")
else:
wait["autoJoin"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Autojoin set to on")
else:
cl.sendText(msg.to,"Autojoin already on")
elif msg.text.lower() == 'autojoin off':
if wait["autoJoin"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Autojoin set to off")
else:
cl.sendText(msg.to,"Autojoin already off")
else:
wait["autoJoin"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Autojoin set to off")
else:
cl.sendText(msg.to,"Autojoin already off")
elif msg.text.lower() == 'protect off':
if wait["protect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection set to off")
else:
cl.sendText(msg.to,"Protection already off")
else:
wait["protect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection set to off")
else:
cl.sendText(msg.to,"Protection already off")
elif msg.text.lower() == 'qr off':
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Qr set to off")
else:
cl.sendText(msg.to,"Protection Qr already off")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Qr set to off")
else:
cl.sendText(msg.to,"Protection Qr already off")
elif msg.text.lower() == 'invit off':
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Invite set to off")
else:
cl.sendText(msg.to,"Protection Invite already off")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Invite set to off")
else:
cl.sendText(msg.to,"Protection Invite already off")
elif msg.text.lower() == 'cancel off':
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Protection Invite set to off")
else:
cl.sendText(msg.to,"Cancel Protection Invite already off")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Protection Invite set to off")
else:
cl.sendText(msg.to,"Cancel Protection Invite already off")
elif "Grup cancel:" in msg.text:
try:
strnum = msg.text.replace("Grup cancel:","")
if strnum == "off":
wait["autoCancel"]["on"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Itu off undangan ditolak??\nSilakan kirim dengan menentukan jumlah orang ketika Anda menghidupkan")
else:
cl.sendText(msg.to,"Off undangan ditolak??Sebutkan jumlah terbuka ketika Anda ingin mengirim")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,strnum + "Kelompok berikut yang diundang akan ditolak secara otomatis")
else:
cl.sendText(msg.to,strnum + "The team declined to create the following automatic invitation")
except:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Nilai tidak benar")
else:
cl.sendText(msg.to,"Weird value")
elif msg.text.lower() == 'autoleave on':
if wait["leaveRoom"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto Leave room set to on")
else:
cl.sendText(msg.to,"Auto Leave room already on")
else:
wait["leaveRoom"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto Leave room set to on")
else:
cl.sendText(msg.to,"Auto Leave room already on")
elif msg.text.lower() == 'autoleave off':
if wait["leaveRoom"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto Leave room set to off")
else:
cl.sendText(msg.to,"Auto Leave room already off")
else:
wait["leaveRoom"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto Leave room set to off")
else:
cl.sendText(msg.to,"Auto Leave room already off")
elif msg.text.lower() == 'share on':
if wait["timeline"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Share set to on")
else:
cl.sendText(msg.to,"Share already on")
else:
wait["timeline"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Share set to on")
else:
cl.sendText(msg.to,"Share already on")
elif msg.text.lower() == 'share off':
if wait["timeline"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Share set to off")
else:
cl.sendText(msg.to,"Share already off")
else:
wait["timeline"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Share set to off")
else:
cl.sendText(msg.to,"Share already off")
elif msg.text.lower() == 'settings':
md = ""
if wait["contact"] == True: md+=" Contact:on \n"
else: md+=" Contact:off\n"
if wait["autoJoin"] == True: md+=" Auto Join:on \n"
else: md +=" Auto Join:off\n"
if wait["autoCancel"]["on"] == True:md+=" Auto cancel:" + str(wait["autoCancel"]["members"]) + "\n"
else: md+= " Group cancel:off \n"
if wait["leaveRoom"] == True: md+=" Auto leave:on \n"
else: md+=" Auto leave:off \n"
if wait["timeline"] == True: md+=" Share:on \n"
else:md+=" Share:off \n"
if wait["autoAdd"] == True: md+=" Auto add:on \n"
else:md+=" Auto add:off \n"
if wait["protect"] == True: md+=" Protect:on \n"
else:md+=" Protect:off \n"
if wait["linkprotect"] == True: md+="Link Protect:on \n"
else:md+="Link Protect:off \n"
if wait["inviteprotect"] == True: md+="Invitation Protect:on \n"
else:md+="Invitation Protect:off \n"
if wait["cancelprotect"] == True: md+="Cancel Protect:on \n"
else:md+="Cancel Protect:off \n"
cl.sendText(msg.to,md)
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendMessage(msg)
elif cms(msg.text,["creator","Creator"]):
msg.contentType = 13
msg.contentMetadata = {'mid': "udee46099e25e71f1fd1817cae9e7c429"}
cl.sendMessage(msg)
elif msg.text.lower() == 'autoadd on':
if wait["autoAdd"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto add set to on")
else:
cl.sendText(msg.to,"Auto add already on")
else:
wait["autoAdd"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto add set to on")
else:
cl.sendText(msg.to,"Auto add already on")
elif msg.text.lower() == 'autoadd off':
if wait["autoAdd"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto add set to off")
else:
cl.sendText(msg.to,"Auto add already off")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Auto add set to off")
else:
cl.sendText(msg.to,"Auto add already off")
elif "Pesan set:" in msg.text:
wait["message"] = msg.text.replace("Pesan set:","")
cl.sendText(msg.to,"We changed the message")
elif msg.text.lower() == 'pesan cek':
if wait["lang"] == "JP":
cl.sendText(msg.to,"Pesan tambahan otomatis telah ditetapkan sebagai berikut \n\n" + wait["message"])
else:
cl.sendText(msg.to,"Pesan tambahan otomatis telah ditetapkan sebagai berikut \n\n" + wait["message"])
elif "Come Set:" in msg.text:
c = msg.text.replace("Come Set:","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"Merupakan string yang tidak bisa diubah")
else:
wait["comment"] = c
cl.sendText(msg.to,"Ini telah diubah\n\n" + c)
elif msg.text in ["Com on","Com:on","Comment on"]:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Aku berada di")
else:
cl.sendText(msg.to,"To open")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Comment Actived")
else:
cl.sendText(msg.to,"Comment Has Been Active")
elif msg.text in ["Come off"]:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Hal ini sudah off")
else:
cl.sendText(msg.to,"It is already turned off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Off")
else:
cl.sendText(msg.to,"To turn off")
elif msg.text in ["Com","Comment"]:
cl.sendText(msg.to,"Auto komentar saat ini telah ditetapkan sebagai berikut:??\n\n" + str(wait["comment"]))
elif msg.text in ["Com Bl"]:
wait["wblack"] = True
cl.sendText(msg.to,"Please send contacts from the person you want to add to the blacklist")
elif msg.text in ["Com hapus Bl"]:
wait["dblack"] = True
cl.sendText(msg.to,"Please send contacts from the person you want to add from the blacklist")
elif msg.text in ["Com Bl cek"]:
if wait["commentBlack"] == {}:
cl.sendText(msg.to,"Nothing in the blacklist")
else:
cl.sendText(msg.to,"The following is a blacklist")
mc = ""
for mi_d in wait["commentBlack"]:
mc += "・" +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif msg.text.lower() == 'jam on':
if wait["clock"] == True:
cl.sendText(msg.to,"Jam already on")
else:
wait["clock"] = True
now2 = datetime.now()
nowT = datetime.strftime(now2,"?%H:%M?")
profile = cl.getProfile()
profile.displayName = wait["cName"] + nowT
cl.updateProfile(profile)
cl.sendText(msg.to,"Jam set on")
elif msg.text.lower() == 'jam off':
if wait["clock"] == False:
cl.sendText(msg.to,"Jam already off")
else:
wait["clock"] = False
cl.sendText(msg.to,"Jam set off")
elif "Jam say:" in msg.text:
n = msg.text.replace("Jam say:","")
if len(n.decode("utf-8")) > 30:
cl.sendText(msg.to,"terlalu lama")
else:
wait["cName"] = n
cl.sendText(msg.to,"Nama Jam Berubah menjadi:" + n)
elif msg.text.lower() == 'update':
if wait["clock"] == True:
now2 = datetime.now()
nowT = datetime.strftime(now2,"?%H:%M?")
profile = cl.getProfile()
profile.displayName = wait["cName"] + nowT
cl.updateProfile(profile)
cl.sendText(msg.to,"Diperbarui")
else:
cl.sendText(msg.to,"Silahkan Aktifkan Jam")
#==============================================================================#
#==============================================================================#
elif msg.text in ["Invite"]:
wait["invite"] = True
cl.sendText(msg.to,"Send Contact")
elif msg.text in ["Steal contact"]:
wait["contact"] = True
cl.sendText(msg.to,"Send Contact")
elif msg.text in ["Like:me","Like me"]: #Semua Bot Ngelike Status Akun Utama
print "[Command]Like executed"
cl.sendText(msg.to,"Like Status Owner")
try:
likeme()
except:
pass
elif msg.text in ["Like:friend","Like friend"]: #Semua Bot Ngelike Status Teman
print "[Command]Like executed"
cl.sendText(msg.to,"Like Status Teman")
try:
likefriend()
except:
pass
elif msg.text in ["Like:on","Like on"]:
if wait["likeOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
wait["likeOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already")
elif msg.text in ["Like off","Like:off"]:
if wait["likeOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
wait["likeOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already")
elif msg.text in ["My simisimi on","Simisimi:on"]:
settings["simiSimi"][msg.to] = True
cl.sendText(msg.to,"Success activated simisimi")
elif msg.text in ["My simisimi off","Simisimi:off"]:
settings["simiSimi"][msg.to] = False
cl.sendText(msg.to,"Success deactive simisimi")
elif msg.text in ["My read on","Read:on"]:
wait['alwayRead'] = True
cl.sendText(msg.to,"Auto Sider ON")
elif msg.text in ["My read off","Read:off"]:
wait['alwayRead'] = False
cl.sendText(msg.to,"Auto Sider OFF")
elif msg.text in ["Sambutan on"]:
if wait["Sambutan"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sambutan Di Aktifkanヾ(*´∀`*)ノ")
else:
wait["Sambutan"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah Onヽ(´▽`)/")
elif msg.text in ["Sambutan off"]:
if wait["Sambutan"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sambutan Di Nonaktifkan( ^∇^)")
else:
wait["Sambutan"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah Off(p′︵‵。)")
elif "Sider on" in msg.text:
try:
del cctv['point'][msg.to]
del cctv['sidermem'][msg.to]
del cctv['cyduk'][msg.to]
except:
pass
cctv['point'][msg.to] = msg.id
cctv['sidermem'][msg.to] = ""
cctv['cyduk'][msg.to]=True
wait["Sider"] = True
cl.sendText(msg.to,"Siap On Cek Sider")
elif "Sider off" in msg.text:
if msg.to in cctv['point']:
cctv['cyduk'][msg.to]=False
wait["Sider"] = False
cl.sendText(msg.to, "Cek Sider Off")
else:
cl.sendText(msg.to, "Heh Belom Di Set")
elif msg.text in ["My autorespon on","Autorespon:on","My respon on","Respon:on"]:
wait["detectMention"] = True
cl.sendText(msg.to,"Auto Respon ON")
elif msg.text in ["My autorespon off","Autorespon:off","My respon off","Respon:off"]:
wait["detectMention"] = False
cl.sendText(msg.to,"Auto Respon OFF")
elif msg.text in ["Tag on","Autokick:on","Responkick on","Responkick:on"]:
wait["kickMention"] = True
cl.sendText(msg.to,"[AUTO RESPOND] Auto Kick yang tag ON")
elif msg.text in ["Tag off","Autokick:off","Responkick off","Responkick:off"]:
wait["kickMention"] = False
cl.sendText(msg.to,"[AUTO RESPOND] Auto Kick yang tag OFF")
#==============================================================================#
elif "らたかn" in msg.text:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("らたかn","")
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
sendMessage(msg.to,"Not found.")
else:
for target in targets:
try:
klist=[cl]
kicker=random.choice(klist)
random.choice(KAC).kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
sendMessage(msg.to,"Grup Dibersihkan")
elif ("Kick " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
cl.kickoutFromGroup(msg.to,[target])
except:
cl.sendText(msg.to,"Error")
elif ("Ulti " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
cl.kickoutFromGroup(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
cl.inviteIntoGroup(msg.to,[target])
cl.cancelGroupInvitation(msg.to,[target])
except:
cl.sendText(msg.to,"Error")
elif "Kick: " in msg.text:
midd = msg.text.replace("Kick: ","")
cl.kickoutFromGroup(msg.to,[midd])
elif 'invite ' in msg.text.lower():
key = msg.text[-33:]
cl.findAndAddContactsByMid(key)
cl.inviteIntoGroup(msg.to, [key])
contact = cl.getContact(key)
elif msg.text.lower() == 'cancel':
if msg.toType == 2:
group = cl.getGroup(msg.to)
if group.invitee is not None:
gInviMids = [contact.mid for contact in group.invitee]
cl.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Tidak ada undangan")
else:
cl.sendText(msg.to,"Invitan tidak ada")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Tidak ada undangan")
else:
cl.sendText(msg.to,"Invitan tidak ada")
elif msg.text.lower() == 'link on':
if msg.toType == 2:
group = cl.getGroup(msg.to)
group.preventJoinByTicket = False
cl.updateGroup(group)
if wait["lang"] == "JP":
cl.sendText(msg.to,"URL open")
else:
cl.sendText(msg.to,"URL open")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"It can not be used outside the group")
else:
cl.sendText(msg.to,"Can not be used for groups other than")
elif msg.text.lower() == 'link off':
if msg.toType == 2:
group = cl.getGroup(msg.to)
group.preventJoinByTicket = True
cl.updateGroup(group)
if wait["lang"] == "JP":
cl.sendText(msg.to,"URL close")
else:
cl.sendText(msg.to,"URL close")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"It can not be used outside the group")
else:
cl.sendText(msg.to,"Can not be used for groups other than")
elif msg.text in ["Url","Gurl"]:
if msg.toType == 2:
g = cl.getGroup(msg.to)
if g.preventJoinByTicket == True:
g.preventJoinByTicket = False
cl.updateGroup(g)
gurl = cl.reissueGroupTicket(msg.to)
cl.sendText(msg.to,"line://ti/g/" + gurl)
elif "Gcreator" == msg.text:
try:
group = cl.getGroup(msg.to)
GS = group.creator.mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': GS}
cl.sendMessage(M)
except:
W = group.members[0].mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': W}
cl.sendMessage(M)
cl.sendText(msg.to,"Creator Grup")
elif msg.text.lower() == 'invite:gcreator':
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
gcmid = ginfo.creator.mid
except:
gcmid = "Error"
if wait["lang"] == "JP":
cl.inviteIntoGroup(msg.to,[gcmid])
else:
cl.inviteIntoGroup(msg.to,[gcmid])
elif ("Gname: " in msg.text):
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.name = msg.text.replace("Gname: ","")
cl.updateGroup(X)
elif msg.text.lower() == 'infogrup':
group = cl.getGroup(msg.to)
try:
gCreator = group.creator.displayName
except:
gCreator = "Error"
md = "[Nama Grup : ]\n" + group.name + "\n\n[Id Grup : ]\n" + group.id + "\n\n[Pembuat Grup :]\n" + gCreator + "\n\n[Gambar Grup : ]\nhttp://dl.profile.line-cdn.net/" + group.pictureStatus
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
cl.sendText(msg.to,md)
elif msg.text.lower() == 'grup id':
gid = cl.getGroupIdsJoined()
h = ""
for i in gid:
h += "[%s]:%s\n" % (cl.getGroup(i).name,i)
cl.sendText(msg.to,h)
#==============================================================================#
elif "Checkmid: " in msg.text:
saya = msg.text.replace("Checkmid: ","")
msg.contentType = 13
msg.contentMetadata = {"mid":saya}
cl.sendMessage(msg)
contact = cl.getContact(saya)
cu = cl.channel.getCover(saya)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
cl.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
cl.sendText(msg.to,"Profile Picture " + contact.displayName)
cl.sendImageWithURL(msg.to,image)
cl.sendText(msg.to,"Cover " + contact.displayName)
cl.sendImageWithURL(msg.to,path)
except:
pass
elif "Checkid: " in msg.text:
saya = msg.text.replace("Checkid: ","")
gid = cl.getGroupIdsJoined()
for i in gid:
h = cl.getGroup(i).id
group = cl.getGroup(i)
if h == saya:
try:
creator = group.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': creator}
md = "Nama Grup :\n" + group.name + "\n\nID Grup :\n" + group.id
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
cl.sendText(msg.to,md)
cl.sendMessage(msg)
cl.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ group.pictureStatus)
except:
creator = "Error"
elif msg.text in ["Friendlist"]:
contactlist = cl.getAllContactIds()
kontak = cl.getContacts(contactlist)
num=1
msgs="═════════List Friend═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Friend═════════\n\nTotal Friend : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif msg.text in ["Memlist"]:
kontak = cl.getGroup(msg.to)
group = kontak.members
num=1
msgs="═════════List Member═════════-"
for ids in group:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Member═════════\n\nTotal Members : %i" % len(group)
cl.sendText(msg.to, msgs)
elif "Grupmember: " in msg.text:
saya = msg.text.replace('Grupmember: ','')
gid = cl.getGroupIdsJoined()
num=1
msgs="═════════List Member═════════-"
for i in gid:
h = cl.getGroup(i).name
gna = cl.getGroup(i)
me = gna.members(i)
msgs+="\n[%i] %s" % (num, me.displayName)
num=(num+1)
msgs+="\n═════════List Member═════════\n\nTotal Members : %i" % len(me)
if h == saya:
cl.sendText(msg.to, msgs)
elif "Friendinfo: " in msg.text:
saya = msg.text.replace('Friendinfo: ','')
gid = cl.getAllContactIds()
for i in gid:
h = cl.getContact(i).displayName
contact = cl.getContact(i)
cu = cl.channel.getCover(i)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
if h == saya:
cl.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
cl.sendText(msg.to,"Profile Picture " + contact.displayName)
cl.sendImageWithURL(msg.to,image)
cl.sendText(msg.to,"Cover " + contact.displayName)
cl.sendImageWithURL(msg.to,path)
elif "Friendpict: " in msg.text:
saya = msg.text.replace('Friendpict: ','')
gid = cl.getAllContactIds()
for i in gid:
h = cl.getContact(i).displayName
gna = cl.getContact(i)
if h == saya:
cl.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif msg.text in ["Friendlistmid"]:
gruplist = cl.getAllContactIds()
kontak = cl.getContacts(gruplist)
num=1
msgs="═════════List FriendMid═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.mid)
num=(num+1)
msgs+="\n═════════List FriendMid═════════\n\nTotal Friend : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif msg.text in ["Blocklist"]:
blockedlist = cl.getBlockedContactIds()
kontak = cl.getContacts(blockedlist)
num=1
msgs="═════════List Blocked═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Blocked═════════\n\nTotal Blocked : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif msg.text in ["Gruplist"]:
gruplist = cl.getGroupIdsJoined()
kontak = cl.getGroups(gruplist)
num=1
msgs="═════════List Grup═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.name)
num=(num+1)
msgs+="\n═════════List Grup═════════\n\nTotal Grup : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif msg.text in ["Gruplistmid"]:
gruplist = cl.getGroupIdsJoined()
kontak = cl.getGroups(gruplist)
num=1
msgs="═════════List GrupMid═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.id)
num=(num+1)
msgs+="\n═════════List GrupMid═════════\n\nTotal Grup : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif "Grupimage: " in msg.text:
saya = msg.text.replace('Grupimage: ','')
gid = cl.getGroupIdsJoined()
for i in gid:
h = cl.getGroup(i).name
gna = cl.getGroup(i)
if h == saya:
cl.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif "Grupname" in msg.text:
saya = msg.text.replace('Grupname','')
gid = cl.getGroup(msg.to)
cl.sendText(msg.to, "[Nama Grup : ]\n" + gid.name)
elif "Grupid" in msg.text:
saya = msg.text.replace('Grupid','')
gid = cl.getGroup(msg.to)
cl.sendText(msg.to, "[ID Grup : ]\n" + gid.id)
elif "Grupinfo: " in msg.text:
saya = msg.text.replace('Grupinfo: ','')
gid = cl.getGroupIdsJoined()
for i in gid:
h = cl.getGroup(i).name
group = cl.getGroup(i)
if h == saya:
try:
creator = group.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': creator}
md = "Nama Grup :\n" + group.name + "\n\nID Grup :\n" + group.id
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
cl.sendText(msg.to,md)
cl.sendMessage(msg)
cl.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ group.pictureStatus)
except:
creator = "Error"
elif msg.text in ["Glist"]:
gid = cl.getGroupIdsJoined()
h = ""
for i in gid:
h += "%s\n" % (cl.getGroup(i).name +" ? ["+str(len(cl.getGroup(i).members))+"]")
cl.sendText(msg.to,"-- List Groups --\n\n"+ h +"\nTotal groups =" +" ["+str(len(gid))+"]")
elif msg.text.lower() == 'gcancel':
gid = cl.getGroupIdsInvited()
for i in gid:
cl.rejectGroupInvitation(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Aku menolak semua undangan")
else:
cl.sendText(msg.to,"He declined all invitations")
elif "Auto add" in msg.text:
thisgroup = cl.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
cl.findAndAddContactsByMids(mi_d)
cl.sendText(msg.to,"Success Add all")
#==============================================================================#
elif "tagall" == msg.text.lower():
group = cl.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "Jumlah:\n" + str(jml) + " Members"
cnt.to = msg.to
cl.sendMessage(cnt)
elif "sider on" == msg.text.lower():
if msg.to in wait2['readPoint']:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
cl.sendText(msg.to,"Cek Sider already on")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
cl.sendText(msg.to, "Set reading point:\n" + datetime.now().strftime('%H:%M:%S'))
print wait2
elif "sider off" == msg.text.lower():
if msg.to not in wait2['readPoint']:
cl.sendText(msg.to,"Cek Sider already off")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
cl.sendText(msg.to, "Delete reading point:\n" + datetime.now().strftime('%H:%M:%S'))
elif "sider" == msg.text.lower():
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
cl.sendText(msg.to, "Sider:\nNone")
else:
chiya = []
for rom in wait2["ROM"][msg.to].items():
chiya.append(rom[1])
cmem = cl.getContacts(chiya)
zx = ""
zxc = ""
zx2 = []
xpesan = 'Lurkers:\n'
for x in range(len(cmem)):
xname = str(cmem[x].displayName)
pesan = ''
pesan2 = pesan+"@a\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}
zx2.append(zx)
zxc += pesan2
msg.contentType = 0
print zxc
msg.text = xpesan+ zxc + "\nLurking time: %s\nCurrent time: %s"%(wait2['setTime'][msg.to],datetime.now().strftime('%H:%M:%S'))
lol ={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}
print lol
msg.contentMetadata = lol
try:
cl.sendMessage(msg)
except Exception as error:
print error
pass
else:
cl.sendText(msg.to, "Lurking has not been set.")
elif "Gbroadcast: " in msg.text:
bc = msg.text.replace("Bc ","")
gid = cl.getGroupIdsJoined()
for i in gid:
cl.sendText(i,"======[BROADCAST]======\n\n"+bc+"\n\n#BROADCAST!!")
elif "Cbroadcast: " in msg.text:
bc = msg.text.replace("Cbroadcast: ","")
gid = cl.getAllContactIds()
for i in gid:
cl.sendText(i, bc)
elif "GbroadcastImage: " in msg.text:
bc = msg.text.replace("GbroadcastImage: ","")
gid = cl.getGroupIdsJoined()
for i in gid:
cl.sendImageWithURL(i, bc)
elif "CbroadcastImage: " in msg.text:
bc = msg.text.replace("CbroadcastImage: ","")
gid = cl.getAllContactIds()
for i in gid:
cl.sendImageWithURL(i, bc)
elif "Spam change: " in msg.text:
wait["spam"] = msg.text.replace("Spam change: ","")
cl.sendText(msg.to,"spam changed")
elif "Spam add: " in msg.text:
wait["spam"] = msg.text.replace("Spam add: ","")
if wait["lang"] == "JP":
cl.sendText(msg.to,"spam changed")
else:
cl.sendText(msg.to,"Done")
elif "Spam: " in msg.text:
strnum = msg.text.replace("Spam: ","")
num = int(strnum)
for var in range(0,num):
cl.sendText(msg.to, wait["spam"])
elif "Spamtag @" in msg.text:
_name = msg.text.replace("Spamtag @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
xname = g.displayName
xlen = str(len(xname)+1)
msg.contentType = 0
msg.text = "@"+xname+" "
msg.contentMetadata ={'MENTION':'{"MENTIONEES":[{"S":"0","E":'+json.dumps(xlen)+',"M":'+json.dumps(g.mid)+'}]}','EMTVER':'4'}
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
cl.sendMessage(msg)
else:
pass
elif "Spam" in msg.text:
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+" ","")
tulisan = jmlh * (teks+"\n")
if txt[1] == "on":
if jmlh <= 100000:
for x in range(jmlh):
cl.sendText(msg.to, teks)
else:
cl.sendText(msg.to, "Out of Range!")
elif txt[1] == "off":
if jmlh <= 100000:
cl.sendText(msg.to, tulisan)
else:
cl.sendText(msg.to, "Out Of Range!")
elif ("Micadd " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
mimic["target"][target] = True
cl.sendText(msg.to,"Target ditambahkan!")
break
except:
cl.sendText(msg.to,"Fail !")
break
elif ("Micdel " in msg.text):
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
del mimic["target"][target]
cl.sendText(msg.to,"Target dihapuskan!")
break
except:
cl.sendText(msg.to,"Fail !")
break
elif msg.text in ["Miclist"]:
if mimic["target"] == {}:
cl.sendText(msg.to,"nothing")
else:
mc = "Target mimic user\n"
for mi_d in mimic["target"]:
mc += "?? "+cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif "Mimic target " in msg.text:
if mimic["copy"] == True:
siapa = msg.text.replace("Mimic target ","")
if siapa.rstrip(' ') == "me":
mimic["copy2"] = "me"
cl.sendText(msg.to,"Mimic change to me")
elif siapa.rstrip(' ') == "target":
mimic["copy2"] = "target"
cl.sendText(msg.to,"Mimic change to target")
else:
cl.sendText(msg.to,"I dont know")
elif "Mimic " in msg.text:
cmd = msg.text.replace("Mimic ","")
if cmd == "on":
if mimic["status"] == False:
mimic["status"] = True
cl.sendText(msg.to,"Reply Message on")
else:
cl.sendText(msg.to,"Sudah on")
elif cmd == "off":
if mimic["status"] == True:
mimic["status"] = False
cl.sendText(msg.to,"Reply Message off")
else:
cl.sendText(msg.to,"Sudah off")
#elif msg.text.lower() in dangerMessage:
# if msg.toType == 2:
# try:
# cl.kickoutFromGroup(msg.to,[msg.from_])
# except:
# cl.kickoutFromGroup(msg.to,[msg.from_])
elif "Setimage: " in msg.text:
wait["pap"] = msg.text.replace("Setimage: ","")
cl.sendText(msg.to, "Pap telah di Set")
elif msg.text in ["Papimage","Papim","Pap"]:
cl.sendImageWithURL(msg.to,wait["pap"])
elif "Setvideo: " in msg.text:
wait["pap"] = msg.text.replace("Setvideo: ","")
cl.sendText(msg.to,"Video Has Ben Set To")
elif msg.text in ["Papvideo","Papvid"]:
cl.sendVideoWithURL(msg.to,wait["pap"])
#==============================================================================#
elif '/image ' in msg.text:
googl = msg.text.replace('/image ',"")
url = 'https://www.google.com/search?hl=en&biw=1366&bih=659&tbm=isch&sa=1&ei=vSD9WYimHMWHvQTg_53IDw&q=' + googl
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
try:
start = timeit.timeit()
cl.sendImageWithURL(msg.to,path)
cl.sendText(msg.to, "Google Image \nType: Search Image\nWaktu dicari: %s" % (start) +"\nTotal Image Links = "+str(len(items)))
print "[Notif] Search Image Google Sucess"
except Exception as e:
cl.sendText(msg.to, str(e))
elif msg.text.lower() == 'mymid':
cl.sendText(msg.to,mid)
elif "Timeline: " in msg.text:
tl_text = msg.text.replace("Timeline: ","")
cl.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+cl.new_post(tl_text)["result"]["post"]["postInfo"]["postId"])
elif "Myname: " in msg.text:
string = msg.text.replace("Myname: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Changed " + string + "")
elif "Mybio: " in msg.text:
string = msg.text.replace("Mybio: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = cl.getProfile()
profile.statusMessage = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Changed " + string)
elif msg.text in ["Myname"]:
h = cl.getContact(mid)
cl.sendText(msg.to,"===[DisplayName]===\n" + h.displayName)
elif msg.text in ["Mybio"]:
h = cl.getContact(mid)
cl.sendText(msg.to,"===[StatusMessage]===\n" + h.statusMessage)
elif msg.text in ["Mypict"]:
h = cl.getContact(mid)
cl.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Myvid"]:
h = cl.getContact(mid)
cl.sendVideoWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Urlpict"]:
h = cl.getContact(mid)
cl.sendText(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Mycover"]:
h = cl.getContact(mid)
cu = cl.channel.getCover(mid)
path = str(cu)
cl.sendImageWithURL(msg.to, path)
elif msg.text in ["Urlcover"]:
h = cl.getContact(mid)
cu = cl.channel.getCover(mid)
path = str(cu)
cl.sendText(msg.to, path)
elif "Getmid @" in msg.text:
_name = msg.text.replace("Getmid @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
cl.sendText(msg.to, g.mid)
else:
pass
elif "Getinfo" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = cl.getContact(key1)
cu = cl.channel.getCover(key1)
try:
cl.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\nHeader :\n" + str(cu))
except:
cl.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\n" + str(cu))
elif "Getbio" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = cl.getContact(key1)
cu = cl.channel.getCover(key1)
try:
cl.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
except:
cl.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
elif "Getname" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = cl.getContact(key1)
cu = cl.channel.getCover(key1)
try:
cl.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
except:
cl.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
elif "Getprofile" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = cl.getContact(key1)
cu = cl.channel.getCover(key1)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
cl.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
cl.sendText(msg.to,"Profile Picture " + contact.displayName)
cl.sendImageWithURL(msg.to,image)
cl.sendText(msg.to,"Cover " + contact.displayName)
cl.sendImageWithURL(msg.to,path)
except:
pass
elif "Getcontact" in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mmid = cl.getContact(key1)
msg.contentType = 13
msg.contentMetadata = {"mid": key1}
cl.sendMessage(msg)
elif "Getpict @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Getpict @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendImageWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Getvid @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Getvid @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendVideoWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Picturl @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Picturl @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendText(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Getcover @" in msg.text:
print "[Command]cover executing"
_name = msg.text.replace("Getcover @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
cu = cl.channel.getCover(target)
path = str(cu)
cl.sendImageWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]cover executed"
elif "Coverurl @" in msg.text:
print "[Command]cover executing"
_name = msg.text.replace("Coverurl @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
cu = cl.channel.getCover(target)
path = str(cu)
cl.sendText(msg.to, path)
except Exception as e:
raise e
print "[Command]cover executed"
elif "Getgrup image" in msg.text:
group = cl.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
cl.sendImageWithURL(msg.to,path)
elif "Urlgrup image" in msg.text:
group = cl.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
cl.sendText(msg.to,path)
elif "Mycopy @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("Mycopy @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
cl.CloneContactProfile(target)
cl.sendText(msg.to, "Copied.")
except Exception as e:
print e
elif msg.text in ["Mybackup","mybackup"]:
try:
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.sendText(msg.to, "Refreshed.")
except Exception as e:
cl.sendText(msg.to, str(e))
#==============================================================================#
elif "/fancytext: " in msg.text.lower():
txt = msg.text.replace("/fancytext: ", "")
t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
cl.sendText(msg.to, t1 + txt + t2)
#-------------------------------------------------
elif "/translate" in msg.text:
cl.sendText(msg.to,"contoh :\n- id to english : /en aku\n- english to id : /id you\n- id to japan : /jp halo\n- japan to id : /jpid kimochi\n- id to korea : /kor pagi\n- id to malaysia : /malay enak\n- id to arab : /arab jalan\n- id to jawa : /jawa kamu")
elif "/id " in msg.text:
isi = msg.text.replace("/id ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "/en " in msg.text:
isi = msg.text.replace("/en ","")
translator = Translator()
hasil = translator.translate(isi, dest='en')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "/jp " in msg.text:
isi = msg.text.replace("/jp ","")
translator = Translator()
hasil = translator.translate(isi, dest='ja')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "/jpid " in msg.text:
isi = msg.text.replace("/jpid ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "/kor " in msg.text:
isi = msg.text.replace("/kor ","")
translator = Translator()
hasil = translator.translate(isi, dest='ko')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "/malay " in msg.text:
isi = msg.text.replace("/malay ","")
translator = Translator()
hasil = translator.translate(isi, dest='ms')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "/arab " in msg.text:
isi = msg.text.replace("/arab ","")
translator = Translator()
hasil = translator.translate(isi, dest='ar')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "/jawa " in msg.text:
isi = msg.text.replace("/jawa ","")
translator = Translator()
hasil = translator.translate(isi, dest='jw')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
#---------------------------------------------------------------
elif "/removechat" in msg.text.lower():
try:
cl.removeAllMessages(op.param2)
print "[Command] Remove Chat"
cl.sendText(msg.to,"Done")
except Exception as error:
print error
cl.sendText(msg.to,"Error")
#---------------------------------------------------------
elif msg.text.lower() == 'welcome':
ginfo = cl.getGroup(msg.to)
cl.sendText(msg.to,"Selamat Datang Di Grup " + str(ginfo.name))
jawaban1 = ("Selamat Datang Di Grup " + str(ginfo.name))
cl.sendText(msg.to,"Owner Grup " + str(ginfo.name) + " :\n" + ginfo.creator.displayName )
elif "Say-id " in msg.text:
say = msg.text.replace("Say-id ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
cl.sendAudio(msg.to,"hasil.mp3")
elif "Say-en " in msg.text:
say = msg.text.replace("Say-en ","")
lang = 'en'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
cl.sendAudio(msg.to,"hasil.mp3")
elif "Say-jp " in msg.text:
say = msg.text.replace("Say-jp ","")
lang = 'ja'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
cl.sendAudio(msg.to,"hasil.mp3")
elif "Say-ar " in msg.text:
say = msg.text.replace("Say-ar ","")
lang = 'ar'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
cl.sendAudio(msg.to,"hasil.mp3")
elif "Say-ko " in msg.text:
say = msg.text.replace("Say-ko ","")
lang = 'ko'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
cl.sendAudio(msg.to,"hasil.mp3")
elif "Kapan " in msg.text:
tanya = msg.text.replace("Kapan ","")
jawab = ("kapan kapan","besok","satu abad lagi","Hari ini","Tahun depan","Minggu depan","Bulan depan","Sebentar lagi")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='id')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
elif "Apakah " in msg.text:
tanya = msg.text.replace("Apakah ","")
jawab = ("Ya","Tidak","Mungkin","Bisa jadi")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='id')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
elif '/video ' in msg.text:
try:
textToSearch = (msg.text).replace('/video ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class': 'yt-uix-tile-link'})
ght = ('https://www.youtube.com' + results['href'])
cl.sendVideoWithURL(msg.to, ght)
except:
cl.sendText(msg.to, "Could not find it")
elif "/youtube " in msg.text:
query = msg.text.replace("/youtube ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html5lib')
hasil = ""
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
hasil += ''.join((a['title'],'\nUrl : http://www.youtube.com' + a['href'],'\n\n'))
cl.sendText(msg.to,hasil)
print '[Command] Youtube Search'
elif "Lirik " in msg.text:
try:
songname = msg.text.lower().replace("Lirik ","")
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
cl.sendText(msg.to, hasil)
except Exception as wak:
cl.sendText(msg.to, str(wak))
elif "Wikipedia " in msg.text:
try:
wiki = msg.text.lower().replace("Wikipedia ","")
wikipedia.set_lang("id")
pesan="Title ("
pesan+=wikipedia.page(wiki).title
pesan+=")\n\n"
pesan+=wikipedia.summary(wiki, sentences=1)
pesan+="\n"
pesan+=wikipedia.page(wiki).url
cl.sendText(msg.to, pesan)
except:
try:
pesan="Over Text Limit! Please Click link\n"
pesan+=wikipedia.page(wiki).url
cl.sendText(msg.to, pesan)
except Exception as e:
cl.sendText(msg.to, str(e))
elif "Music " in msg.text:
try:
songname = msg.text.lower().replace("Music ","")
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'This is Your Music\n'
hasil += 'Judul : ' + song[0]
hasil += '\nDurasi : ' + song[1]
hasil += '\nLink Download : ' + song[4]
cl.sendText(msg.to, hasil)
cl.sendText(msg.to, "Please Wait for audio...")
cl.sendAudioWithURL(msg.to, song[4])
except Exception as njer:
cl.sendText(msg.to, str(njer))
elif "Image " in msg.text:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
cl.sendImageWithURL(msg.to,path)
except:
pass
elif "/cekig " in msg.text:
try:
instagram = msg.text.replace("/cekig ","")
response = requests.get("https://www.instagram.com/"+instagram+"?__a=1")
data = response.json()
namaIG = str(data['user']['full_name'])
bioIG = str(data['user']['biography'])
mediaIG = str(data['user']['media']['count'])
verifIG = str(data['user']['is_verified'])
usernameIG = str(data['user']['username'])
followerIG = str(data['user']['followed_by']['count'])
profileIG = data['user']['profile_pic_url_hd']
privateIG = str(data['user']['is_private'])
followIG = str(data['user']['follows']['count'])
link = "Link: " + "https://www.instagram.com/" + instagram
text = "Name : "+namaIG+"\nUsername : "+usernameIG+"\nBiography : "+bioIG+"\nFollower : "+followerIG+"\nFollowing : "+followIG+"\nPost : "+mediaIG+"\nVerified : "+verifIG+"\nPrivate : "+privateIG+"" "\n" + link
cl.sendText(msg.to, str(text))
cl.sendImageWithURL(msg.to, profileIG)
except Exception as e:
cl.sendText(msg.to, str(e))
elif "/postig" in msg.text:
separate = msg.text.split(" ")
user = msg.text.replace(separate[0] + " ","")
if user.startswith("@"):
user = user.replace("@","")
profile = "https://www.instagram.com/" + user
with requests.session() as x:
x.headers['user-agent'] = 'Mozilla/5.0'
end_cursor = ''
for count in range(1, 999):
print('PAGE: ', count)
r = x.get(profile, params={'max_id': end_cursor})
data = re.search(r'window._sharedData = (\{.+?});</script>', r.text).group(1)
j = json.loads(data)
for node in j['entry_data']['ProfilePage'][0]['user']['media']['nodes']:
if node['is_video']:
page = 'https://www.instagram.com/p/' + node['code']
r = x.get(page)
url = re.search(r'"video_url": "([^"]+)"', r.text).group(1)
print(url)
cl.sendVideoWithURL(msg.to,url)
else:
print (node['display_src'])
cl.sendImageWithURL(msg.to,node['display_src'])
end_cursor = re.search(r'"end_cursor": "([^"]+)"', r.text).group(1)
elif msg.text.lower() == 'time':
timeNow = datetime.now()
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
inihari = datetime.today()
hr = inihari.strftime('%A')
bln = inihari.strftime('%m')
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bulan = blan[k-1]
rst = hasil + ", " + inihari.strftime('%d') + " - " + bln + " - " + inihari.strftime('%Y') + "\nJam : [ " + inihari.strftime('%H:%M:%S') + " ]"
cl.sendText(msg.to, rst)
elif "Checkdate " in msg.text:
tanggal = msg.text.replace("Checkdate ","")
r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)
data=r.text
data=json.loads(data)
lahir = data["data"]["lahir"]
usia = data["data"]["usia"]
ultah = data["data"]["ultah"]
zodiak = data["data"]["zodiak"]
cl.sendText(msg.to,"============ I N F O R M A S I ============\n"+"Date Of Birth : "+lahir+"\nAge : "+usia+"\nUltah : "+ultah+"\nZodiak : "+zodiak+"\n============ I N F O R M A S I ============")
elif msg.text.lower() == 'kalender':
wait2['setTime'][msg.to] = datetime.today().strftime('TANGGAL : %Y-%m-%d \nHARI : %A \nJAM : %H:%M:%S')
cl.sendText(msg.to, "KALENDER\n\n" + (wait2['setTime'][msg.to]))
#==============================================================================#
elif msg.text.lower() == 'ifconfig':
botKernel = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO NetStat===")
elif msg.text.lower() == 'system':
botKernel = subprocess.Popen(["df","-h"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO SYSTEM===")
elif msg.text.lower() == 'kernel':
botKernel = subprocess.Popen(["uname","-srvmpio"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO KERNEL===")
elif msg.text.lower() == 'cpu':
botKernel = subprocess.Popen(["cat","/proc/cpuinfo"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO CPU===")
elif msg.text.lower() == 'reboot':
print "[Command]Restart"
try:
cl.sendText(msg.to,"Restarting...")
cl.sendText(msg.to,"Restart Success")
restart_program()
except:
cl.sendText(msg.to,"Please wait")
restart_program()
pass
elif "Turn off" in msg.text:
try:
import sys
sys.exit()
except:
pass
elif msg.text.lower() == 'runtime':
cl.sendText(msg.to,"「Please wait..」\nType :Loading...\nStatus : Loading...")
eltime = time.time() - mulai
van = "Type : Bot Sedang Berjalan \nStatus : Aktif \nMySelbot sudah berjalan selama"+waktu(eltime)
cl.sendText(msg.to,van)
#==============================================================================#
#==============================================================================#
elif "Ban @" in msg.text:
if msg.toType == 2:
_name = msg.text.replace("Ban @","")
_nametarget = _name.rstrip()
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,_nametarget + " Not Found")
else:
for target in targets:
try:
wait["blacklist"][target] = True
cl.sendText(msg.to,_nametarget + " Succes Add to Blacklist")
except:
cl.sendText(msg.to,"Error")
elif "Unban @" in msg.text:
if msg.toType == 2:
_name = msg.text.replace("Unban @","")
_nametarget = _name.rstrip()
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,_nametarget + " Not Found")
else:
for target in targets:
try:
del wait["blacklist"][target]
cl.sendText(msg.to,_nametarget + " Delete From Blacklist")
except:
cl.sendText(msg.to,_nametarget + " Not In Blacklist")
elif "Ban:" in msg.text:
nk0 = msg.text.replace("Ban:","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
cl.sendText(msg.to,_name + " Succes Add to Blacklist")
except:
cl.sendText(msg.to,"Error")
elif "Unban:" in msg.text:
nk0 = msg.text.replace("Unban:","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
del wait["blacklist"][target]
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
cl.sendText(msg.to,_name + " Delete From Blacklist")
except:
cl.sendText(msg.to,_name + " Not In Blacklist")
elif msg.text in ["Clear"]:
wait["blacklist"] = {}
cl.sendText(msg.to,"Blacklist Telah Dibersihkan")
elif msg.text.lower() == 'ban:on':
wait["wblacklist"] = True
cl.sendText(msg.to,"Send Contact")
elif msg.text.lower() == 'unban:on':
wait["dblacklist"] = True
cl.sendText(msg.to,"Send Contact")
elif msg.text in ["Banlist"]:
if wait["blacklist"] == {}:
cl.sendText(msg.to,"Tidak Ada Blacklist")
else:
cl.sendText(msg.to,"Daftar Banlist")
num=1
msgs="══════════List Blacklist═════════"
for mi_d in wait["blacklist"]:
msgs+="\n[%i] %s" % (num, cl.getContact(mi_d).displayName)
num=(num+1)
msgs+="\n══════════List Blacklist═════════\n\nTotal Blacklist : %i" % len(wait["blacklist"])
cl.sendText(msg.to, msgs)
elif msg.text in ["Conban","Contactban","Contact ban"]:
if wait["blacklist"] == {}:
cl.sendText(msg.to,"Tidak Ada Blacklist")
else:
cl.sendText(msg.to,"Daftar Blacklist")
h = ""
for i in wait["blacklist"]:
h = cl.getContact(i)
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': i}
cl.sendMessage(M)
elif msg.text in ["Midban","Mid ban"]:
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
num=1
cocoa = "══════════List Blacklist═════════"
for mm in matched_list:
cocoa+="\n[%i] %s" % (num, mm)
num=(num+1)
cocoa+="\n═════════List Blacklist═════════\n\nTotal Blacklist : %i" % len(matched_list)
cl.sendText(msg.to,cocoa)
elif msg.text.lower() == 'scan blacklist':
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
cl.sendText(msg.to,"Tidak ada Daftar Blacklist")
return
for jj in matched_list:
try:
cl.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
#==============================================#
if op.type == 17:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
if wait["protect"] == True:
if wait["blacklist"][op.param2] == True:
try:
cl.kickoutFromGroup(op.param1,[op.param2])
G = cl.getGroup(op.param1)
G.preventJoinByTicket = True
cl.updateGroup(G)
except:
try:
cl.kickoutFromGroup(op.param1,[op.param2])
G = cl.getGroup(op.param1)
G.preventJoinByTicket = True
cl.updateGroup(G)
except:
pass
if op.type == 19:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["protect"] == True:
wait ["blacklist"][op.param2] = True
cl.kickoutFromGroup(op.param1,[op.param2])
cl.inviteIntoGroup(op.param1,[op.param2])
if op.type == 13:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
cl.kickoutFromGroup(op.param1,[op.param2])
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
cl.cancelGroupInvitation(op.param1,[op.param3])
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["cancelprotect"] == True:
wait ["blacklist"][op.param2] = True
cl.cancelGroupInvitation(op.param1,[op.param3])
if op.type == 11:
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["linkprotect"] == True:
wait ["blacklist"][op.param2] = True
G = cl.getGroup(op.param1)
G.preventJoinByTicket = True
cl.updateGroup(G)
cl.kickoutFromGroup(op.param1,[op.param2])
if op.type == 5:
if wait["autoAdd"] == True:
if (wait["message"] in [""," ","\n",None]):
pass
else:
cl.sendText(op.param1,str(wait["message"]))
if op.type == 11:
if wait["linkprotect"] == True:
if op.param2 not in Bots:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = True
cl.kickoutFromGroup(op.param1,[op.param3])
cl.updateGroup(G)
#==============================================================================#
#------------------------------------------------------------------------------#
#==============================================================================#
if op.type == 55:
try:
if op.param1 in wait2['readPoint']:
if op.param2 in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += op.param2
wait2['ROM'][op.param1][op.param2] = op.param2
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
else:
pass
except:
pass
if op.type == 59:
print op
except Exception as error:
print error
def autolike():
count = 1
while True:
try:
for posts in cl.activity(1)["result"]["posts"]:
if posts["postInfo"]["liked"] is False:
if wait["likeOn"] == True:
cl.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
print "Like"
if wait["commentOn"] == True:
if posts["userInfo"]["writerMid"] in wait["commentBlack"]:
pass
else:
cl.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
except:
count += 1
if(count == 50):
sys.exit(0)
else:
pass
thread2 = threading.Thread(target=autolike)
thread2.daemon = True
thread2.start()
def likefriend():
for zx in range(0,20):
hasil = cl.activity(limit=20)
if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
try:
cl.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1001)
print "Like"
except:
pass
else:
print "Already Liked"
time.sleep(0.60)
def likeme():
for zx in range(0,20):
hasil = cl.activity(limit=20)
if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
if hasil['result']['posts'][zx]['userInfo']['mid'] in mid:
try:
cl.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1002)
print "Like"
except:
pass
else:
print "Status Sudah di Like"
while True:
try:
Ops = cl.fetchOps(cl.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(cl.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
cl.Poll.rev = max(cl.Poll.rev, Op.revision)
bot(Op)
|
[
"noreply@github.com"
] |
inctoolsproject.noreply@github.com
|
e78b30fcb6695dc5625f9d11ac29bb5e123a5958
|
eb278a6dc07e4a3476b530aa0159a63225e3f022
|
/br2gm/parser.py
|
6405d9e20f7fec0cab17bd2a04cba9d42504fe09
|
[
"MIT"
] |
permissive
|
vpavlin/br2gm
|
cf405adf3ab9b38c47b793363e9b44a86b144c78
|
7e9c5f293e119a263402728ad0f45149cfdcfa17
|
refs/heads/master
| 2020-03-26T18:34:58.660826
| 2015-04-14T08:48:28
| 2015-04-14T08:48:28
| 33,774,389
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,115
|
py
|
#!/usr/bin/env python
from __future__ import print_function
import os,sys
from bs4 import BeautifulSoup
import urllib2
class Parser():
soup = None
__songs_list = []
def __init__(self, url):
content = self.loadHtml(url)
self.soup = BeautifulSoup(content)
def loadHtml(self, url):
print("Pulling content from %s" % url)
response = urllib2.urlopen(url)
content = response.read()
return content
def getSongsList(self):
get_info = {"artist": self.getArtist, "title": self.getSongTitle}
for item in self.soup.find_all("div", class_="cht-entry-details"):
item_data = {"artist": None, "title": None}
for key, func in get_info.iteritems():
item_data[key] = func(item)
self.__songs_list.append(item_data)
return self.__songs_list
def getArtist(self, data):
return data.find("div", class_="cht-entry-artist").get_text().strip()
def getSongTitle(self, data):
return data.find("div", class_="cht-entry-title").get_text().strip()
|
[
"vpavlin@redhat.com"
] |
vpavlin@redhat.com
|
75ad5176c48d5e8bb527d154f405e2ec09a96f3c
|
1967b30267e5703c44da1283dfe91b252f48bf21
|
/bin/easy_install-3.4
|
1e90abad76665012715c4126fa12b95e05cc0823
|
[] |
no_license
|
AlexanderMcNulty/evileye
|
47ea9197609bfc81a6872c9317c5d05dd5cbbd80
|
11440037b8f2f7adabffe955d41482b248625d13
|
refs/heads/master
| 2021-05-14T09:47:23.149645
| 2018-01-09T22:06:49
| 2018-01-09T22:06:49
| 116,335,096
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 248
|
4
|
#!/home/ammc/evileye/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
|
[
"alexander.mcnulty92@gmail.com"
] |
alexander.mcnulty92@gmail.com
|
2f64d7e54c25dc8d0acdd2ed35ea0961604697bd
|
22fde560021d023cf77a99bc23471d6d8ad73931
|
/esgf/parse2.py
|
ae7832e77bf52022bcc6b8d12709a518ecb8ff0a
|
[] |
no_license
|
cmip6dr/requestReview
|
4e886346d34b3ffbbfc7fcb092298d7b71db5589
|
4c12751c78a71ae0b5c325e6185432119f1d3018
|
refs/heads/master
| 2023-03-10T01:52:31.274954
| 2023-03-01T21:43:33
| 2023-03-01T21:43:33
| 136,451,663
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 389
|
py
|
ar6 = open( 'AR6_priority_variables_02.csv', 'r' ).readlines()
rr = open( 'RankedCmipVariables.csv', 'r' ).readlines()
ppp = [x.split('\t')[2].strip() for x in ar6 if len(x.split('\t')) > 2]
print( ppp[0] )
ss = set(ppp )
assert '3hr.huss' in ss
oo = open( 'p1_out.csv', 'w' )
for l in rr[1:]:
id = l.split(',')[0].strip()
oo.write( '%s, %s\n' % (id, id in ss ) )
oo.close()
|
[
"mjuckes@rslmj01.badc.rl.ac.uk"
] |
mjuckes@rslmj01.badc.rl.ac.uk
|
21332153db3487202c8f1fe8ae1cf61950134863
|
4d7f7f3afb954a46be8d0643b973e04f55b659d0
|
/08 Other Common Tasks/import_random.py
|
4eeca1af15d7eb245d04cdce1963bcd1edc454cd
|
[
"MIT"
] |
permissive
|
gitter-badger/survival-python
|
28d3566610bf494ecfe7912f0e538d731baa193f
|
c9c7f336ecd0b8196934386d334f53cd79cb7284
|
refs/heads/master
| 2022-12-23T07:44:08.711731
| 2020-01-08T01:56:12
| 2020-01-08T01:56:12
| 290,586,968
| 0
| 0
|
MIT
| 2020-08-26T19:30:48
| 2020-08-26T19:30:47
| null |
UTF-8
|
Python
| false
| false
| 288
|
py
|
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f']
count = 0
while count < 10:
random_int = random.randint(0, 9)
random.shuffle(letters)
choice = random.choice(letters)
print('RandInt: {}, Shuffle: {}, Choice: {}'.format(random_int, letters, choice))
count += 1
|
[
"prepxc@gmail.com"
] |
prepxc@gmail.com
|
26cfc889d7b6163db0344cbcb86c169815ade65c
|
569fd2b3d67f67d6246a5d7544d949b1e510943e
|
/hw2/hw2_additional.py
|
7d701724577befa70b1ec627bfb15b8a3bd71b69
|
[] |
no_license
|
melnikova12/PYTHON_2year
|
a97070a127a61218c3e6981745142e46d7ca021d
|
c53a389fb951f54aca8d512b9c397832a91df544
|
refs/heads/master
| 2020-03-28T05:32:42.268548
| 2019-06-13T10:16:51
| 2019-06-13T10:16:51
| 147,782,993
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,305
|
py
|
import json
import urllib.request
token = '13b9626cc3dc9e1b5f11fe0799be0923770da2ff'
print('Важное примечание: программа разделена отступами, поэтому для продолжения работы Enter нужно будет нажимать 2 раза')
#функция, которая получает на вход список репозиториев
def getting_users():
users = []
a = input('Введите имена пользователей гитхаба, с которыми будет произведена работа (когда закончите вводить, нажмите Enter 2 раза): ')
while a != '':
users.append(a)
a = input() #для того, чтобы закончить цикл
print('Список введеных репозиториев: ', users)
return users
getting_users()
#функция ищет репозитории пользователя
#задание1
#Выбрать какого-то одного пользователя из полученного списка и
#распечатать список его репозиториев (name) и их описания (description).
#Выбор пользователя должен осуществляться с помощью ввода с клавиатуры (функция input()).
def repositories(username, token):
username = input('Выберите пользователя из данного списка: ')
url = 'https://api.github.com/users/%s/repos?access_token=%s' % (username, token)
# по этой ссылке мы будем доставать джейсон, попробуйте вставить ссылку в браузер и посмотреть, что там
response = urllib.request.urlopen(url) # посылаем серверу запрос и достаем ответ
text = response.read().decode('utf-8') # читаем ответ в строку
data = json.loads(text) # превращаем джейсон-строку в объекты питона
print("1. Количество репозиториев у пользователя: ", len(data)) # сколько у пользователя репозиториев
for i in data:
print('Название репозитория и его описание: ')
print('{}: "{}".'.format(i["name"], i["description"])) #названия и описания репозиториев
repositories(input(), token)
#задание2
#Распечатать список языков (language) выбранного пользователя и количество репозиториев, в котором они используются
def languages(username,token):
d = {}
username = input('Повторно выберите пользователя для анализа языков в репозитории: ')
url = 'https://api.github.com/users/%s/repos?access_token=%s' % (username, token)
response = urllib.request.urlopen(url)
text = response.read().decode('utf-8')
data = json.loads(text)
for i in data:
print('2. В репозитории ',i["name"],' используются следующие языки:', i["language"])
if i['language'] in d:
d[i['language']] +=1
else:
d[i['language']] = 1
for i in d:
print('Язык {} встречается в следующем количестве репозиториев: {}'.format(i,d[i]))
return
languages(input(), token)
#задание3
#Узнать, у кого из пользователей в списке больше всего репозиториев.
def reps(users,token):
leader = '' #имя пользователя гитхаба
number = 0 #число подписчиков
for user in users:
url = 'https://api.github.com/users/%s/repos?access_token=%s' % (user, token)
response = urllib.request.urlopen(url)
text = response.read().decode('utf-8')
data = json.loads(text)
if len(data) > number:
number = len(data)
leader = user
print('3. Пользователь, у которого наибольшее количество репозиториев: ', leader)
return
users = getting_users()
reps(users, token)
#задание5
#Узнать, у кого из пользователей списка больше всего фолловеров?
def followers(users, token):
leader = '' #имя пользователя гитхаба
number = 0 #число подписчиков
for user in users:
url = 'https://api.github.com/users/%s/followers?access_token=%s' % (user, token)
response = urllib.request.urlopen(url)
text = response.read().decode('utf-8')
data = json.loads(text)
if len(data) > number:
number = len(data)
leader = user
print('4. Пользователь, у которого наибольшее количество подписчиков: ', leader)
return
users = getting_users()
followers(users, token)
|
[
"noreply@github.com"
] |
melnikova12.noreply@github.com
|
64468551b280b660478ce46441e8b4893ada4082
|
95b57cb90ea0625ede16679b0a6a324342c1ec28
|
/stars/apps/ad/migrations/0001_initial.py
|
ad4709638085a107cff557befb20438d72f7dd3e
|
[] |
no_license
|
lisongwei15931/stars
|
2814f5cc9d08dd26a25048f91b27ff1607a659cb
|
3d6198c2a1abc97fa9286408f52c1f5153883b7a
|
refs/heads/master
| 2022-11-27T07:08:52.048491
| 2016-03-18T09:33:55
| 2016-03-18T09:33:55
| 54,242,594
| 0
| 0
| null | 2022-11-22T00:36:28
| 2016-03-19T02:10:35
|
Python
|
UTF-8
|
Python
| false
| false
| 1,385
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='RollingAd',
fields=[
('id', models.AutoField(serialize=False, primary_key=True)),
('title', models.CharField(max_length=128, verbose_name='\u6807\u9898')),
('link_url', models.CharField(max_length=128, verbose_name='\u94fe\u63a5\u5730\u5740')),
('position', models.CharField(max_length=30, verbose_name='\u5e7f\u544a\u4f4d\u7f6e', choices=[(b'home_ad', b'\xe4\xb8\xbb\xe9\xa1\xb5'), (b'other', b'\xe5\x85\xb6\xe4\xbb\x96')])),
('image', models.ImageField(upload_to=b'images/products/%Y/%m/', max_length=255, verbose_name='Image')),
('description', models.TextField(default=b'', max_length=255, verbose_name='Description')),
('order_num', models.PositiveIntegerField(default=0, verbose_name='\u987a\u5e8f\u53f7')),
('valid', models.BooleanField(default=True, verbose_name='\u542f\u7528')),
],
options={
'ordering': ['-order_num', 'id'],
'abstract': False,
'verbose_name': 'Rolling advertisement',
},
),
]
|
[
"lisongwei1593@gmail.com"
] |
lisongwei1593@gmail.com
|
d793585dda84fb7a7352f30ab7d808f989a4c619
|
817b6bd0b18d5f93de46283bb961185a0b70e71f
|
/K2_Funding_Ticket/CTR_preprocess.py
|
023e6566be40c1f93e1fcf3a78a7bbd7967e35a6
|
[] |
no_license
|
mattstirling/CTR_Recon
|
5e75f07f39fdd20a02c380ba5d214695b63cc603
|
fdf3633c936ecfc977814c04c7f03f0c325694bc
|
refs/heads/master
| 2021-01-17T11:07:02.994311
| 2017-08-14T22:29:42
| 2017-08-14T22:29:42
| 52,452,978
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,651
|
py
|
'''
Created on Feb 23, 2016
@author: mstirling
'''
import pandas as pd, os, ConfigParser, re
from Map_Rules import apply_map_rule # @UnresolvedImport
def filename_to_RWyyyymmdd(filename):
match = re.search(r'.*_D_([0-9]{4})([0-9]{2})([0-9]{2})_.*',filename)
if match: return match.group(1) + '/' + match.group(2) + '/' + match.group(3)
#open config file
config = ConfigParser.ConfigParser()
config.read('config.ini')
#in folder
in_folder = config.get('filename','in_folder_CTR')
#in map files
map_folder = config.get('filename','in_folder_map')
map_file = config.get('filename','in_file_map')
#out files
out_folder = config.get('filename','out_folder')
out_file = config.get('filename','out_file_CTR')
#get list of in_files
#want only ANVIL repo files + Impact triparty files
#want only _Repo_Reverse_Repo_D_
all_filenames = [f for f in os.listdir(in_folder) if os.path.isfile(os.path.join(in_folder, f))]
in_filenames = ([f for f in all_filenames
if f[-4:] == '.csv'
and (f[:2] == 'K2')
and ('K2_Funding_Ticket_D_' in f)])
#No good way to filter out the K2_Bermuda_Swap_Option_D_ files
#prefix the directory
in_filenames = [in_folder + f for f in in_filenames]
#open each file into a dataframe (all have same header)
df_list = []
for f in in_filenames:
df_list.append(pd.read_csv(f))
#merge all dataframes into 1
df_merge = pd.concat(df_list,axis=0)
df_merge.reset_index(inplace=True)
#filter on the maturity date
business_date = filename_to_RWyyyymmdd(in_filenames[0])
#df_merge = df_merge[(~df_merge['Maturity Date'].str.contains(business_date))]
print 'CTR num records: ' + str(len(df_merge.index))
print 'CTR num columns: ' + str(len(df_merge.columns))
#reorder columns
df_merge.sort_index(axis=1,inplace=True)
#apply mapping rules
df_map = pd.read_csv(map_folder+map_file)
for i in df_map['Column Name'].index:
this_col = str(df_map.at[i,'Column Name'])
this_map_rule = str(df_map.at[i,'CTR Map Rule'])
#apply the mapping rule if rule 'not nan/blank'
if not this_map_rule == 'nan':
for j in df_merge.index:
df_merge.at[j, this_col] = apply_map_rule(df_merge.at[j, this_col], this_map_rule)
#sort the CTR dataframe by Name
sort_col = 'Name'
#write out_files
try: os.stat(out_folder[:-1])
except: os.mkdir(out_folder[:-1])
#df_merge.to_csv(out_folder + out_file_merged,index=False,columns=out_cols_FX_Deals)
df_merge.to_csv(out_folder + out_file,index=False)
print 'done.'
print 'from ' + in_folder
print 'to ' + out_folder
|
[
"mstirling@ScotiaFalcon"
] |
mstirling@ScotiaFalcon
|
5570b9a2b688c2bd3b579b6ef02e6f547264f598
|
4b30fa26f7c5dfb413950fc4dc9e4e89129944c4
|
/euler015_v2.py
|
6c79b525d39aad898e47c1e98c9b9c75c4ed8aba
|
[] |
no_license
|
sadimauro/projecteuler
|
ca6f6cc3e8eac83bdb667c88a9b892923a3df57c
|
a07b71ecdf7f0cc7b53fcd021c67c5a7518d8571
|
refs/heads/master
| 2021-07-08T00:12:46.272408
| 2020-07-11T12:32:56
| 2020-07-11T12:32:56
| 143,607,960
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 367
|
py
|
#!/usr/bin/python3
import time
tStart = time.time()
import math
def calcRoutes(m,n):
return int(math.factorial(m+n) / (math.factorial(m) * math.factorial(n)))
#for i in range(1,20):
# print(str(i) + " -> " + str(calcRoutes(i,i)))
print(__file__ + ": answer: " + str(calcRoutes(20,20)))
print("Run time: " + '{:.20f}'.format(time.time() - tStart) + " sec")
|
[
"steve@localhost.localdomain"
] |
steve@localhost.localdomain
|
73ec9580beeac6a40c205536e0df04b1b5544478
|
c6a4716045e01eae2542702a9f35f5f0c66a5fb7
|
/bars.py
|
fbace09c1291494faf647eb1bb122ccf1e33ad12
|
[] |
no_license
|
a05558/Code
|
a72ae14d6611ff8af91a1bc8ce98095e74d21434
|
8164967903990099ad3e0b0f69d4ea9225e1a22c
|
refs/heads/master
| 2020-08-30T11:57:31.784698
| 2019-10-31T14:10:59
| 2019-10-31T14:10:59
| 214,753,103
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 351
|
py
|
#!/usr/bin/env python3
"""
Bars Module
===========
"""
def starbar(num):
"""Print * SplitLine
:arg num: lenght
"""
print('*' * num)
def hashbar(num):
"""Print # SplitLine
:arg num:Line Lenght
"""
print('#' * num)
def simplebar(num):
"""Print - Split Line
:arg num:Line Lenght
"""
print('-' * num)
|
[
"a05558@126.com"
] |
a05558@126.com
|
f151b257af1d0a1b944861e19b26624b83abf4f9
|
91ff804355b6101816f0980277dce07c4e845ee6
|
/audio_splitter.py
|
32c58bc34efdcb93bc81dbcc52809e3860dc4768
|
[
"MIT"
] |
permissive
|
productivity-in-tech/pit_transcriptor_amazon
|
f5e16342ccd5c2b3dc7caeb9bb1618c3f46f23ed
|
0b9707765eb2912e4146df7ae16637fe95e31cca
|
refs/heads/master
| 2023-08-03T08:35:29.534818
| 2020-04-11T19:24:31
| 2020-04-11T19:24:31
| 206,214,545
| 2
| 1
|
MIT
| 2023-07-22T15:16:53
| 2019-09-04T02:33:48
|
HTML
|
UTF-8
|
Python
| false
| false
| 3,536
|
py
|
from pathlib import Path
import boto3
import click
import json
import logging
import os
import requests
import shutil
import sys
import time
import typing
def start_transcription(
key,
*,
storage,
transcribe,
bucket,
ChannelIdentification=True,
lang='en-US',
):
transcribe_job_uri = f'{storage.meta.endpoint_url}/{bucket}/{key}'
click.echo(Path(key).suffix[1:])
transcribe.start_transcription_job(
TranscriptionJobName=key,
Media={'MediaFileUri': transcribe_job_uri},
MediaFormat= Path(key).suffix[1:],
LanguageCode=lang,
Settings={'ChannelIdentification': ChannelIdentification},
)
return key
@click.group()
def cli():
pass
@cli.command()
@click.option('--channels', is_flag=True)
@click.option('--check', '-c', is_flag=True)
@click.argument('base_audio_file')
def transcription(
channels,
base_audio_file,
check,
directory,
):
# Amazon Information
bucket = os.environ['BUCKET_NAME']
storage = boto3.client('s3')
transcribe = boto3.client('transcribe')
key=Path(base_audio_file).name.replace(' ', '')
if check:
job = transcribe.get_transcription_job(TranscriptionJobName=key)
job_status = job['TranscriptionJob']['TranscriptionJobStatus']
if job_status != 'IN_PROGRESS':
job_uri = job['TranscriptionJob']['Transcript']['TranscriptFileUri']
r = requests.get(job_uri)
r.raise_for_status()
with open(f'{key}.json', 'w') as json_file:
json_file.write(json.dumps(r.json()))
click.echo('Job: {key} complete and written')
return # Terminates the script
storage.upload_file(
Filename=base_audio_file,
Bucket=bucket,
Key=key,
)
return start_transcription(
key=key, bucket=bucket, storage=storage,
transcribe=transcribe, ChannelIdentification=channels,
)
@cli.command()
@click.argument('directory')
@click.option('--check', '-c', is_flag=True)
@click.option('--channels', is_flag=True)
@click.option('--file-format', default='mp3')
def bulk_transcription(
directory,
check,
channels,
file_format,
):
bucket = os.environ['BUCKET_NAME']
storage = boto3.client('s3')
transcribe = boto3.client('transcribe')
for path in Path(directory).rglob(f'*.{file_format}'):
key = path.name.replace(' ', '')
if check:
job = transcribe.get_transcription_job(TranscriptionJobName=key)
job_status = job['TranscriptionJob']['TranscriptionJobStatus']
if job_status != 'IN_PROGRESS':
job_uri = job['TranscriptionJob']['Transcript']['TranscriptFileUri']
r = requests.get(job_uri)
r.raise_for_status()
with open(f'{key}.json', 'w') as json_file:
json_file.write(json.dumps(r.json()))
click.echo(f'Job: {key} complete and written')
continue # Terminates the script
storage.upload_file(
Filename=str(path),
Bucket=bucket,
Key=key,
)
start_transcription(
key=key, bucket=bucket, storage=storage,
transcribe=transcribe, ChannelIdentification=channels,
)
return
if __name__ == '__main__':
cli()
|
[
"kjaymiller@gmail.com"
] |
kjaymiller@gmail.com
|
f81fdbd05eca974c4a3328021bab8e00dca44ae2
|
7e634099fe67db053ddebfb043203bf74c9bf6e7
|
/coder-interview-guide/11-打印两个链表的公共部分.py
|
ade336965972ccfcb814d5ecbc9e300e05cbe5f0
|
[] |
no_license
|
longjiemin/Interviews-and-algorithms-python-
|
40a2b0231f1a63437152ec200bf0a6b20d385c78
|
0d8ada1d8aacdfc826b30c48ee0d38935bf7b892
|
refs/heads/master
| 2020-03-13T20:11:40.146583
| 2018-10-15T12:47:00
| 2018-10-15T12:47:00
| 131,268,575
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,421
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 16:22:11 2018
@author: longjiemin
"""
#1
#打印两个有序列表的公共部分
#难度:一星
#说明:
#完成:
class list_node():
def __init__(self,data=None,next=None):
self.data = data
self.next = next
class LList(object):
def __init__(self,nums):
self.head = None
if nums is not None:
for i in nums:
self.append(i)
def append(self,elem):
if self.head is None:
self.head = list_node(elem)
return
p = self.head
while p.next is not None:
p = p.next
p.next = list_node(elem)
def __repr__(self):
nums_all = 'LList:'
p = self.head
while p is not None:
nums_all += str(p.data)
if p.next is not None:
nums_all += '->'
p = p.next
return nums_all
def get_public(LList1,LList2):
cur1 = LList1.head
cur2 = LList2.head
while None not in (cur1,cur2):
if cur1.data== cur2.data:
print(cur1.data)
cur1 = cur1.next
cur2 = cur2.next
elif cur1.data < cur2.data:
cur1 = cur1.next
else:
cur2 = cur2.next
return
|
[
"longjiemin11@gmail.com"
] |
longjiemin11@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.