blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
281
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 6
116
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 313
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 18.2k
668M
⌀ | star_events_count
int64 0
102k
| fork_events_count
int64 0
38.2k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 107
values | src_encoding
stringclasses 20
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 4
6.02M
| extension
stringclasses 78
values | content
stringlengths 2
6.02M
| authors
listlengths 1
1
| author
stringlengths 0
175
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
572253b9a187470080137315d72e1e91c8ee594b
|
a30cb7c68459b10d21cb91d00745a3e05ebb6c41
|
/pygame/08_sprites.py
|
53d8da65846927cf1a84bf9898368071bd15e381
|
[] |
no_license
|
LyceeClosMaire/FormationBiblio
|
2f5172214da2be3868003df8e197a02098d69317
|
8cd14f6add80f00bd34e3c1de934ef2400a9d152
|
refs/heads/master
| 2021-01-19T09:49:35.217001 | 2017-05-24T13:37:28 | 2017-05-24T13:37:28 | 87,790,941 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,270 |
py
|
import pygame
from pygame.locals import *
# les définitions de classes sont introduites par le mot clé class
# puis le nom de la classe, puis entre parenthèses la classe dont elle hérite
class Ball(pygame.sprite.Sprite):
# la méthode __init__ (avec des doubles tirets bas des deux côtés) est très
# importante, c'est celle qui est appelée lorsqu'on construit un objet de
# la classe.
# notez le premier paramètre, conventionnellement appelé "self" ("soi-même")
# il désigne l'objet qu'on est en train de construire
def __init__(self, position, speed):
# lorsque l'on hérite d'une classe, il est préférable de commencer le constructeur
# par un appel au constructeur de la classe parente que l'on retrouve avec super()
super().__init__()
# les attributs de l'objet (les données qui lui sont attachées) doivent
# être initialisée, généralement dans __init__()
self.speed = speed
# rect est un attribut standard des Sprites, vous devez toujours l'initialiser
# pour que vos sprites marchent correctement avec les fonctions de collision
self.rect = pygame.rect.Rect( (0,0), (50,50) )
self.rect.center = position
# de même image est un attribut standard, utilisé par draw() sur un Group
self.image = pygame.Surface( (50,50), SRCALPHA )
self.image.fill( (0,0,0,0) )
pygame.draw.circle(self.image, (255,0,0), (25,25), 25)
# la méthode update() est celle qui sera appelée à chaque tour de boucle pour
# mettre à jour l'état interne de votre Sprite qui est toujours le premier paramètre
# de toute méthode (fonction attachée à un objet)
def update(self):
self.rect.move_ip(self.speed)
# la méthode draw() sera appelée pour dessiner le sprite sur une surface
def draw(self, surface):
# voici ce que fait Group par défaut :
surface.blit( self.image, self.rect )
# les définitions de classes ou fonctions se font généralement dans un module
# à part mais ici pour l'exemple tout est réuni dans un même programme
pygame.init()
clock = pygame.time.Clock()
window = pygame.display.set_mode( (800,600) )
winrect = window.get_rect()
# il est possible de créer autant d'objets de la classe Ball que l'on souhaite
ball1 = Ball( (10,10), (3,3) )
ball2 = Ball( (500,500), (-1,-4) )
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT or(event.type == KEYUP and event.key == K_ESCAPE):
running = False
# les Sprites doivent être mis à jour manuellement, ou par l'intermédiaire d'un
# Group comme nous le verrons
# Notez que le paramètre "self" n'est pas passé entre parenthèse mais automatiquement
# à cause de la syntaxe objet.méthode()
ball1.update()
ball2.update()
window.fill( (0,0,0) )
# le détail du dessin peut être ignoré mais il nous faut encore dessiner les balles
# une par une, Group palliera à ceci. Nous dessinons directement sur window.
ball1.draw(window)
ball2.draw(window)
pygame.display.flip()
pygame.quit()
|
[
"[email protected]"
] | |
6bfd23840261bb11b4ad1cbe4485024aaf39ee33
|
caa34a2291ecadb8daa5ff147565d284f41b26ca
|
/spring1718_assignment2_v2/learn_keras.py
|
05d03821429cd8e8da1b9f85292bd464ab87476c
|
[] |
no_license
|
shuyanzhu/leran_cs231n
|
c287446efa1e2c9724c3316d82ea03297dd26089
|
210c1f7ec9622d5bbcf9f12b5bab06fc8ffeea98
|
refs/heads/master
| 2020-04-16T18:26:24.052223 | 2019-02-26T06:16:12 | 2019-02-26T06:16:12 | 164,188,886 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,678 |
py
|
import numpy as np
import tensorflow as tf
# 加载数据
def load_cifar10():
cifar10 = tf.keras.datasets.cifar10.load_data()
(X_train, y_train), (X_test, y_test) = cifar10
X_train = X_train.astype(np.float32)
y_train = y_train.astype(np.int32).flatten()
X_test = X_test.astype(np.float32)
y_test = y_test.astype(np.int32).flatten()
val_size = 1000
X_val = X_train[:val_size]
y_val = y_train[:val_size]
X_train = X_train[val_size:]
y_train = y_train[val_size:]
mean_pixel = X_train.mean(axis=(0, 1, 2), keepdims=True)
std_pixel = X_train.std(axis=(0, 1, 2), keepdims=True)
X_train = (X_train - mean_pixel) / std_pixel
X_val = (X_val - mean_pixel) / std_pixel
X_test = (X_test - mean_pixel) / std_pixel
print('Trian data size', X_train.shape)
print('Train labels size', y_train.shape)
print('Validation data size', X_val.shape)
print('Validation labels size', y_val.shape)
print('Test data size', X_test.shape)
print('Test labels size', y_test.shape)
return X_train, y_train, X_val, y_val, X_test, y_test
# 建立模型
def inference(inputs):
x = tf.layers.BatchNormalization()(inputs)
x = tf.layers.Conv2D(16, [5, 5], activation='relu', padding='same')(x)
x = tf.layers.BatchNormalization()(x)
x = tf.layers.Conv2D(32, [3, 3], activation='relu', padding='same')(x)
x = tf.layers.Flatten()(x)
x = tf.layers.Dropout()(x)
x = tf.layers.BatchNormalization()(x)
x = tf.layers.Dense(120, activation='relu')(x)
x = tf.layers.Dropout()(x)
x = tf.layers.BatchNormalization()(x)
outputs = tf.layers.Dense(10, activation='softmax')(x)
return outputs
if __name__ == '__main__':
# 导入数据
X_train, y_train, X_val, y_val, X_test, y_test = load_cifar10()
train_dset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
train_dset = train_dset.batch(64).repeat()
validation_dset = tf.data.Dataset.from_tensor_slices((X_val, y_val))
validation_dset = validation_dset.batch(64).repeat()
# 构建模型
inputs = tf.keras.Input(shape=(32, 32, 3))
outputs=inference(inputs)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer=tf.train.AdamOptimizer(5e-4),
loss = 'sparse_categorical_crossentropy',
metrics=['accuracy'])
checkpoint = tf.keras.callbacks.ModelCheckpoint('./model-{epoch:02d}.hdf5', monitor='val_acc', save_best_only=True, verbose=1)
history = model.fit(train_dset, epochs=5, steps_per_epoch=49000//64, validation_data = validation_dset, validation_steps=1000//64, callbacks=[checkpoint])
print(history.history)
|
[
"[email protected]"
] | |
d6ed4c471e16de0dbe3a1f1b89a719fd27fbf993
|
f5b0d6cca8caadb34da340592514154fd711bca5
|
/archive/Front-end/moments.py
|
fcaa4aec0fef16e6b3f1f36af92b05ec1bb49b31
|
[] |
no_license
|
DmitryBol/reel
|
3e66eed5b18c3e26b147c0e8baa8e9043b3b26ea
|
e08de8ed4be222c2369d8b7579509fa5ccd3df07
|
refs/heads/master
| 2021-06-07T10:32:50.473918 | 2020-02-04T17:08:26 | 2020-02-04T17:08:26 | 130,555,036 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,649 |
py
|
# xi - random variable, equals payment for combination
# eta - random variable, equals the number of freespins given for combination
# zeta - random variable, equals payment for freespin
def Exi2(self, width, lines):
s = 0
for str_with_count in self.simple_num_comb:
string = str_with_count[0]
payment = self.get_simple_payment(string)
s += str_with_count[1] / self.all_combinations() * (payment ** 2)
for scatter_comb in self.scatter_num_comb:
scat = scatter_comb[0]
counts = scatter_comb[1]
for cnt in range(width + 1):
s += ((self.symbol[scat].payment[cnt] * len(lines)) ** 2) * counts[cnt] / self.all_combinations()
return s
def Exieta(self, width, lines):
s = 0
for scatter_comb in self.scatter_num_comb:
scat = scatter_comb[0]
counts = scatter_comb[1]
for cnt in range(width + 1):
s += (self.symbol[scat].payment[cnt] * len(lines)) * self.symbol[scat].scatter[cnt] * \
counts[cnt] / self.all_combinations()
return s
def Eeta(self, width):
s = 0
for scatter_comb in self.scatter_num_comb:
scat = scatter_comb[0]
counts = scatter_comb[1]
for cnt in range(width + 1):
s += self.symbol[scat].scatter[cnt] * counts[cnt] / self.all_combinations()
return s
def Eeta2(self, width):
s = 0
for scatter_comb in self.scatter_num_comb:
scat = scatter_comb[0]
counts = scatter_comb[1]
for cnt in range(width + 1):
s += (self.symbol[scat].scatter[cnt] ** 2) * counts[cnt] / self.all_combinations()
return s
|
[
"[email protected]"
] | |
a69149ec8b9dd6535e90898b9807d97f229a412f
|
3b46e9f7e2fef169589f336f09f00a9294cb3b04
|
/test/core/test_drop.py
|
72e7efc40fd48127ce67ee9e678a8d3cf8b19500
|
[] |
no_license
|
Vayana/sumpter
|
79128ac2bcb4fe6cd05435e9e80e4ad6cb8ba28b
|
f18d7c5c3f8d32a2ae8abf58a70a31614bdc2e39
|
refs/heads/master
| 2020-12-25T18:16:33.833216 | 2016-09-15T10:44:18 | 2016-09-15T10:44:18 | 467,042 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,576 |
py
|
#############################################################################
# Copyright 2010 Dhananjay Nene
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#############################################################################
__author__ = '<a href="[email protected]">Naresh Khalasi</a>'
from sumpter import *
import unittest
class TestDrop(unittest.TestCase):
def setUp(self):
self.ctx = {1:'hello','world':'foo'}
self.val = ['foo',('bar','baz'),{'boom':555}]
def tearDown(self):
pass
def get_new_drop(self):
return Drop(self.ctx,self.val)
def testConstruction(self):
drop = self.get_new_drop()
self.assert_(isinstance(drop.id,(int,long)))
self.assertEqual(drop.trace,[])
self.assertEqual(drop.parents,[])
self.assertEqual(drop.children,[])
self.assertEqual(drop.alive,True)
self.assertEqual(drop.ctx, self.ctx)
self.assertEqual(drop.val, self.val)
def testEmptyConstruction(self):
drop = Drop(None,None)
self.assertEqual(drop.ctx,{})
self.assertEqual(drop.val,None)
def testDifferentIds(self):
drop1 = Drop(None,None)
drop2 = Drop(None,None)
self.assertNotEqual(drop1.id, drop2.id)
def testChildCreation(self):
drop_parent = self.get_new_drop()
drop_child = drop_parent.create_child('hello')
self.assertEqual(drop_child.ctx,self.ctx)
self.assertEqual(drop_child.val,'hello')
self.assertEqual(drop_parent.children,[drop_child])
self.assertEqual(drop_child.parents,[drop_parent])
def testTrace(self):
drop = self.get_new_drop()
drop.record('One')
drop.record('Two')
self.assertEqual(drop.trace,['One','Two'])
self.assertEqual(drop.get_trace(),'One=>Two')
def testKillDrop(self):
drop = self.get_new_drop()
drop.kill()
self.assertEqual(drop.alive,False)
def testRecordAKilledDrop(self):
drop = self.get_new_drop()
drop.kill()
try :
drop.record('foo')
self.fail('Should have raised a runtime error on drop.record() for a killed drop')
except Exception as e :
self.assertEquals(e,PypeRuntimeError('inactive-drop-operation-record',drop,'foo'))
def testCreateChildOnKilledDrop(self):
drop = self.get_new_drop()
drop.kill()
try :
drop.create_child('hello')
self.fail('Should have raised a runtime error on drop.create_child() for a killed drop')
except Exception as e :
self.assertEquals(e,PypeRuntimeError('inactive-drop-operation-create-child',drop))
def testKillAKilledDrop(self):
drop = self.get_new_drop()
drop.kill()
try :
drop.kill()
self.fail('Should have raised a runtime error on drop.kill() for a killed drop')
except Exception as e :
self.assertEquals(e,PypeRuntimeError('inactive-drop-operation-kill',drop))
|
[
"[email protected]"
] | |
2e5daa13e1b08a262d40a179079d7d11029e9af2
|
5a0d6fff86846117420a776e19ca79649d1748e1
|
/rllib_exercises/serving/do_rollouts.py
|
d2dff98d01aa7e23c66a2e98eb958ee472389934
|
[] |
no_license
|
ray-project/tutorial
|
d823bafa579fca7eeb3050b0a13c01a542b6994e
|
08f4f01fc3e918c997c971f7b2421551f054c851
|
refs/heads/master
| 2023-08-29T08:46:38.473513 | 2022-03-21T20:43:22 | 2022-03-21T20:43:22 | 89,322,668 | 838 | 247 | null | 2022-03-21T20:43:22 | 2017-04-25T05:55:26 |
Jupyter Notebook
|
UTF-8
|
Python
| false | false | 1,596 |
py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import argparse
import gym
from ray.rllib.utils.policy_client import PolicyClient
parser = argparse.ArgumentParser()
parser.add_argument(
"--no-train", action="store_true", help="Whether to disable training.")
parser.add_argument(
"--off-policy",
action="store_true",
help="Whether to take random instead of on-policy actions.")
if __name__ == "__main__":
args = parser.parse_args()
import pong_py
env = pong_py.PongJSEnv()
client = PolicyClient("http://localhost:8900")
eid = client.start_episode(training_enabled=not args.no_train)
obs = env.reset()
rewards = 0
episode = []
f = open("out.txt", "w")
while True:
if args.off_policy:
action = env.action_space.sample()
client.log_action(eid, obs, action)
else:
action = client.get_action(eid, obs)
next_obs, reward, done, info = env.step(action)
episode.append({
"obs": obs.tolist(),
"action": float(action),
"reward": reward,
})
obs = next_obs
rewards += reward
client.log_returns(eid, reward, info=info)
if done:
print("Total reward:", rewards)
f.write(json.dumps(episode))
f.write("\n")
f.flush()
rewards = 0
client.end_episode(eid, obs)
obs = env.reset()
eid = client.start_episode(training_enabled=not args.no_train)
|
[
"[email protected]"
] | |
e9806015f09ccc031ad62365dc83e32b6cc6f466
|
1923a90cc154450343ed650085f2ee97ddca9181
|
/env/bin/django-admin
|
c972bbc6f98452dd8790ec25fd08d1b23049c102
|
[] |
no_license
|
Demieno/django-gulp-docker-ansible
|
230c95a107a5e28b8ed55f2f0d26d8075df130ec
|
f2e2f74f70c32c02f65a702033042c540bac938a
|
refs/heads/master
| 2020-03-07T18:06:59.295552 | 2018-04-01T12:58:01 | 2018-04-01T12:58:01 | 127,628,674 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 291 |
#!/var/idpowers/redcross/env/bin/python3.5
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
|
[
"[email protected]"
] | ||
c8e7deb719db05703d93fe764028941e8baac0db
|
25768f25147068914d7a88db6765411e33a9f708
|
/django_itchat-master/wechat/app/views_bak.py
|
02461fd22dc2129827659afb23ab1ed59a21adf4
|
[] |
no_license
|
QzeroQ/python
|
d00739ca4630b2e84c65d726c9e0ad09a60f8a83
|
23e7fd4b3867bcced17febfadaf6094965707420
|
refs/heads/master
| 2022-04-15T11:15:53.468501 | 2020-03-26T16:24:21 | 2020-03-26T16:24:21 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 20,542 |
py
|
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from wxpy import *
import uuid
from wechat.settings import BASE_DIR, MEDIA_ROOT
import os, time, base64, json, random
from .models import *
from django.contrib.auth.models import User as uuu
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
# Create your views here.
qr_path = os.path.join(BASE_DIR, 'wechat/')
def path_check(qr_path):
if os.path.exists(qr_path):
os.remove(qr_path)
class WXBot(object):
def __init__(self, request):
self.qr_s = ''
self.qr_path = qr_path + request.user.username + '.png'
def callback(self, uuid, status, qrcode):
f = open(self.qr_path, 'wb')
f.write(qrcode)
f.close()
def get_qr(self):
bot = Bot(cache_path=False, qr_callback=self.callback)
return bot
# 获取登录二维码
@login_required
def qr_img(request):
if request.method == 'POST':
for i in range(5):
time.sleep(2)
if os.path.exists(qr_path + request.user.username + '.png'):
res = {
'img': str(base64.b64encode(open(qr_path + request.user.username + '.png', 'rb').read()),
encoding='utf8')
}
return JsonResponse(res)
continue
# 获取数据库里的群列表 和 组列表
@login_required
def get_group_list(request):
uuid_str = str(uuid.uuid4())
group_list = groups_name.objects.all()
set_list = grouping.objects.all()
set_res = []
for i in set_list:
set_name = []
obj = i.group.all()
for j in obj:
set_name.append(j.name)
d = {
'id': i.id,
'set_name': i.group_name,
'group_names': ','.join(set_name),
'num': len(obj)
}
set_res.append(d)
return render(request, 'app/group_list.html', {'data': group_list, 'set': set_res, 'uuid': uuid_str})
# 添加群
@login_required
def create_group(request):
if request.method == 'POST':
d = {
'count': 0,
'name_list': []
}
a = WXBot(request)
bot = a.get_qr()
groups = bot.groups()
print(groups)
d['count'] = len(groups)
for i in groups:
d['name_list'].append(i.nick_name)
groups_name.objects.get_or_create(
name=i.nick_name, users_num=len(i.members), owner=i.owner.name
)
bot.logout()
path_check(qr_path=qr_path + request.user.username + '.png')
return JsonResponse(d)
else:
return render(request, 'app/create_group.html')
# 删除群
@login_required
def delete_group(request):
if request.method == 'POST':
id = request.POST.get('id', '')
typ = request.POST.get('typ', 'one') # 默认单个删除
if id:
if typ == 'one':
u = groups_name.objects.filter(id=int(id))
if u:
u[0].delete()
return JsonResponse(
{
'msg': '删除成功!',
'status': True
}
)
else:
return JsonResponse(
{
'msg': '该群不存在!',
'status': False
}
)
else:
id_list = json.loads(id)
for i in id_list:
u = groups_name.objects.filter(id=int(i))
u[0].delete()
return JsonResponse(
{
'msg': '删除成功!',
'status': True
}
)
else:
return JsonResponse(
{
'msg': '参数错误!',
'status': False
}
)
# 添加组
def add_set(request):
if request.method == 'POST':
set_name = request.POST.get('set_name', '')
group_id_list = request.POST.get('group_name', '')
if set_name and group_id_list:
g_l = [int(x) for x in json.loads(group_id_list)]
if grouping.objects.filter(group_name=set_name):
return JsonResponse(
{
'status': False,
'msg': '群名重复,请检查!'
}
)
grouping_obj = grouping.objects.create(group_name=set_name)
grouping_obj.group.set(groups_name.objects.filter(id__in=g_l))
return JsonResponse(
{
'status': True,
'msg': '添加成功!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '参数有误!'
}
)
group_list = groups_name.objects.all()
return render(request, 'app/add_set.html', {'data': group_list})
# 删除组
def delete_set(request):
if request.method == 'POST':
id = request.POST.get('id', '')
typ = request.POST.get('typ', 'one')
if id:
if typ == 'one':
obj = grouping.objects.filter(id=int(id))
if obj:
obj[0].delete()
return JsonResponse(
{
'status': True,
'msg': '删除成功!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '组不存在!'
}
)
else:
id_list = json.loads(id)
for i in id_list:
obj = grouping.objects.filter(id=int(i))
obj[0].delete()
return JsonResponse(
{
'status': True,
'msg': '删除成功!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '参数有误!'
}
)
# 编辑组
def edit_set(request):
if request.method == 'POST':
set_id = request.POST.get('set_id', '')
set_name = request.POST.get('set_name', '')
group_id_list = request.POST.get('group_name', '')
if set_name and group_id_list and set_id:
g_l = [int(x) for x in json.loads(group_id_list)]
if grouping.objects.exclude(id=int(set_id)).filter(group_name=set_name):
return JsonResponse(
{
'status': False,
'msg': '群名重复,请检查!'
}
)
grouping_obj = grouping.objects.get(id=int(set_id))
grouping_obj.group.set(groups_name.objects.filter(id__in=g_l))
return JsonResponse(
{
'status': True,
'msg': '添加成功!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '参数有误!'
}
)
set_id = request.GET.get('set_id', '')
group_name = []
weixuan = []
grouping_name = ''
if set_id:
obj = grouping.objects.filter(id=int(set_id))
if obj:
grouping_name = obj[0].group_name
group_name = obj[0].group.all()
id_list = []
for i in group_name:
id_list.append(i.id)
weixuan = groups_name.objects.exclude(id__in=id_list)
return render(request, 'app/edit_set.html',
{'group_name': group_name, 'weixuan': weixuan, 'grouping_name': grouping_name, 'set_id': set_id})
# 组发送
def send_set(request):
uuid_str = str(uuid.uuid4())
set_list = grouping.objects.all()
set_res = []
for i in set_list:
set_name = []
obj = i.group.all()
for j in obj:
set_name.append(j.name)
d = {
'id': i.id,
'set_name': i.group_name,
'group_names': ','.join(set_name),
'num': len(obj)
}
set_res.append(d)
return render(request, 'app/set_send.html', {'set': set_res, 'uuid': uuid_str})
# 提交审核 添加任务
@login_required
def add_task(request):
if request.method == 'POST':
t = request.POST.get('type', 'group') # 默认是组发 群发为 set
content = request.POST.get('content', '')
group_name = request.POST.get('group_name', '')
send_type = request.POST.get('send_type', 'text') # 默认是文字
uuid = request.POST.get('uuid') # 区分任务
if send_type == 'text':
if content and groups_name:
if t == 'group':
task.objects.create(
message=content, group_name=group_name, typ='群发'
)
return JsonResponse({'status': True, 'msg': '添加审核成功,请等待管理员审核!'})
else:
set_id = json.loads(group_name)
l = []
for i in set_id:
for j in grouping.objects.get(id=int(i)).group.all():
d = {"gname": j.name, "owner": j.owner}
l.append(d)
print(l)
task.objects.create(
message=content, group_name=json.dumps(l, ensure_ascii=False), typ='组发'
)
return JsonResponse({'status': True, 'msg': '添加审核成功,请等待管理员审核!'})
else:
return JsonResponse({'status': False, 'msg': '参数错误!'})
else:
if groups_name:
if send_type == 'file':
message_type = '文件'
elif send_type == 'video':
message_type = '视频'
else:
message_type = '图片'
f_obj = file.objects.filter(uuid_str=uuid)
if f_obj:
if t == 'group':
task.objects.create(
message=uuid, uuid_str=uuid, group_name=group_name, typ='群发', message_type=message_type
)
return JsonResponse({'status': True, 'msg': '添加审核成功,请等待管理员审核!'})
else:
set_id = json.loads(group_name)
l = []
for i in set_id:
for j in grouping.objects.get(id=int(i)).group.all():
d = {"gname": j.name, "owner": j.owner}
l.append(d)
print(l)
task.objects.create(
message=uuid, uuid_str=uuid, group_name=json.dumps(l, ensure_ascii=False), typ='组发',
message_type=message_type
)
return JsonResponse({'status': True, 'msg': '添加审核成功,请等待管理员审核!'})
else:
return JsonResponse({'status': False, 'msg': '尚未上传附件,请先上传附件后再提交!'})
else:
return JsonResponse({'status': False, 'msg': '参数错误!'})
# 审核列表
@login_required
def check_list(request):
if request.method == 'POST':
data = {
'msg': '',
'data': [],
'count': '',
'code': 0,
}
task_list = task.objects.all()
for i in task_list:
if i.message_type != '文字':
file_path = file.objects.get(uuid_str=i.uuid_str).file_path
f = file_path.split('==')[-1]
fie =file_path.split('/')[-1]
d = {
'id': i.id,
'message': f,
'message_type': i.message_type,
'group': i.group_name,
'status': i.status,
'typ': i.typ,
'date': i.date.strftime('%Y-%m-%d %H:%M:%S'),
'uuid': i.uuid_str,
'fie_yuanben': fie
}
else:
d = {
'id': i.id,
'message': i.message,
'message_type': i.message_type,
'group': i.group_name,
'status': i.status,
'typ': i.typ,
'date': i.date.strftime('%Y-%m-%d %H:%M:%S'),
'uuid': i.uuid_str,
}
data['data'].append(d)
return JsonResponse(data)
return render(request, 'app/check_list.html')
# 删除任务
@login_required
def delete_task(request):
if request.method == 'POST':
id = request.POST.get('id', '')
typ = request.POST.get('typ', 'one')
if id:
if typ == 'one':
s = task.objects.filter(id=int(id))
if s:
s[0].delete()
return JsonResponse(
{
'status': True,
'msg': '成功!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '参数有误!'
}
)
else:
id_list = json.loads(id)
for i in id_list:
s = task.objects.filter(id=int(i))
s[0].delete()
return JsonResponse(
{
'status': True,
'msg': '成功!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '参数有误!'
}
)
# 审核
@login_required
def check(request):
if request.method == 'POST':
group_name = request.POST.get('group_name', '')
message = request.POST.get('message', '')
id = request.POST.get('id', '')
if group_name and message and id:
group_name = json.loads(group_name)
t = task.objects.get(id=int(id))
t.message = message
t.status = '审核通过'
t.save()
return JsonResponse(
{
'status': True,
'msg': '审核通过!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '参数有误!'
}
)
return render(request, 'app/check.html')
# 发送
@login_required
def send(request):
if request.method == 'POST':
group_name = request.POST.get('group_name', '')
message = request.POST.get('message', '')
message_type = request.POST.get('message_type', '')
id = request.POST.get('id', '')
uuid = request.POST.get('uuid', '')
if group_name and message and id:
group_name = json.loads(group_name)
a = WXBot(request)
bot = a.get_qr()
groups = bot.groups()
for i in group_name:
print(i)
print(message)
try:
if message_type == '文字': # todo
groups.search(i['gname'])[0].send(message)
elif message_type == '文件':
path = file.objects.get(uuid_str=uuid).file_path
groups.search(i['gname'])[0].send_file(path)
elif message_type == '视频':
path = file.objects.get(uuid_str=uuid).file_path
groups.search(i['gname'])[0].send_video(path)
elif message_type == '图片':
path = file.objects.get(uuid_str=uuid).file_path
groups.search(i['gname'])[0].send_image(path)
else:
pass
except:
with open('error.log', 'a+') as f:
f.write('发送失败:{0} >>>{1}\n'.format(i['gname'], message))
pass
time.sleep(random.random())
bot.logout()
path_check(qr_path=qr_path + request.user.username + '.png')
t = task.objects.get(id=int(id))
t.status = '已发送'
t.save()
return JsonResponse(
{
'status': True,
'msg': '发送成功!'
}
)
else:
return JsonResponse(
{
'status': False,
'msg': '参数有误!'
}
)
return render(request, 'app/send.html')
# 登录
def do_login(request):
if request.method == "POST":
username = request.POST.get("username", "")
password = request.POST.get("password", "")
user = authenticate(username=username, password=password)
if user and user.is_active:
try:
session_urls = []
role_name = []
role_list = User.objects.get(username=username).myuser.role.all()
for role in role_list:
role_name.append(role.role_name)
permission_list = role.permission.all()
for permission in permission_list:
session_urls.append(permission.url)
request.session['urls'] = json.dumps(session_urls)
request.session['role_name'] = json.dumps(role_name)
except:
# 这块表示该用户没有设置任何角色
return render(request, 'login.html', {"err": "该账号异常,请联系管理员!"})
login(request, user)
return redirect(reverse('get_group_list'))
else:
return render(request, 'login.html', {"err": "账号密码错误或被冻结,请联系管理员!"})
return render(request, 'login.html')
def do_logout(request):
logout(request)
return redirect(reverse('do_login'))
def forbidden(request):
return render(request, 'forbidden.html')
# 上传
def upload(request):
res = {
"code": 0,
"msg": "上传成功",
"data": {
"src": "http://cdn.layui.com/123.jpg"
}
}
now = str(datetime.now().strftime('%Y%m%d%H%M%S'))
if request.method == 'POST':
uuid = request.GET.get('uuid')
f = request.FILES.get('file')
file_name = now + '==' + f.name
video_list = [
'rm','rmvb','mpeg1-4','mov','mtv','dat','wmv','avi','3gp','amv','dmv','flv','mp3','mp4'
]
for i in video_list:
if i in file_name.lower():
res['code'] = -1
res['msg'] = '暂不支持视频文件!'
return JsonResponse(res)
path = os.path.join(MEDIA_ROOT, file_name)
destination = open(path, 'wb+') # 打开特定的文件进行二进制的写操作
for chunk in f.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
f_obj = file.objects.get_or_create(
uuid_str=uuid
)
f_obj[0].file_path = path
f_obj[0].save()
res['msg'] = f.name + ',上传成功!'
return JsonResponse(res)
|
[
"[email protected]"
] | |
28e8929dcdb43772a641cbd6eb02bb3d55f91533
|
1d83e050df3bbdabba07c7b65eca312ebe080f7c
|
/src/.ipynb_checkpoints/compress-checkpoint.py
|
534cd7b53bf9eff30bdc0e2b06152df49ff20bd0
|
[] |
no_license
|
shamiksharma/dhs2019
|
98211af781d1c86c21ec4b3effae2f7000e3bc57
|
71276da7033a95c3962408ac9e34cb3a7bcff05d
|
refs/heads/master
| 2022-03-06T07:38:11.909717 | 2019-11-22T09:27:01 | 2019-11-22T09:27:01 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,680 |
py
|
import os, logging
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
logging.getLogger("tensorflow").setLevel(logging.CRITICAL)
logging.getLogger("tensorflow_hub").setLevel(logging.CRITICAL)
import tensorflow as tf
from tensorflow import lite
from utils import DataGenerator, get_train_data
def compress(saved_model_path, tflite_model_path, img_size, quantize=None, device=None):
converter = lite.TFLiteConverter.from_saved_model(saved_model_path)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
if quantize:
sample_dataset = DataGenerator(get_train_data(), 10, img_size).sample()
sample_images = sample_dataset[0]
def representative_dataset_gen():
for index in range(sample_images.shape[0] - 1):
yield [sample_images[index:index+1]]
converter.representative_dataset = tf.lite.RepresentativeDataset(representative_dataset_gen)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8, tf.lite.OpsSet.SELECT_TF_OPS]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
tflite_model = converter.convert()
x = open(tflite_model_path, "wb").write(tflite_model)
print (x)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--saved_model", default=None, required=True)
parser.add_argument("--output", default=None, required=True)
parser.add_argument("--imgsize", default=256, required=False)
args = parser.parse_args()
compress(args.saved_model, args.output, int(args.imgsize), quantize=False)
|
[
"[email protected]"
] | |
7fff68255bdd4958ff339290d7b266500468f8b9
|
8b6b2eacbfeb97c5ea8b487ea784f296beae1b18
|
/td-auth-master/tutordudes/payment/apps.py
|
a8db0e02d53a92e4ab6b078f7d3f1104a5047861
|
[] |
no_license
|
FaizanM2000/Project-Demo-1
|
c1ff244d457a2d8243e607dafec74931da0702b7
|
e4aa4a0beed58ea7e3bf802beafeae6f6f9e8a6f
|
refs/heads/main
| 2023-08-05T07:12:14.477072 | 2021-09-18T08:06:43 | 2021-09-18T08:06:43 | 403,812,761 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 250 |
py
|
from django.apps import AppConfig
class PaymentConfig(AppConfig):
name = 'tutordudes.payment'
def ready(self):
try:
import tutordudes.payment.signals # noqa F401
except ImportError:
pass
|
[
"[email protected]"
] | |
ab4791fb3dadc7e1bed926e757b5eb84a780446e
|
1ab01e3a556e4effd333e6bfb1970c8cd309da40
|
/minirank/sofia_ml.py
|
75e4e121b82750220ab6074c6d0bc696c52bb227
|
[] |
no_license
|
aurora1625/minirank
|
19009cf8011091dfb58db0d8595035826f59f3e1
|
c5b0ff33053867df7121dc94c2dc463100801421
|
refs/heads/master
| 2020-12-25T12:42:45.282193 | 2012-12-21T14:47:01 | 2012-12-21T14:47:01 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,767 |
py
|
import sys, tempfile
import numpy as np
from sklearn import datasets
import _sofia_ml
if sys.version_info[0] < 3:
bstring = basestring
else:
bstring = str
def sgd_train(X, y, b, alpha, n_features=None, model='rank', max_iter=100, step_probability=0.5):
"""
Minimizes an expression of the form
Loss(X, y, b) + 0.5 * alpha * (||w|| ** 2)
where Loss is an Hinge loss defined on pairs of images
Parameters
----------
X : input data
y : target labels
b : blocks (aka query_id)
alpha: float
model : {'rank', 'combined-ranking', 'roc'}
Returns
-------
coef
None
"""
if isinstance(X, bstring):
if n_features is None:
n_features = 2 ** 17 # the default in sofia-ml TODO: parse file to see
w = _sofia_ml.train(X, n_features, alpha, max_iter, False, model,
step_probability)
else:
with tempfile.NamedTemporaryFile() as f:
datasets.dump_svmlight_file(X, y, f.name, query_id=b)
w = _sofia_ml.train(f.name, X.shape[1], alpha, max_iter, False, model,
step_probability)
return w, None
def sgd_predict(data, coef, blocks=None):
# TODO: isn't query_id in data ???
s_coef = ''
for e in coef:
s_coef += '%.5f ' % e
s_coef = s_coef[:-1]
if isinstance(X, bstring):
return _sofia_ml.predict(data, s_coef, False)
else:
X = np.asarray(data)
if blocks is None:
blocks = np.ones(X.shape[0])
with tempfile.NamedTemporaryFile() as f:
y = np.ones(X.shape[0])
datasets.dump_svmlight_file(X, y, f.name, query_id=blocks)
prediction = _sofia_ml.predict(f.name, s_coef, False)
return prediction
|
[
"[email protected]"
] | |
0d6eebcca8341a60b672a11fb77f631f6af68501
|
b3203d01b01d8dbb3298fa25a2bc2da3e20b0019
|
/enumnamecrawler/valueassigner/increment.py
|
39877eb27b520b42aeb7b6f28aa1c7009b0353f9
|
[
"MIT"
] |
permissive
|
yinyin/enumnamecrawler
|
17acfe45727b697249c8a004972a9076740f5152
|
48e98ff16db91e6e21cbf0641642672ca728f6d0
|
refs/heads/master
| 2021-03-30T20:23:12.774056 | 2018-03-21T17:04:47 | 2018-03-21T17:04:47 | 125,081,811 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 909 |
py
|
# -*- coding: utf-8 -*-
class Incrementer(object):
def __init__(self, base=-1, step=-1, *args, **kwds):
# type: (int, int) -> None
super(Incrementer, self).__init__(*args, **kwds)
if step == 0:
raise ValueError("step value must != 0: %r" % (step, ))
self.base = base
self.step = step
def _compute_base(self, v_max, v_min):
if self.step > 0:
c = v_max
dstep = self.step - 1
else:
c = v_min
dstep = self.step + 1
return int((c - self.base + dstep) / self.step) * self.step + self.base
def __call__(self, enumelements):
v_max = self.base
v_min = self.base
for enumelem in enumelements:
if enumelem.value is None:
continue
aux = enumelem.value
v_max = max(v_max, aux)
v_min = min(v_min, aux)
c = self._compute_base(v_max, v_min)
for enumelem in enumelements:
if enumelem.value is not None:
continue
enumelem.value = c
c = c + self.step
|
[
"[email protected]"
] | |
15701489ab41edd41261b2b31779b163a468529e
|
44a2741832c8ca67c8e42c17a82dbe23a283428d
|
/cmssw/HeavyIonsAnalysis/JetAnalysis/python/jets/akVs3CaloJetSequence_pPb_mix_cff.py
|
3d77c27baa5beb48450caf86750981f27c601170
|
[] |
no_license
|
yenjie/HIGenerator
|
9ff00b3f98b245f375fbd1b565560fba50749344
|
28622c10395af795b2b5b1fecf42e9f6d4e26f2a
|
refs/heads/master
| 2021-01-19T01:59:57.508354 | 2016-06-01T08:06:07 | 2016-06-01T08:06:07 | 22,097,752 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,519 |
py
|
import FWCore.ParameterSet.Config as cms
from PhysicsTools.PatAlgos.patHeavyIonSequences_cff import *
from HeavyIonsAnalysis.JetAnalysis.inclusiveJetAnalyzer_cff import *
akVs3Calomatch = patJetGenJetMatch.clone(
src = cms.InputTag("akVs3CaloJets"),
matched = cms.InputTag("ak3HiGenJetsCleaned")
)
akVs3Caloparton = patJetPartonMatch.clone(src = cms.InputTag("akVs3CaloJets"),
matched = cms.InputTag("hiGenParticles")
)
akVs3Calocorr = patJetCorrFactors.clone(
useNPV = False,
# primaryVertices = cms.InputTag("hiSelectedVertex"),
levels = cms.vstring('L2Relative','L3Absolute'),
src = cms.InputTag("akVs3CaloJets"),
payload = "AKVs3Calo_HI"
)
akVs3CalopatJets = patJets.clone(jetSource = cms.InputTag("akVs3CaloJets"),
jetCorrFactorsSource = cms.VInputTag(cms.InputTag("akVs3Calocorr")),
genJetMatch = cms.InputTag("akVs3Calomatch"),
genPartonMatch = cms.InputTag("akVs3Caloparton"),
jetIDMap = cms.InputTag("akVs3CaloJetID"),
addBTagInfo = False,
addTagInfos = False,
addDiscriminators = False,
addAssociatedTracks = False,
addJetCharge = False,
addJetID = False,
getJetMCFlavour = False,
addGenPartonMatch = True,
addGenJetMatch = True,
embedGenJetMatch = True,
embedGenPartonMatch = True,
embedCaloTowers = False,
embedPFCandidates = False
)
akVs3CaloJetAnalyzer = inclusiveJetAnalyzer.clone(jetTag = cms.InputTag("akVs3CalopatJets"),
genjetTag = 'ak3HiGenJetsCleaned',
rParam = 0.3,
matchJets = cms.untracked.bool(True),
matchTag = 'akPu3CalopatJets',
pfCandidateLabel = cms.untracked.InputTag('particleFlow'),
trackTag = cms.InputTag("generalTracks"),
fillGenJets = True,
isMC = True,
genParticles = cms.untracked.InputTag("hiGenParticles"),
eventInfoTag = cms.InputTag("hiSignal")
)
akVs3CaloJetSequence_mc = cms.Sequence(
akVs3Calomatch
*
akVs3Caloparton
*
akVs3Calocorr
*
akVs3CalopatJets
*
akVs3CaloJetAnalyzer
)
akVs3CaloJetSequence_data = cms.Sequence(akVs3Calocorr
*
akVs3CalopatJets
*
akVs3CaloJetAnalyzer
)
akVs3CaloJetSequence_jec = akVs3CaloJetSequence_mc
akVs3CaloJetSequence_mix = akVs3CaloJetSequence_mc
akVs3CaloJetSequence = cms.Sequence(akVs3CaloJetSequence_mix)
|
[
"[email protected]"
] | |
3f0d333958350a92ac434aa6a8017a17d263453d
|
2d929ed82d53e7d70db999753c60816ed00af171
|
/Python/http/http_proxy.py
|
413b48f03f8f201e702d427e39d87f53adca2682
|
[] |
no_license
|
nyannko/socket-example
|
b058e68e8d41a8a9f5b6a29108f7de394751c904
|
934e9791b1ee92f0dd3092bb07541f1e833b4105
|
refs/heads/master
| 2021-09-10T19:19:24.590441 | 2018-03-14T22:13:49 | 2018-03-14T22:13:49 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,577 |
py
|
# HTTP proxy
from http.server import BaseHTTPRequestHandler, HTTPServer
from urlpath import URL
import socket
import urllib
HOST = "127.0.0.1"
PORT = 8000
# Run `curl -x http://127.0.0.1:8000 http://www.moe.edu.cn' to test proxy
class ProxyHandler(BaseHTTPRequestHandler):
# GET method
def do_GET(self):
# todo add try catch here
url = URL(self.path)
ip = socket.gethostbyname(url.netloc)
port = url.port
if port is None:
port = 80
path = url.path
print("Connected to {} {} {}".format(url ,ip ,port))
# close connection
del self.headers["Proxy-Connection"]
self.headers["Connection"] = "close"
# reconstruct headers
send_data = "GET " + path + " " + self.protocol_version + "\r\n"
header = ""
for k, v in self.headers.items():
header += "{}: {}\r\n".format(k, v)
send_data += header + "\r\n"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.connect((ip, port))
s.sendall(send_data.encode())
# receive data from remote
received_data = b""
while 1:
data = s.recv(4096)
if not data:
break
received_data += data
s.close()
# send data to client
self.wfile.write(received_data)
def main():
try:
server = HTTPServer((HOST, PORT), ProxyHandler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
8f8199b6e1f6dfc54c783f31a9ee7c30b7a68a8b
|
86c082438a001ba48617aa756439b34423387b40
|
/src/the_tale/the_tale/accounts/jinjaglobals.py
|
a2404ff781af031fd621d00f6e3091150a03094c
|
[
"BSD-3-Clause"
] |
permissive
|
lustfullyCake/the-tale
|
a6c02e01ac9c72a48759716dcbff42da07a154ab
|
128885ade38c392535f714e0a82fb5a96e760f6d
|
refs/heads/master
| 2020-03-27T21:50:56.668093 | 2018-06-10T17:39:48 | 2018-06-10T17:39:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,295 |
py
|
# coding: utf-8
from dext.common.utils import jinja2
from the_tale.accounts import logic
from the_tale.accounts import conf
@jinja2.jinjaglobal
def login_page_url(next_url='/'):
return jinja2.Markup(logic.login_page_url(next_url))
@jinja2.jinjaglobal
def login_url(next_url='/'):
return jinja2.Markup(logic.login_url(next_url))
@jinja2.jinjaglobal
def logout_url():
return jinja2.Markup(logic.logout_url())
@jinja2.jinjaglobal
def forum_complaint_theme():
return conf.accounts_settings.FORUM_COMPLAINT_THEME
@jinja2.jinjaglobal
def account_sidebar(user_account, page_account, page_caption, page_type, can_moderate=False):
from the_tale.forum.models import Thread
from the_tale.game.bills.prototypes import BillPrototype
from the_tale.linguistics.prototypes import ContributionPrototype
from the_tale.linguistics.relations import CONTRIBUTION_TYPE
from the_tale.accounts.friends.prototypes import FriendshipPrototype
from the_tale.accounts.clans.logic import ClanInfo
from the_tale.blogs.models import Post as BlogPost, POST_STATE as BLOG_POST_STATE
bills_count = BillPrototype.accepted_bills_count(page_account.id)
threads_count = Thread.objects.filter(author=page_account._model).count()
threads_with_posts = Thread.objects.filter(post__author=page_account._model).distinct().count()
templates_count = ContributionPrototype._db_filter(account_id=page_account.id,
type=CONTRIBUTION_TYPE.TEMPLATE).count()
words_count = ContributionPrototype._db_filter(account_id=page_account.id,
type=CONTRIBUTION_TYPE.WORD).count()
folclor_posts_count = BlogPost.objects.filter(author=page_account._model, state=BLOG_POST_STATE.ACCEPTED).count()
friendship = FriendshipPrototype.get_for_bidirectional(user_account, page_account)
return jinja2.Markup(jinja2.render('accounts/sidebar.html',
context={'user_account': user_account,
'page_account': page_account,
'page_caption': page_caption,
'master_clan_info': ClanInfo(page_account),
'own_clan_info': ClanInfo(user_account),
'friendship': friendship,
'bills_count': bills_count,
'templates_count': templates_count,
'words_count': words_count,
'folclor_posts_count': folclor_posts_count,
'threads_count': threads_count,
'threads_with_posts': threads_with_posts,
'can_moderate': can_moderate,
'page_type': page_type,
'commission': conf.accounts_settings.MONEY_SEND_COMMISSION}))
|
[
"[email protected]"
] | |
c9e7ae0545df0f3c5342fff8f7224657d822ed17
|
644c809d4f2c1c5087ca8714619b01b253cc52c4
|
/python3.7libs/hipie/parmutils.py
|
8f0f3be8bfc5c00a757a90564377e666053aee8f
|
[
"MIT"
] |
permissive
|
MaxSteven/hipie
|
65db0b9d57e4e3c6fcc789e6e942610a400d7ebd
|
6fe66e3c02c94023fc5761bf51960a84bda87094
|
refs/heads/main
| 2023-08-17T08:13:56.414038 | 2021-10-01T21:15:26 | 2021-10-01T21:15:50 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,471 |
py
|
from __future__ import annotations
from typing import Optional, Union
from collections import Iterable
import hou
def _unpack_parm_from_kwargs(parms: Union[hou.Parm, hou.ParmTuple, list[hou.ParmTuple]]) -> Optional[hou.Parm]:
if isinstance(parms, hou.Parm) or isinstance(parms, hou.ParmTuple):
return parms
if isinstance(parms, Iterable):
if not parms:
return None
return parms[0]
return None
def is_color_ramp(parms) -> bool:
parm: hou.Parm = _unpack_parm_from_kwargs(parms)
if parm is None:
return False
parm_template = parm.parmTemplate() # type: hou.ParmTemplate
if parm_template.type() == hou.parmTemplateType.Ramp and parm_template.parmType() == hou.rampParmType.Color:
return True
return False
def is_color_parm(parms) -> bool:
parm: hou.Parm = _unpack_parm_from_kwargs(parms)
if parm is None:
return False
parm_template = parm.parmTemplate() # type: hou.ParmTemplate
if (parm_template.type() == hou.parmTemplateType.Float and
parm_template.numComponents() == 3 and
parm_template.namingScheme() == hou.parmNamingScheme.RGBA):
return True
return False
def is_float_ramp(parms) -> bool:
parm: hou.Parm = _unpack_parm_from_kwargs(parms)
if parm is None:
return False
parm_template = parm.parmTemplate() # type: hou.ParmTemplate
if parm_template.type() == hou.parmTemplateType.Ramp and parm_template.parmType() == hou.rampParmType.Float:
return True
return False
def get_multiparm_top_parent(parm: hou.Parm) -> hou.Parm:
parent = parm
while parent.isMultiParmInstance():
parent = parent.parentMultiParm()
return parent
def is_multiparm_folder(parm: Union[hou.Parm, hou.ParmTuple]) -> bool:
pt: hou.ParmTemplate = parm.parmTemplate()
if not isinstance(pt, hou.FolderParmTemplate):
return False
ptf: hou.FolderParmTemplate = pt
if ptf.folderType() in (hou.folderType.MultiparmBlock, hou.folderType.ScrollingMultiparmBlock, hou.folderType.TabbedMultiparmBlock):
return True
return False
def ramp_to_string(ramp: hou.Ramp) -> str:
basis = ramp.basis()
basis = ", ".join(f"hou.{b}" for b in basis)
return f"hou.Ramp(({basis}), {ramp.keys()}, {ramp.values()})"
def parm_value_string(parm: hou.Parm):
# that way I can evaluate ordered menus as integers
try:
expression = parm.expression()
return expression
except hou.OperationFailed:
value = parm.eval()
if isinstance(value, str):
value = f'"{value}"'
return str(value)
def parm_tuple_value_string(parm_tuple: hou.ParmTuple) -> str:
return parm_value_string(parm_tuple[0]) if len(parm_tuple) == 1 else f"({', '.join(parm_value_string(p) for p in parm_tuple)})"
def multiparm_to_string(parm: Union[hou.Parm, hou.ParmTuple]) -> str:
node: hou.SopNode = parm.node()
template: hou.FolderParmTemplate = parm.parmTemplate()
child_templates: list[hou.ParmTemplate] = template.parmTemplates()
child_names: list[str] = [t.name() for t in child_templates]
child_names: list[str] = [n.replace("#", "{}") for n in child_names]
num_instances = parm.eval()[0] # no nested multiparms (yet)
offset = parm.multiParmStartOffset()
dict_strings = []
for i in range(num_instances):
multiparm_index = offset + i
instance_output = []
for cti, ct in enumerate(child_templates):
parm_name = child_names[cti].format(multiparm_index)
parm_instance = node.parmTuple(parm_name)
instance_output.append(parm_tuple_as_dict_item(parm_instance, ct))
dict_strings.append(f"{{{','.join(instance_output)}}}")
return f"({','.join(dict_strings)},)"
def parm_tuple_as_dict_item(parm_tuple: hou.ParmTuple, parm_template: hou.ParmTemplate = None) -> str:
parm_template: hou.ParmTemplate = parm_tuple.parmTemplate() if parm_template is None else parm_template
if is_multiparm_folder(parm_tuple):
value = multiparm_to_string(parm_tuple)
else:
value = parm_tuple_value_string(parm_tuple)
if not isinstance(value, hou.Ramp):
return f'"{parm_template.name()}": {value}'
def node_verb_parms(node: hou.SopNode, num_tabs = 1, tab=" ") -> str:
verb_parms = node.verb().parms()
parm_tuples: list[hou.ParmTuple] = node.parmTuples()
output = "{"
tabs = tab * num_tabs
for parm_tuple in parm_tuples:
parent: hou.Parm = parm_tuple.parentMultiParm()
is_ramp_parm = (parent is not None and parent.parmTemplate().type() == hou.parmTemplateType.Ramp) or isinstance(parm_tuple.parmTemplate(), hou.RampParmTemplate)
is_at_default = not is_multiparm_folder(parm_tuple) and parm_tuple.isAtDefault()
if not is_ramp_parm and parm_tuple.name() in verb_parms and not is_at_default:
output += f"\n{tabs}{parm_tuple_as_dict_item(parm_tuple)},"
parms: list[hou.Parm] = node.parms()
ramps = [p for p in parms if p.parmTemplate().type() == hou.parmTemplateType.Ramp]
for ramp in ramps:
try:
ramp.expression()
continue
except hou.OperationFailed:
if ramp.name() in verb_parms and not ramp.isAtDefault():
output += f'\n{tabs}"{ramp.name()}": {ramp_to_string(ramp.eval())}'
output += "}"
return output
|
[
"[email protected]"
] | |
a0b84ed3cb8ceed015324f058cdd123228f78465
|
a924464293776c703da006f3fca48bf6cd9cd9b4
|
/webAutoTest/test_py/__init__.py
|
66e18c33aba85ce624c1c4194c3815df5001f562
|
[] |
no_license
|
zhangxiaoxiaotian/123
|
2ea08f6f29aec29004d89c7614144d00a2c54ec2
|
341646b65603c2bd9ee90b9e64f40ce2dfd2f127
|
refs/heads/master
| 2020-04-25T10:30:59.465883 | 2019-02-26T14:09:50 | 2019-02-26T14:09:59 | 172,712,002 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 284 |
py
|
#coding=utf-8
# *******************************************************************
# Filename @ __init__.py.py
# Author @ XiaoTian
# Create date @ 2019/2/26 9:50
# Email @ [email protected]
# ********************************************************************
|
[
"[email protected]"
] | |
fcc6802012379ff2c4773260e513034d4e1eafa3
|
3207c6cacac66d8b60c14511ba9ef0ace34ab066
|
/tk.py
|
05ea2be6dd52d4926447aead494c7c3e8f1af96a
|
[] |
no_license
|
xiaoqiwang19/Google-Translator
|
df0ae232141017e0dc242ad5c556ad8f186e5956
|
b46c6e0197e80fa65a7d90c677a2a2a3a770d4c4
|
refs/heads/master
| 2020-07-18T08:42:28.419681 | 2018-11-29T08:53:28 | 2018-11-29T08:53:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,611 |
py
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import execjs
class Py4Js():
def __init__(self):
self.ctx = execjs.compile("""
function TL(a) {
var k = "";
var b = 406644;
var b1 = 3293161072;
var jd = ".";
var $b = "+-a^+6";
var Zb = "+-3^+b+-f";
for (var e = [], f = 0, g = 0; g < a.length; g++) {
var m = a.charCodeAt(g);
128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023),
e[f++] = m >> 18 | 240,
e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
e[f++] = m >> 6 & 63 | 128),
e[f++] = m & 63 | 128)
}
a = b;
for (f = 0; f < e.length; f++) a += e[f],
a = RL(a, $b);
a = RL(a, Zb);
a ^= b1 || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1E6;
return a.toString() + jd + (a ^ b)
};
function RL(a, b) {
var t = "a";
var Yb = "+";
for (var c = 0; c < b.length - 2; c += 3) {
var d = b.charAt(c + 2),
d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
}
return a
}
""")
def getTk(self, text):
return self.ctx.call("TL", text)
|
[
"[email protected]"
] | |
ff19ab6c5c4db1a74fcc72827dcbec96c6306d73
|
b622852ef7f7859da4f58abb2cec90247402ab80
|
/checkout/admin.py
|
b4c26d931beb6c1168d34f68369ed552c073aaf9
|
[] |
no_license
|
Code-Institute-Submissions/Forth-Milestone-Project
|
7bbca04c90788382c69d9fb8a38ddc756de6cd4e
|
30e2c876f03315b99db221d65a7e9bbaeecdf8f3
|
refs/heads/master
| 2022-12-15T11:29:22.190347 | 2020-08-31T22:38:40 | 2020-08-31T22:38:40 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 871 |
py
|
from django.contrib import admin
from .models import Order, OrderLineItem
class OrderLineItemAdminInline(admin.TabularInline):
model = OrderLineItem
readonly_fields = ('lineitem_total',)
class OrderAdmin(admin.ModelAdmin):
inlines = (OrderLineItemAdminInline,)
readonly_fields = ('order_number', 'date',
'delivery_cost', 'order_total',
'grand_total',)
fields = ('order_number', 'user_account', 'date', 'first_name', 'last_name',
'email', 'phone_number', 'country',
'postcode', 'town_or_city', 'street_address1',
'street_address2', 'county', 'delivery_cost',
'order_total', 'grand_total',)
list_display = ('order_number', 'date', 'first_name', 'last_name', 'grand_total',)
ordering = ('-date',)
admin.site.register(Order, OrderAdmin)
|
[
"[email protected]"
] | |
8deb1a85735181e79b051c236ee4cfb72110ef68
|
6e1b2ff8d323e71f64ba499b898997b863d50c49
|
/tkinter/tkinter.py
|
de879ca9c17a31f4e26594db522681c9c121bf45
|
[] |
no_license
|
Anchal-Mittal/Python
|
fab5a4d7b56fc72ba67ee9916107c427f669fb80
|
2b5147c762be22c06327fec14653d920751a5fff
|
refs/heads/master
| 2021-09-11T14:10:09.432809 | 2018-04-08T16:32:28 | 2018-04-08T16:32:28 | 109,740,579 | 1 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 899 |
py
|
from tkinter import *
'''
from tkinter import *
root = Tk()
.
.
.
root.mainloop()
This is basic layout for any GUI application.
'''
root = Tk()
topFrame = Frame(root)
#Frame() is used to create a frame, a kind of invisible rectangle where we can put out widgets.
topFrame.pack()
#Anytime we want anything to be displayed, we need to pack() it.
bottomFrame = Frame(root)
#This is a bottom frame, another invisible container for widgets.
bottomFrame.pack(side = BOTTOM)
#side = BOTTOM is used to explicitly set the frame to BOTTOM end.
button1 = Button(topFrame,text = "SUBMIT", fg = "green")
#Creating a button with Button Object.
button2 = Button(topFrame,text = "DISPLAY", fg = "blue")
button3 = Button(bottomFrame,text = "RESET", fg = "red")
#To display the buttons, we need to pack() them.
button1.pack(side = LEFT)
button2.pack(side = LEFT)
button3.pack(side = BOTTOM)
root.mainloop()
|
[
"[email protected]"
] | |
c5ecd02296aa16caffcde786d3ab77fae28405d1
|
28c598bf75f3ab287697c7f0ff1fb13bebb7cf75
|
/build/bdist.win32/winexe/temp/OpenSSL.crypto.py
|
6acfec583072680d7cf8126acf30df4957600e19
|
[] |
no_license
|
keaysma/solinia_depreciated
|
4cb8811df4427261960af375cf749903d0ca6bd1
|
4c265449a5e9ca91f7acf7ac05cd9ff2949214ac
|
refs/heads/master
| 2020-03-25T13:08:33.913231 | 2014-09-12T08:23:26 | 2014-09-12T08:23:26 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 343 |
py
|
def __load():
import imp, os, sys
try:
dirname = os.path.dirname(__loader__.archive)
except NameError:
dirname = sys.prefix
path = os.path.join(dirname, 'crypto.pyd')
#print "py2exe extension module", __name__, "->", path
mod = imp.load_dynamic(__name__, path)
## mod.frozen = 1
__load()
del __load
|
[
"[email protected]"
] | |
b4494671f38f7126a6d2398e2a96b7c336e7f55d
|
2a34a824e1a2d3bac7b99edcf19926a477a157a0
|
/src/cr/vision/io/videowriter.py
|
7277eb9220a2e28a1d27d3f2748e3fc3a6ce7fee
|
[
"Apache-2.0"
] |
permissive
|
carnotresearch/cr-vision
|
a7cb07157dbf470ed3fe560ef85d6e5194c660ae
|
317fbf70c558e8f9563c3d0ba3bebbc5f84af622
|
refs/heads/master
| 2023-04-10T22:34:34.833043 | 2021-04-25T13:32:14 | 2021-04-25T13:32:14 | 142,256,002 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,323 |
py
|
'''
Wrapper for OpenCV video writer
'''
import cv2
class VideoWriter:
'''Wrapper class for OpenCV video writer'''
def __init__(self, filepath, fourcc='XVID', fps=15, frame_size=(640, 480), is_color=True):
'''Constructor'''
self.filepath = filepath
if isinstance(fourcc, str):
fourcc = cv2.VideoWriter_fourcc(*fourcc)
elif isinstance(fourcc, int):
pass
else:
raise "Invalid fourcc code"
self.stream = cv2.VideoWriter(filepath, fourcc, fps, frame_size)
self.counter = 0
def write(self, frame):
'''Writes a frame to output file'''
self.stream.write(frame)
self.counter += 1
print(self.counter)
def is_open(self):
'''Returns if the stream is open for writing'''
if self.stream is None:
return False
return self.stream.isOpened()
def stop(self):
'''Stop serving more frames'''
if self.stream is None:
# nothing to do
return
self.stream.release()
self.stream = None
def __del__(self):
# Ensure cleanup
self.stop()
def __enter__(self):
return self
def __exit__(self):
self.stop()
def __call__(self, frame):
self.write(frame)
|
[
"[email protected]"
] | |
0eb38fbdaa1bb3dd0e54fe7c6543fc623c91fe2c
|
79a1ad6306a8a812170039e32dd732bd690a054e
|
/spider/scrapy_static/scrapy_static/middlewares.py
|
2428796e3a39c7ff8b6e1ce7c3e467a8aab9c631
|
[] |
no_license
|
yang7776/Django_example
|
9cca6957873edb154b6ce879f6c903987ddcf361
|
6cc1acc52699093043355b90d736bec41c0e5ade
|
refs/heads/master
| 2022-12-13T07:44:48.380374 | 2021-12-02T07:27:34 | 2021-12-02T07:27:34 | 168,083,715 | 0 | 0 | null | 2022-12-07T12:17:43 | 2019-01-29T03:37:46 |
Python
|
UTF-8
|
Python
| false | false | 4,805 |
py
|
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import random
import os
import json
from scrapy import signals
from spider.user_agent_util import PC_USER_AGENT
# from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware
# from spider.ip_spider import checkip
IP_PATH = os.path.join(os.path.abspath("../.."), r"spider\proxy_ip.json")
class RandomUserAgentMiddleware(object):
def __init__(self, user_agent=''):
self.user_agent = user_agent
def process_request(self, request, spider):
# 随机选择一个用户代理
user_agent = random.choice(PC_USER_AGENT)
print("正在配置用户代理为:%s" % user_agent)
# request.headers["User-Agent"] = user_agent
request.headers.setdefault('User-Agent', user_agent)
class RandomProxyIpSpiderMiddleware(object):
def __init__(self, ip=''):
self.ip = ip
def choise_ip(self):
with open(IP_PATH, "r") as f:
ips_dic = json.loads(f.read())
ips = ips_dic["anonymity_ips"]
now_ip = random.choice(ips)["ip"]
return now_ip
def process_request(self, request, spider):
now_ip = self.choise_ip()
print("正在配置代理ip为:%s" % now_ip )
request.meta["proxy"] = now_ip
class ScrapyStaticSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Request, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class ScrapyStaticDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
|
[
"[email protected]"
] | |
16e0739edad97ed1235596b5089565cd8efa8f70
|
5b314502919bd7e12521ad126752d279912cd33d
|
/prodcons.py
|
d5e07a09cc1bdc3dcf283f36db18ea8f09ee3142
|
[
"Apache-2.0"
] |
permissive
|
xshi0001/base_function
|
68576d484418b4cda8576f729d0b48a90d0258a1
|
77ed58289151084cc20bfc3328d3ca83e6a19366
|
refs/heads/master
| 2020-12-03T02:24:14.694973 | 2017-06-27T10:51:16 | 2017-06-27T10:51:16 | 95,935,169 | 1 | 0 | null | 2017-07-01T01:39:11 | 2017-07-01T01:39:11 | null |
UTF-8
|
Python
| false | false | 1,533 |
py
|
# -*-coding=utf-8
from Queue import Queue
from random import randint
from MyThread import MyThread
from time import sleep
def queue_test(q):
#q=Queue(10);
for i in range(10):
temp = randint(1, 10)
print temp
q.put("number:", temp)
print "size of queue is %d" % q.qsize()
def writeQ(q, i):
print "producter object for Q"
data = randint(1, 10)
#print "data is %d" %data
q.put(i, 1)
print "size now in producter is %d" % q.qsize()
def readQ(q):
print "consumer object for Q"
data = q.get(1)
print data
print "now after consume Q size is %d" % q.qsize()
def writer(q, loop):
for i in range(loop):
writeQ(q, i)
sleep_time = randint(1, 3)
sleep(sleep_time)
def reader(q, loop):
for i in range(loop):
readQ(q)
sleep_time = randint(2, 5)
sleep(sleep_time)
funcs = [writer, reader]
nfuncs = len(funcs)
def area_test(a):
a = a * 10
def main():
'''
a=2
print "a=%d" %a
area_test(a)
print "a now is a= %d" %a
q=Queue(10);
print "main q size %d" %q.qsize()
queue_test(q)
print "after function q size %d" %q.qsize()
'''
threads = []
q = Queue(10)
loop = 10
for i in range(nfuncs):
t = MyThread(funcs[i], (q, loop))
threads.append(t)
for i in range(nfuncs):
threads[i].start()
'''
for i in range(nfuncs):
threads[i].join()
'''
#print "end of main"
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
f02ee036bd722639ffc53e3f04de37fbe2c45144
|
db689b4539346a60446357e3f57594f50d64a0d8
|
/run.py
|
625302547aaf4f7042ab37fce1facb24e5307fce
|
[
"MIT"
] |
permissive
|
kigensky/Password-locker
|
9c7922b621433460203479d44373516b74c8a5a3
|
c1fbfa64f8af2855e1b85e33999a231ab32a54a1
|
refs/heads/main
| 2023-03-31T21:51:39.202912 | 2021-04-11T12:50:32 | 2021-04-11T12:50:32 | 356,191,715 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,136 |
py
|
from user import User, Credentials
def create_new_user(username,password):
'''
Function to create a new user with the username and password
'''
new_user = User(username,password)
return new_user
def save_user(user):
'''
Function to save a new user
'''
user.save_user()
def display_user():
"""
Function to display existing user
"""
return User.display_user()
def login_user(username,password):
"""
function that checks whether a user exist and then login the user in.
"""
check_user = Credentials.verify_user(username,password)
return check_user
def create_new_credential(account,userName,password):
"""
Function that creates new credentials for a given user account
"""
new_credential = Credentials(account,userName,password)
return new_credential
def save_credentials(credentials):
"""
Function to save Credentials to the credentials list
"""
credentials. save_details()
def display_accounts_details():
"""
Function that returns all the saved credential.
"""
return Credentials.display_credentials()
def delete_credential(credentials):
"""
Function to delete a Credentials from credentials list
"""
credentials.delete_credentials()
def find_credential(account):
"""
Function that finds a Credentials by an account name and returns the Credentials that belong to that account
"""
return Credentials.find_credential(account)
def check_credendtials(account):
"""
Function that check if a Credentials exists with that account name and return true or false
"""
return Credentials.if_credential_exist(account)
def generate_Password():
'''
generates a random password for the user.
'''
auto_password=Credentials.generatePassword()
return auto_password
def copy_password(account):
"""
A funct that copies the password using the pyperclip framework
We import the framework then declare a function that copies the emails.
"""
return Credentials.copy_password(account)
def passlocker():
print("Hello Welcome to your Accounts Password Store...\n Please enter one of the following to proceed.\n CA --- Create New Account \n LI --- Have An Account \n")
short_code=input("").lower().strip()
if short_code == "ca":
print("Sign Up")
print('*' * 50)
username = input("User_name: ")
while True:
print(" TP - To type your own pasword:\n GP - To generate random Password")
password_Choice = input().lower().strip()
if password_Choice == 'tp':
password = input("Enter Password\n")
break
elif password_Choice == 'gp':
password = generate_Password()
break
else:
print("Invalid password please try again")
save_user(create_new_user(username,password))
print("*"*85)
print(f"Hello {username}, Your account has been created succesfully! Your password is: {password}")
print("*"*85)
elif short_code == "li":
print("*"*50)
print("Enter your User name and your Password to log in:")
print('*' * 50)
username = input("User name: ")
password = input("password: ")
login = login_user(username,password)
if login_user == login:
print(f"Hello {username}.Welcome To PassWord Locker Manager")
print('\n')
while True:
print("Use these short codes:\n CC - Create a new credential \n DC - Display Credentials \n FC - Find a credential \n GP - Generate A randomn password \n D - Delete credential \n EX - Exit the application \n")
short_code = input().lower().strip()
if short_code == "cc":
print("Create New Credential")
print("."*20)
print("Account name ....")
account = input().lower()
print("Your Account username")
userName = input()
while True:
print(" TP - To type your own pasword if you already have an account:\n GP - To generate random Password")
password_Choice = input().lower().strip()
if password_Choice == 'tp':
password = input("Enter Your Own Password\n")
break
elif password_Choice == 'gp':
password = generate_Password()
break
else:
print("Invalid password please try again")
save_credentials(create_new_credential(account,userName,password))
print('\n')
print(f"Account Credential for: {account} - UserName: {userName} - Password:{password} created succesfully")
print('\n')
elif short_code == "dc":
if display_accounts_details():
print("Here's your list of acoounts: ")
print('*' * 30)
print('_'* 30)
for account in display_accounts_details():
print(f" Account:{account.account} \n User Name:{username}\n Password:{password}")
print('_'* 30)
print('*' * 30)
else:
print("You don't have any credentials saved yet..........")
elif short_code == "fc":
print("Enter the Account Name you want to search for")
search_name = input().lower()
if find_credential(search_name):
search_credential = find_credential(search_name)
print(f"Account Name : {search_credential.account}")
print('-' * 50)
print(f"User Name: {search_credential.userName} Password :{search_credential.password}")
print('-' * 50)
else:
print("That Credential does not exist")
print('\n')
elif short_code == "d":
print("Enter the account name of the Credentials you want to delete")
search_name = input().lower()
if find_credential(search_name):
search_credential = find_credential(search_name)
print("_"*50)
search_credential.delete_credentials()
print('\n')
print(f"Your stored credentials for : {search_credential.account} successfully deleted!!!")
print('\n')
else:
print("That Credential you want to delete does not exist in your store yet")
elif short_code == 'gp':
password = generate_Password()
print(f" {password} Has been generated succesfull. You can proceed to use it to your account")
elif short_code == 'ex':
print("Thanks for using passwords store manager.. See you next time!")
break
else:
print("Wrong entry... Check your entry again and let it match those in the menu")
else:
print("Please enter a valid input to continue")
if __name__ == '__main__':
passlocker()
|
[
"[email protected]"
] | |
77687b39d779c1e2e66e81bff622db67cfb34acf
|
b379d7833a2ec1d424b5e0ab276dd622a8487e86
|
/tutorial/migrations/0001_initial.py
|
736e7168d62aa25c267cd33167aa8d99e3d9e082
|
[] |
no_license
|
WillCup/DjangoCN
|
053bd43a9a7f83a67c7c48aab3c977c7ac33f94f
|
2524b74aef4bc9ad73c96a76ac96434c585cabc8
|
refs/heads/master
| 2021-01-21T17:41:54.010330 | 2017-02-27T04:19:37 | 2017-02-27T04:19:37 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 621 |
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-26 14:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Tutorial',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
options={
'verbose_name': '教程',
'verbose_name_plural': '教程',
},
),
]
|
[
"[email protected]"
] | |
009c2748d295bb10656f44e9a02eb8dcccbef81c
|
65021fb03247d30c929e44af6daa11828d820cae
|
/Chapter 6/pizza.py
|
bf10a1cb877f907cbc736b9cedb282851d4c011e
|
[] |
no_license
|
alvindrakes/python-crashcourse-code
|
6a56d4072a55464142ea1260bbcaf8de9bc10ab5
|
4eacac787ea7445d1f2fde53a03ed7ccf9bd3037
|
refs/heads/master
| 2020-03-22T09:48:43.275671 | 2018-07-15T07:29:25 | 2018-07-15T07:29:25 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 310 |
py
|
# store info about a pizza being oddered
pizza = {
'crust' : 'thick',
'toppings' : ['mushrooms', 'extra cheese'],
}
#summarize the order
print("Your ordered a " + pizza['crust'] + "-crust pizza " +
"with the following topings:" )
for topping in pizza['toppings']:
print("\t" + topping)
|
[
"[email protected]"
] | |
4aed54428f5cec4dfefc14c5a98a46043798cf76
|
f60c71a1182b3313061d31644da92ca2013c0d81
|
/train.py
|
e413db33d00d8f89551bdbf191857fd97635bdc8
|
[] |
no_license
|
BrandyJer/iqiyi-workspace-TF
|
1dc0b7a82604feb9bb73ade9a46cf12eafea8c15
|
8d68018c35b3b15b397beab70f2d93f299d2424e
|
refs/heads/master
| 2020-03-09T21:56:22.686925 | 2018-04-11T02:46:52 | 2018-04-11T02:46:52 | 129,022,627 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,873 |
py
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 9 12:54:02 2017
@author: linjian_sx
"""
"""
jiezhen change:
line22 => 24
line32 => 33
line40 => 41
line63 => 64
line81 => 82
line85 => 86
"""
from datetime import datetime
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.python.ops import control_flow_ops
import os
import random
import time
from PIL import Image
from decode_tools import decode_from_tfrecords
#from zf_net import tiny_darknet
from net import tiny_darknet
max_iters = 100000
#for code test
#max_iters = 100
#os.environ["CUDA_VISIBLE_DEVICES"] = ""
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
def train(is_ft=False):
with tf.Graph().as_default():
with tf.variable_scope("model") as scope:
# train_queue = ["train_data2.tfrecords"]
train_queue = ["train_data.tfrecords"]
images, labels = decode_from_tfrecords(train_queue,128)
logits = tiny_darknet(images)
logits = tf.nn.softmax(tf.reduce_mean(logits,[1,2]))
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits)
reg_loss = tf.add_n(tf.losses.get_regularization_losses())
total_loss = tf.reduce_mean(loss)+reg_loss
opt = tf.train.MomentumOptimizer(0.01,0.9)
global_step = tf.Variable(0, name='global_step', trainable=False)
train_op = slim.learning.create_train_op(total_loss, opt, global_step=global_step)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
if update_ops:
updates = tf.group(*update_ops)
total_loss = control_flow_ops.with_dependencies([updates], total_loss)
saver = tf.train.Saver(tf.all_variables())
init = tf.initialize_all_variables()
# sess = tf.Session(config=tf.ConfigProto(log_device_placement=False))
sess = tf.Session()
sess.run(init)
tf.train.start_queue_runners(sess=sess)
if is_ft:#if not train model
# model_file=tf.train.latest_checkpoint('./model_max')
model_file=tf.train.latest_checkpoint('/root/JZ_test_models/darknet0_model')
saver.restore(sess, model_file)
#is_ft = False
ckpt = tf.train.get_checkpoint_state('/root/JZ_test_models/darknet0_model')
if ckpt and ckpt.model_checkpoint_path: ######断点训练
model_file=tf.train.latest_checkpoint('/root/JZ_test_models/darknet0_model')
saver.restore(sess, model_file)
tf.logging.set_verbosity(tf.logging.INFO)
loss_cnt = 0.0
loss_flag = 999.0
for step in range(max_iters):
_, loss_value = sess.run([train_op, total_loss])
assert not np.isnan(loss_value), 'Model diverged with loss = NaN'
loss_cnt+=loss_value
if step % 10 == 0:
format_str = ('%s: step %d, loss = %.2f')
if step == 0:
avg_loss_cnt = loss_cnt
else:
avg_loss_cnt = loss_cnt/10.0
print(format_str % (datetime.now(), step, avg_loss_cnt))
loss_cnt = 0.0
if step % 200 == 0 or (step + 1) == max_iters:
# if step % 50 == 0 or (step + 1) == max_iters:
# checkpoint_path = os.path.join('/root/classify/model', 'model.ckpt')
checkpoint_path = os.path.join('/root/JZ_test_models/darknet0_model', 'model.ckpt')#save model path
saver.save(sess, checkpoint_path, global_step=step)
train()
|
[
"[email protected]"
] | |
a618bd2571db03d8262b8233c0af56287cb540db
|
50dcaae873badd727e8416302a88f9c0bff0a438
|
/bookstore/migrations/0002_auto_20170101_0049.py
|
d3e6f7c0947c25e5f8687afb88146674f49c0239
|
[] |
no_license
|
jattoabdul/albaitulilm
|
4ae0dc857509012e8aa5d775cda64305de562251
|
c5586edaed045fec925a6c0bb1be5e220cbd8d15
|
refs/heads/master
| 2021-01-13T00:00:01.397037 | 2017-02-12T23:32:42 | 2017-02-12T23:32:42 | 81,761,579 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 641 |
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-31 23:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bookstore', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'ordering': ['title'], 'verbose_name_plural': 'Books'},
),
migrations.AddField(
model_name='author',
name='image',
field=models.ImageField(blank=True, upload_to='authors', verbose_name="Author's Avatar"),
),
]
|
[
"[email protected]"
] | |
0c31e87961f953b76d38d1cb94d7c18e3c7b56b9
|
d715648cb69bdbfe5ee2bee32eaad3772b4aeb83
|
/scripts/get_rich_info.py
|
f8b42583d5b28a27bc02205d3725e8b3d86ca538
|
[
"MIT"
] |
permissive
|
drobotun/python_pefile_scripts
|
3f5570479c9b3fd2ab0f47ee9e5847f6818b4016
|
4feee14414984580d12894a2319fc926995e6108
|
refs/heads/master
| 2022-11-16T07:26:23.854775 | 2020-07-07T17:22:07 | 2020-07-07T17:22:07 | 275,241,407 | 1 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 8,608 |
py
|
"""
Скрипт, выводящий информацию о содержании Rich-сигнатуры PE-файла.
Пример использования:
python get_rich_info.py d:/file.exe
"""
import sys
import hashlib
import pefile
__COMPID_DICT = {
0: 'Unknown',
1: 'Import0',
2: 'Linker510',
3: 'Cvtomf510',
4: 'Linker600',
5: 'Cvtomf600',
6: 'Cvtres500',
7: 'Utc11_Basic',
8: 'Utc11_C',
9: 'Utc12_Basic',
10: 'Utc12_C',
11: 'Utc12_CPP',
12: 'AliasObj60',
13: 'VisualBasic60',
14: 'Masm613',
15: 'Masm710',
16: 'Linker511',
17: 'Cvtomf511',
18: 'Masm614',
19: 'Linker512',
20: 'Cvtomf512',
21: 'Utc12_C_Std',
22: 'Utc12_CPP_Std',
23: 'Utc12_C_Book',
24: 'Utc12_CPP_Book',
25: 'Implib700',
26: 'Cvtomf700',
27: 'Utc13_Basic',
28: 'Utc13_C',
29: 'Utc13_CPP',
30: 'Linker610',
31: 'Cvtomf610',
32: 'Linker601',
33: 'Cvtomf601',
34: 'Utc12_1_Basic',
35: 'Utc12_1_C',
36: 'Utc12_1_CPP',
37: 'Linker620',
38: 'Cvtomf620',
39: 'AliasObj70',
40: 'Linker621',
41: 'Cvtomf621',
42: 'Masm615',
43: 'Utc13_LTCG_C',
44: 'Utc13_LTCG_CPP',
45: 'Masm620',
46: 'ILAsm100',
47: 'Utc12_2_Basic',
48: 'Utc12_2_C',
49: 'Utc12_2_CPP',
50: 'Utc12_2_C_Std',
51: 'Utc12_2_CPP_Std',
52: 'Utc12_2_C_Book',
53: 'Utc12_2_CPP_Book',
54: 'Implib622',
55: 'Cvtomf622',
56: 'Cvtres501',
57: 'Utc13_C_Std',
58: 'Utc13_CPP_Std',
59: 'Cvtpgd1300',
60: 'Linker622',
61: 'Linker700',
62: 'Export622',
63: 'Export700',
64: 'Masm700',
65: 'Utc13_POGO_I_C',
66: 'Utc13_POGO_I_CPP',
67: 'Utc13_POGO_O_C',
68: 'Utc13_POGO_O_CPP',
69: 'Cvtres700',
70: 'Cvtres710p',
71: 'Linker710p',
72: 'Cvtomf710p',
73: 'Export710p',
74: 'Implib710p',
75: 'Masm710p',
76: 'Utc1310p_C',
77: 'Utc1310p_CPP',
78: 'Utc1310p_C_Std',
79: 'Utc1310p_CPP_Std',
80: 'Utc1310p_LTCG_C',
81: 'Utc1310p_LTCG_CPP',
82: 'Utc1310p_POGO_I_C',
83: 'Utc1310p_POGO_I_CPP',
84: 'Utc1310p_POGO_O_C',
85: 'Utc1310p_POGO_O_CPP',
86: 'Linker624',
87: 'Cvtomf624',
88: 'Export624',
89: 'Implib624',
90: 'Linker710',
91: 'Cvtomf710',
92: 'Export710',
93: 'Implib710',
94: 'Cvtres710',
95: 'Utc1310_C',
96: 'Utc1310_CPP',
97: 'Utc1310_C_Std',
98: 'Utc1310_CPP_Std',
99: 'Utc1310_LTCG_C',
100: 'Utc1310_LTCG_CPP',
101: 'Utc1310_POGO_I_C',
102: 'Utc1310_POGO_I_CPP',
103: 'Utc1310_POGO_O_C',
104: 'Utc1310_POGO_O_CPP',
105: 'AliasObj710',
106: 'AliasObj710p',
107: 'Cvtpgd1310',
108: 'Cvtpgd1310p',
109: 'Utc1400_C',
110: 'Utc1400_CPP',
111: 'Utc1400_C_Std',
112: 'Utc1400_CPP_Std',
113: 'Utc1400_LTCG_C',
114: 'Utc1400_LTCG_CPP',
115: 'Utc1400_POGO_I_C',
116: 'Utc1400_POGO_I_CPP',
117: 'Utc1400_POGO_O_C',
118: 'Utc1400_POGO_O_CPP',
119: 'Cvtpgd1400',
120: 'Linker800',
121: 'Cvtomf800',
122: 'Export800',
123: 'Implib800',
124: 'Cvtres800',
125: 'Masm800',
126: 'AliasObj800',
127: 'PhoenixPrerelease',
128: 'Utc1400_CVTCIL_C',
129: 'Utc1400_CVTCIL_CPP',
130: 'Utc1400_LTCG_MSIL',
131: 'Utc1500_C',
132: 'Utc1500_CPP',
133: 'Utc1500_C_Std',
134: 'Utc1500_CPP_Std',
135: 'Utc1500_CVTCIL_C',
136: 'Utc1500_CVTCIL_CPP',
137: 'Utc1500_LTCG_C',
138: 'Utc1500_LTCG_CPP',
139: 'Utc1500_LTCG_MSIL',
140: 'Utc1500_POGO_I_C',
141: 'Utc1500_POGO_I_CPP',
142: 'Utc1500_POGO_O_C',
143: 'Utc1500_POGO_O_CPP',
144: 'Cvtpgd1500',
145: 'Linker900',
146: 'Export900',
147: 'Implib900',
148: 'Cvtres900',
149: 'Masm900',
150: 'AliasObj900',
151: 'Resource900',
152: 'AliasObj1000',
153: 'Cvtpgd1600',
154: 'Cvtres1000',
155: 'Export1000',
156: 'Implib1000',
157: 'Linker1000',
158: 'Masm1000',
159: 'Phx1600_C',
160: 'Phx1600_CPP',
161: 'Phx1600_CVTCIL_C',
162: 'Phx1600_CVTCIL_CPP',
163: 'Phx1600_LTCG_C',
164: 'Phx1600_LTCG_CPP',
165: 'Phx1600_LTCG_MSIL',
166: 'Phx1600_POGO_I_C',
167: 'Phx1600_POGO_I_CPP',
168: 'Phx1600_POGO_O_C',
169: 'Phx1600_POGO_O_CPP',
170: 'Utc1600_C',
171: 'Utc1600_CPP',
172: 'Utc1600_CVTCIL_C',
173: 'Utc1600_CVTCIL_CPP',
174: 'Utc1600_LTCG_C ',
175: 'Utc1600_LTCG_CPP',
176: 'Utc1600_LTCG_MSIL',
177: 'Utc1600_POGO_I_C',
178: 'Utc1600_POGO_I_CPP',
179: 'Utc1600_POGO_O_C',
180: 'Utc1600_POGO_O_CPP',
181: 'AliasObj1010',
182: 'Cvtpgd1610',
183: 'Cvtres1010',
184: 'Export1010',
185: 'Implib1010',
186: 'Linker1010',
187: 'Masm1010',
188: 'Utc1610_C',
189: 'Utc1610_CPP',
190: 'Utc1610_CVTCIL_C',
191: 'Utc1610_CVTCIL_CPP',
192: 'Utc1610_LTCG_C ',
193: 'Utc1610_LTCG_CPP',
194: 'Utc1610_LTCG_MSIL',
195: 'Utc1610_POGO_I_C',
196: 'Utc1610_POGO_I_CPP',
197: 'Utc1610_POGO_O_C',
198: 'Utc1610_POGO_O_CPP',
199: 'AliasObj1100',
200: 'Cvtpgd1700',
201: 'Cvtres1100',
202: 'Export1100',
203: 'Implib1100',
204: 'Linker1100',
205: 'Masm1100',
206: 'Utc1700_C',
207: 'Utc1700_CPP',
208: 'Utc1700_CVTCIL_C',
209: 'Utc1700_CVTCIL_CPP',
210: 'Utc1700_LTCG_C ',
211: 'Utc1700_LTCG_CPP',
212: 'Utc1700_LTCG_MSIL',
213: 'Utc1700_POGO_I_C',
214: 'Utc1700_POGO_I_CPP',
215: 'Utc1700_POGO_O_C',
216: 'Utc1700_POGO_O_CPP',
217: 'AliasObj1200',
218: 'Cvtpgd1800',
219: 'Cvtres1200',
220: 'Export1200',
221: 'Implib1200',
222: 'Linker1200',
223: 'Masm1200',
224: 'Utc1800_C',
225: 'Utc1800_CPP',
226: 'Utc1800_CVTCIL_C',
227: 'Utc1800_CVTCIL_CPP',
228: 'Utc1800_LTCG_C ',
229: 'Utc1800_LTCG_CPP',
230: 'Utc1800_LTCG_MSIL',
231: 'Utc1800_POGO_I_C',
232: 'Utc1800_POGO_I_CPP',
233: 'Utc1800_POGO_O_C',
234: 'Utc1800_POGO_O_CPP',
235: 'AliasObj1210',
236: 'Cvtpgd1810',
237: 'Cvtres1210',
238: 'Export1210',
239: 'Implib1210',
240: 'Linker1210',
241: 'Masm1210',
242: 'Utc1810_C',
243: 'Utc1810_CPP',
244: 'Utc1810_CVTCIL_C',
245: 'Utc1810_CVTCIL_CPP',
246: 'Utc1810_LTCG_C ',
247: 'Utc1810_LTCG_CPP',
248: 'Utc1810_LTCG_MSIL',
249: 'Utc1810_POGO_I_C',
250: 'Utc1810_POGO_I_CPP',
251: 'Utc1810_POGO_O_C',
252: 'Utc1810_POGO_O_CPP',
253: 'AliasObj1400',
254: 'Cvtpgd1900',
255: 'Cvtres1400',
256: 'Export1400',
257: 'Implib1400',
258: 'Linker1400',
259: 'Masm1400',
260: 'Utc1900_C',
261: 'Utc1900_CPP',
262: 'Utc1900_CVTCIL_C',
263: 'Utc1900_CVTCIL_CPP',
264: 'Utc1900_LTCG_C ',
265: 'Utc1900_LTCG_CPP',
266: 'Utc1900_LTCG_MSIL',
267: 'Utc1900_POGO_I_C',
268: 'Utc1900_POGO_I_CPP',
269: 'Utc1900_POGO_O_C',
270: 'Utc1900_POGO_O_CPP',
}
try:
file_path = sys.argv[1]
except IndexError:
print('Не указан файл для поиска RICH сигнатуры.')
sys.exit(0)
try:
pe = pefile.PE(file_path)
except FileNotFoundError:
print('Не удается найти указанный файл:', sys.argv[1])
sys.exit(0)
except pefile.PEFormatError:
print('Файл', sys.argv[1], 'не является PE файлом Windows.')
sys.exit(0)
if pe.RICH_HEADER is not None:
print('Rich key: ', pe.RICH_HEADER.key.hex())
for i in range(0, len(getattr(pe.RICH_HEADER, 'values', [])), 2):
comp_id = pe.RICH_HEADER.values[i]
comp_cnt = pe.RICH_HEADER.values[i + 1]
comp_name = __COMPID_DICT.get((comp_id & 0xffff0000) >> 16, '*Unknown*')
comp_build = comp_id & 0xffff
print(comp_name)
print('\tbuild:', comp_build)
print('\tcount:', comp_cnt)
hasher = hashlib.new('md5')
for i in range(0, len(getattr(pe.RICH_HEADER, 'values', []))):
hasher.update(pe.RICH_HEADER.values[i].to_bytes(8, byteorder='little'))
print('MD5 хеш от RICH сигнатуры:', hasher.hexdigest())
else:
print('Файл', sys.argv[1], 'не содержит RICH сигнатуру.')
|
[
"[email protected]"
] | |
8c9ebc6aadd3e018657f22c56f8dbe1d613c2f87
|
177d2ec17641005ec242a15767995367f84d825e
|
/T2/TOME1.py
|
834ec096c9277bacfe96cc7dd7602d51309dcffd
|
[] |
no_license
|
ttkbot/Newbot2-4-61
|
f05968db0e7d16eda87fb83b1e11367b8ef17c68
|
0dd79e5f67eb925cc0dd9ae586b0e5d90229b3b2
|
refs/heads/master
| 2020-03-07T18:56:01.470929 | 2018-04-19T21:35:17 | 2018-04-19T21:35:17 | 127,656,984 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 350,768 |
py
|
# -*- coding: utf-8 -*-
import LINEVIT
from LINEVIT.lib.curve.ttypes import *
from datetime import datetime
import time, random, sys, ast, re, os, io, json, subprocess, threading, string, codecs, requests, ctypes, urllib, urllib2, urllib3, wikipedia, tempfile
from bs4 import BeautifulSoup
from urllib import urlopen
from io import StringIO
from threading import Thread
from gtts import gTTS
from googletrans import Translator
cl = LINEVIT.LINE()
cl.login(token="ErBXleyxQt3khOyFNIn4.4njzDnCKlLBeMThs5Bey5a.SAxeilT39JXxjn4XgLyByJ60CqrG3EtKvQEM1oY5AMo=")
cl.loginResult()
#ki1 = LINEVIT.LINE()
#ki1.login(token="
#ki1.loginResult()
#ki2 = LINEVIT.LINE()
#ki2.login(token="
#ki2.loginResult()
#ki3 = LINEVIT.LINE()
#ki3.login(token="
#ki3.loginResult()
#ki4 = LINEVIT.LINE()
#ki4.login(token="
#ki4.loginResult()
#ki5 = LINEVIT.LINE()
#ki5.login(token="
#ki5.loginResult()
#ki6 = LINEVIT.LINE()
#ki6.login(token="
#ki6.loginResult()
#ki7 = LINEVIT.LINE()
#ki7.login(token="
#ki7.loginResult()
#ki8 = LINEVIT.LINE()
#ki8.login(token="
#ki8.loginResult()
#ki9 = LINEVIT.LINE()
#ki9.login(token="
#ki9.loginResult()
#ki10 = LINEVIT.LINE()
#ki10.login(token="
#ki10.loginResult()
#ki11 = LINEVIT.LINE()
#ki11.login(token="
#ki11.loginResult()
print "login success"
reload(sys)
sys.setdefaultencoding('utf-8')
helpMessage ="""
╔═════════════════════
║ [SELF BOT]
║[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
╚═════════════════════
╔══════════════════
║ [☬ ชุดคำสั่ง ที่ 1 ☬]
╚══════════════════
╔═════════════════════
║☬➣『คท』
║☬➣『เปิด คท』
║☬➣『ปิด คท』
║☬➣『#คท』 ไวรัส คท
║☬➣『คท @』
║☬➣『ไอดี』
║☬➣『ไอดีกลุ่ม ทั้งหมด:』
║☬➣『Mid』
║☬➣『Mid @』
║☬➣『Allmid』
║☬➣『Mc:』
║☬➣『Gift,แจก』
║☬➣『คิก1 -- คิก10 แจก』
║☬➣『Mid @』
║☬➣『Cn: 』 ตั้งชื่อ
║☬➣『ตั้งชื่อ: 』ตั้งชื่อ นาฬิกา
║☬➣『เปิด นาฬิกา』
║☬➣『ปิด นาฬิกา』
║☬➣『กลุ่ม』
║☬➣『Tl: text』
║☬➣『Tx:』 สร้างชื่อไวรัส
║☬➣『ออน』เช็คเวลา ออนไลน์
║☬➣『เปิด ดึงกลับ』
║☬➣『ปิด ดึงกลับ』
║☬➣『เปิด เข้ากลุ่ม』
║☬➣『ปิด เข้ากลุ่ม』
║☬➣『เปิด เพิ่มเพื่อย』
║☬➣『ปิด เพิ่มเพื่อน』
║☬➣『เปิด ออกแชท』
║☬➣『ปิด ออกแชท』
║☬➣『เปิด แชร์』
║☬➣『ปิด แชร์』
║☬➣『Add message: text』
║☬➣『Message:』
║☬➣『คอมเม้น: 』
║☬➣『เปิด คอมเม้น』
║☬➣『ปิด คอมเม้น』
║☬➣ 『เวลา』เช็ค วัน - เวลา
║☬➣『ยูทูป 』
║☬➣『ขอเพลง』
║☬➣『siri:』
║☬➣『Siri-en』
║☬➣『พูด』
║☬➣『/พูด』 คิกเกอพูดตาม
║☬➣ 『/ 』 สติกเกอร์
║☬➣ 『ลบแชต』
║☬➣『ลบรัน』
║☬➣『คิก1 -- คิก10 ลบรัน』
║☬➣『Log-in / ขอลิ้ง』
║☬➣『ลบ』
║☬➣『 . 』
║☬➣『ประกาศ:』
║☬➣『ผู้สร้าง』
║☬➣『ผู้สร้างกลุ่ม』
║☬➣『ทีมงาน』
║☬➣『รีบอท / รีบูต』
║☬➣『รีคิก』
╚═════════════════════
──┅═✥===========✥═┅──
╔═════════════════════
║ [By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
║ ติดต่อ [LINE ID : 4545272]
╚═════════════════════
ลิ้ง: http://line.me/ti/p/9r-uE5EU09
──┅═✥===========✥═┅──
"""
helpMessage2 ="""
╔═════════════════════
║ [SELF BOT]
║[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
╚═════════════════════
╔══════════════════
║ [☬ ชุดคำสั่ง ที่ 2 ☬]
╚══════════════════
╔═════════════════════
║☬➣『บอท』
║☬➣『#บอท』
║☬➣『คิกมา』
║☬➣『คิกออก』
║☬➣『คิก1--10』 คิกเกอร์เข้า
║☬➣『บิน』 คำสั่งบินl
║☬➣『 Nk: 』
║☬➣『Kill』
║☬➣『เทส』
║☬➣『ยกเชิญ』
║☬➣『Cancel』
║☬➣『เปิด ลิ้ง』
║☬➣『ปิด ลิ้ง』
║☬➣『เป้ด เชิญ』
║☬➣『ปิด เชิญ』
║☬➣『เชิญ』
║☬➣『ลิ้ง』
║☬➣『Spam on/off』
║☬➣『รูปกลุ่ม』
║☬➣『#ดึงรูป』
║☬➣『Gurl』
║☬➣『Vps』
║☬➣『เชคค่า』
║☬➣『แทค』
║☬➣『เปิดหมด』
║☬➣『ปิดหมด』
║☬➣『แบน』
║☬➣『ลบแบน』
║☬➣『แบน @』
║☬➣『ลบแบน @』
║☬➣『ล้างดำ』
║☬➣『Cb』
║☬➣『Bl』
║☬➣『สั่งดำ @』
║☬➣『เปิด อ่าน』
║☬➣『ปิด อ่าน』
║☬➣『ลิสกลุ่ม』
║☬➣『Gcancel: 』
║☬➣『Gcancel on/off』
║☬➣『แปลงร่าง @』
║☬➣『กลับร่าง』
║☬➣『คิกทั้งหมด @』
║☬➣『คิก1- 10 แปลงร่าง @』
║☬➣『คิก คืนร่าง』
║☬➣『ตั้งเวลา』
║☬➣『.ใครอ่าน』
║☬➣『เพื่อน』
║☬➣『#เพื่อน』
║☬➣『บล็อค』
║☬➣『เปิด ล็อคชื่อ』
║☬➣『ปิด ล็อคชื่อ』
║☬➣『เปิด ป้องกัน』
║☬➣『ปิดป้องกัน』
║☬➣ 『รูป』 รูปเรา
║☬➣ 『ปก』 รูแปก เรา
║☬➣ 『โปรวีดีโอ』 วีดีโอโปร เรา
║☬➣ 『ตัส』 ตัสเรา
║☬➣ 『ลิ้งรูป』 ลิ้งรูปเรา
║☬➣ 『ลิ้งปก』 ลิ้งปกเรา
║☬➣ 『Hack @』ขโโมย คท + Mid
║☬➣ 『/รูป @』 ขโมย รูป
║☬➣ 『/ปก @』 ขโมย รูปปก
║☬➣ 『/ตัส @』 ขโมย ตัส
║☬➣ 『เชคหมด』เชครูป ปก ตัส
║☬➣『Sk』
║☬➣『Sp』
║☬➣『Bot Speed』
║☬➣『Key』
║☬➣『Qr on/off』
║☬➣『Backup on/off』
║☬➣『Protect On/off』
║☬➣『Namelock On/off』
╚═════════════════════
──┅═✥===========✥═┅──
╔═════════════════════
║ [By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
║ ติดต่อ [LINE ID : 4545272]
╚═════════════════════
ลิ้ง: http://line.me/ti/p/9r-uE5EU09
──┅═✥===========✥═┅──
"""
helpMessage3 ="""
╔═════════════════════
║ [SELF BOT]
║[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
╚═════════════════════
╔══════════════════
║ [☬ ชุดคำสั่ง ที่ 3 ☬]
╚══════════════════
╔═══════════════════
║ ✟ New function ✟
╠═══════════════════
║☬➣〘Protact on/off
║☬➣〘Qr on/off
║☬➣〘Invit on/off〙
║☬➣〘Cancel on/off〙
╚═══════════════════
╔═══════════════════
║ ✟โหมดเรียนเเบบ✟
╠═══════════════════
║☬➣〘Mimic: on/off〙
║☬➣〘Micadd @〙
║☬➣ Micdel @〙
╠═══════════════════
║ ✟ New function ✟
╠═══════════════════
║☬➣〘Contact on/off〙
║☬➣〘Autojoin on/off〙
║☬➣〘Autoleave on/off〙
║☬➣〘Autoadd on/off〙
║☬➣〘Like me〙
║☬➣〘Like friend〙
║☬➣〘Like on〙
║☬➣〘Respon on/off〙
║☬➣〘Read on/off〙
║☬➣〘Simisimi on/off〙
╠══════════════════
║ ✟ New function ✟
╠══════════════════
║☬➣〘Kalender〙
║☬➣〘tr-id 〙
║☬➣〘tr-en 〙
║☬➣〘tr-jp 〙
║☬➣〘tr-ko 〙
║☬➣〘say-id 〙
║☬➣〘say-en 〙
║☬➣〘say-jp 〙
║☬〘say-ko 〙
║☬➣〘profileig 〙
║☬➣〘checkdate 〙
╚══════════════════
──┅═✥===========✥═┅──
╔═════════════════════
║[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
║ ติดต่อ [LINE ID : 4545272]
╚═════════════════════
ลิ้ง: http://line.me/ti/p/9r-uE5EU09
──┅═✥===========✥═┅──
╔════════════════════
║ ✦เปิด/ปิดข้อความต้อนรับ✦
╠════════════════════
║☬Hhx1 on ➠เปิดต้อนรับ
║☬Hhx1 off ➠ปิดต้อนรับ
║☬Hhx2 on ➠เปิดออกกลุ่ม
║☬Hhx2 off ➠ปิดออกกลุ่ม
║☬Hhx3 on ➠เปิดพูดถึงคนลบ
║☬Hhx3 off ➠ปิดพูดถึงคนลบ
║☬Mbot on ➠เปิดเเจ้งเตือน
║☬Mbot off ➠ปิดเเจ้งเตือน
║☬M on ➠เปิดเเจ้งเตือนตนเอง
║☬M off ➠ปิดเเจ้งเตือนตนเอง
║☬Tag on ➠เปิดกล่าวถึงเเท็ค
║☬Tag off ➠ปิดกล่าวถึงเเท็ค
║☬Kicktag on ➠เปิดเตะคนเเท็ค
║☬Kicktag off ➠ปิดเตะคนเเท็ค
╚═════════════════════
╔═════════════════════
║ ✦โหมดตั้งค่าข้อความ✦
╠═════════════════════
║☬Hhx1˓: ➠ไส่ข้อความต้อนรับ
║☬Hhx2˓: ➠ไส่ข้อความออกจากกลุ่ม
║☬Hhx3˓: ➠ไส่ข้อความเมื่อมีคนลบ
║☬Tag1: ➠ใส่ข้อความแทค
║☬Tag2: ➠ ใส่ข้อความแทค
╚═════════════════════
╔═════════════════════
║ ✦โหมดเช็คตั้งค่าข้อความ✦
╠═════════════════════
║☬Hhx1 ➠เช็คข้อความต้อนรับ
║☬Hhx2 ➠เช็คข้อความคนออก
║☬Hhx3 ➠เช็คข้อความคนลบ
║☬Tag1 ➠เช็ตข้อความแทค
║☬Tag2 ➠เช็คข้อความแทค
╚═════════════════════
──┅═✥===========✥═┅──
╔═════════════════════
║[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
║ ติดต่อ [LINE ID : 4545272]
╚═════════════════════
ลิ้ง: http://line.me/ti/p/9r-uE5EU09
──┅═✥===========✥═┅──
"""
KAC=[cl]
mid = cl.getProfile().mid
#Amid1 = ki1.getProfile().mid
#Amid2 = ki2.getProfile().mid
#Amid3 = ki3.getProfile().mid
#Amid4 = ki4.getProfile().mid
#Amid5 = ki5.getProfile().mid
#Amid6 = ki6.getProfile().mid
#Amid7 = ki7.getProfile().mid
#Amid8 = ki8.getProfile().mid
#Amid9 = ki9.getProfile().mid
#Amid10 = ki10.getProfile().mid
protectname = []
protecturl = []
protection = []
autocancel = {}
autoinvite = []
autoleaveroom = []
targets = []
mid = cl.getProfile().mid
Bots = ["ue0d25974d7242e56c49ad1d2e5b118e4",mid]
self = ["ue0d25974d7242e56c49ad1d2e5b118e4",mid]
admin = "ue0d25974d7242e56c49ad1d2e5b118e4"
admsa = "ue0d25974d7242e56c49ad1d2e5b118e4"
owner = "ue0d25974d7242e56c49ad1d2e5b118e4"
adminMID = "ue0d25974d7242e56c49ad1d2e5b118e4"
Creator="ue0d25974d7242e56c49ad1d2e5b118e4"
wait = {
"alwayRead":False,
"detectMention":True,
"kickMention":False,
"steal":False,
'pap':{},
'invite':{},
"spam":{},
'contact':False,
'autoJoin':True,
'autoCancel':{"on":True, "members":1},
'leaveRoom':True,
'timeline':True,
'autoAdd':True,
'message':"[ตอบรับ อัตโนมัติ]\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\nhttp://line.me/ti/p/9r-uE5EU09",
"lang":"JP",
"commentOn":True,
"comment1":"""
[ AOTO LIKE ]
[ SELF BOT ]
[ รับติดตั้ง เชลบอท ราคาประหยัด ]
[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]
http://line.me/ti/p/9r-uE5EU09
─██─███─███─██─██─██▄█
─██─▀██▄██▀─▀█▄█▀─██▀█
▄██▄▄█▀▀▀─────▀──▄██▄▄█
[ By. ผู้สร้าง พญาไฟ ]
http://line.me/ti/p/9r-uE5EU09
""",
"acommentOn":False,
"bcommentOn":False,
"ccommentOn":False,
"Protectcancl":False,
"pautoJoin":False,
"commentBlack":{},
"wblack":False,
"dblack":False,
"clock":False,
"cName":"",
"likeOn":True,
"pname":False,
"blacklist":{},
"whitelist":{},
"wblacklist":False,
"dblacklist":False,
"qr":False,
"Backup":False,
"protectionOn":False,
"winvite":False,
"ainvite":False,
"binvite":False,
"protect":False,
"cancelprotect":False,
"inviteprotect":False,
"linkprotect":False,
"Hhx1":False,
"Hhx2":False,
"Hhx3":False,
"Notifed":False,
"Notifedbot":False,
"atjointicket":False,
"pnharfbot":{},
"pname":{},
"pro_name":{},
"tag1":"\n[🔯ยังไม่มีข้อความ ตอบกลับ🔯]",
"tag2":"\n[🔯ยังไม่มีข้อความ ตอบกลับ🔯]",
"posts":False,
}
wait2 = {
"readPoint":{},
"readMember":{},
"setTime":{},
"ROM":{}
}
mimic = {
"copy":False,
"copy2":False,
"status":False,
"target":{}
}
settings = {
"simiSimi":{}
}
res = {
'num':{},
'us':{},
'au':{},
}
setTime = {}
setTime = wait2['setTime']
mulai = time.time()
blacklistFile='blacklist.txt'
pendinglistFile='pendinglist.txt'
contact = cl.getProfile()
mybackup = cl.getProfile()
mybackup.displayName = contact.displayName
mybackup.statusMessage = contact.statusMessage
mybackup.pictureStatus = contact.pictureStatus
#contact = ki1.getProfile()
#backup = ki1.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki2.getProfile()
#backup = ki2.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki3.getProfile()
#backup = ki3.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki4.getProfile()
#backup = ki4.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki5.getProfile()
#backup = ki5.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki6.getProfile()
#backup = ki6.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki7.getProfile()
#backup = ki7.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki8.getProfile()
#backup = ki8.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki9.getProfile()
#backup = ki9.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki10.getProfile()
#backup = ki10.getProfile()
#backup.displayName = contact.displayName
#backup.statusMessage = contact.statusMessage
#backup.pictureStatus = contact.pictureStatus
#contact = ki11.getProfile()
#backup = ki11.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 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 yt(query):
with requests.session() as s:
isi = []
if query == "":
query = "S1B tanysyz"
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')
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
if 'watch?v' in a['href']:
b = a['href'].replace('watch?v=', '')
isi += ['youtu.be' + b]
return isi
def _images_get_next_item(s):
start_line = s.find('rg_di')
if start_line == -1: #If no links are found then give an error!
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+90)
end_content = s.find(',"ow"',start_content-90)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
#Getting all links with the help of '_images_get_next_image'
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) #Append all the links in the list named 'Links'
time.sleep(0.1) #Timer could be used to slow down the request for image downloads
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)
day, hours = divmod(hours,24)
return '%02d วัน %02d ชั่วโมง %02d นาที %02d วินาที' % (day,hours, mins, secs)
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(self, messageObject):
return self.Talk.client.sendMessage(0,messageObject)
def sendText(self, Tomid, text):
msg = Message()
msg.to = Tomid
msg.text = text
return self.Talk.client.sendMessage(0, msg)
def sendImage(self, to_, path):
M = Message(to=to_, text=None, contentType = 1)
M.contentMetadata = None
M.contentPreview = None
M2 = self._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': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://obs-sg.line-apps.com/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
return True
def sendImage2(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 = cl.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.')
return True
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 NOTIFIED_READ_MESSAGE(op):
try:
if op.param1 in wait2['readPoint']:
Name = cl.getContact(op.param2).displayName
if Name in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += "\n・" + Name
wait2['ROM'][op.param1][op.param2] = "・" + Name
else:
pass
except:
pass
def bot(op):
try:
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
cl.findAndAddContactsByMid(op.param1)
if (wait["message"] in [""," ","\n",None]):
pass
else:
cl.sendText(op.param1,str(wait["message"]))
if op.type == 11:
if op.param3 == '1':
if op.param1 in wait['pname']:
try:
G = cl.getGroup(op.param1)
except:
try:
G = ki1.getGroup(op.param1)
except:
try:
G = ki2.getGroup(op.param1)
except:
try:
G = ki3.getGroup(op.param1)
except:
try:
G = ki4.getGroup(op.param1)
except:
try:
G = ki5.getGroup(op.param1)
except:
pass
G.name = wait['pro_name'][op.param1]
try:
cl.updateGroup(G)
except:
try:
ki1.updateGroup(G)
except:
try:
ki2.updateGroup(G)
except:
try:
ki2.updateGroup(G)
except:
try:
ki3.updateGroup(G)
except:
try:
ki4.updateGroup(G)
except:
pass
if op.param2 in ken:
pass
else:
try:
ki1.kickoutFromGroup(op.param1,[op.param2])
except:
try:
ki1.kickoutFromGroup(op.param1,[op.param2])
except:
try:
ki2.kickoutFromGroup(op.param1,[op.param2])
except:
try:
ki3.kickoutFromGroup(op.param1,[op.param2])
except:
try:
ki4.kickoutFromGroup(op.param1,[op.param2])
except:
pass
cl.sendText(op.param1,"Group Name Lock")
ki1.sendText(op.param1,"Haddeuh dikunci Pe'a")
ki2.sendText(op.param1,"Wekawekaweka (Har Har)")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
cl.sendMessage(c)
if op.type == 13:
if op.param3 in mid:
if op.param2 in mid:
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
cl.updateGroup(G)
Ticket = cl.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid1:
G = ki1.getGroup(op.param1)
G.preventJoinByTicket = False
ki1.updateGroup(X)
Ti = ki1.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki1.updateGroup(X)
Ti = ki1.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid2:
X = ki2.getGroup(op.param1)
X.preventJoinByTicket = False
ki2.updateGroup(X)
Ti = ki2.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki2.updateGroup(X)
Ti = ki2.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid3:
X = ki3.getGroup(op.param1)
X.preventJoinByTicket = False
ki3.updateGroup(X)
Ti = ki3.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki3.updateGroup(X)
Ti = ki3.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid4:
G = ki4.getGroup(op.param1)
G.preventJoinByTicket = False
ki4.updateGroup(X)
Ti = ki4.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki4.updateGroup(X)
Ti = ki4.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid5:
G = ki5.getGroup(op.param1)
G.preventJoinByTicket = False
ki5.updateGroup(X)
Ti = ki5.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki5.updateGroup(X)
Ti = ki5.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid6:
G = ki6.getGroup(op.param1)
G.preventJoinByTicket = False
ki6.updateGroup(X)
Ti = ki6.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki6.updateGroup(X)
Ti = ki6.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid7:
G = ki7.getGroup(op.param1)
G.preventJoinByTicket = False
ki7.updateGroup(X)
Ti = ki7.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki7.updateGroup(X)
Ti = ki7.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid8:
G = ki8.getGroup(op.param1)
G.preventJoinByTicket = False
ki8.updateGroup(X)
Ti = ki8.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki8.updateGroup(X)
Ti = ki8.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid9:
G = ki9.getGroup(op.param1)
G.preventJoinByTicket = False
ki9.updateGroup(X)
Ti = ki9.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki9.updateGroup(X)
Ti = ki9.reissueGroupTicket(op.param1)
if op.param3 in mid:
if op.param2 in Amid10:
G = ki10.getGroup(op.param1)
G.preventJoinByTicket = False
ki10.updateGroup(X)
Ti = ki10.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ki10.updateGroup(X)
Ti = ki10.reissueGroupTicket(op.param1)
if op.param3 in Amid1:
if op.param2 in Amid2:
X = ki2.getGroup(op.param1)
X.preventJoinByTicket = False
ki2.updateGroup(X)
Ti = ki1.reissueGroupTicket(op.param1)
ki1.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki2.updateGroup(X)
Ti = ki2.reissueGroupTicket(op.param1)
if op.param3 in Amid2:
if op.param2 in Amid3:
X = ki3.getGroup(op.param1)
X.preventJoinByTicket = False
ki3.updateGroup(X)
Ti = ki2.reissueGroupTicket(op.param1)
ki2.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki3.updateGroup(X)
Ti = ki3.reissueGroupTicket(op.param1)
if op.param3 in Amid3:
if op.param2 in Amid4:
X = ki4.getGroup(op.param1)
X.preventJoinByTicket = False
ki4.updateGroup(X)
Ti = ki4.reissueGroupTicket(op.param1)
ki3.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki4.updateGroup(X)
Ti = ki4.reissueGroupTicket(op.param1)
if op.param3 in Amid4:
if op.param2 in Amid5:
X = ki5.getGroup(op.param1)
X.preventJoinByTicket = False
ki5.updateGroup(X)
Ti = ki5.reissueGroupTicket(op.param1)
ki4.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki5.updateGroup(X)
Ti = ki5.reissueGroupTicket(op.param1)
if op.param3 in Amid5:
if op.param2 in Amid6:
X = ki6.getGroup(op.param1)
X.preventJoinByTicket = False
ki6.updateGroup(X)
Ti = ki6.reissueGroupTicket(op.param1)
ki5.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki6.updateGroup(X)
Ti = ki6.reissueGroupTicket(op.param1)
if op.param3 in Amid6:
if op.param2 in Amid7:
X = ki7.getGroup(op.param1)
X.preventJoinByTicket = False
ki7.updateGroup(X)
Ti = ki7.reissueGroupTicket(op.param1)
ki6.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki.updateGroup(X)
Ti = ki7.reissueGroupTicket(op.param1)
if op.param3 in Amid7:
if op.param2 in Amid8:
X = ki8.getGroup(op.param1)
X.preventJoinByTicket = False
ki8.updateGroup(X)
Ti = ki8.reissueGroupTicket(op.param1)
ki7.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki8.updateGroup(X)
Ti = ki8.reissueGroupTicket(op.param1)
if op.param3 in Amid8:
if op.param2 in Amid9:
X = ki9.getGroup(op.param1)
X.preventJoinByTicket = False
ki9.updateGroup(X)
Ti = ki9.reissueGroupTicket(op.param1)
ki8.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki9.updateGroup(X)
Ti = ki9.reissueGroupTicket(op.param1)
if op.param3 in Amid9:
if op.param2 in Amid10:
X = ki10.getGroup(op.param1)
X.preventJoinByTicket = False
ki7.updateGroup(X)
Ti = ki10.reissueGroupTicket(op.param1)
ki9.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki10.updateGroup(X)
Ti = ki10.reissueGroupTicket(op.param1)
if op.param3 in Amid10:
if op.param2 in Amid1:
X = ki.getGroup(op.param1)
X.preventJoinByTicket = False
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
ki10.acceptGroupInvitationByTicket(op.param1,Ticket)
X.preventJoinByTicket = True
ki.updateGroup(X)
Ti = ki.reissueGroupTicket(op.param1)
#===========================================
if op.type == 32:
if not op.param2 in Bots:
if wait["protectionOn"] == True:
try:
klist=[ki1,ki2,ki3,ki4,ki5,ki6,ki7,ki8,ki9,ki10]
kicker = random.choice(klist)
G = kicker.getGroup(op.param1)
kicker.kickoutFromGroup(op.param1,[op.param2])
kicker.inviteIntoGroup(op.param1, [op.param3])
except Exception, e:
print e
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)
cl.sendText(op.param1, "Your invitation was declined\n\n[SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]]\n\nhttp://line.me/ti/p/9r-uE5EU09")
else:
cl.acceptGroupInvitation(op.param1)
cl.sendText(op.param1, "Your invitation was declined\n\n[SEL FBOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]]\n\nhttp://line.me/ti/p/9r-uE5EU09")
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 Amid1 in op.param3:
G = cl.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ki1.rejectGroupInvitation(op.param1)
else:
ki1.acceptGroupInvitation(op.param1)
else:
ki1.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ki1.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:
ki1.cancelGroupInvitation(op.param1, matched_list)
if Amid2 in op.param3:
G = cl.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ki2.rejectGroupInvitation(op.param1)
else:
ki2.acceptGroupInvitation(op.param1)
else:
ki2.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ki2.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:
ki2.cancelGroupInvitation(op.param1, matched_list)
if op.type == 11:
if not op.param2 in Bots:
if wait["qr"] == True:
try:
klist=[ki1,ki2,ki3,ki4,ki5,ki6,ki7,ki8,ki9,ki10]
kicker = random.choice(klist)
G = kicker.getGroup(op.param1)
G.preventJoinByTicket = True
kicker.updateGroup(G)
except Exception, e:
print e
if op.type == 11:
if not op.param2 in Bots:
if wait["protectionOn"] == True:
try:
klist=[ki1,ki2,ki3,ki4,ki5,ki6,ki7,ki8,ki9,ki10]
kicker = random.choice(klist)
G = kicker.getGroup(op.param1)
G.preventJoinByTicket = True
kicker.updateGroup(G)
kicker.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = True
kicker.updateGroup(G)
except Exception, e:
print e
if op.type == 13:
G = cl.getGroup(op.param1)
I = G.creator
if not op.param2 in Bots:
if wait["protectionOn"] == True:
klist=[ki1,ki2,ki3,ki4,ki5,ki6,ki7,ki8,ki9,ki10]
kicker = random.choice(klist)
G = kicker.getGroup(op.param1)
if G is not None:
gInviMids = [contact.mid for contact in G.invitee]
kicker.cancelGroupInvitation(op.param1, gInviMids)
if op.type == 19:
if not op.param2 in Bots:
try:
gs = ki1.getGroup(op.param1)
gs = ki2.getGroup(op.param1)
targets = [op.param2]
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)
except:
pass
except Exception, e:
print e
if not op.param2 in Bots:
if wait["Backup"] == True:
try:
random.choice(KAC).inviteIntoGroup(op.param1, [op.param3])
except Exception, e:
print e
if not op.param2 in Bots:
if wait["protectionOn"] == True:
try:
klist=[ki1,ki2,ki3,ki4,ki5,ki6,ki7,ki8,ki9,ki10]
kicker = random.choice(klist)
G = kicker.getGroup(op.param1)
G.preventJoinByTicket = False
kicker.updateGroup(G)
invsend = 0
Ticket = kicker.reissueGroupTicket(op.param1)
kl1.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.1)
X = kicker.getGroup(op.param1)
X.preventJoinByTicket = True
kl1.kickoutFromGroup(op.param1,[op.param2])
kicker.kickoutFromGroup(op.param1,[op.param2])
kl1.leaveGroup(op.param1)
kicker.updateGroup(X)
except Exception, e:
print e
if not op.param2 in Bots:
try:
gs = ki1.getGroup(op.param1)
gs = ki2.getGroup(op.param1)
targets = [op.param2]
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)
except:
pass
except Exception, e:
print e
if not op.param2 in Bots:
if wait["Backup"] == True:
try:
random.choice(KAC).inviteIntoGroup(op.param1, [op.param3])
except Exception, e:
print e
if op.type == 19:
if mid in op.param3:
if op.param2 in Bots:
pass
try:
ki1.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group、\n["+op.param1+"]\nの\n["+op.param2+"]\nを蹴る事ができませんでした。\nブラックリストに追加します。")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
G = ki1.getGroup(op.param1)
G.preventJoinByTicket = False
ki1.updateGroup(G)
Ti = ki1.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = cl.getGroup(op.param1)
X.preventJoinByTicket = True
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid1 in op.param3:
if op.param2 in Bots:
pass
try:
ki2.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki2.getGroup(op.param1)
X.preventJoinByTicket = False
ki2.updateGroup(X)
Ti = ki2.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki1.getGroup(op.param1)
X.preventJoinByTicket = True
ki1.updateGroup(X)
Ticket = ki1.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid2 in op.param3:
if op.param2 in Bots:
pass
try:
ki3.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki3.getGroup(op.param1)
X.preventJoinByTicket = False
ki3.updateGroup(X)
Ti = ki3.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki2.getGroup(op.param1)
X.preventJoinByTicket = True
ki2.updateGroup(X)
Ticket = ki2.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid3 in op.param3:
if op.param2 in Bots:
pass
try:
ki4.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki4.getGroup(op.param1)
X.preventJoinByTicket = False
ki4.updateGroup(X)
Ti = ki4.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki3.getGroup(op.param1)
X.preventJoinByTicket = True
ki3.updateGroup(X)
Ticket = ki3.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid4 in op.param3:
if op.param2 in Bots:
pass
try:
ki5.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki5.getGroup(op.param1)
X.preventJoinByTicket = False
ki5.updateGroup(X)
Ti = ki5.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki4.getGroup(op.param1)
X.preventJoinByTicket = True
ki4.updateGroup(X)
Ticket = ki4.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid5 in op.param3:
if op.param2 in Bots:
pass
try:
ki6.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki6.getGroup(op.param1)
X.preventJoinByTicket = False
ki6.updateGroup(X)
Ti = ki6.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki5.getGroup(op.param1)
X.preventJoinByTicket = True
ki5.updateGroup(X)
Ticket = ki5.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid6 in op.param3:
if op.param2 in Bots:
pass
try:
ki7.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki7.getGroup(op.param1)
X.preventJoinByTicket = False
ki7.updateGroup(X)
Ti = ki7.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki6.getGroup(op.param1)
X.preventJoinByTicket = True
ki6.updateGroup(X)
Ticket = ki6.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid7 in op.param3:
if op.param2 in Bots:
pass
try:
ki8.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki8.getGroup(op.param1)
X.preventJoinByTicket = False
ki8.updateGroup(X)
Ti = ki8.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki7.getGroup(op.param1)
X.preventJoinByTicket = True
ki7.updateGroup(X)
Ticket = ki7.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid8 in op.param3:
if op.param2 in Bots:
pass
try:
ki9.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki9.getGroup(op.param1)
X.preventJoinByTicket = False
ki9.updateGroup(X)
Ti = ki9.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki8.getGroup(op.param1)
X.preventJoinByTicket = True
ki8.updateGroup(X)
Ticket = ki8.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid9 in op.param3:
if op.param2 in Bots:
pass
try:
ki10.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki10.getGroup(op.param1)
X.preventJoinByTicket = False
ki10.updateGroup(X)
Ti = ki10.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki9.getGroup(op.param1)
X.preventJoinByTicket = True
ki9.updateGroup(X)
Ticket = ki9.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if Amid10 in op.param3:
if op.param2 in Bots:
pass
try:
ki1.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client が蹴り規制orグループに存在しない為、\n["+op.param1+"]\nの\n["+op.param2+"]\nBecause the client does not exist in the kick regulation or group.\nAdd it to the blacklist.")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
X = ki1.getGroup(op.param1)
X.preventJoinByTicket = False
ki1.updateGroup(X)
Ti = ki1.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki1.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki2.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki3.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki4.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki5.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki6.acceptGroupInvitationByTicket(op.param1,Ti)
time.sleep(0.01)
ki7.acceptGroupInvitationByTicket(op.param1,Ti)
ki8.acceptGroupInvitationByTicket(op.param1,Ti)
ki9.acceptGroupInvitationByTicket(op.param1,Ti)
ki10.acceptGroupInvitationByTicket(op.param1,Ti)
X = ki10.getGroup(op.param1)
X.preventJoinByTicket = True
ki10.updateGroup(X)
Ticket = ki10.reissueGroupTicket(op.param1)
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
if op.type == 13:
if mid in op.param3:
if wait["pautoJoin"] == True:
cl.acceptGroupInvitation(op.param1)
else:
cl.rejectGroupInvitation(op.param1)
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.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 = [cName + "\n" + str(wait["tag1"]) , cName + "\n" + str(wait["tag2"])]
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_)
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention"] == True:
contact = cl.getContact(msg.from_)
cName = contact.displayName
balas = ["Dont Tag Me!! Im Busy",cName + ""]
ret_ = "[Auto] " + 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_)
msg.contentType = 7
msg.text = ''
msg.contentMetadata = {
'STKPKGID': '9662',
'STKTXT': '[]',
'STKVER': '16',
'STKID':'697'
}
cl.sendMessage(msg)
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","-_-","Alin 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["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,"already")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
cl.sendText(msg.to,"decided not to comment")
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"Done deleted")
wait["dblack"] = False
else:
wait["dblack"] = False
cl.sendText(msg.to,"It is not in the black list")
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
cl.sendText(msg.to,"Done already")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
cl.sendText(msg.to,"Done done aded")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
cl.sendText(msg.to,"Done deleted")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
cl.sendText(msg.to,"It is not in the black list")
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 = "post URL\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = "URL→\n" + msg.contentMetadata["postEndUrl"]
cl.sendText(msg.to,msg.text)
elif msg.text is None:
return
elif msg.text in ["คำสั่ง"]:
print "\nHelp pick up..."
if wait["lang"] == "JP":
cl.sendText(msg.to, helpMessage + "")
else:
cl.sendText(msg.to,helpt)
elif msg.text in ["คำสั่ง2"]:
print "\nHelp pick up..."
if wait["lang"] == "JP":
cl.sendText(msg.to, helpMessage2 + "")
else:
cl.sendText(msg.to,helpt)
elif msg.text in ["คำสั่ง3"]:
print "\nHelp pick up..."
if wait["lang"] == "JP":
cl.sendText(msg.to, helpMessage3 + "")
else:
cl.sendText(msg.to,helpt)
cl.sendText(msg.to,helpt)
elif ("Gn:" in msg.text):
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.name = msg.text.replace("Gn:","")
cl.updateGroup(X)
else:
cl.sendText(msg.to,"It can't be used besides the group.")
elif "Kick:" in msg.text:
midd = msg.text.replace("Kick:"," ")
klist=[ki7,ki6,ki5,ki1,cl]
kicker = random.choice(klist)
kicker.kickoutFromGroup(msg.to,[midd])
if op.type == 25:
msg = op.message
if msg.contentType == 13:
if wait["winvite"] == True:
if msg.from_ == admin:
_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 + " was here")
break
elif invite in wait["blacklist"]:
cl.sendText(msg.to,"Sorry, " + _name + " On Blacklist")
cl.sendText(msg.to,"Call my daddy to use command !, \n➡Unban: " + invite)
break
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,"Done Invite : \n➡" + _name)
wait["winvite"] = False
break
except:
try:
ki1.findAndAddContactsByMid(invite)
ki1.inviteIntoGroup(op.param1,[invite])
wait["winvite"] = False
except:
cl.sendText(msg.to,"Negative, Error detected")
wait["winvite"] = False
break
if msg.contentType == 13:
if wait['ainvite'] == 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:
ki1.sendText(msg.to, _name + " สมาชิกอยู่ในกลุ่มเเล้ว")
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
ki1.findAndAddContactsByMid(target)
ki1.inviteIntoGroup(msg.to,[target])
ki1.sendText(msg.to,"Invite " + _name)
wait['ainvite'] = False
break
except:
ki1.sendText(msg.to,"Error")
wait['ainvite'] = False
break
if msg.contentType == 13:
if wait['binvite'] == 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:
ki2.sendText(msg.to, _name + " สมาชิกอยู่ในกลุ่มเเล้ว")
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
ki2.findAndAddContactsByMid(target)
ki2.inviteIntoGroup(msg.to,[target])
ki2.sendText(msg.to,"Invite " + _name)
wait['binvite'] = False
break
except:
ki2.sendText(msg.to,"Error")
wait['binvite'] = False
break
elif "Contact" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.to}
cl.sendMessage(msg)
elif msg.text.lower() == 'บอท':
msg.contentType = 13
msg.contentMetadata = {'mid': Amid1}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid2}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid3}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid4}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid5}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid6}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid7}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid8}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid9}
cl.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid10}
cl.sendMessage(msg)
elif msg.text.lower() == '#บอท':
msg.contentType = 13
msg.contentMetadata = {'mid': Amid1}
ki1.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid2}
ki2.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid3}
ki3.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid4}
ki4.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid5}
ki5.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid6}
ki6.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid7}
ki7.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid8}
ki8.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid9}
ki9.sendMessage(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid10}
ki10.sendMessage(msg)
elif "คท" == msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendMessage(msg)
elif "vdo:" in msg.text.lower():
if msg.toType == 2:
query = msg.text.split(":")
try:
if len(query) == 3:
isi = yt(query[2])
hasil = isi[int(query[1])-1]
cl.sendText(msg.to, hasil)
else:
isi = yt(query[1])
cl.sendText(msg.to, isi[0])
except Exception as e:
cl.sendText(msg.to, str(e))
elif 'ยูทูป ' in msg.text:
try:
textToSearch = (msg.text).replace('ยูทูป ', "").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'})
cl.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
cl.sendText(msg.to,"Could not find it")
elif msg.text in ["55","555"]:
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "100",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
ki2.sendMessage(msg)
ki3.sendMessage(msg)
ki4.sendMessage(msg)
ki5.sendMessage(msg)
ki6.sendMessage(msg)
ki7.sendMessage(msg)
ki8.sendMessage(msg)
ki9.sendMessage(msg)
ki10.sendMessage(msg)
elif msg.text in ["Lol"]:
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "10",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
ki2.sendMessage(msg)
elif "youname " in msg.text.lower():
txt = msg.text.replace("youname ", "")
cl.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Bl " in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
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,"Done Banned")
print "[Command] Bannad"
except:
pass
#===========================================
#----------------------------------------------------------------------------
#------------------------------- UNBAN BY TAG -------------------------------
elif "Wl " in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
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,"Done Unbanned")
print "[Command] Unbannad"
except:
pass
# elif 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)
# else:
# if msg.contentType == 7:
# msg.contentType = 7
# msg.text = None
# msg.contentMetadata = {
# "STKID": "6",
# "STKPKGID": "1",
# "STKVER": "100" }
# cl.sendMessage(msg)
# elif msg.contentType == 13:
# msg.contentType = 13
# msg.contentMetadata = {'mid': msg.contentMetadata["mid"]}
# cl.sendMessage(msg)
elif "Mimic:" in msg.text:
if msg.from_ in admin:
cmd = msg.text.replace("Mimic:","")
if cmd == "on":
if mimic["status"] == False:
mimic["status"] = True
cl.sendText(msg.to,"Mimic on\n\nเปิดการเลียนเเบบ")
else:
cl.sendText(msg.to,"Mimic already on\n\nเปิดการเลียนเเบบ")
elif cmd == "off":
if mimic["status"] == True:
mimic["status"] = False
cl.sendText(msg.to,"Mimic off\n\nปิดการเลียนเเบบ")
else:
cl.sendText(msg.to,"Mimic already off\n\nปิดการเลียนเเบบ")
elif "add:" in cmd:
target0 = msg.text.replace("Mimic:add:","")
target1 = target0.lstrip()
target2 = target1.replace("@","")
target3 = target2.rstrip()
_name = target3
gInfo = cl.getGroup(msg.to)
targets = []
for a in gInfo.members:
if _name == a.displayName:
targets.append(a.mid)
if targets == []:
cl.sendText(msg.to,"No targets\n\nเกิดผิดพลาด")
else:
for target in targets:
try:
mimic["target"][target] = True
cl.sendText(msg.to,"Success added target")
cl.sendMessageWithMention(msg.to,target)
break
except:
cl.sendText(msg.to,"โปรเเกรมเลียนเเบบทำงาน")
break
elif "del:" in cmd:
target0 = msg.text.replace("Mimic:del:","")
target1 = target0.lstrip()
target2 = target1.replace("@","")
target3 = target2.rstrip()
_name = target3
gInfo = cl.getGroup(msg.to)
targets = []
for a in gInfo.members:
if _name == a.displayName:
targets.append(a.mid)
if targets == []:
cl.sendText(msg.to,"No targets\n\nเกิดข้อผิดพลาด")
else:
for target in targets:
try:
del mimic["target"][target]
cl.sendText(msg.to,"Success deleted target")
cl.sendMessageWithMention(msg.to,target)
break
except:
cl.sendText(msg.to,"คุณลบการเลียนเเบบผู้ใช้นี้")
break
elif cmd == "list":
if mimic["target"] == {}:
cl.sendText(msg.to,"No target")
else:
lst = "<<List Target>>"
total = len(mimic["target"])
for a in mimic["target"]:
if mimic["target"][a] == True:
stat = "On"
else:
stat = "Off"
lst += "\n-> " + cl.getContact(a).displayName + " | " + stat
cl.sendText(msg.to,lst + "\nTotal: " + total)
#----------------------------------------------------------------------------
elif msg.text.lower() in ["botkill"]:
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,"There was no blacklist user")
return
for jj in matched_list:
ki1.kickoutFromGroup(msg.to,[jj])
pass
elif msg.text.lower() in ["admins","mee","ผู้สร้าง"]:
msg.contentType = 13
adm = 'uf0bd4970771f26a8cef66473d59bcc69'
msg.contentMetadata = {'mid': adm}
cl.sendMessage(msg)
cl.sendText(msg.to,"Add Line http://line.me/ti/p/9r-uE5EU09")
cl.sendText(msg.to,"👆 สนใจ บอท ทักมาคุย กันได้นะครับ 👆")
#=========================================
elif msg.text in ["ของขวัญ","Gift","แจก"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '1'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["คิก1 แจก","Gift 1"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '2'}
msg.text = None
ki1.sendMessage(msg)
elif msg.text in ["คิก2 แจก","Gift 2"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '3'}
msg.text = None
ki2.sendMessage(msg)
elif msg.text in ["คิก3 แจก","Gift 3"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '4'}
msg.text = None
ki3.sendMessage(msg)
elif msg.text in ["Bot3 Gift","3 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '4'}
msg.text = None
ki3.sendMessage(msg)
elif msg.text in ["คิก4 แจก","Gift 4"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '5'}
msg.text = None
ki4.sendMessage(msg)
elif msg.text in ["คิก5 แจก","Gift 5"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '6'}
msg.text = None
ki5.sendMessage(msg)
elif msg.text in ["คิก6 แจก","Gift 6"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '7'}
msg.text = None
ki6.sendMessage(msg)
elif msg.text in ["คิก7 แจก","Gift 7"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '8'}
msg.text = None
ki7.sendMessage(msg)
elif msg.text in ["คิก8 แจก"," Gift 8"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '9'}
msg.text = None
ki8.sendMessage(msg)
elif msg.text in ["คิก9 แจก","Gift 9"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '10'}
msg.text = None
ki9.sendMessage(msg)
elif msg.text in ["คิก10 แจก","Gift 10"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '3b92ccf5-54d3-4765-848f-c9ffdc1da020',
'PRDTYPE': 'THEME',
'MSGTPL': '11'}
msg.text = None
ki10.sendMessage(msg)
#====================================================
#VPS STUFF - VPS NEEDED TO RUN THIS COMMAND :)
elif msg.text in ["vps","kernel","Vps"]:
if msg.from_ in admin:
botKernel = subprocess.Popen(["uname","-svmo"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel)
print "[Command]Kernel executed"
else:
cl.sendText(msg.to,"Command denied.")
cl.sendText(msg.to,"Admin permission required.")
print "[Error]Command denied - Admin permission required"
elif "ผู้สร้างกลุ่ม" == 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,"old user")
elif 'ขอเพลง ' in msg.text:
try:
textToSearch = (msg.text).replace('ขอเพลง ', "").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'})
cl.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
cl.sendText(msg.to,"Could not find it")
elif "#set" in msg.text:
cl.sendText(msg.to, "Let's see who lazy to type")
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
wait2['ROM'][msg.to] = {}
print wait2
elif "#read" in msg.text:
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
chiya = ""
else:
chiya = ""
for rom in wait2["ROM"][msg.to].items():
print rom
chiya += rom[1] + "\n"
cl.sendText(msg.to, "people who reading%s\n is this\n\n\nDate and time I started it:\n[%s]" % (wait2['readMember'][msg.to],setTime[msg.to]))
else:
cl.sendText(msg.to, "read point not set\nReading point setting you send it it will send an esxisting one")
elif msg.text in ["Myginfoid","ไอดีกลุ่ม ทั้งหมด"]:
gid = cl.getGroupIdsJoined()
g = ""
for i in gid:
g += "[%s]:%s\n" % (cl.getGroup(i).name,i)
cl.sendText(msg.to,g)
elif msg.text in ["P1 invite","P1 Invite"]:
wait["ainvite"] = True
ki.sendText(msg.to,"Send Contact")
elif msg.text in ["P2 invite","P2 Invite"]:
wait["binvite"] = True
kk.sendText(msg.to,"Send Contact")
#==================================================
elif "ประกาศ:" in msg.text:
bctxt = msg.text.replace("ประกาศ:", "")
a = cl.getGroupIdsJoined()
for manusia in a:
cl.sendText(manusia, (bctxt))
elif msg.text.lower() == 'bann':
blockedlist = cl.getBlockedContactIds()
cl.sendText(msg.to, "Please wait...")
kontak = cl.getContacts(blockedlist)
num=1
msgs="User Blocked List\n"
for ids in kontak:
msgs+="\n%i. %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n\nTotal %i blocked user(s)" % len(kontak)
cl.sendText(msg.to, msgs)
elif "#หำ1:" in msg.text:
string = msg.text.replace("#หำ1:","")
if len(string.decode('utf-8')) <= 20:
profile = ki.getProfile()
profile.displayName = string
ki.updateProfile(profile)
elif msg.text in ["คิกมา","มาหำ","#Kicker","#kicker","Kicker","kicker","•••"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
ki1.sendText(msg.to,"[SELF BOT\ทBy:☬ധู้さန້ণق↔ധഖาໄฟ☬ ]")
ki2.sendText(msg.to,"[Do not think will try.]")
ki3.sendText(msg.to,"[ By: ☬ധู้さန້ণق↔ധഖาໄฟ☬ ]")
ki1.sendText(msg.to,"Hello " + str(ginfo.name) + "\n[By:☬ധู้さန້ণق↔ധഖาໄฟ☬ ]")
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki1.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki1.updateGroup(G)
elif msg.text in ["คิก"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.0)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki1.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki1.updateGroup(G)
elif msg.text in ["คิกออก","บอทออก","Bye","#bye"]:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
ki1.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki1.leaveGroup(msg.to)
ki2.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki2.leaveGroup(msg.to)
ki3.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki3.leaveGroup(msg.to)
ki4.sendText(msg.to,"Bye~Bye\nลาก่อย" + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki4.leaveGroup(msg.to)
ki5.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki5.leaveGroup(msg.to)
ki6.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]]")
ki6.leaveGroup(msg.to)
ki7.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki7.leaveGroup(msg.to)
ki8.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki8.leaveGroup(msg.to)
ki9.sendText(msg.to,"Bye~Bye\nลาก่อย " + str(ginfo.name) + "\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki9.leaveGroup(msg.to)
ki10.sendText(msg.to,"Bye~Bye\ลาก่อย " + str(ginfo.name) + "\n[By ☬ധู้さန້ণق↔ധഖาໄฟ☬]")
ki10.leaveGroup(msg.to)
except:
pass
elif msg.text.lower() == '#byeall':
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
ki1.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
ki6.leaveGroup(msg.to)
ki7.leaveGroup(msg.to)
ki8.leaveGroup(msg.to)
ki9.leaveGroup(msg.to)
ki10.leaveGroup(msg.to)
except:
pass
elif "#v10" in msg.text:
cl.sendText(msg.to,"""[SELF BOT]\n[By:☬ധู้さန້ণق↔ധഖาໄฟ☬]")
คำสั่งบอท siri
คำนี้เป็นการล็อกห้องสั่งแล้วทุกคนจะทำอะไรไม่ได้นอกจากเจ้าของห้องทำได้คนเดียวเช่น•เปิดลิงค์•เชิญเพื่อน•เปลี่ยนรูปกลุ่ม•เปลี่ยนชื่อกลุ่มไรแบบนี้• บอทจะไม่เตะเเอทมินทุกกรณี
มีตั้งเเต่ชุดบอท 12-37 บอท
ชุดล๊อกห้อง
ล๊อกกันรันสติ๊กเกอร์
Set:StampLimitation:on
ล๊อกชื่อกลุ่ม
Set:changenamelock:on
ล๊อกการเชิญของสมาชิก
Set:blockinvite:on
ล๊อกแอทมินกลุ่ม
Set:ownerlock:on
ล๊อกรูปกลุ่ม
Set:iconlock:on
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:changeowner
เปลี่ยนเจ้าของห้องสั่งแล้วส่งคอลแทคคนที่จะเป็นเจ้าของห้องคนต่อไปลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:addblacklist
บัญชีดำแบ็คลิสคนไม่ให้เข้ากลุ่มสั่งแล้วส่งคอลแทคคนที่เราจะแบ็คลิสลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:addwhitelist
บัญชีขาวแก้ดำสั่งแล้วส่งคอลแทคคนที่เราจะแก้แบ๊คลิสลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Set:blockinvite:off ปลดล็อกการเชิญ
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Set:blockinvite:on ล็อกการเชิญ
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:inviteurl เปิดลิงค์
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:DenyURLInvite ปิดลิงค์
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:cancelinvite ยกเลิกค้างเชิญสั่ง2ครั้ง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:groupcreator เช็คเจ้าของบ้านตัวจริง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:extracreator เช็คเจ้าของบ้านคนสำรอง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:changeextraowner
เพิ่มเจ้าของบ้านคนที2หรือเรียกคนสำรองสั่งแล้วส่งคอลแทคคนที่จะเป็นคนสำรองลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Set:turncreator
สลับให้เจ้าของบ้านคนที่2เป็นตัวจริง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
ดูคนอ่าน
สั่งตั้งค่าก่อนแล้วค่อยสั่งอ่านคน
Setlastpoint ตั้งค่า
Viewlastseen สั่งอ่าน
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
สนใจติดต่อที่
By: ☬ധู้さန້ণق↔ധഖาໄฟ☬
LINE ID 4545272
http://line.me/ti/p/9r-uE5EU09
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
""")
#==================================================
elif msg.text in ["Invite"]:
if msg.from_ in admin:
wait["winvite"] = True
cl.sendText(msg.to,"โปรดส่ง คท ด้วย")
elif msg.text in ["เชิญ"]:
if msg.from_ in admin:
wait["winvite"] = True
cl.sendText(msg.to,"โปรดส่ง คท ด้วย")
elif msg.text in ["invite on"]:
if msg.from_ in admin:
wait["winvite"] = False
cl.sendText(msg.to,"ปิดการเชิญ แล้ว.")
elif msg.text in ["Bot1 invite contact","1เชิญ"]:
if msg.from_ in admin:
wait["ainvite"] = True
ki1.sendText(msg.to,"send contact")
elif msg.text in ["Bot2 invite contact","2เชิญ"]:
if msg.from_ in admin:
wait["binvite"] = True
ki2.sendText(msg.to,"send contact")
elif ("Ktc " 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])
except:
cl.sendText(msg.to,"Error")
elif '123zzz' in msg.text.lower():
key = msg.text[-33:]
cl.findAndAddContactsByMid(key)
cl.inviteIntoGroup(msg.to, [key])
contact = cl.getContact(key)
elif msg.text in ["ยกเลิก"]:
if msg.toType == 2:
X = cl.getGroup(msg.to)
if X.invitee is not None:
gInviMids = [contact.mid for contact in X.invitee]
cl.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"No one is inviting。")
else:
cl.sendText(msg.to,"Sorry, nobody absent")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["บอทยกเลิก"]:
if msg.toType == 2:
klist=[ki1,ki2,ki3,ki4,ki5,ki6,ki7]
kicker = random.choice(klist)
G = kicker.getGroup(msg.to)
if G.invitee is not None:
gInviMids = [contact.mid for contact in G.invitee]
kicker.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
kicker.sendText(msg.to,"No one is inviting")
else:
kicker.sendText(msg.to,"Sorry, nobody absent")
else:
if wait["lang"] == "JP":
kicker.sendText(msg.to,"Can not be used outside the group")
else:
kicker.sendText(msg.to,"Not for use less than group")
elif msg.text in ["#Link on"]:
if msg.toType == 2:
uye = random.choice(KAC)
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
uye.updateGroup(X)
if wait["lang"] == "JP":
uye.sendText(msg.to,"done")
else:
uye.sendText(msg.to,"already open")
else:
if wait["lang"] == "JP":
uye.sendText(msg.to,"Can not be used outside the group")
else:
uye.sendText(msg.to,"Not for use less than group")
elif msg.text in ["เปิดลิ้ง"]:
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
if wait["lang"] == "JP":
cl.sendText(msg.to,"อนุญาติ ให้มีการเชิญ\nด้วยลิ้งแล้ว👌")
else:
cl.sendText(msg.to,"already open")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["ปิดลิ้ง"]:
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = True
cl.updateGroup(X)
if wait["lang"] == "JP":
cl.sendText(msg.to,"ปิดการเชิญ\nด้วยลิ้งแล้ว👌")
else:
cl.sendText(msg.to,"already close")
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text.lower() == 'ginfo':
ginfo = cl.getGroup(msg.to)
try:
gCreator = ginfo.creator.displayName
except:
gCreator = "Error"
if wait["lang"] == "JP":
if ginfo.invitee is None:
sinvitee = "0"
else:
sinvitee = str(len(ginfo.invitee))
msg.contentType = 13
msg.contentMetadata = {'mid': ginfo.creator.mid}
cl.sendText(msg.to,"[Nama]\n" + str(ginfo.name) + "\n[Group Id]\n" + msg.to + "\n\n[Group Creator]\n" + gCreator + "\n\nAnggota:" + str(len(ginfo.members)) + "\nInvitation:" + sinvitee + "")
cl.sendMessage(msg)
elif msg.text in ["!Glist","Myginfo"]:
gs = cl.getGroupIdsJoined()
L = "☫『 Groups List 』☫\n"
for i in gs:
L += "[⭐] %s \n" % (cl.getGroup(i).name + " | [ " + str(len (cl.getGroup(i).members)) + " ]")
cl.sendText(msg.to, L + "\nTotal Group : [ " + str(len(gs)) +" ]")
elif msg.text in ["Selfbot"]:
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendMessage(msg)
cl.sendText(msg.to,"[SELFBOT\nBy:☬ധู้さန້ণق↔ധഖาໄฟ☬]")
elif "ไอดี" == msg.text:
key = msg.to
cl.sendText(msg.to, key)
elif ("Hack " in msg.text):
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mi = cl.getContact(key1)
cl.sendText(msg.to,"Mid:" + key1)
elif "Mid:" in msg.text:
mmid = msg.text.replace("Mid:","")
msg.contentType = 13
msg.contentMetadata = {"mid":mmid}
cl.sendMessage(msg)
# elif "Phet Keyy" in msg.text:
# cl.sendText(msg.to,""" [{PHET HACK BOT}] \n\n key Only Kicker #\n\n[Kb1 in]\n[1Aditname:]\n[B Cancel]\n[kick @]\n[Ban @]\n[kill]\n[BotChat]\n[Respons]\n[Pb1 Gift]\n[Pb1 bye]\n\n
#❦❧〖฿❂Ŧ〗☞ᵀËÄM ທஇລ❂ق B❂T✓
#❦❧ ᵀËÄM ℓℓπ้ी૪ B❂T ✓
#❦❧ ᵀËÄM ທஇລ❂قB❂T ✓
#☠Ҝŋ β☢ȶȶ ƿℓαÿєᴿ☠
#✍ Ŧ€₳M ж Ħ₳ʗҜ฿❂Ŧ ✈
#Ŧ€₳M ✍ ທஇລ❂قীள้௭ิњ ✈
#☢Ŧ€₳M≈ನန้ণএ≈฿❂Ŧ☢
#・⋆ ざঝণのঝ ⋆ ・
#♤ のю४ণধபӘທ ♤
#🇹?? ฿ΘŧŧĽÎη℮Ŧђάίłάήđ 🇹🇭
#[By.🐯 हईທຮຮๅજईह 🐯]
#[By.β•`BF.บั้ม•`]
#[By.Gυ Tєʌм HʌcκBoт]
#[By.❦〖Ᵽɧëȶ〗☞ᵀËÄM ທஇລ❂ق B❂T✓]
#""")
elif msg.text.lower() == 'ยกเลิก1':
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
cl.cancelGroupInvitation(msg.to,[_mid])
cl.sendText(msg.to,"I pretended to cancel and canceled(๑و•̀ω•́)و")
elif msg.text.lower() == 'บอทยกเลิก1':
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
ki1.cancelGroupInvitation(msg.to,[_mid])
ki1.sendText(msg.to,"I pretended to cancel and canceled(๑و•̀ω•́)و")
cl.sendText(msg.to,"I pretended to cancel and canceled(๑و•̀ω•́)و")
elif "คท @" in msg.text:
msg.contentType = 13
_name = msg.text.replace("คท @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
msg.contentMetadata = {'mid': g.mid}
cl.sendMessage(msg)
else:
pass
elif "#cb" in msg.text:
nk0 = msg.text.replace("#cb","")
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,"😏")
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,"😏")
except:
cl.sendText(msg.to,"😏")
elif "แบนหมด" in msg.text:
nk0 = msg.text.replace("แบนหมด","")
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,"Target Locked")
except:
cl.sendText(msg.to,"Error")
elif "ลบแบน ทั้งหมด" in msg.text:
nk0 = msg.text.replace("ลบแบน ทั้งหมด","")
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,"Target Unlocked")
except:
cl.sendText(msg.to,"Error")
elif "Mid" == msg.text:
cl.sendText(msg.to,mid)
elif msg.text == "กลุ่ม":
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
gCreator = ginfo.creator.displayName
except:
gCreator = "ไม่พบผู้สร้างกลุ่ม"
if wait["lang"] == "JP":
if ginfo.invitee is None:
sinvitee = "0"
else:
sinvitee = str(len(ginfo.invitee))
if ginfo.preventJoinByTicket == True:
u = "[ปิด]"
else:
u = "[เปิด]"
cl.sendText(msg.to,"[ชื่อของกลุ่ม]:\n" + str(ginfo.name) + "\n[Gid]:\n" + msg.to + "\n[ผู้สร้างกลุ่ม:]\n" + gCreator + "\n[ลิ้งค์รูปกลุ่ม]:\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\n[จำนวนสมาชิก]:" + str(len(ginfo.members)) + "คน\n[จำนวนค้างเชิญ]:" + sinvitee + "คน\n[สถานะลิ้งค์]:" + u + "URL\n[By: ☬ധู้さန້ণق↔ധഖาໄฟ☬]")
else:
cl.sendText(msg.to,"Nama Gourp:\n" + str(ginfo.name) + "\nGid:\n" + msg.to + "\nCreator:\n" + gCreator + "\nProfile:\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif "Bot1@@" in msg.text:
group = cl.getGroup(msg.to)
k = len(group.members)//100
for j in xrange(k+1):
msg = Message(to=msg.to)
txt = u''
s=0
d=[]
for i in group.members[j*200 : (j+1)*200]:
d.append({"S":str(s), "E" :str(s+8), "M":i.mid})
s += 9
txt += u'@Krampus\n'
msg.text = txt
msg.contentMetadata = {u'MENTION':json.dumps({"MENTIONEES":d})}
ki1.sendMessage(msg)
elif msg.text in ["Bot?","เทส"]:
ki1.sendText(msg.to,"😈คิกเกอร๋.1 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki2.sendText(msg.to,"😈คิกเกอร์.2 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki3.sendText(msg.to,"😈คิกเกอร์.3 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki4.sendText(msg.to,"😈คิกเกอร์.4 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki5.sendText(msg.to,"😈คิกเกอร์.5 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki6.sendText(msg.to,"😈คิกเกอร์.6 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki7.sendText(msg.to,"😈คิกเกอร์.7 รายงานต้ว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki8.sendText(msg.to,"😈คิกเกอร์.8 รายงานตีว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki9.sendText(msg.to,"😈คิกเกอร์.9 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
ki10.sendText(msg.to,"😈คิกเกอร์.10 รายงานตัว😈\n[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n[ลิ้ง] http://line.me/ti/p/9r-uE5EU09 ")
elif "/พูด " in msg.text:
bctxt = msg.text.replace("/พูด ","")
ki1.sendText(msg.to,(bctxt))
ki2.sendText(msg.to,(bctxt))
ki3.sendText(msg.to,(bctxt))
ki4.sendText(msg.to,(bctxt))
ki5.sendText(msg.to,(bctxt))
ki6.sendText(msg.to,(bctxt))
ki7.sendText(msg.to,(bctxt))
ki8.sendText(msg.to,(bctxt))
ki9.sendText(msg.to,(bctxt))
ki10.sendText(msg.to,(bctxt))
elif "All mid" == msg.text:
ki1.sendText(msg.to,Amid1)
ki2.sendText(msg.to,Amid2)
ki3.sendText(msg.to,Amid3)
ki4.sendText(msg.to,Amid4)
ki5.sendText(msg.to,Amid5)
ki6.sendText(msg.to,Amid6)
ki7.sendText(msg.to,Amid7)
ki8.sendText(msg.to,Amid8)
ki9.sendText(msg.to,Amid9)
ki10.sendText(msg.to,Amid10)
elif msg.text in ["Protect:on","Protect on","เปิดป้องกัน"]:
if wait["protectionOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already on\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Protection On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["protectionOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Already on\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Qr:off","Qr off"]:
if wait["qr"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Protection QR PRO Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["qr"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection QR PRO Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Already off\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Qr:on","Qr on"]:
if wait["qr"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already on\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Protection QR PRO On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["qr"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection QR PRO On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["Protect:off","Protect off","ปิดป้องกัน"]:
if wait["protectionOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Protection Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["protectionOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Protection Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Already off\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif "เปิด ล็อคชื่อ" in msg.text:
if msg.to in wait['pname']:
cl.sendText(msg.to,"ล็อคชื่อ สำเร็จ.👌..")
else:
cl.sendText(msg.to,"bone..")
wait['pname'][msg.to] = True
wait['pro_name'][msg.to] = cl.getGroup(msg.to).name
elif "ปิด ล็อคชื่อ" in msg.text:
if msg.to in wait['pname']:
cl.sendText(msg.to,"ปิด ล็อคชื่อแล้ว.👌.")
del wait['pname'][msg.to]
else:
cl.sendText(msg.to,"bone..")
elif "ปิด เชิญ" == msg.text:
gid = msg.to
autocancel[gid] = "poni"
cl.sendText(msg.to,"ปิดการเชิญเข้ากลุ่ม\nของสมาชิกแล้ว.👌.")
elif "เปิด เชิญ" == msg.text:
try:
del autocancel[msg.to]
cl.sendText(msg.to,"เปิด ให้สมาชิกทุกคน\nสามรถเชิญเพื่อนได้.👌.")
except:
pass
elif "Cn: " in msg.text:
string = msg.text.replace("Cn: ","")
if len(string.decode('utf-8')) <= 20:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
cl.sendText(msg.to,"Name " + string + " Done Bosqu")
elif msg.text in ["invite:on"]:
if msg.from_ in admin:
wait["winvite"] = True
cl.sendText(msg.to,"send contact")
elif "Mc " in msg.text:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
cl.sendText(msg.to,"Mc: " + key1)
elif "Mc: " in msg.text:
mmid = msg.text.replace("Mc: ","")
msg.contentType = 13
msg.contentMetadata = {"mid":mmid}
ki1.sendMessage(msg)
ki2.sendMessage(msg)
ki3.sendMessage(msg)
ki4.sendMessage(msg)
ki5.sendMessage(msg)
ki6.sendMessage(msg)
ki7.sendMessage(msg)
ki8.sendMessage(msg)
ki9.sendMessage(msg)
ki10.sendMessage(msg)
elif msg.text in ["K on","เปิด คท","Contact on","K:on"]:
if wait["contact"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
else:
wait["contact"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
elif msg.text in ["contact v"]:
if msg.from_ in admin:
wait["winvite"] = True
random.choice(KAC).sendText(msg.to,"send contact")
elif msg.text in ["K:off","ปิด คท","Contact off","K off"]:
if wait["contact"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah off Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu ")
else:
wait["contact"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
elif msg.text in ["Auto join on","Join on","Join:on","เปิด เข้ากลุ่ม","Poin on"]:
if wait["autoJoin"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
else:
wait["autoJoin"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
elif msg.text in ["Join off","Auto join off","ปิด เข้ากลุ่ม","Join:off","Poin off"]:
if wait["autoJoin"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah off Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
else:
wait["autoJoin"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah off Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
elif "Gcancel:" in msg.text:
try:
strnum = msg.text.replace("Gcancel:","")
if strnum == "off":
wait["autoCancel"]["on"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Invitation refused turned off\nTo turn on please specify the number of people and send")
else:
cl.sendText(msg.to,"关了邀请拒绝。要时开请指定人数发送")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,strnum + " The group of people and below decided to automatically refuse invitation")
else:
cl.sendText(msg.to,strnum + "使人以下的小组用自动邀请拒绝")
except:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Value is wrong")
else:
cl.sendText(msg.to,"Bizarre ratings")
elif msg.text in ["Leave:on","Auto leave on","เปิด ออกแชท","Leave on"]:
if wait["leaveRoom"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["leaveRoom"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"要了开。")
elif msg.text in ["Leave:off","Auto leave off","ปิด ออกแชท","Leave off"]:
if wait["leaveRoom"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
else:
wait["leaveRoom"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"already")
elif msg.text in ["เปิด แชร์","Share on","Share:on"]:
if wait["timeline"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["timeline"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"要了开。")
elif msg.text in ["ปิด แชร์","Share off","Share:off"]:
if wait["timeline"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
else:
wait["timeline"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"done")
else:
cl.sendText(msg.to,"要了关断。")
elif msg.text in ["Like on","เปิด ไลค์"]:
if wait["likeOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"เปิดอยู่แล้ว。")
else:
wait["likeOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"เปิดระบบออโต้ไลค์.👌")
elif msg.text in ["ปิด ไลค์","Like off"]:
if wait["likeOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"ปิดอยู่แล้ว")
else:
wait["likeOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"ปิดระบบออโต้ไลค์.👌")
#========================================
#========================================
elif msg.text in ["เชคค่า","เช็คค่า","Set"]:
print "Setting pick up..."
md = "SELF BOT\nBy:☬ധู้さန້ণق↔ധഖาໄฟ☬\n\n"
if wait["likeOn"] == True: md+=" ออโต้ไลค์ : ✔ \n"
else:md+=" ออโต้ไลค์ : ❌ \n"
if wait["alwayRead"] == True: md+=" อ่าน : ✔ ??\n"
else:md+=" อ่าน : ❌ \n"
if wait["detectMention"] == True: md+=" ตอบแทค : ✔ \n"
else:md+=" ตอบแทค : ❌ \n"
if wait["kickMention"] == True: md+=" ออโต้เตะ: ✔ \n"
else:md+=" ออโต้เตะ : ❌ \n"
if wait["Notifed"] == True: md+=" Notifed : ✔ \n"
else:md+=" Notifed : ❌ \n"
if wait["Notifedbot"] == True: md+=" Notifedbot : ✔ \n"
else:md+=" Notifedbot : ❌ \n"
if wait["acommentOn"] == True: md+=" Hhx1 : ✔ \n"
else:md+=" Hhx1 : ❌ \n"
if wait["bcommentOn"] == True: md+=" Hhx2 : ✔ \n"
else:md+=" Hhx2 : ❌ \n"
if wait["ccommentOn"] == True: md+=" Hhx3 : ✔ \n"
else:md+=" Hhx3 : ❌ \n"
if wait["Protectcancl"] == True: md+=" Cancel : ✔ \n"
else:md+=" Cancel : ❌ \n"
if wait["winvite"] == True: md+=" เชิญ: ✔ \n"
else:md+=" เชิญ : ❌ \n"
if wait["pname"] == True: md+=" ล็อคชื่อ : ✔ \n"
else:md+=" ล็อคชื่อ : ❌ \n"
if wait["contact"] == True: md+=" Contact : ✔ \n"
else: md+=" Contact : ❌ \n"
if wait["autoJoin"] == True: md+=" ออโต้เข้ากลุ่ม : ✔ \n"
else: md +=" ออโต้เข้ากลุ่ม : ❌ \n"
if wait["autoCancel"]["on"] == True:md+=" Group cancel :" + str(wait["autoCancel"]["members"]) + " \n"
else: md+= " Group cancel : ❌ \n"
if wait["leaveRoom"] == True: md+=" ออโต้ ออกแชท : ✔ \n"
else: md+=" ออโต้ ออกแชท: ❌ \n"
if wait["timeline"] == True: md+=" ออโต้ แชร์ : ✔ \n"
else:md+=" ออโต้ แชร์ : ❌ \n"
if wait["clock"] == True: md+=" ชื่อ นาฬิกา : ✔ \n"
else:md+=" ชื่อ นาฬิกา : ❌ \n"
if wait["autoAdd"] == True: md+=" ออโต้ เพิ่มเพื่อน : ✔ \n"
else:md+=" ออโต้ เพิ่มเพื่อน : ❌ \n"
if wait["commentOn"] == True: md+=" ออโต้ คอมเม้น : ✔ \n"
else:md+=" ออโต้ คอมเม้น : ❌ \n"
if wait["Backup"] == True: md+=" ดึงกลับ : ✔ \n"
else:md+=" ดึงกลับ : ❌ \n"
if wait["qr"] == True: md+=" ป้องกัน QR : ✔ \n"
else:md+=" ป้องกัน QR : ❌ \n"
cl.sendText(msg.to,md)
msg.contentType = 13
msg.contentMetadata = {'mid': admsa}
cl.sendMessage(msg)
#========================================
elif msg.text in ["รีบอท","รีบูต"]:
if msg.from_ in Creator:
cl.sendText(msg.to, "เชลบอท ได้รีสตาร์ตแล้ว.👌\nกรุณาตั้งค่าใหม่อีกครั้ง.👈")
restart_program()
print "@Restart"
else:
cl.sendText(msg.to, "No Access")
#========================================
elif msg.text.lower() == 'รีคิก':
if msg.toType == 2:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
cl.sendText(msg.to,"waitting...")
ki1.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
ki6.leaveGroup(msg.to)
ki7.leaveGroup(msg.to)
ki8.leaveGroup(msg.to)
ki9.leaveGroup(msg.to)
ki10.leaveGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
ki1.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
ki6.leaveGroup(msg.to)
ki7.leaveGroup(msg.to)
ki8.leaveGroup(msg.to)
ki9.leaveGroup(msg.to)
ki10.leaveGroup(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
ki1.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
ki6.leaveGroup(msg.to)
ki7.leaveGroup(msg.to)
ki8.leaveGroup(msg.to)
ki9.leaveGroup(msg.to)
ki10.leaveGroup(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
ki1.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
ki6.leaveGroup(msg.to)
ki7.leaveGroup(msg.to)
ki8.leaveGroup(msg.to)
ki9.leaveGroup(msg.to)
ki10.leaveGroup(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
ki1.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
ki6.leaveGroup(msg.to)
ki7.leaveGroup(msg.to)
ki8.leaveGroup(msg.to)
ki9.leaveGroup(msg.to)
ki10.leaveGroup(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
ki1.leaveGroup(msg.to)
ki2.leaveGroup(msg.to)
ki3.leaveGroup(msg.to)
ki4.leaveGroup(msg.to)
ki5.leaveGroup(msg.to)
ki6.leaveGroup(msg.to)
ki7.leaveGroup(msg.to)
ki8.leaveGroup(msg.to)
ki9.leaveGroup(msg.to)
ki10.leaveGroup(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki1.updateGroup(G)
print "kicker ok"
G.preventJoinByTicket(G)
ki1.updateGroup(G)
#================================================#
elif msg.text in ["Gcreator:inv","เชิญเเอทมิน"]:
if msg.from_ in admin:
ginfo = cl.getGroup(msg.to)
gCreator = ginfo.creator.mid
try:
cl.findAndAddContactsByMid(gCreator)
cl.inviteIntoGroup(msg.to,[gCreator])
print "success inv gCreator"
except:
pass
#============================
elif "คิก1 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก1 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki1.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki1.CloneContactProfile(target)
ki1.sendText(msg.to, "คิกเกอร์ 1.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก2 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก2 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki2.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki2.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki2.CloneContactProfile(target)
ki2.sendText(msg.to, "คิกเกอร์ 2.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก3 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก3 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki3.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki3.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki3.CloneContactProfile(target)
ki3.sendText(msg.to, "คิกเกอร์ 3.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก4 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก4 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki4.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki4.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki4.CloneContactProfile(target)
ki4.sendText(msg.to, "คิกเกอร์ 4.👌\nแปลงร่าง อวตาง\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก5 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก5 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki5.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki5.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki5.CloneContactProfile(target)
ki5.sendText(msg.to, "คิกเกอร์ 5.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก6 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก6 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki6.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki6.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki6.CloneContactProfile(target)
ki6.sendText(msg.to, "คิกเกอร์ 6.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก7 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก7 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki7.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki7.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki7.CloneContactProfile(target)
ki7.sendText(msg.to, "คิกเกอร์ 7.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก8 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก8 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki8.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki8.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki8.CloneContactProfile(target)
ki8.sendText(msg.to, "คิกเกอร์ 8.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก9 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก9 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki9.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki9.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki9.CloneContactProfile(target)
ki9.sendText(msg.to, "คิกเกอร์ 9.👌\nแปลงร้าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
elif "คิก10 แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิก10 แปลงร่าง @","")
_nametarget = _name.rstrip(' ')
gs = ki10.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki10.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
ki10.CloneContactProfile(target)
ki10.sendText(msg.to, "คิกเกอร์ 10.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
#=======================================================#
elif "คิกทั้งหมด @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("คิกทั้งหมด @","")
_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:
ki1.CloneContactProfile(target)
ki1.sendText(msg.to, "คิกเกอร์ 1.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki2.CloneContactProfile(target)
ki2.sendText(msg.to, "คิกเกอร์ 2.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki3.CloneContactProfile(target)
ki3.sendText(msg.to, "คิกเกอร์ 3.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki4.CloneContactProfile(target)
ki4.sendText(msg.to, "คิกเกอร์ 4.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki5.CloneContactProfile(target)
ki5.sendText(msg.to, "คิกเกอร์ 5.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki6.CloneContactProfile(target)
ki6.sendText(msg.to, "คิกเกอร์ 6.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki7.CloneContactProfile(target)
ki7.sendText(msg.to, "คิกเกอร์ 7.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki8.CloneContactProfile(target)
ki8.sendText(msg.to, "คิกเกอร์ 8.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki9.CloneContactProfile(target)
ki9.sendText(msg.to, "คิกเกอร์ 9.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
ki10.CloneContactProfile(target)
ki10.sendText(msg.to, "คิกเกอร์ 10.👌\nแปลงร่าง อวตาล\nเสร็จเรียบร้อย (^_^)")
except Exception as e:
print e
#====================================
#================================
elif "Nk: " in msg.text:
if msg.from_ in Creator:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ti)
G = ki2.getGroup(msg.to)
G.preventJoinByTicket = True
ki3.updateGroup(G)
nk0 = msg.text.replace("Nk: ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
targets = []
for s in X.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:
if target not in admin:
ki1.kickoutFromGroup(msg.to,[target])
ki1.leaveGroup(msg.to)
ki2sendText(msg.to,"Succes BosQ")
ki3.sendText(msg.to,"Pakyu~")
else:
cl.sendText(msg.to,"Admin Detected")
else:
cl.sendText(msg.to,"Lu sape!")
#=================================
elif msg.text in ["Backup:on","Backup on","เปิด ดึงกลับ","เปิดการเชิญกลับ"]:
if wait["Backup"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Backup On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["Backup"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Backup On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Sudah on Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Backup:off","Backup off","ปิด ดีงกลับ","ปิดการเชิญกลับ"]:
if wait["Backup"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah off Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Backup Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["Backup"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Backup Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Sudah off Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
#===========================================#
elif msg.text in ["Reject","ลบรัน"]:
gid = cl.getGroupIdsInvited()
for i in gid:
cl.rejectGroupInvitation(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"ปฎิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["ลบ"]:
gid = ki11.getGroupIdsInvited()
for i in gid:
ki11.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki11.sendText(msg.to,"ปฎิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
#=============================================#
elif msg.text in ["Login","ขอลิ้ง"]:
if not LINEVITLogged:
lgncall = msg.to
ki11.login(qr=True,callback=logincall)
ki11.loginResult()
user2 = ki11.getProfile().mid
LINEVITLogged = True
now2 = datetime.datetime.now()
nowT = datetime.datetime.strftime(now2,"%H")
nowM = datetime.datetime.strftime(now2,"%M")
nowS = datetime.datetime.strftime(now2,"%S")
tm = "\n\n"+nowT+":"+nowM+":"+nowS
cl.sendText(user1,"ล็อกอินสำเร็จ พร้อมใช้งานแล้ว (`・ω・´)"+tm)
else:
cl.sendText(msg.to,"ได้ทำการล็อคอินไปแล้ว")
elif msg.text.lower() == ".":
gs = []
try:
gs = cl.getGroup(msg.to).members
except:
try:
gs = cl.getRoom(msg.to).contacts
except:
pass
tlist = ""
for i in gs:
tlist = tlist+i.displayName+" "+i.mid+"\n\n"
if AsulLogged == True:
try:
ki11.sendText(user1,tlist)
except:
ki11.new_post(tlist)
else:
cl.sendText(msg.to,"ยังไม่ได้ล็อคอิน")
#========================================#
elif msg.text in ["Reject1","คิก1 ลบรัน"]:
gid = ki1.getGroupIdsInvited()
for i in gid:
ki1.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki1.sendText(msg.to,"คิกเกอร์ 1\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject2","คิก2 ลบรัน"]:
gid = ki2.getGroupIdsInvited()
for i in gid:
ki2.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki2.sendText(msg.to,"คิกเกอร์ 2\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject3","คิก3 ลบรัน"]:
gid = ki3.getGroupIdsInvited()
for i in gid:
ki3.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki3.sendText(msg.to,"คิกเกอร์ 3\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject4","คิก4 ลบรัน"]:
gid = ki4.getGroupIdsInvited()
for i in gid:
ki4.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki4.sendText(msg.to,"คิกเกอร์ 4\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject5","คิก5 ลบรัน"]:
gid = ki5.getGroupIdsInvited()
for i in gid:
ki5.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki5.sendText(msg.to,"คิกเกอร์ 5\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject6","คิก6 ลบรัน"]:
gid = ki6.getGroupIdsInvited()
for i in gid:
ki6.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki6.sendText(msg.to,"คิกเกอร์ 6\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject7","คิก7 ลบรัน"]:
gid = ki7.getGroupIdsInvited()
for i in gid:
ki7.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki7.sendText(msg.to,"คิกเกอร์ 7\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject8","คิก8 ลบรัน"]:
gid = ki8.getGroupIdsInvited()
for i in gid:
ki8.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki8.sendText(msg.to,"คิกเกอร์ 8\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject9","คิก9 ลบรัน"]:
gid = ki9.getGroupIdsInvited()
for i in gid:
ki9.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki9.sendText(msg.to,"คิกเกอร์ 9\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
elif msg.text in ["Reject10","คิก10 ลบรัน"]:
gid = ki10.getGroupIdsInvited()
for i in gid:
ki10.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki10.sendText(msg.to,"คิกเกอร์ 10\nปฏิเสธกลุ่มเชิญเรียบร้อยแล้ว.👌")
else:
cl.sendText(msg.to,"拒绝了全部的邀请。")
elif msg.text in ["Y1 rgroups","Y1 rgroup"]:
gid = ki.getGroupIdsInvited()
for i in gid:
ki.rejectGroupInvitation(i)
if wait["lang"] == "JP":
ki.sendText(msg.to,"Bot All invitations is clean")
else:
ki.sendText(msg.to,"拒绝了全部的邀请。")
elif msg.text in ["Add:on","เปิด เพิ่มเพื่อน","Auto add:on","Add on"]:
if wait["autoAdd"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
else:
wait["autoAdd"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ok Bosqu")
else:
cl.sendText(msg.to,"Sudah on Bosqu")
elif msg.text in ["Add:off","Auto add off","ปิด เพิ่มเพื่อน","Add off"]:
if wait["autoAdd"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah off Bosqu")
else:
cl.sendText(msg.to,"Ok Bosqu")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Ok Bosqu")
else:
cl.sendText(msg.to,"Sudah off Bosqu")
elif msg.text in ["ลบแชต"]:
cl.removeAllMessages(op.param2)
cl.sendText(msg.to,"ทำการลบเรียบร้อย👌")
cl.sendText(msg.to,"Ok")
# elif "รัน @" in msg.text:
# _name = msg.text.replace("รัน @","")
# _nametarget = _name.rstrip(' ')
# gs = cl.getGroup(msg.to)
# for g in gs.members:
# if _nametarget == g.displayName:
# cl.sendText(msg.to,"เริ่มทำการรัน")
# cl.sendText(g.mid,"[☬Ŧ€ΆM฿❂Ŧ↔Pђãỳãƒir€☬]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n http://line.me/ti/p/9r-uE5EU09")
# cl.sendText(msg.to, "ทำการรันเรียบร้อย")
# print "Done spam"
#========================================
elif msg.text.lower() == 'ออน':
cl.sendText(msg.to, "โปรดรอสักครู่....")
eltime = time.time() - mulai
van = "[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\nระยะเวลาที่บอททำงาน\n"+waktu(eltime)
cl.sendText(msg.to,van)
#========================================
elif "Message set:" in msg.text:
wait["message"] = msg.text.replace("Message set:","")
cl.sendText(msg.to,"message changed\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif "Add message: " in msg.text:
wait["message"] = msg.text.replace("Add message: ","")
if wait["lang"] == "JP":
cl.sendText(msg.to,"message changed\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"done。\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Message","Com"]:
if wait["lang"] == "JP":
cl.sendText(msg.to,"message change to\n\n" + wait["message"])
else:
cl.sendText(msg.to,"The automatic appending information is set as follows。\n\n" + wait["message"])
elif "Coms set:" in msg.text:
c = msg.text.replace("คอมเม้น:","Coms set:","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"String that can not be changed")
else:
wait["comment"] = c
cl.sendText(msg.to,"changed\n\n" + c)
elif "Add comment: " in msg.text:
c = msg.text.replace("Add comment: ","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"String that can not be changed")
else:
wait["comment"] = c
cl.sendText(msg.to,"changed\n\n" + c)
elif msg.text in ["เปิด คอมเม้น","Com on","Comment:on"]:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
cl.sendText(msg.to,"Already on")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["ปิด คอมเม้น","Com off","Comment:off"]:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
cl.sendText(msg.to,"Already off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Done")
else:
cl.sendText(msg.to,"Already off")
elif msg.text in ["Comment","Coms"]:
cl.sendText(msg.to,"message changed to\n\n" + str(wait["comment"]))
elif msg.text in ["HHX1","Hhx1"]:
cl.sendText(msg.to,"[เช็คข้อความต้อนรับของคุณ]\n\n" + str(wait["acomment"]))
elif msg.text in ["HHX2","Hhx2"]:
cl.sendText(msg.to,"[เช็คข้อความกล่าวถึงคนออกจากกลุ่ม]\n\n" + str(wait["bcomment"]))
elif msg.text in ["HHX3","Hhx3"]:
cl.sendText(msg.to,"[เช็คข้อความกล่าวถึงคนลบสมาชิก]\n\n" + str(wait["ccomment"]))
elif "Hhx1:" in msg.text:
c = msg.text.replace("Hhx1:","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["acomment"] = c
cl.sendText(msg.to,"➠ ตั้งค่าข้อความต้อนรับ👌\n\n" + c)
elif "Hhx2:" in msg.text:
c = msg.text.replace("Hhx2:","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["bcomment"] = c
cl.sendText(msg.to,"➠ ตั้งค่าข้อความกล่าวถึงคนออกจากกลุ่ม👌\n\n" + c)
elif "Hhx3:" in msg.text:
c = msg.text.replace("Hhx3:","")
if c in [""," ","\n",None]:
cl.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["ccomment"] = c
cl.sendText(msg.to,"➠ ตั้งค่าข้อความกล่าวถึงคนลบสมาชิก👌\n\n" + c)
elif msg.text in ["Hhx1 on"]:
if wait["acommentOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ เปิดข้อความต้อนรับเเล้ว👌")
else:
cl.sendText(msg.to,"Already on")
else:
wait["acommentOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ เปิดข้อความต้อนรับเเล้ว👌")
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["Hhx2 on"]:
if wait["bcommentOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
cl.sendText(msg.to,"Already on")
else:
wait["bcommentOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["Hhx3 on"]:
if wait["ccommentOn"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
cl.sendText(msg.to,"Already on")
else:
wait["ccommentOn"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["Hhx1 off"]:
if wait["acommentOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ ปิดข้อความต้อนรับเเล้ว👌")
else:
cl.sendText(msg.to,"Already off")
else:
wait["acommentOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ ปิดข้อความต้อนรับเเล้ว👌")
else:
cl.sendText(msg.to,"Already off")
elif msg.text in ["Hhx2 off"]:
if wait["bcommentOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
cl.sendText(msg.to,"Already off")
else:
wait["bcommentOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
cl.sendText(msg.to,"Already off")
elif msg.text in ["Hhx3 off"]:
if wait["ccommentOn"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
cl.sendText(msg.to,"Already off")
else:
wait["ccommentOn"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
cl.sendText(msg.to,"Already off")
elif msg.text in ["Gurl"]:
if msg.toType == 2:
uye = random.choice(KAC)
x = cl.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
uye.updateGroup(x)
gurl = uye.reissueGroupTicket(msg.to)
uye.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
uye.sendText(msg.to,"Can not be used outside the group")
else:
uye.sendText(msg.to,"Not for use less than group")
elif "Ambil QR: " in msg.text:
if msg.toType == 2:
gid = msg.text.replace("Ambil QR: ","")
gurl = cl.reissueGroupTicket(gid)
cl.sendText(msg.to,"line://ti/g/" + gurl)
else:
cl.sendText(msg.to,"Not for use less than group")
elif "Y1 gurl: " in msg.text:
if msg.toType == 2:
gid = msg.text.replace("Y1 gurl: ","")
x = ki.getGroup(gid)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
ki.updateGroup(x)
gurl = ki.reissueGroupTicket(gid)
ki.sendText(msg.to,"line://ti/g/" + gurl)
else:
ki.sendText(msg.to,"Not for use less than group")
elif "Y2 gurl: " in msg.text:
if msg.toType == 2:
gid = msg.text.replace("Y2 gurl: ","")
x = kk.getGroup(gid)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
kk.updateGroup(x)
gurl = kk.reissueGroupTicket(gid)
kk.sendText(msg.to,"line://ti/g/" + gurl)
else:
kk.sendText(msg.to,"Not for use less than group")
#========================================
elif msg.text in ["Comment bl "]:
wait["wblack"] = True
cl.sendText(msg.to,"add to comment bl")
elif msg.text in ["Comment wl "]:
wait["dblack"] = True
cl.sendText(msg.to,"wl to comment bl")
elif msg.text in ["Comment bl confirm"]:
if wait["commentBlack"] == {}:
cl.sendText(msg.to,"confirmed")
else:
cl.sendText(msg.to,"Blacklist s")
mc = ""
for mi_d in wait["commentBlack"]:
mc += "・" +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif msg.text in ["เปิด นาฬิกา","Clock:on","Clock on","Jam on","Jam:on"]:
if wait["clock"] == True:
cl.sendText(msg.to,"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,"done")
elif msg.text in ["ปิด นาฬิกา","Clock:off","Clock off","Jam off","Jam:off"]:
if wait["clock"] == False:
cl.sendText(msg.to,"already off")
else:
wait["clock"] = False
cl.sendText(msg.to,"done")
elif "ตั้งชื่อ: " in msg.text:
n = msg.text.replace("ตั้งชื่อ: ","")
if len(n.decode("utf-8")) > 13:
cl.sendText(msg.to,"changed")
else:
wait["cName"] = n
cl.sendText(msg.to,"Changed to:\n\n" + n)
elif msg.text in ["Up"]:
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,"Refresh to update")
else:
cl.sendText(msg.to,"Please turn on the name clock")
elif "/ " in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'id'
kata = msg.text.replace("/ ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
path = "http://chart.apis.google.com/chart?chs=480x80&cht=p3&chtt=" + result + "&chts=FFFFFF,70&chf=bg,s,000000"
urllib.urlretrieve(path, "steal.png")
tts = gTTS(text=result, lang='id')
tts.save('tts.mp3')
cl.sendImage(msg.to,"steal.png")
cl.sendText(msg.to,"DITAMPILKAN UNTUK TEXT\n" + "" + kata + "\n「SUKSES」")
cl.sendAudio(msg.to,'tts.mp3')
#========================================
elif "/ปก @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("/ปก @","")
_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:
pass
print "[Command]dp executed"
elif "Hack2mid:" in msg.text:
umid = msg.text.replace("Hack2mid:","")
contact = cl.getContact(umid)
try:
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
except:
image = "https://www.1and1.co.uk/digitalguide/fileadmin/DigitalGuide/Teaser/not-found-t.jpg"
try:
cl.sendImageWithUrl(msg.to,image)
except Exception as error:
cl.sendText(msg.to,(error))
pass
elif "/รูป" in msg.text:
if msg.toType == 2:
msg.contentType = 0
steal0 = msg.text.replace("/รูป","")
steal1 = steal0.lstrip()
steal2 = steal1.replace("@","")
steal3 = steal2.rstrip()
_name = steal3
group = cl.getGroup(msg.to)
targets = []
for g in group.members:
if _name == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Gak da orange")
else:
for target in targets:
try:
contact = cl.getContact(target)
try:
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
except:
image = "https://www.1and1.co.uk/digitalguide/fileadmin/DigitalGuide/Teaser/not-found-t.jpg"
try:
cl.sendImageWithUrl(msg.to,image)
except Exception as error:
cl.sendText(msg.to,(error))
pass
except:
cl.sendText(msg.to,"Error!")
break
else:
cl.sendText(msg.to,"Tidak bisa dilakukan di luar grup")
#===============================================
elif msg.text in ["Sp","sp","Speed"]:
cl.sendText(msg.to, "Progress.......")
start = time.time()
time.sleep(0.001)
elapsed_time = time.time() - start
cl.sendText(msg.to, "%sseconds" % (elapsed_time))
print "[Command]Speed palsu executed"
elif msg.text in ["Bot Speed"]:
ki1.sendText(msg.to, "Progress.......")
start = time.time()
time.sleep(0.001)
elapsed_time = time.time() - start
ki1.sendText(msg.to, "%sseconds" % (elapsed_time))
ki2.sendText(msg.to, "%sseconds" % (elapsed_time))
ki3.sendText(msg.to, "%sseconds" % (elapsed_time))
ki4.sendText(msg.to, "%sseconds" % (elapsed_time))
ki5.sendText(msg.to, "%sseconds" % (elapsed_time))
ki6.sendText(msg.to, "%sseconds" % (elapsed_time))
ki7.sendText(msg.to, "%sseconds" % (elapsed_time))
ki8.sendText(msg.to, "%sseconds" % (elapsed_time))
ki9.sendText(msg.to, "%sseconds" % (elapsed_time))
ki10.sendText(msg.to, "%sseconds" % (elapsed_time))
print "[Command]Speed palsu executed"
elif msg.text in ["Keybot"]:
ki.sendText(msg.to, "[SELFBOT\nBy.☬ധู้さန້ণق↔ധഖาໄฟ☬]\n\n❂͜͡☆➣ Namelock on\n❂͜͡☆➣ Namelock off\n❂͜͡☆➣ Blockinvite on\n❂͜͡☆➣ Blockinvite off\n❂͜͡☆➣ Backup on\n❂͜͡☆➣ Backup off\n\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
#========================================
elif msg.text in ["กลับร่าง","Mebb"]:
try:
cl.updateDisplayPicture(mybackup.pictureStatus)
cl.updateProfile(mybackup)
cl.sendText(msg.to, "Backup Sukses Bosqu")
except Exception as e:
cl.sendText(msg.to, str (e))
#=================================================
elif msg.text == "#mid on":
cl.sendText(msg.to, "Done..")
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
now2 = datetime.now()
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
wait2['ROM'][msg.to] = {}
print wait2
elif msg.text == "#mid off":
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
chiya = ""
else:
chiya = ""
for rom in wait2["ROM"][msg.to].items():
print rom
chiya += rom[1] + "\n"
cl.sendText(msg.to, "%s\n\n%s\nReadig point creation:\n [%s]\n" % (wait2['readMember'][msg.to],chiya,setTime[msg.to]))
else:
cl.sendText(msg.to, "Ketik Lurking dulu dudul Baru bilang result Point.")
#========================================
#-------------------Fungsi spam finish----------------------------
elif "รูปกลุ่ม" in msg.text:
if msg.from_ in admin:
group = cl.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
cl.sendImageWithUrl(msg.to,path)
elif "#Turn off bots" in msg.text:
if msg.from_ in admsa:
try:
import sys
sys.exit()
except:
pass
#-----------------------------------------------
elif msg.text in ["ลิ้ง","url"]:
if msg.toType == 2:
x = cl.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
cl.updateGroup(x)
gurl = cl.reissueGroupTicket(msg.to)
cl.sendText(msg.to,"[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]\nline://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
elif msg.text in ["Notifed on","เปิดแจ้งเตือน","M on"]:
if msg.from_ in admin:
if wait["Notifed"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Notifed On\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
wait["Notifed"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Notifed On\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
elif msg.text in ["Notifed off","ปิดแจ้งเตือน","M off"]:
if msg.from_ in admin:
if wait["Notifed"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Notifed Off\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
wait["Notifed"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Notifed Off\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
elif msg.text in ["Notifedbot on","เปิดเเจ้งเตือนบอท","Mbot on"]:
if msg.from_ in admin:
if wait["Notifedbot"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"All bot Notifed On\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
wait["Notifedbot"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"All bot Notifed On\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
elif msg.text in ["Notifedbot off","ปิดแจ้งเตือนบอท","Mbot off"]:
if msg.from_ in admin:
if wait["Notifedbot"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"All bot Notifed Off\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
wait["Notifedbot"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"All bot Notifed Off\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
cl.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนบอทเเล้ว")
#=================================================
elif "Spam " in msg.text:
if msg.from_ in admin:
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+ " ","")
tulisan = jmlh * (teks+"\n")
#Keke cantik <3
if txt[1] == "on":
if jmlh <= 10000:
for x in range(jmlh):
cl.sendText(msg.to, teks)
else:
cl.sendText(msg.to, "Out of range! ")
elif txt[1] == "off":
if jmlh <= 10000:
cl.sendText(msg.to, tulisan)
else:
cl.sendText(msg.to, "Out of range! ")
#-----------------------------------------------
elif "Mid @" in msg.text:
_name = msg.text.replace("Mid @","")
_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 msg.text in ["เปิดหมด","Phet All on","Phet all on"]:
cl.sendText(msg.to,"[SELF BOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
cl.sendText(msg.to,"Please wait......")
cl.sendText(msg.to,"Turn on all protection")
cl.sendText(msg.to,"Qr:on")
cl.sendText(msg.to,"Backup:on")
cl.sendText(msg.to,"Read:on")
cl.sendText(msg.to,"Respon:on")
cl.sendText(msg.to,"Responkick:on")
cl.sendText(msg.to,"Protect:on")
cl.sendText(msg.to,"Namelock:on")
cl.sendText(msg.to,"Blockinvite:on")
elif msg.text in ["ปิดหมด","Phet All off","Phet all off"]:
cl.sendText(msg.to,"[SELFBOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
cl.sendText(msg.to,"Please wait......")
cl.sendText(msg.to,"Turn off all protection")
cl.sendText(msg.to,"Qr:off")
cl.sendText(msg.to,"Backup:off")
cl.sendText(msg.to,"Read:off")
cl.sendText(msg.to,"Respon:off")
cl.sendText(msg.to,"Responkick:off")
cl.sendText(msg.to,"Protect:off")
cl.sendText(msg.to,"Namelock:off")
cl.sendText(msg.to,"Blockinvite:off")
cl.sendText(msg.to,"Link off")
elif msg.text in ["ทีมงาน"]:
msg.contentType = 13
cl.sendText(msg.to, "[TEAM SELFBOT]\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
cl.sendText(msg.to, "ผู้สร้าง.. SELFBOT\nBy.🔯ധู้さန້ণق↔ധഖาໄฟ🔯")
msg.contentMetadata = {'mid': 'uf0bd4970771f26a8cef66473d59bcc69'}
cl.sendMessage(msg)
cl.sendText(msg.to, "ผู้จัดการ .SELFBOT\nBy.☬ധู้さန້ণق↔ധഖาໄฟ☬")
msg.contentMetadata = {'mid': 'u6c8aab6ee167a596be2cf045ee2f90df'}
cl.sendMessage(msg)
cl.sendText(msg.to, "หวานใจ\nBy.ผู้สร้างพญาไฟ")
msg.contentMetadata = {'mid': 'u2743230861d1c637647d9ca2a8c1fc14'}
cl.sendMessage(msg)
cl.sendText(msg.to, "ประธาน:")
msg.contentMetadata = {'mid': 'u5b671f4148aa5bbec186b5b7cb295271'}
cl.sendMessage(msg)
cl.sendText(msg.to, "รองประธาน:💫 By. พยัค")
msg.contentMetadata = {'mid': 'u7988143c47d3faacf1856a72011eea93'}
cl.sendMessage(msg)
cl.sendText(msg.to, "รปภ.:SELFBOT")
msg.contentMetadata = {'mid': 'u5b671f4148aa5bbec186b5b7cb295271'}
cl.sendMessage(msg)
cl.sendText(msg.to, "ตัวเเทนสมาชิก:By.บอล")
msg.contentMetadata = {'mid': 'ueabd832a84add1392a2ff758f97b3c8e'}
cl.sendMessage(msg)
#========================================
elif "#คท" in msg.text:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.to+"',"}
cl.sendMessage(msg)
elif "บิน" in msg.text:
if msg.toType == 2:
print "Kickall ok"
_name = msg.text.replace("บิน","")
gs = ki1.getGroup(msg.to)
gs = ki2.getGroup(msg.to)
gs = ki3.getGroup(msg.to)
gs = ki4.getGroup(msg.to)
gs = ki5.getGroup(msg.to)
gs = ki6.getGroup(msg.to)
gs = ki7.getGroup(msg.to)
gs = ki8.getGroup(msg.to)
gs = ki9.getGroup(msg.to)
gs = ki10.getGroup(msg.to)
ki1.sendText(msg.to, "Hello all...😁😁 {}")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found.")
# ki.sendText(msg.to,"Not found.")
else:
for target in targets:
if not target in Bots:
try:
klist=[ki1,ki2,ki3,ki4,ki5,ki5,ki6,ki7,ki8,ki9,ki10]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
pass
# ki3.sendText(msg,to,"Nuke Finish")
# ki2.sendText(msg,to,"
elif msg.text in ["Kill"]:
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 == []:
random.choice(KAC).sendText(msg.to,"Fuck You")
return
for jj in matched_list:
try:
klist=[ki1,ki2,ki3,ki4,ki5,ki5,ki6,ki7,ki8,ki9,ki10]
kicker = random.choice(klist)
kicker.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
elif ("PK4 " in msg.text):
if msg.from_ in admin:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
ki6.kickoutFromGroup(msg.to,[target])
except:
ki6.sendText(msg.to,"Error")
elif "KK2 " in msg.text:
nk0 = msg.text.replace("KK2 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
gs.preventJoinByTicket = False
cl.updateGroup(gs)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
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:
ki2.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
ki2.leaveGroup(msg.to)
gs = cl.getGroup(msg.to)
gs.preventJoinByTicket = True
cl.updateGroup(gs)
gs.preventJoinByTicket(gs)
cl.updateGroup(gs)
elif "KK1 " in msg.text:
nk0 = msg.text.replace("KK1 ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
gs = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
gs.preventJoinByTicket = False
cl.updateGroup(gs)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
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:
ki1.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
ki1.leaveGroup(msg.to)
gs = cl.getGroup(msg.to)
gs.preventJoinByTicket = True
cl.updateGroup(gs)
gs.preventJoinByTicket(gs)
cl.updateGroup(gs)
#-----------------------------------------------------------
elif "contactjoin:" in msg.text:
try:
source_str = 'abcdefghijklmnopqrstuvwxyz1234567890@:;./_][!&%$#)(=~^|'
name = "".join([random.choice(source_str) for x in xrange(10)])
amid = msg.text.replace("contactjoin:","")
cl.sendText(msg.to,str(cl.channel.createAlbumF(msg.to,name,amid)))
except Exception as e:
try:
cl.sendText(msg.to,str(e))
except:
pass
elif ("PK2 " 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:
ki2.kickoutFromGroup(msg.to,[target])
except:
ki2.sendText(msg.to,"Error")
elif ("PK3 " 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:
ki5.kickoutFromGroup(msg.to,[target])
except:
ki5.sendText(msg.to,"Error")
elif ("PK " 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 "สั่งดำ @" in msg.text:
_name = msg.text.replace("Blacklist @","")
_kicktarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _kicktarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found")
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,"Success Boss")
except:
cl.sendText(msg.to,"error")
elif "แบน @" in msg.text:
if msg.toType == 2:
print "[BL]ok"
_name = msg.text.replace("แบน @","")
_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:
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,"Success Masuk daftar orang bejat Boss")
except:
cl.sendText(msg.to,"Error")
elif "ลบแบน @" in msg.text:
if msg.toType == 2:
print "[WL]ok"
_name = msg.text.replace("ลบแบน @","")
_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:
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,"Sudah di keluarkan dari daftar bejat Boss")
except:
cl.sendText(msg.to,"There was no blacklist user")
elif msg.text in ["Clear ban","ล้างดำ"]:
wait["blacklist"] = {}
cl.sendText(msg.to,"clear")
elif msg.text in ["Ban"]:
wait["wblacklist"] = True
cl.sendText(msg.to,"send contact to ban")
elif msg.text in ["Unban"]:
wait["dblacklist"] = True
cl.sendText(msg.to,"send contact to ban")
elif msg.text in ["Banlist","Mcheck"]:
if wait["blacklist"] == {}:
cl.sendText(msg.to,"Nothing double thumbs up")
else:
cl.sendText(msg.to,"Daftar Banlist")
mc = "[⎈]Blacklist [⎈]\n"
for mi_d in wait["blacklist"]:
mc += "[✗] " + cl.getContact(mi_d).displayName + " \n"
cl.sendText(msg.to, mc + "")
elif msg.text in ["Me ban","Cekban","Mcheck mid"]:
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)
cocoa = "[⎈]Mid Blacklist [⎈]"
for mm in matched_list:
cocoa += "\n" + mm + "\n"
cl.sendText(msg.to,cocoa + "")
#=============================================
elif msg.text in ["Simisimi on","Simisimi:on"]:
settings["simiSimi"][msg.to] = True
cl.sendText(msg.to,"Success activated simisimi")
elif msg.text in ["Simisimi off","Simisimi:off"]:
settings["simiSimi"][msg.to] = False
cl.sendText(msg.to,"Success deactive simisimi")
elif msg.text in ["เปิด อ่าน","Read on","Read:on"]:
wait['alwayRead'] = True
cl.sendText(msg.to,"เปิดอ่านข้อความอัตโนมัติ.👌")
elif msg.text in ["ปิด อ่าน","Read off","Read:off"]:
wait['alwayRead'] = False
cl.sendText(msg.to,"ปิดอ่านข้อความอัตโนมัติ.👌")
elif msg.text in ["Tag on","Autorespon:on","Respon on","Respon:on"]:
wait["detectMention"] = True
cl.sendText(msg.to,"Auto Respon ON")
elif msg.text in ["Tag off","Autorespon:off","Respon off","Respon:off"]:
wait["detectMention"] = False
cl.sendText(msg.to,"Auto Respon OFF")
elif msg.text in ["Tag1","Tag1"]:
cl.sendText(msg.to,"ข้อความแทคล่าสุดคือ\n\n" + str(wait["tag1"]))
elif msg.text in ["Tag2","Tag2"]:
cl.sendText(msg.to,"ข้อความแทคล่าสุดคือ\n\n" + str(wait["tag2"]))
elif "Tag1:" in msg.text:
wait["tag1"] = msg.text.replace("Tag1: ","")
cl.sendText(msg.to,"ข้อความแทคล่าสุดคือ")
elif "Tag2:" in msg.text:
wait["tag2"] = msg.text.replace("Tag2: ","")
cl.sendText(msg.to,"ข้อความแทคล่าสุดคือ")
elif msg.text in ["Kicktag on","Autokick:on","Responkick on","Responkick:on"]:
wait["kickMention"] = True
cl.sendText(msg.to,"Auto Kick ON")
elif msg.text in ["Kicktag off","Autokick:off","Responkick off","Responkick:off"]:
wait["kickMention"] = False
cl.sendText(msg.to,"Auto Kick OFF")
elif msg.text in ["Cancel on","cancel on"]:
if msg.from_ in admin:
if wait["Protectcancl"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Semua Undangan On")
else:
cl.sendText(msg.to,"done")
else:
wait["Protectcancl"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Semua Undangan On")
else:
cl.sendText(msg.to,"done")
elif msg.text in ["Cancel off","cancel off"]:
if msg.from_ in admin:
if wait["Protectcancl"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Semua Undangan Off")
else:
cl.sendText(msg.to,"done")
else:
wait["Protectcancl"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Cancel Semua Undangan Off")
else:
cl.sendText(msg.to,"done")
#==============================================================================#
#==============================================================================#
elif "Phackmid:" in msg.text:
saya = msg.text.replace("Phackmid:","")
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 "#Phackgid:" in msg.text:
saya = msg.text.replace("#Phackgid:","")
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","เช็คเพื่อนทั้งหมด","#เพื่อน","เพื่อนทั้งหมด","Fyall"]:
contactlist = cl.getAllContactIds()
kontak = cl.getContacts(contactlist)
num=1
msgs="═════════รายชื่อเพื่อน═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n════════รายชื่อเพื่อย════════\n\nเจำนวนเพื่อน : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif msg.text in ["เพื่อน","Memlist","Nameall"]:
kontak = cl.getGroup(msg.to)
group = kontak.members
num=1
msgs="═════════รายชื่อเพื่อน═════════-"
for ids in group:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n════════รายชื่อเพื่อน════════\n\nจำนวนเพื่อน : %i" % len(group)
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 ["Blocklist","บล็อค","Pbann"]:
blockedlist = cl.getBlockedContactIds()
kontak = cl.getContacts(blockedlist)
num=1
msgs="═══════รายชื่อ ที่บล็อค═══════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n══════รายชื่อ ที่บล็อค══════\n\nจำนวนที่บล็อค : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif msg.text in ["#Myginfoall"]:
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 ["#ไอดีกลุ่ม","Myginfogidall"]:
gruplist = cl.getGroupIdsJoined()
kontak = cl.getGroups(gruplist)
num=1
msgs="════════ไอดี กลุ่ม════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.id)
num=(num+1)
msgs+="\n════════ไอดี กลุ่ม═══════\n\nไอดีกลุ่มรวม : %i" % len(kontak)
cl.sendText(msg.to, msgs)
elif "1991258ชื่อกลุ่ม" in msg.text:
saya = msg.text.replace('1991258ชื่อกลุ่ม','')
gid = cl.getGroup(msg.to)
cl.sendText(msg.to, "[Nama Grup : ]\n" + gid.name)
elif "Gid" in msg.text:
saya = msg.text.replace('Gid','')
gid = cl.getGroup(msg.to)
cl.sendText(msg.to, "[ID Grup : ]\n" + gid.id)
elif msg.text in ["ลิสกลุ่ม","#Meginfoall"]:
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():
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 = "[SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]:\n" + str(jml) + " Members"
cnt.to = msg.to
cl.sendMessage(cnt)
elif "lurk 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,"Lurking already on\nเปิดการอ่านอัตโนมัต")
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, "เปิดการอ่านอัตโนมัต\nSet reading point:\n" + datetime.now().strftime('%H:%M:%S'))
print wait2
elif "lurk off" == msg.text.lower():
if msg.to not in wait2['readPoint']:
cl.sendText(msg.to,"Lurking already off\nปิดการอ่านอัตโนมัต")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
cl.sendText(msg.to, "ปิดการอ่านอัตโนมัต\nDelete reading point:\n" + datetime.now().strftime('%H:%M:%S'))
elif "lurkers" == msg.text.lower():
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
cl.sendText(msg.to, "Lurkers:\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 msg.text in ["เปิดอ่าน","R on","ตั้งเวลา"]:
cl.sendText(msg.to,"lurk on")
elif msg.text in ["ปิดอ่าน","R off"]:
cl.sendText(msg.to,"lurk off")
elif msg.text in ["ใครอ่าน","Ry"]:
cl.sendText(msg.to,"lurkers")
elif msg.text in ["Ry20"]:
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"llurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
cl.sendText(msg.to,"lurkers")
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","Heckmic"]:
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 "Phetmic " in msg.text:
cmd = msg.text.replace("Phetmic ","")
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 "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 msg.text in ["Sk"]:
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "100",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "10",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "9",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "7",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "6",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "4",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "3",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "110",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "101",
"STKPKGID": "1",
"STKVER": "100" }
ki1.sendMessage(msg)
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "247",
"STKPKGID": "3",
"STKVER": "100" }
ki1.sendMessage(msg)
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","Mename"]:
h = cl.getContact(mid)
cl.sendText(msg.to,"===[DisplayName]===\n" + h.displayName)
elif msg.text in ["ตัส","Mey1"]:
h = cl.getContact(mid)
cl.sendText(msg.to,"===[StatusMessage]===\n" + h.statusMessage)
elif msg.text in ["รูป","Mey2"]:
h = cl.getContact(mid)
cl.sendImageWithUrl(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["โปรวีดีโอ","Mey3"]:
h = cl.getContact(mid)
cl.sendVideoWithUrl(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["ลิ้งรูป","Mey4"]:
h = cl.getContact(mid)
cl.sendText(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["ปก","Mey5"]:
h = cl.getContact(mid)
cu = cl.channel.getCover(mid)
path = str(cu)
cl.sendImageWithUrl(msg.to, path)
elif msg.text in ["ลิ้งปก","Mey6"]:
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 "#22Getinfo" 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 "Ph4" 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 "Ph2" 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 "mh2" 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 "#ดึงรูป" in msg.text:
nk0 = msg.text.replace("#ดึงรูป","")
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,"!!..ผิดพลาด")
pass
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
elif "#pictall" in msg.text:
nk0 = msg.text.replace("#pictall","")
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,"!!..ผิดพลาด")
pass
else:
for target in targets:
try:
contact = cl.getContact(target)
cu = cl.channel.getCover(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
path = str(cu)
cl.sendImageWithUrl(msg.to, path)
except Exception as e:
raise e
elif "เชคหมด" in msg.text:
nk0 = msg.text.replace("เชคหมด","")
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,"!!..ผิดพลาด")
pass
else:
for target in targets:
try:
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\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 Exception as e:
raise e
elif "Ph3vdo @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Ph3vdo @","")
_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 "Ph3url @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Ph3url @","")
_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 "2url @" in msg.text:
print "[Command]cover executing"
_name = msg.text.replace("2url @","")
_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 "Ph2url @" in msg.text:
print "[Command]cover executing"
_name = msg.text.replace("Ph2url @","")
_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 "เจ้งเตือน" in msg.text:
group = cl.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
cl.sendImageWithUrl(msg.to,path)
elif "แปลงร่าง @" in msg.text:
print "[COPY] Ok"
_name = msg.text.replace("แปลงร่าง @","")
_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 ["Mybb"]:
try:
cl.updateDisplayPicture(backup.pictureStatus)
cl.updateProfile(backup)
cl.sendText(msg.to, "Refreshed.")
except Exception as e:
cl.sendText(msg.to, str(e))
#==========================================================#
elif "[Auto Respond]" in msg.text:
cl.sendImageWithUrl(msg.to, "http://dl.profile.line.naver.jp/0hlGvN3GXvM2hLNx8goPtMP3dyPQU8GSIgJVUpCTpiPVtiA3M2clJ-C2hia11mUn04cAJ-DWljOVBj")
elif "Fancytext: " in msg.text:
txt = msg.text.replace("Fancytext: ", "")
cl.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Tx: " in msg.text:
txt = msg.text.replace("Tx: ", "")
cl.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Bx: " in msg.text:
txt = msg.text.replace("Bx: ", "")
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
ki1.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Tx10: " in msg.text:
txt = msg.text.replace("Tx10: ", "")
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
cl.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Tr-id " in msg.text:
isi = msg.text.replace("Tr-id ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "Tr-en " in msg.text:
isi = msg.text.replace("Tr-en ","")
translator = Translator()
hasil = translator.translate(isi, dest='en')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "Tr-th " in msg.text:
isi = msg.text.replace("Tr-th ","")
translator = Translator()
hasil = translator.translate(isi, dest='th')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "Tr-jp" in msg.text:
isi = msg.text.replace("Tr-jp ","")
translator = Translator()
hasil = translator.translate(isi, dest='ja')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "Tr-ko" in msg.text:
isi = msg.text.replace("Tr-ko ","")
translator = Translator()
hasil = translator.translate(isi, dest='ko')
A = hasil.text
A = A.encode('utf-8')
cl.sendText(msg.to, A)
elif "Id@en" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'en'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO ENGLISH----\n" + "" + result + "\n------SUKSES-----")
elif "En@id" in msg.text:
bahasa_awal = 'en'
bahasa_tujuan = 'id'
kata = msg.text.replace("En@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM EN----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@jp" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ja'
kata = msg.text.replace("Id@jp ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO JP----\n" + "" + result + "\n------SUKSES-----")
elif "Jp@id" in msg.text:
bahasa_awal = 'ja'
bahasa_tujuan = 'id'
kata = msg.text.replace("Jp@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM JP----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@th" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'th'
kata = msg.text.replace("Id@th ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO TH----\n" + "" + result + "\n------SUKSES-----")
elif "Th@id" in msg.text:
bahasa_awal = 'th'
bahasa_tujuan = 'id'
kata = msg.text.replace("Th@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM TH----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@jp" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ja'
kata = msg.text.replace("Id@jp ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO JP----\n" + "" + result + "\n------SUKSES-----")
elif "Id@ar" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ar'
kata = msg.text.replace("Id@ar ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO AR----\n" + "" + result + "\n------SUKSES-----")
elif "Ar@id" in msg.text:
bahasa_awal = 'ar'
bahasa_tujuan = 'id'
kata = msg.text.replace("Ar@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM AR----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@ko" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ko'
kata = msg.text.replace("Id@ko ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO KO----\n" + "" + result + "\n------SUKSES-----")
elif "Ko@id" in msg.text:
bahasa_awal = 'ko'
bahasa_tujuan = 'id'
kata = msg.text.replace("Ko@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
cl.sendText(msg.to,"----FROM KO----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif msg.text.lower() == 'welcome':
ginfo = cl.getGroup(msg.to)
cl.sendText(msg.to,"Selamat Datang Di Grup " + str(ginfo.name))
jawaban1 = ("ยินดีต้อนรับเข้าสู่กลุ่ม " + str(ginfo.name))
cl.sendText(msg.to,"Owner Grup " + str(ginfo.name) + " :\n" + ginfo.creator.displayName )
tts = gTTS(text=jawaban1, lang='th')
tts.save('hasil.mp3')
cl.sendAudioWithUrl(msg.to,'hasil.mp3')
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.sendAudioWithUrl(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.sendAudioWithUrl(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.sendAudioWithUrl(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.sendAudioWithUrl(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.sendAudioWithUrl(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.sendAudioWithUrl(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.sendAudioWithUrl(msg.to,'tts.mp3')
elif '#dy ' in msg.text:
try:
textToSearch = (msg.text).replace('#dy ', "").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 'mp4 ' in msg.text:
try:
textToSearch = (msg.text).replace('mp4 ',"").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 "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 "/vk " in msg.text:
try:
wiki = msg.text.lower().replace("/vk ","")
wikipedia.set_lang("th")
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 "#ค้นหารูปภาพ:" in msg.text:
search = msg.text.replace("ค้นหารูปภาพ:","")
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 "#Profileig " in msg.text:
try:
instagram = msg.text.replace("#Profileig ","")
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.sendImageWithUrl(msg.to, profileIG)
cl.sendText(msg.to, str(text))
except Exception as e:
cl.sendText(msg.to, str(e))
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 in ["Time","เวลา"]:
timeNow = datetime.now()
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["วันอาทิต์", "วันจันทร์", "วันอังคาร", "วันพุธ", "วันพฤหัสบดี", "วันศุกร์", "วันเสาร์"]
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): bln = bulan[k-1]
rst = hasil + ", " + inihari.strftime('%d') + " - " + bln + " - " + inihari.strftime('%Y') + "\nเวลาขณะนี้ : [ " + inihari.strftime('%H:%M:%S') + " ]"
cl.sendText(msg.to, rst)
#========================================================#
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 in ["Pmcheck","เชคดำ","เช็คดำ"]:
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 ["Mcheckcontact","Cb"]:
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() == '1kill':
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 == []:
ki1.sendText(msg.to,"Tidak ada Daftar Blacklist")
return
for jj in matched_list:
try:
ki1.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
#==============================================#
elif msg.text in ["in on"]:
if msg.from_ in admin:
if wait["pautoJoin"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
else:
wait["pautoJoin"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"already on")
else:
cl.sendText(msg.to,"done")
elif msg.text in ["in off"]:
if msg.from_ in admin:
if wait["pautoJoin"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
else:
wait["pautoJoin"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"already off")
else:
cl.sendText(msg.to,"done")
elif "/ตัส" 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,"[name]\n" + contact.displayName + "\n[mid]\n" + contact.mid + "\n[statusmessage]\n" + contact.statusMessage + "\n[profilePicture]\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[homePicture]\n" + str(cu))
except:
cl.sendText(msg.to,"[name]\n" + contact.displayName + "\n[mid]\n" + contact.mid + "\n[statusmessage]\n" + contact.statusMessage + "\n[homePicture]\n" + str(cu))
#=============================================
elif msg.text in ["!Sp"]:
start = time.time()
cl.sendText(msg.to, "Waiting...")
elapsed_time = time.time() - start
cl.sendText(msg.to, "%sTamii Server" % (elapsed_time))
# ----------------- BAN MEMBER BY TAG 2TAG ATAU 10TAG MEMBER
elif ("Bl " in msg.text):
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
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,"Succes Banned Bos")
except:
pass
#-------------Fungsi Respon Start---------------------#
elif msg.text in ["#Cinvite"]:
if msg.from_ in admin:
wait["winvite"] = True
cl.sendText(msg.to,"send contact 😉")
elif "Gift @" in msg.text:
_name = msg.text.replace("Gift @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
msg.contentType = 2
msg.contentMetadata={'PRDID': '89131c1a-e549-4bd5-9e60-e24de0d2e252',
'PRDTYPE': 'THEME',
'MSGTPL': '10'}
msg.text = None
cl.sendMessage(msg,g)
cl.sendText(msg.to, "Done...")
elif msg.text in ["Mchecky"]:
if wait["blacklist"] == {}:
cl.sendText(msg.to,"nothing")
else:
cl.sendText(msg.to,"Blacklist user\nมีบัญชีดำของคุณอยู่กลุ่มนี้")
xname = ""
for mi_d in wait["blacklist"]:
xname = cl.getContact(mi_d).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(mm)+'}]}','EMTVER':'4'}
try:
cl.sendMessage(msg)
except Exception as error:
print error
elif msg.text in ["Name me","Men"]:
G = cl.getProfile()
X = G.displayName
cl.sendText(msg.to,X)
elif "siri " in msg.text.lower():
query = msg.text.lower().replace("siri ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'https://google-translate-proxy.herokuapp.com/api/tts'
params = {'language': 'th', 'speed': '1', 'query': query}
r = s.get(url, params=params)
mp3 = r.url
cl.sendAudioWithUrl(msg.to, mp3)
elif "siri:" in msg.text.lower():
query = msg.text.lower().replace("siri:","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'https://google-translate-proxy.herokuapp.com/api/tts'
params = {'language': 'th', 'speed': '1', 'query': query}
r = s.get(url, params=params)
mp3 = r.url
cl.sendAudioWithUrl(msg.to, mp3)
elif "siri-en " in msg.text.lower():
query = msg.text.lower().replace("siri-en ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'https://google-translate-proxy.herokuapp.com/api/tts'
params = {'language': 'en', 'speed': '1', 'query': query}
r = s.get(url, params=params)
mp3 = r.url
cl.sendAudioWithUrl(msg.to, mp3)
elif "พูด " in msg.text.lower():
query = msg.text.lower().replace("พูด ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'https://google-translate-proxy.herokuapp.com/api/tts'
params = {'language': 'th', 'speed': '1', 'query': query}
r = s.get(url, params=params)
mp3 = r.url
cl.sendAudioWithUrl(msg.to, mp3)
elif msg.text in ["คิก1","K1"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki1.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki1.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki1.updateGroup(G)
elif msg.text in ["คิก2","K2"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki2.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki2.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki2.updateGroup(G)
elif msg.text in ["คิก3","K3"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki3.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki3.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki3.updateGroup(G)
elif msg.text in ["คิก4","K4"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki4.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki4.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki4.updateGroup(G)
elif msg.text in ["คิก5","K5"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki5.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki5.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki5.updateGroup(G)
elif msg.text in ["คิก6","K6"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki6.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki6.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki6.updateGroup(G)
elif msg.text in ["คิก7","K7"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki7.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki7.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki7.updateGroup(G)
elif msg.text in ["คิก8","K8"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki8.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki8.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki8.updateGroup(G)
elif msg.text in ["คิก9","K9"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki9.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki9.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki9.updateGroup(G)
elif msg.text in ["คิก10","K10"]:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki10.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki10.updateGroup(G)
print "kickers_Ok"
G.preventJoinByTicket(G)
ki10.updateGroup(G)
elif '/w ' in msg.text.lower():
try:
wiki = msg.text.lower().replace("/w ","")
wikipedia.set_lang("th")
pesan="Wikipedia : "
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="Text Terlalu Panjang Silahkan Click link di bawah ini\n"
pesan+=wikipedia.page(wiki).url
cl.sendText(msg.to, pesan)
except Exception as e:
cl.sendText(msg.to, str(e))
elif "/go " in msg.text:
tanggal = msg.text.replace("/go ","")
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,"Tanggal Lahir : "+lahir+"\n\nUmur : "+usia+"\n\nUltah : "+ultah+"\n\nZodiak : "+zodiak)
elif "declined" in msg.text:
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
cl.leaveGroup(msg.to)
except:
pass
elif "[Auto] " in msg.text:
msg.contentType = 13
_name = msg.text.replace("[Auto] ","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
msg.contentMetadata = {'mid': g.mid}
cl.sendMessage(msg)
else:
pass
elif "☜ʕ•ﻌ•ʔ " in msg.text:
msg.contentType = 13
_name = msg.text.replace("☜ʕ•ﻌ•ʔ ","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
msg.contentMetadata = {'mid': g.mid}
cl.sendMessage(msg)
else:
pass
if op.type == 25:
msg = op.message
if msg.text.lower() in ["pheytcg fgtagg all"]:
group = cl.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
mention(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, len(nama)):
nm2 += [nama[j]]
mention(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, len(nama)):
nm3 += [nama[k]]
mention(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, len(nama)):
nm4 += [nama[l]]
mention(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, 400):
nm4 += [nama[l]]
mention(msg.to, nm4)
for h in range(401, len(nama)):
nm5 += [nama[h]]
mention(msg.to, nm5)
if jml > 500:
cl.sendText(msg.to,'Member melebihi batas.')
cnt = Message()
cnt.text = "PHET TAG DONE : " + str(jml) + " Members"
cnt.to = msg.to
cl.sendMessage(cnt)
if op.type == 26:
msg = op.message
if msg.text.lower() in ["1123"]:
group = cl.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
mention(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, len(nama)):
nm2 += [nama[j]]
mention(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, len(nama)):
nm3 += [nama[k]]
mention(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, len(nama)):
nm4 += [nama[l]]
mention(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, 400):
nm4 += [nama[l]]
mention(msg.to, nm4)
for h in range(401, len(nama)):
nm5 += [nama[h]]
mention(msg.to, nm5)
if jml > 500:
cl.sendText(msg.to,'Member melebihi batas.')
cnt = Message()
cnt.text = "PHET TAG DONE : " + str(jml) + " Members"
cnt.to = msg.to
cl.sendMessage(cnt)
elif msg.text in ["คท"]:
cl.sendText(msg.to,"😆เช็คจัง กลัวบอทหลุด ล่ะสิ😆")
elif msg.text in ["เทสบอท"]:
cl.sendText(msg.to,"SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]")
elif msg.text in [".อยู่ไหม"]:
cl.sendText(msg.to,"อยู่...")
elif msg.text in ["/อยู่ไหม"]:
cl.sendText(msg.to,"เรื่องของกู...")
elif msg.text in ["/ออนไหม"]:
cl.sendText(msg.to,"ออน")
elif msg.text in ["/ปิดป้องกัน"]:
cl.sendText(msg.to,"ปิดป้องกัน")
elif "/ตั้งเวลา" == 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,"Lurking already on\nเปิดการอ่านอัตโนมัตกรุณาพิมพ์ ➠ /อ่าน")
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, "โปรเเกรมเปิดการอ่านอัตโนมัต\nSet reading point:\n" + datetime.now().strftime('%H:%M:%S'))
print wait2
elif "/ปิดการอ่าน" == msg.text.lower():
if msg.to not in wait2['readPoint']:
cl.sendText(msg.to,"Lurking already off\nปิดการอ่านอัตโนมัต")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
cl.sendText(msg.to, "ปิดการอ่านอัตโนมัต\nDelete reading point:\n" + datetime.now().strftime('%H:%M:%S'))
elif "/อ่าน" == msg.text.lower():
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
cl.sendText(msg.to, "SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬] \n\nLurkers:\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, "กรุณาตั้งเวลาการอ่านใหม่อีกครั้งโปรดพิมพ์ ➠ /ตั้งเวลา")
elif 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)
else:
if msg.contentType == 7:
msg.contentType = 7
msg.text = None
msg.contentMetadata = {
"STKID": "6",
"STKPKGID": "1", "STKVER": "100" }
cl.sendMessage(msg)
if op.type == 26:
msg = op.message
if msg.contentType == 16:
url = msg.contentMetadata['postEndUrl']
cl.like(url[25:58], url[66:], likeType=1001)
cl.comment(url[25:58], url[66:], wait["comment1"])
ki1.like(url[25:58], url[66:], likeType=1001)
ki1.comment(url[25:58], url[66:], wait["comment1"])
ki2.like(url[25:58], url[66:], likeType=1001)
ki2.comment(url[25:58], url[66:], wait["comment1"])
ki3.like(url[25:58], url[66:], likeType=1001)
ki3.comment(url[25:58], url[66:], wait["comment1"])
ki4.like(url[25:58], url[66:], likeType=1001)
ki4.comment(url[25:58], url[66:], wait["comment1"])
ki5.like(url[25:58], url[66:], likeType=1001)
ki5.comment(url[25:58], url[66:], wait["comment1"])
ki6.like(url[25:58], url[66:], likeType=1001)
ki6.comment(url[25:58], url[66:], wait["comment1"])
ki7.like(url[25:58], url[66:], likeType=1001)
ki7.comment(url[25:58], url[66:], wait["comment1"])
ki8.like(url[25:58], url[66:], likeType=1001)
ki8.comment(url[25:58], url[66:], wait["comment1"])
ki9.like(url[25:58], url[66:], likeType=1001)
ki9.comment(url[25:58], url[66:], wait["comment1"])
ki10.like(url[25:58], url[66:], likeType=1001)
ki10.comment(url[25:58], url[66:], wait["comment1"])
print ("AUTO LIKE SELFBOT")
print ("Auto Like By.☬ധู้さန້ণق↔ധഖาໄฟ☬")
if op.type == 15:
if wait["Notifed"] == True:
if op.param2 in Bots:
return
cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n เเล้วพบใหม่นะ ")
print "MEMBER OUT GROUP"
if op.type == 17:
if wait["Notifed"] == True:
if op.param2 in Bots:
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.sendImageWithUrl(op.param1,image)
msg.contentType = 7
msg.contentMetadata={
'STKPKGID': '9662',
'STKTXT': '[]',
'STKVER': '16',
'STKID':'707'
}
cl.sendMessage(msg)
print "MEMBER HAS JOIN THE GROUP"
if op.type == 19:
if wait["Notifed"] == True:
if op.param2 in Bots:
return
cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
print "MEMBER HAS KICKOUT FROM THE GROUP"
if op.type == 15:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ki1.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n Bye~bye ")
ki2.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n Bye~bye ")
print "MEMBER OUT GROUP"
if op.type == 17:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ginfo = cl.getGroup(op.param1)
contact = cl.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendImageWithUrl(op.param1,image)
cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n[🙋ยินดีตอนรับ][By. ☬ധู้さန້ণق↔ധഖาໄฟ☬]")
print "MEMBER HAS JOIN THE GROUP"
if op.type == 19:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ki1.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
ki2.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
print "MEMBER HAS KICKOUT FROM THE GROUP"
if op.type == 15:
if wait["bcommentOn"] == True:
if op.param2 in Bots:
return
cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["bcomment"]))
print "MEMBER OUT GROUP"
if op.type == 17:
if wait["acommentOn"] == True:
if op.param2 in Bots:
return
cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["acomment"]))
print "MEMBER HAS JOIN THE GROUP"
if op.type == 19:
if wait["ccommentOn"] == True:
if op.param2 in Bots:
return
cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["ccomment"]))
print "MEMBER HAS KICKOUT FROM THE GROUP"
if op.type == 13:
if wait["Protectcancl"] == True:
if op.param2 not in Bots:
group = cl.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
random.choice(KAC).cancelGroupInvitation(op.param1, gMembMids)
if op.param3 == "1":
if op.param1 in protectname:
group = cl.getGroup(op.param1)
try:
group.name = wait["pro_name"][op.param1]
cl.updateGroup(group)
cl.sendText(op.param1, "Groupname protect now")
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except Exception as e:
print e
pass
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 a2():
now2 = datetime.now()
nowT = datetime.strftime(now2,"%M")
if nowT[14:] in ["10","20","30","40","50","00"]:
return False
else:
return True
def nameUpdate():
while True:
try:
#while a2():
#pass
if wait["clock"] == True:
now2 = datetime.now()
nowT = datetime.strftime(now2,"༺%H:%M༻")
profile = cl.getProfile()
profile.displayName = wait["cName"] + nowT
cl.updateProfile(profile)
time.sleep(600)
except:
pass
thread2 = threading.Thread(target=nameUpdate)
thread2.daemon = True
thread2.start()
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)
|
[
"[email protected]"
] | |
e2db064b4c559a481a1ab0ba635a84b59bd259e2
|
3e19d4f20060e9818ad129a0813ee758eb4b99c6
|
/conftest.py
|
1b0f10a63a7f6eddd9bf25df6187cc5b35adee18
|
[
"MIT"
] |
permissive
|
ReyvanZA/bitfinex_ohlc_import
|
07bf85f4de8b0be3dc6838e188160d2b4963f284
|
6d6d548187c52bcd7e7327f411fab515c83faef1
|
refs/heads/master
| 2020-08-11T14:22:15.832186 | 2019-10-31T17:51:21 | 2019-11-11T11:33:28 | 214,579,369 | 0 | 0 |
MIT
| 2019-11-11T11:33:29 | 2019-10-12T04:48:12 | null |
UTF-8
|
Python
| false | false | 546 |
py
|
import pytest
@pytest.fixture
def symbols_fixture():
# symbols for testing
return [
"btcusd",
"ltcbtc",
"ethusd"
]
def candles_fixture():
return [[
1518272040000,
8791,
8782.1,
8795.8,
8775.8,
20.01209543
],
[
1518271980000,
8768,
8790.7,
8791,
8768,
38.41333393
],
[
1518271920000,
8757.3,
8768,
8770.6396831,
8757.3,
20.92449167
]]
|
[
"[email protected]"
] | |
9381d068197c349cb06a7e1fb6788be3e1f31f2d
|
244f5954023a1cd3afda8792a67c0efdc86894b5
|
/lab15/lab15_2.py
|
e3fe37e99c18dad70a3f06537f643fd907cad41c
|
[] |
no_license
|
RideSVEL/python-labs
|
81436fdb293bbd50950297d5c99f9466f025e1d7
|
6dc953e854536032e9cc168e9c71198a583e12a9
|
refs/heads/master
| 2023-03-08T06:18:26.276986 | 2021-02-20T09:54:08 | 2021-02-20T09:54:08 | 337,844,124 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,479 |
py
|
import csv
import plotly.graph_objs as go
from plotly.subplots import make_subplots
def csv_dict_reader(file_obj):
vacancies = []
reader = csv.DictReader(file_obj, delimiter=',')
for line in reader:
try:
vacancies.append(int(line["Salary"]))
except Exception as e:
print(e)
continue
return vacancies
if __name__ == "__main__":
with open("../lab1314/export.csv", encoding="utf-8") as f_obj:
shoto = csv_dict_reader(f_obj)
with open("../lab1314/export2.csv", encoding="utf-8") as f_obj:
shoto2 = csv_dict_reader(f_obj)
fig = make_subplots(
rows=2, cols=1,
subplot_titles=("Первая зависимость", "Вторая зависимость"))
fig.add_trace(go.Scatter(x=[i for i in range(len(shoto))], y=shoto, name="Зависимость зарплат по Java"), row=1,
col=1)
fig.add_trace(go.Scatter(x=[i for i in range(len(shoto))], y=shoto2, name="Зависимость зарплат по Java"), row=2,
col=1)
fig.update_xaxes(title_text="Номер", row=1, col=1)
fig.update_xaxes(title_text="Номер", row=2, col=1)
fig.update_yaxes(title_text="Зарплата", row=1, col=1)
fig.update_yaxes(title_text="Зарплата", row=2, col=1)
fig.update_traces(hoverinfo="all", hovertemplate="Номер: %{x}<br>Зарплата: %{y}")
fig.write_html("second_first.html")
|
[
"[email protected]"
] | |
60ab9709117a44651283b12cfa345466f72a209a
|
8ca3fcb2dba13d99a62f292401ae70ff4eeb2120
|
/RobotCode/revlib/revvy/mcu/rrrc_transport.py
|
6d80d8b493aa88b94b5706a3626bb47386e14bd2
|
[] |
no_license
|
FRC1076/FRCRevolution
|
76decd5bd5bf4e40e6d422c8750885f9be3fb258
|
75c19ff8802fc193b085eac12337fa4426d0a917
|
refs/heads/main
| 2023-02-18T02:07:26.137426 | 2021-01-03T18:01:15 | 2021-01-03T18:01:15 | 315,189,903 | 1 | 0 | null | 2020-12-31T17:35:40 | 2020-11-23T03:26:13 | null |
UTF-8
|
Python
| false | false | 9,998 |
py
|
# SPDX-License-Identifier: GPL-3.0-only
import struct
import binascii
from enum import Enum
from threading import Lock
from typing import NamedTuple
from revvy.utils.functions import retry
from revvy.utils.stopwatch import Stopwatch
crc7_table = (
0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f,
0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77,
0x19, 0x10, 0x0b, 0x02, 0x3d, 0x34, 0x2f, 0x26,
0x51, 0x58, 0x43, 0x4a, 0x75, 0x7c, 0x67, 0x6e,
0x32, 0x3b, 0x20, 0x29, 0x16, 0x1f, 0x04, 0x0d,
0x7a, 0x73, 0x68, 0x61, 0x5e, 0x57, 0x4c, 0x45,
0x2b, 0x22, 0x39, 0x30, 0x0f, 0x06, 0x1d, 0x14,
0x63, 0x6a, 0x71, 0x78, 0x47, 0x4e, 0x55, 0x5c,
0x64, 0x6d, 0x76, 0x7f, 0x40, 0x49, 0x52, 0x5b,
0x2c, 0x25, 0x3e, 0x37, 0x08, 0x01, 0x1a, 0x13,
0x7d, 0x74, 0x6f, 0x66, 0x59, 0x50, 0x4b, 0x42,
0x35, 0x3c, 0x27, 0x2e, 0x11, 0x18, 0x03, 0x0a,
0x56, 0x5f, 0x44, 0x4d, 0x72, 0x7b, 0x60, 0x69,
0x1e, 0x17, 0x0c, 0x05, 0x3a, 0x33, 0x28, 0x21,
0x4f, 0x46, 0x5d, 0x54, 0x6b, 0x62, 0x79, 0x70,
0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38,
0x41, 0x48, 0x53, 0x5a, 0x65, 0x6c, 0x77, 0x7e,
0x09, 0x00, 0x1b, 0x12, 0x2d, 0x24, 0x3f, 0x36,
0x58, 0x51, 0x4a, 0x43, 0x7c, 0x75, 0x6e, 0x67,
0x10, 0x19, 0x02, 0x0b, 0x34, 0x3d, 0x26, 0x2f,
0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c,
0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04,
0x6a, 0x63, 0x78, 0x71, 0x4e, 0x47, 0x5c, 0x55,
0x22, 0x2b, 0x30, 0x39, 0x06, 0x0f, 0x14, 0x1d,
0x25, 0x2c, 0x37, 0x3e, 0x01, 0x08, 0x13, 0x1a,
0x6d, 0x64, 0x7f, 0x76, 0x49, 0x40, 0x5b, 0x52,
0x3c, 0x35, 0x2e, 0x27, 0x18, 0x11, 0x0a, 0x03,
0x74, 0x7d, 0x66, 0x6f, 0x50, 0x59, 0x42, 0x4b,
0x17, 0x1e, 0x05, 0x0c, 0x33, 0x3a, 0x21, 0x28,
0x5f, 0x56, 0x4d, 0x44, 0x7b, 0x72, 0x69, 0x60,
0x0e, 0x07, 0x1c, 0x15, 0x2a, 0x23, 0x38, 0x31,
0x46, 0x4f, 0x54, 0x5d, 0x62, 0x6b, 0x70, 0x79)
def crc7(data, crc=0xFF):
"""
>>> crc7(b'foobar')
16
"""
for b in data:
crc = crc7_table[b ^ ((crc << 1) & 0xFF)]
return crc
class TransportException(Exception):
pass
class RevvyTransportInterface:
def read(self, length): raise NotImplementedError()
def write(self, data): raise NotImplementedError()
class Command:
OpStart = 0
OpRestart = 1
OpGetResult = 2
OpCancel = 3
@staticmethod
def create(op, command, payload=b''):
payload_length = len(payload)
if payload_length > 255:
raise ValueError(f'Payload is too long ({payload_length} bytes, 255 allowed)')
pl = bytearray(6 + payload_length)
if payload:
pl[6:] = payload
payload_checksum = binascii.crc_hqx(pl[6:], 0xFFFF)
high_byte, low_byte = divmod(payload_checksum, 256) # get bytes of unsigned short
else:
high_byte = low_byte = 0xFF
# fill header
pl[0:5] = op, command, payload_length, low_byte, high_byte
# calculate header checksum
pl[5] = crc7(pl[0:5])
return pl
@staticmethod
def start(command, payload: bytes):
"""
>>> Command.start(2, b'')
bytearray(b'\\x00\\x02\\x00\\xff\\xffQ')
"""
return Command.create(Command.OpStart, command, payload)
@staticmethod
def get_result(command):
"""
>>> Command.get_result(2)
bytearray(b'\\x02\\x02\\x00\\xff\\xff=')
"""
return Command.create(Command.OpGetResult, command)
@staticmethod
def cancel(command):
return Command.create(Command.OpCancel, command)
class ResponseStatus(Enum):
Ok = 0
Busy = 1
Pending = 2
Error_UnknownOperation = 3
Error_InvalidOperation = 4
Error_CommandIntegrityError = 5
Error_PayloadIntegrityError = 6
Error_PayloadLengthError = 7
Error_UnknownCommand = 8
Error_CommandError = 9
Error_InternalError = 10
# errors not sent by MCU
Error_Timeout = 11
class ResponseHeader(NamedTuple):
status: ResponseStatus
payload_length: int
payload_checksum: int
raw: bytes
@staticmethod
def create(data: bytes):
try:
header_bytes = data[0:4]
if crc7(header_bytes) != data[4]:
raise ValueError('Header checksum mismatch')
status, _payload_length, _payload_checksum = struct.unpack('<BBH', header_bytes)
return ResponseHeader(status=ResponseStatus(status),
payload_length=_payload_length,
payload_checksum=_payload_checksum,
raw=header_bytes)
except IndexError as e:
raise ValueError('Header too short') from e
def validate_payload(self, payload):
return self.payload_checksum == binascii.crc_hqx(payload, 0xFFFF)
def is_same_as(self, response_header):
return self.raw == response_header
class Response(NamedTuple):
status: ResponseStatus
payload: bytes
class RevvyTransport:
_mutex = Lock() # we only have a single I2C interface
timeout = 5 # [seconds] how long the slave is allowed to respond with "busy"
def __init__(self, transport: RevvyTransportInterface):
self._transport = transport
self._stopwatch = Stopwatch()
def send_command(self, command, payload=b'') -> Response:
"""
Send a command and get the result.
This function waits for commands to finish processing, so execution time depends on the MCU.
The function detects integrity errors and retries incorrect writes and reads.
@param command:
@param payload:
@return:
"""
with self._mutex:
# create commands in advance, they can be reused in case of an error
command_start = Command.start(command, payload)
command_get_result = None
try:
# once a command gets through and a valid response is read, this loop will exit
while True: # assume that integrity error is random and not caused by implementation differences
# send command and read back status
header = self._send_command(command_start)
# wait for command execution to finish
if header.status == ResponseStatus.Pending:
# lazily create GetResult command
if not command_get_result:
command_get_result = Command.get_result(command)
header = self._send_command(command_get_result)
while header.status == ResponseStatus.Pending:
header = self._send_command(command_get_result)
# check result
# return a result even in case of an error, except when we know we have to resend
if header.status != ResponseStatus.Error_CommandIntegrityError:
response_payload = self._read_payload(header)
return Response(header.status, response_payload)
except TimeoutError:
return Response(ResponseStatus.Error_Timeout, b'')
def _read_response_header(self, retries=5) -> ResponseHeader:
"""
Read header part of response message
Header is always 5 bytes long and it contains the length of the variable payload
@param retries: How many times the read can be retried in case an error happens
@return: The header data
"""
def _read_response_header_once():
header_bytes = self._transport.read(5)
return ResponseHeader.create(header_bytes)
header = retry(_read_response_header_once, retries)
if not header:
raise BrokenPipeError('Read response header: Retry limit reached')
return header
def _read_payload(self, header: ResponseHeader, retries=5) -> bytes:
"""
Read the rest of the response
Reading always starts with the header (nondestructive) so we need to read the header and verify that
we receive the same header as before
@param header: The expected header
@param retries: How many times the read can be retried in case an error happens
@return: The payload bytes
"""
if header.payload_length == 0:
return b''
def _read_payload_once():
# read header and payload
response_bytes = self._transport.read(5 + header.payload_length)
response_header, response_payload = response_bytes[0:4], response_bytes[5:] # skip checksum byte
# make sure we read the same response data we expect
if not header.is_same_as(response_header):
raise ValueError('Read payload: Unexpected header received')
# make sure data is intact
if not header.validate_payload(response_payload):
raise ValueError('Read payload: payload contents invalid')
return response_payload
payload = retry(_read_payload_once, retries)
if not payload:
raise BrokenPipeError('Read payload: Retry limit reached')
return payload
def _send_command(self, command: bytes) -> ResponseHeader:
"""
Send a command and return the response header
This function waits for the slave MCU to finish processing the command and returns if it is done or the
timeout defined in the class header elapses.
@param command: The command bytes to send
@return: The response header
"""
self._transport.write(command)
self._stopwatch.reset()
while self._stopwatch.elapsed < self.timeout:
response = self._read_response_header()
if response.status != ResponseStatus.Busy:
return response
raise TimeoutError
|
[
"[email protected]"
] | |
39f30a152021b558142e3bade498e9422e46157c
|
2269adac5b400ea2d299bd863918d02676546731
|
/src/exercises/ex1/escape_room.py
|
3db09292ffa3cf5a3b9194af9ae0c6ed0a1f94ab
|
[] |
no_license
|
emengbenben/network-security-2019
|
2d168d0b897f4007c90a89d3e0f629f0f960ddb1
|
bc7f3ac80db7bdd491150c0eb72f9edf96249c8f
|
refs/heads/master
| 2020-04-19T08:18:58.975630 | 2019-04-17T19:58:08 | 2019-04-17T19:58:08 | 168,072,553 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 17,304 |
py
|
import random
class EscapeRoom:
door = "closed"
locked = True
hammer = False
glasses = False
glasses_wear = False
mirror = False
hairpin = False # judge hairpin visible or not
floor = False # judge whether player look floor or not
pry = False
clock = 100
chest = "locked" # three stutus: locked, unlocked and open
board = "closed" # two stutus: closed and open
stutas = "locked"
hairpin_get = False # judge whether get hairpin or not
code = 0
code_string = ""
comma_digit_list = ""
def start(self):
'''This method initializes the game'''
self.code = random.randint(0, 9999)
self.code_string = str(self.code)
while len(self.code_string) < 4:
self.code_string = '0' + self.code_string # prepend zero's (e.g., 0123)
list1 = [digit for digit in self.code_string]
list2 = list(set(list1))
list2.sort()
self.comma_digit_list = ", ".join(list2)
def command(self, command_string):
'''This command accepts the user's command within the game'''
response = "" # this is the response string
commandParts = command_string.split(" ")
command = commandParts[0]
if command == "look":
response = self.lookCommand(commandParts[1:], command_string)
elif command == "get":
response = self.getCommand(commandParts[1:], command_string)
elif command == "inventory":
response = self.inventoryCommand(commandParts[1:], command_string)
elif command == "unlock":
response = self.unlockCommand(commandParts[1:], command_string)
elif command == "open":
response = self.openCommand(commandParts[1:], command_string)
elif command == "pry":
response = self.pryCommand(commandParts[1:], command_string)
elif command == "wear":
response = self.wearCommand(commandParts[1:], command_string)
else:
response = "This is not an effective command."
self.clock = self.clock - 1 # clock-1 after a command
if(self.clock == 0):
response = response +"\nOh no! The clock starts ringing!!! After a few seconds, the room fills with a deadly gas..."
return response
def lookCommand(self, commandParts, command_string):
response = ""
if command_string == "look":
str1 = "You are in a locked room. There is only one door \n"
str2 = "and it has a numeric keypad. Above the door is a clock that reads "+str(self.clock)+ ".\n"
str3 = "Across from the door is a large mirror. Below the mirror is an old chest.\n"
str4 = "\nThe room is old and musty and the floor is creaky and warped."
response = str1+str2+str3+str4
elif commandParts[0] == "in":
if command_string == "look in chest":
if (self.hammer == False):
response = "Inside the chest you see: a hammer."
else:
response = "Inside the chest you see: ."
elif command_string == "look in board":
if (self.glasses == False):
response = "Inside the board you see: a glasses."
else:
response = "Inside the board you see: ."
else:
response = "You don't see that here."
else:
if command_string == "look door":
if (self.glasses == False):
response = "The door is strong and highly secured. The door is locked and requires a 4-digit code to open."
else:
string1 = "The door is strong and highly secured. The door is locked and requires a 4-digit code to open."
string2 = " But now you're wearing these glasses you notice something! There are smudges on the digits "
string3 = self.comma_digit_list + "."
response = string1 +string2 +string3
elif command_string == "look mirror":
self.mirror = True
if (self.hairpin_get == False):
self.hairpin = True
response = "You look in the mirror and see yourself... wait, there's a hairpin in your hair. Where did that come from?"
else:
response = "You look in the mirror and see yourself."
elif command_string == "look chest":
response = "An old chest. It looks worn, but it's still sturdy."
elif command_string == "look floor":
response = "The floor makes you nervous. It feels like it could fall in. One of the boards is loose."
self.floor = True
elif command_string == "look board":
if (self.floor == False):
response = "You don't see that here."
else:
if (self.pry == False):
response = "The board is loose, but won't come up when you pull on it. Maybe if you pried it open with something."
else:
response = "The board has been pulled open. You can look inside."
elif command_string == "look hairpin":
self.hairpin = True
if (self.mirror == False):
response = "You don't see that here."
else:
response = "You see nothing special."
elif command_string == "look hammer":
if (self.hammer == False):
response = "You don't see that here."
else:
response = "You see nothing special."
elif command_string == "look glasses":
if (self.glasses == False):
response = "You see nothing special."
else:
response = "These look like spy glasses. Maybe they reveal a clue!"
elif command_string == "look clock":
response = "You see nothing special."
else:
response = "You don't see that here."
return response
def getCommand(self, commandParts, command_string):
response = ""
if len(commandParts) > 1 and commandParts[1] == "from":
if command_string == "get hammer from chest":
if self.chest == "locked":
response = "It's not open."
else:
if (self.hammer == False):
response = "You got it."
self.hammer = True
else:
response = "You don't see that."
elif command_string == "get glasses from board":
if (self.board == "closed"):
response = "It's not open."
else:
if (self.glasses == False):
response = "You got it."
self.glasses = True
else:
response = "You don't see that."
else:
if commandParts[2] != "chest" and commandParts[2] != "board":
response = "You can't get something out of that!"
else:
response = "You don't see that."
else:
if command_string == "get hairpin":
if (self.hairpin == False):
response = "You don't see that."
else:
if (self.hairpin_get == False):
response = "You got it."
self.hairpin_get = True
else:
response = "You already have that."
elif command_string == "get board":
if (self.floor == False):
response = "You don't see that."
else:
response = "You can't get that."
elif command_string == "get door":
response = "You can't get that."
elif command_string == "get clock":
response = "You can't get that."
elif command_string == "get mirror":
response = "You can't get that."
elif command_string == "get chest":
response = "You can't get that."
elif command_string == "get floor":
response = "You can't get that."
elif command_string == "get hammer":
if (self.hammer == True):
response = "You already have that."
else:
response = "You don't see that."
elif command_string == "get glasses":
if (self.glasses == True):
response = "You already have that."
else:
response = "You don't see that."
else:
response = "You don't see that."
return response
def inventoryCommand(self, commandParts, command_string):
response = ""
if self.hairpin_get == True:
if self.hammer == True:
if self.glasses == True:
inventoryList = ["hairpin", " a hammer", " a glasses"]
else:
inventoryList = ["hairpin", " a hammer"]
else:
inventoryList = ["hairpin"]
else:
inventoryList =[]
inventoryString = ",".join(inventoryList)
string = "You are carrying a "
response = string + inventoryString +"."
return response
def unlockCommand(self, commandParts, command_string):
response = ""
if len(commandParts) == 1:
response = "with what?"
else:
if commandParts[0] == "chest":
if self.chest == "open":
response = "It's already unlocked."
else:
if commandParts[2] == "hairpin":
self.chest = "open"
response = "You hear a click! It worked!"
else:
response = "You don't have a unlocker-name"
elif commandParts[0] == "door":
if self.door == "open":
response = "It's already unlocked."
else:
if commandParts[2].isdigit() == False:
"That's not a valid code."
else:
if len(commandParts[2]) == 4:
if commandParts[2] == self.code_string:
self.door = "open"
response = "You hear a click! It worked!"
else:
response = "That's not the right code!"
else:
response = "The code must be 4 digits."
elif commandParts[0] == "hairpin":
if self.hairpin == False:
response = "You don't see that here."
else:
response = "You can't unlock that!"
elif commandParts[0] == "board":
if self.floor == False:
response = "You don't see that here."
else:
response = "You can't unlock that!"
elif commandParts[0] == "hammer":
if self.hammer == False:
response = "You don't see that here."
else:
response = "You can't unlock that!"
elif commandParts[0] == "glasses":
if self.glasses == False:
response = "You don't see that here."
else:
response = "You can't unlock that!"
elif commandParts[0] == "clock":
response = "You can't unlock that!"
elif commandParts[0] == "mirror":
response = "You can't unlock that!"
elif commandParts[0] == "floor":
response = "You can't unlock that!"
else:
response = "You don't see that here."
return response
def openCommand(self, commandParts, command_string):
response = ""
if commandParts[0] == "chest":
if self.chest == "locked":
response = "It's locked."
else:
if self.chest == "unlocked":
response = "It's already open!"
else:
response = "You open the chest."
self.chest = "unlocked"
elif commandParts[0] == "door":
if self.door == "closed":
response = "It's locked."
else:
response = "You open the door."
elif commandParts[0] == "hairpin":
if self.hairpin == False:
response = "You don't see that."
else:
response = "You can't open that!"
elif commandParts[0] == "board":
if self.floor == False:
response = "You don't see that."
else:
response = "You can't open that!"
elif commandParts[0] == "hammer":
if self.hammer == False:
response = "You don't see that."
else:
response = "You can't open that!"
elif commandParts[0] == "glasses":
if self.glasses == False:
response = "You don't see that."
else:
response = "You can't open that!"
elif commandParts[0] == "clock":
response = "You can't open that!"
elif commandParts[0] == "mirror":
response = "You can't open that!"
elif commandParts[0] == "floor":
response = "You can't open that!"
else:
response = "You don't see that."
return response
def pryCommand(self, commandParts, command_string):
response = ""
if commandParts[0] == "board":
if (self.floor == False): # board is invisble
response = "You don't see that."
else:
if self.hammer == True: # if player has hammer
if command_string == "pry board with hammer":
if self.board == "closed": # board is still closed
self.board = "open"
str1 = "You use the hammer to pry open the board. It takes some work, "
str2 = "but with some blood and sweat, you manage to get it open."
response = str1 + str2
else:
response = "It's already pried open." # board is open
else:
response = "You don't have a tool-name"
else:
response = "You don't have a hammer."
elif commandParts[0] == "hairpin":
if self.hairpin == False:
response = "You don't see that."
else:
response = "Don't be stupid! That won't work!"
elif commandParts[0] == "hammer":
if self.hammer == False:
response = "You don't see that."
else:
response = "You can't open that!"
elif commandParts[0] == "glasses":
if self.glasses == False:
response = "You don't see that."
else:
response = "You can't open that!"
elif commandParts[0] == "door":
response = "Don't be stupid! That won't work!"
elif commandParts[0] == "chest":
response = "Don't be stupid! That won't work!"
elif commandParts[0] == "clock":
response = "Don't be stupid! That won't work!"
elif commandParts[0] == "mirror":
response = "Don't be stupid! That won't work!"
elif commandParts[0] == "floor":
response = "Don't be stupid! That won't work!"
else:
response = "You don't see that."
return response
def wearCommand(self, commandParts, command_string):
response = ""
if commandParts[0] == "glasses":
if self.glasses == False:
response = "You don't have a glasses."
else:
if self.glasses_wear == False:
response = "You are now wearing the glasses."
self.glasses_wear == True
else:
response = "You're already wearing them!"
else:
response = "You don't have a object-name."
return response
def status(self):
'''Reports whether the users is "dead", "locked", or "escaped"'''
string = ""
if (self.door == "closed"):
if (self.clock > 0):
self.stutas = "locked"
else:
self.stutas = "dead"
else:
if (self.clock > 0):
self.stutas = "escaped"
else:
self.stutas = "dead"
return self.stutas
|
[
"[email protected]"
] | |
a48b2bc04a6cf0d51de8bdba04a43f510ca35a0e
|
5f2666a87071c1bc2383146a2dc8bc0d90a177cc
|
/books/urls.py
|
e366f85a260fc7ae70ab84888af3e15bbd678461
|
[] |
no_license
|
sripiranavany/Book-store-
|
f83c2d72617b1f9cff117bad471f94bbcf9c5020
|
5d901861e4456a6eac82d51f03fa4a10ad97793e
|
refs/heads/main
| 2023-05-11T20:16:11.182952 | 2021-05-29T16:15:32 | 2021-05-29T16:15:32 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 164 |
py
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="book.all"),
path('<int:id>', views.show, name="book.show")
]
|
[
"[email protected]"
] | |
115866da3b93fdf3c0843a55197fbb667c547c6b
|
6428d06cdb42ae32afa4a13bb0bbdc2fc013f402
|
/gcn/GCNNetworkV1.py
|
ea9586a9f748b8eebf5e42cc6ed6f3b9795c9c88
|
[] |
no_license
|
kason-seu/pytorchstudy
|
c46dc4723d772ec17eb95c43c94530d15c3e2021
|
b27e487bbb8203b32a87e47ba8a6c147f8f2434e
|
refs/heads/master
| 2023-02-01T08:36:00.184753 | 2020-12-13T10:31:42 | 2020-12-13T10:31:42 | 305,136,249 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,459 |
py
|
import numpy as np
from utils import load_data
import utils
seed = 2
class GCNNetwork:
def __init__(self):
self.n_x = None
self.n_y = None
self.n_h = None
self.m = None
self.W1 = None
self.W2 = None
self.X = None
self.Y =None
def layer_sizes(self, X, Y, hidden_dim) -> tuple:
"""
Arguments:
X -- input dataset of shape (input size, number of examples)
Y -- labels of shape (output size, number of examples)
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size of the output layer
"""
self.X = X
self.Y = Y
self.m = X.shape[0] #代表样本个数
self.n_x = X.shape[1] # size of input layer, 代表样本特征个数
self.n_h = hidden_dim
self.n_y = Y.shape[1] # size of output layer
return self.n_x, self.n_h, self.n_y
def initialize_parameters(self, A) -> dict:
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
params -- python dictionary containing your parameters:
W1 -- weight matrix of shape (n_h, n_x)
W2 -- weight matrix of shape (n_y, n_h)
"""
self.A = A
np.random.seed(seed)
#self.W1 = np.random.rand(self.n_x, self.n_h)
self.W1 = np.random.uniform(-np.sqrt(1./self.n_h), np.sqrt(1./self.n_h), (self.n_x, self.n_h))
#self.W2 = np.random.rand(self.n_h, self.n_y)
self.W2 = np.random.uniform(-np.sqrt(1./self.n_h), np.sqrt(1./self.n_y), (self.n_h, self.n_y))
assert (self.W1.shape == (self.n_x, self.n_h))
assert (self.W2.shape == (self.n_h, self.n_y))
parameters = {"W1": self.W1,
"W2": self.W2
}
return parameters
def foward_propagation(self, A, X, parameters) -> dict:
W1 = parameters["W1"]
W2 = parameters["W2"]
assert(A.shape[0] == self.m)
assert(X.shape[0] == self.m)
assert(W1.shape[0] == X.shape[1])
Z1 = np.dot(np.dot(A, X), W1)
OUT1 = utils.relu(Z1)
assert(A.shape[0] == OUT1.shape[0])
assert(OUT1.shape[1] == W2.shape[0])
Z2 = np.dot(np.dot(A, OUT1), W2)
OUT2 = utils.sigmod(Z2)
cache = {
"Z1":Z1,
"OUT1":OUT1,
"Z2":Z2,
"OUT2":OUT2
}
return cache
def backward_propagation(self, parameters, cache, X, Y, train_mask) -> dict:
W1 = parameters["W1"]
W2 = parameters["W2"]
OUT1 = cache["OUT1"]
OUT2 = cache["OUT2"]
OUT2[~train_mask] = Y[~train_mask]
dL_dZ2 = OUT2 - Y
dL_dW2 = np.dot(np.dot(self.A, OUT1).transpose(), dL_dZ2)
temp = np.dot(np.dot(self.A.transpose(), dL_dZ2), W2.transpose())
dL_dZ1 = temp * utils.relu_diff(OUT1)
dL_dW1 = np.dot(np.dot(self.A, X).transpose(), dL_dZ1)
grads = {
"dW1" : dL_dW1,
"dW2" : dL_dW2
}
return grads
def update_grads(self, parameters, grads, learning_rate = 1.2):
W1 = parameters["W1"]
W2 = parameters["W2"]
dW1 = grads["dW1"]
dW2 = grads["dW2"]
self.W1 = W1 - learning_rate * dW1
self.W2 = W2 - learning_rate * dW2
parameters = {
"W1" : self.W1,
"W2" : self.W2
}
return parameters
def calc_loss(self, X, Y, A, mask):
N = mask.sum()
preds = self.forward(X, A)
loss = np.sum(Y[mask] * np.log(preds[mask]))
loss = np.asscalar(-loss) / N
return loss
def compute_cost(self, OUT2, Y, TRAIN_MASK) -> float:
'''
计算损失函数
:param OUT2:
:param Y:
:return:
cost float
'''
m = TRAIN_MASK.sum()
print("m = " + str(m))
loss = np.sum(Y[TRAIN_MASK] * np.log(OUT2[TRAIN_MASK]))
loss = np.asscalar(-loss) / m
# logprobs = np.log(OUT2[TRAIN_MASK])
# cost = np.sum(-1 * np.dot(Y[TRAIN_MASK], logprobs.T))
# cost = np.squeeze(cost) # makes sure cost is the dimension we expect.
# # E.g., turns [[17]] into 17
# assert(isinstance(cost, float))
return loss
def loss_accuracy(self, OUT2, Y, TARIN_MASK):
""" Combination of calc_loss and compute_accuracy to reduce the need to forward propagate twice """
# from calc_loss
N = TARIN_MASK.sum()
loss = np.sum(Y[TARIN_MASK] * np.log(OUT2[TARIN_MASK]))
loss = np.asscalar(-loss) / N
loss = np.sum(Y[TARIN_MASK] * np.log(OUT2[TARIN_MASK]))
loss = np.asscalar(-loss) / N
# from compute_accuracy
out = OUT2
out_class = np.argmax(out[TARIN_MASK], axis=1)
expected_class = np.argmax(Y[TARIN_MASK], axis=1)
num_correct = np.sum(out_class == expected_class).astype(float)
accuracy = num_correct / expected_class.shape[0]
return loss, accuracy
def loss_accuracy_2(self, X, Y, A, mask, parameters):
""" Combination of calc_loss and compute_accuracy to reduce the need to forward propagate twice """
# from calc_loss
N = mask.sum()
preds = self.foward_propagation(A,X,parameters)["OUT2"]
loss = np.sum(Y[mask] * np.log(preds[mask]))
loss = np.asscalar(-loss) / N
# from compute_accuracy
out = preds
out_class = np.argmax(out[mask], axis=1)
expected_class = np.argmax(Y[mask], axis=1)
num_correct = np.sum(out_class == expected_class).astype(float)
accuracy = num_correct / expected_class.shape[0]
return loss, accuracy
if __name__ == '__main__' :
A = np.random.randn(5,5)
X_assess = np.random.randn(5, 2)
Y_assess = np.random.randn(5, 1)
gcn = GCNNetwork()
adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask,yy_train = load_data("cora")
gcn.layer_sizes(features, yy_train, 8)
print("The size of 样本 is: n_x = " + str(gcn.m))
print("The size of the input layer is: n_x = " + str(gcn.n_x))
print("The size of the hidden layer is: n_x = " + str(gcn.n_h))
print("The size of the output layer is: n_x = " + str(gcn.n_y))
parameters = gcn.initialize_parameters(adj)
print(parameters.get("W1").shape)
print(parameters.get("W2").shape)
for i in range(100):
cache = gcn.foward_propagation(gcn.A, gcn.X, parameters)
#print("cache 前向传播结果: " + str(cache))
# cost = gcn.compute_cost(cache['OUT2'], y_train, train_mask)
# print("cost = %f" % cost)
train_loss, train_accuracy = gcn.loss_accuracy(cache['OUT2'], y_train,train_mask)
val_loss, val_accuracy = gcn.loss_accuracy_2(gcn.X, y_val, gcn.A, val_mask, parameters)
print("Epoch:", '%04d' % (i + 1), "train_loss=", "{:.5f}".format(train_loss),
"train_acc=", "{:.5f}".format(train_accuracy), "val_loss=", "{:.5f}".format(val_loss),
"val_acc=", "{:.5f}".format(val_accuracy))
grads = gcn.backward_propagation(parameters, cache, features, y_train, train_mask)
parameters = gcn.update_grads(parameters, grads, 0.14750295365340862)
#print(parameters)
|
[
"[email protected]"
] | |
0f78e329d5c2bcd2818a520afbace07bcd5247a1
|
91b38e09f02d50c17832fb5c5887d381477483bf
|
/ligas/models.py
|
e5b6a2574ffc58ce74db5fa3ff09587d5a7ffa37
|
[] |
no_license
|
CharlesTenorio/apisuperbol
|
e13e24c03a3a312357012bf0f64e6097e0a2ec43
|
0f262d78547ba4000199f6832aa66627a7c1f164
|
refs/heads/master
| 2023-04-05T18:23:10.090622 | 2021-03-11T23:24:19 | 2021-03-11T23:24:19 | 335,382,790 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 485 |
py
|
from django.db import models
class Liga(models.Model):
id = models.PositiveIntegerField(primary_key=True)
nome= models.CharField(max_length=80)
cc=models.CharField(max_length=2)
has_leaguetable=models.IntegerField(),
has_toplist=models.IntegerField()
def __str__(self):
return self.nome
class Meta:
db_table = 'liga'
managed = True
verbose_name = 'Liga'
verbose_name_plural = 'Ligas'
# Create your models here.
|
[
"[email protected]"
] | |
fbb34322a5265ba6ed348bdfb50d79c29c8505b3
|
d08cd5ae98dee9b0171f574b99cf28422e4c2022
|
/sentences.py
|
d2033e1e3c1737421042c38364dcc9558b18fb7a
|
[
"BSD-3-Clause"
] |
permissive
|
xhu4/sentences
|
c3363370d840755edcd78f1474d9a364dffec2b3
|
7e9014682bf5dc3034eb608cf9a3b0496e15a9a6
|
refs/heads/master
| 2020-03-26T22:33:45.037557 | 2018-12-27T22:30:08 | 2018-12-27T22:30:08 | 145,469,322 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,682 |
py
|
# coding: utf-8
from __future__ import print_function
from timeit import default_timer as timer
from collections import defaultdict
import itertools as it
import argparse
def count_len(list_sentences):
"""
Create a dictionary based on list_sentences, with key = n and value = set
of all sentences with n words.
INPUT: list_sentences a list of sentences
OUTPUT: dict_set_sentences a dictionary as described above
"""
dict_set_sentences = defaultdict(set)
for sentence in list_sentences:
dict_set_sentences[len(sentence.split())].add(sentence)
return dict_set_sentences
def to_tuple(set_sentences):
"""
Change each sentence to tuple of words.
INPUT: set_sentences a set of sentences
OUTPUT: set_tuples a set of corresponding tuples
"""
result = set()
for sentence in set_sentences:
result.add(tuple(sentence.split()))
return result
def amam(set_tuples, nwords):
"""
Given a set of sentences in the form of word tuples, remove all 'duplicate'
tuples. One tuple is duplicate with another if they contain a same nwords
subtuple.
INPUT: set_tuples a set of tuples with same length
nwords length of subtuple to determine 'duplicativeness'
OUTPUT: None
"""
if set_tuples == set():
return None
if nwords <= 0:
x = set_tuples.pop()
set_tuples.clear()
set_tuples.add(x)
return None
s = set()
news = set()
to_remove = set()
for t in set_tuples:
for st in it.combinations(t, nwords):
if st in s:
to_remove.add(t)
news.clear()
break
news.add(st)
s.update(news)
news.clear()
set_tuples -= to_remove
return None
def form_subdict(set_tuples, nwords):
"""
Given a set of tuples, for each tuple, generate subtuple with length
nwords. Return a dictionary. Each key is a possible subtuple and the
corresponding value is a list of all original tuples that contain subtuple.
"""
d = defaultdict(list)
for t in set_tuples:
for st in it.combinations(t, nwords):
d[st].append(t)
return d
def form_subset(set_tuples, nwords):
"""
Given a set of tuples, form a set of all possible subtuples with length
nwords.
"""
subset = set()
for tpl in set_tuples:
subset.update(set(it.combinations(tpl, nwords)))
return subset
def ambn_new(longer_set, shorter_set, nwords):
"""
Given a set of longer tuples (longer_set) and a set of shorter tuples
(shorter_set). Delete all tuples in shorter_set which contains at least one
nwords-subtuple that also is a subtuple of a sentence of longer_set.
"""
if shorter_set == set() or nwords <= 0:
shorter_set.clear()
return None
to_remove = set()
ls = form_subset(longer_set, nwords)
for tpl in shorter_set:
for subtpl in it.combinations(tpl, nwords):
if subtpl in ls:
to_remove.add(tpl)
break
shorter_set -= to_remove
return None
def ambn_legacy(longer_set, shorter_set, nwords):
"""
Given a set of longer tuples (longer_set) and a set of shorter tuples
(shorter_set). Delete all tuples in shorter_set which contains at least one
nwords-subtuple that also is a subtuple of a sentence of longer_set.
"""
if shorter_set == set() or nwords <= 0:
shorter_set.clear()
return None
sd = form_subdict(shorter_set, nwords)
for longer_tuple in longer_set:
for sub_longer_string in it.combinations(longer_tuple, nwords):
if sub_longer_string in sd:
for shorter_tuple in sd[sub_longer_string]:
shorter_set.discard(shorter_tuple)
return None
# Use ambn_new instead of ambn_legacy
ambn = ambn_new
def amb(longer_set, shorter_set, nwords):
"""
Given a set of longer tuples (longer_set) and a set of shorter tuples
(shorter_set). Delete all tuples in shorter_set which is a subtuple of a
sentence of longer_set.
"""
if shorter_set == set() or nwords <= 0 or longer_set is shorter_set:
return None
for longer_tuple in longer_set:
for sub_longer_tuple in it.combinations(longer_tuple, nwords):
shorter_set.discard(sub_longer_tuple)
return None
def remove_dist_1(dict_set_tuple_words):
"""
Not used.
Given a dictionary of set of word tuples with key being length of each
tuple. Filter out distance 1 tuples.
"""
ls = sorted(dict_set_tuple_words.keys(), reverse=True)
for l in ls:
for t in dict_set_tuple_words[l]:
dict_set_tuple_words[l-1] -= set(it.combinations(t, l-1))
return None
def remove_dist_n(dict_set_sentences, n, outfile=None):
"""
Given a dictionary (result of count_len), filter out distance n sentences.
Write result to outfile if provided. Return number of lines in result.
"""
nout = 0
if(n % 2 == 0):
k = divmod(n, 2)[0]
j = k-1
else:
k = divmod(n-1, 2)[0]
j = k
# sk = sorted(dict_set_sentences.keys(), reverse=True)
max_n_words = max(dict_set_sentences.keys())
dict_set_tuple_words = defaultdict(set)
for l in range(max_n_words, max_n_words-n, -1):
dict_set_tuple_words[l] = to_tuple(dict_set_sentences[l])
for l in range(max_n_words, 0, -1):
dict_set_tuple_words[l-n] = to_tuple(dict_set_sentences[l-n])
ls = dict_set_tuple_words[l]
if ls != set():
amam(dict_set_tuple_words[l], l-k)
amb(ls, dict_set_tuple_words[l-n], l-n)
amb(ls, dict_set_tuple_words[l-n+1], l-n+1)
for i in range(1, k):
ambn(ls, dict_set_tuple_words[l-2*i], l-k-i)
for i in range(1, j+1):
ambn(ls, dict_set_tuple_words[l-2*i+1], l-j-i)
nout += len(dict_set_tuple_words[l])
if outfile is not None:
for tw in dict_set_tuple_words[l]:
outfile.write(' '.join(tw)+'\n')
del dict_set_tuple_words[l]
del dict_set_sentences[l]
return nout
def main(infile, outfile, distance):
tic = timer()
lines = infile.readlines()
nin = len(lines)
print(nin, "input lines.")
if distance == 0:
lines = set(lines)
nout = len(lines)
if outfile is not None:
for line in lines:
outfile.write(line)
else:
dict_set_tuple_words = count_len(lines)
nout = remove_dist_n(dict_set_tuple_words, distance, outfile)
dur = timer() - tic
print(nout, "output lines.")
print("Wallclock time: {}seconds\n".format(dur))
return (nin, nout, dur)
def get_num_lines(file_name):
with open(file_name, 'r') as F:
return len(F.readlines())
# parse input arguments
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Solve Big Sentences Problem.')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
help='input file')
parser.add_argument('-d', '--dist', nargs='?', type=int, default=0,
metavar='K', help='Distance k, default: 0')
parser.add_argument('-o', '--outfile', nargs='?', metavar='filename',
type=argparse.FileType('w'),
help=('Output filename. No output file will be '
'generated if not provided.'))
args = parser.parse_args()
main(args.infile, args.outfile, args.dist)
|
[
"[email protected]"
] | |
3d0a4c8bd3561d4e8736d49b4ffafb57123215b3
|
947d4102433b136ac65e6bbebd28ca51c53d1f5f
|
/ansible/roles/test/files/acstests/acs_base_test.py
|
b77680006bd90e7d5a7505850b531ff7d5426cf2
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
SW-CSA/sonic-mgmt
|
eac574040a20cea724208a442f7492f840dd1ec3
|
d50a683dc3ab0206e1fef9230c136b4c19b084f1
|
refs/heads/201811
| 2023-09-01T13:14:29.166752 | 2019-03-21T08:08:43 | 2019-03-21T08:08:43 | 142,762,730 | 2 | 5 |
NOASSERTION
| 2019-11-05T06:55:46 | 2018-07-29T13:21:25 |
Python
|
UTF-8
|
Python
| false | false | 1,190 |
py
|
"""
Base classes for test cases
Tests will usually inherit from one of these classes to have the controller
and/or dataplane automatically set up.
"""
import ptf
from ptf.base_tests import BaseTest
from ptf import config
import ptf.testutils as testutils
################################################################
#
# Thrift interface base tests
#
################################################################
class ACSDataplaneTest(BaseTest):
def setUp(self):
BaseTest.setUp(self)
self.test_params = testutils.test_params_get()
print "You specified the following test-params when invoking ptf:"
print self.test_params
# shows how to use a filter on all our tests
testutils.add_filter(testutils.not_ipv6_filter)
self.dataplane = ptf.dataplane_instance
self.dataplane.flush()
if config["log_dir"] != None:
filename = os.path.join(config["log_dir"], str(self)) + ".pcap"
self.dataplane.start_pcap(filename)
def tearDown(self):
if config["log_dir"] != None:
self.dataplane.stop_pcap()
testutils.reset_filters()
BaseTest.tearDown(self)
|
[
"[email protected]"
] | |
190dda0548865aa9ca670c1e154a5fcb36617a03
|
9feacae54b852982e791699131a5dced342fd134
|
/CodeReview/ch2/remove_dups.py
|
c86d7e4fa8310f3f4f10607b49ffb97ecfd429aa
|
[] |
no_license
|
hoyeongkwak/workspace
|
bd89f981e73f4aff2eb4a7d8c914925968651af3
|
c70d8dcd18a401af04296f71f02335ac3048240f
|
refs/heads/master
| 2023-06-23T01:54:13.608849 | 2021-07-23T13:48:22 | 2021-07-23T13:48:22 | 276,769,601 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 878 |
py
|
from LinkedList import LinkedList
def remove_dups(ll):
if ll.head is None:
return
current = ll.head
seen = set([current.value])
while current.next:
if current.next.value in seen:
current.next = current.next.next
else:
seen.add(current.next.value)
current = current.next
return ll
def remove_dups_followup(ll):
if ll.head is None:
return
current = ll.head
while current:
runner = current
while runner.next:
if runner.next.value == current.value:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
return ll.head
ll = LinkedList()
ll.generate(100, 0, 9)
print(ll)
remove_dups(ll)
print(ll)
ll.generate(100, 0, 9)
print(ll)
remove_dups_followup(ll)
print(ll)
|
[
"[email protected]"
] | |
00f65ca762f76f54444ea65692ecde4774dbdecc
|
d2c88caf05eed0c16db0f592bc876845232e1370
|
/tccli/services/cr/__init__.py
|
5c384eca0cc18a816ea88260a5faa51d5439a8be
|
[
"Apache-2.0"
] |
permissive
|
jaschadub/tencentcloud-cli
|
f3549a2eea93a596b3ff50abf674ff56f708a3fc
|
70f47d3c847b4c6197789853c73a50105abd0d35
|
refs/heads/master
| 2023-09-01T11:25:53.278666 | 2022-11-10T00:11:41 | 2022-11-10T00:11:41 | 179,168,651 | 0 | 0 |
Apache-2.0
| 2022-11-11T06:35:51 | 2019-04-02T22:32:21 |
Python
|
UTF-8
|
Python
| false | false | 83 |
py
|
# -*- coding: utf-8 -*-
from tccli.services.cr.cr_client import action_caller
|
[
"[email protected]"
] | |
7ed290f433d9a0eed89b2e3be392eeb589ccaf5f
|
97f68c7e547d36c70fd5492d0a999a9dea1a6792
|
/api/views/cmdb/history.py
|
e0029a52f63c34347404e7bd80106924a2c51adf
|
[
"MIT"
] |
permissive
|
jimmy201602/cmdb
|
cce437ca684c02a35a043ffc1b4dcc7331128387
|
4d52a72bdb42fb8ce58973910f4915daf435c01f
|
refs/heads/master
| 2021-03-19T14:02:53.366894 | 2019-08-28T13:50:08 | 2019-08-28T13:50:08 | 205,183,046 | 1 | 0 |
MIT
| 2019-08-29T14:31:23 | 2019-08-29T14:31:23 | null |
UTF-8
|
Python
| false | false | 2,054 |
py
|
# -*- coding:utf-8 -*-
import datetime
from flask import abort
from flask import request
from api.lib.cmdb.history import AttributeHistoryManger
from api.lib.utils import get_page
from api.lib.utils import get_page_size
from api.resource import APIView
class RecordView(APIView):
url_prefix = "/history/records"
def get(self):
page = get_page(request.values.get("page", 1))
page_size = get_page_size(request.values.get("page_size"))
_start = request.values.get("start")
_end = request.values.get("end")
username = request.values.get("username", "")
start, end = None, None
if _start:
try:
start = datetime.datetime.strptime(_start, '%Y-%m-%d %H:%M:%S')
except ValueError:
abort(400, 'incorrect start date time')
if _end:
try:
end = datetime.datetime.strptime(_end, '%Y-%m-%d %H:%M:%S')
except ValueError:
abort(400, 'incorrect end date time')
numfound, total, res = AttributeHistoryManger.get_records(start, end, username, page, page_size)
return self.jsonify(numfound=numfound,
records=res,
page=page,
total=total,
start=_start,
end=_end,
username=username)
class CIHistoryView(APIView):
url_prefix = "/history/ci/<int:ci_id>"
def get(self, ci_id):
result = AttributeHistoryManger.get_by_ci_id(ci_id)
return self.jsonify(result)
class RecordDetailView(APIView):
url_prefix = "/history/records/<int:record_id>"
def get(self, record_id):
username, timestamp, attr_dict, rel_dict = AttributeHistoryManger.get_record_detail(record_id)
return self.jsonify(username=username,
timestamp=timestamp,
attr_history=attr_dict,
rel_history=rel_dict)
|
[
"[email protected]"
] | |
a21e57c2bcdd545f6e90c3f5eb811263beb9a0a9
|
70c7ff22e5eca801f56bc25541cd894cee840864
|
/eventex/subscriptions/admin.py
|
34d51fc89dade74112afdd3400e966a07708fbb4
|
[] |
no_license
|
rogeriofonseca/eventex
|
54edfe346242c9d187c1a9f6bbf1700d254cc434
|
b1b0435a0da03bdf5d46aa98a00fda037239e2c8
|
refs/heads/master
| 2020-12-05T11:14:57.073368 | 2017-02-07T02:39:12 | 2017-02-07T02:39:12 | 66,811,851 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,065 |
py
|
from django.contrib import admin
from django.utils.timezone import now
from eventex.subscriptions.models import Subscription
class SubscriptionModelAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'phone', 'cpf', 'created_at',
'subscribed_today', 'paid')
date_hierarchy = 'created_at'
search_fields = ('name', 'email', 'phone', 'cpf', 'created_at')
list_filter = ('paid', 'created_at')
actions = ['mark_as_paid']
def subscribed_today(self, obj):
return obj.created_at == now().date()
subscribed_today.short_description = 'inscrito hoje?'
subscribed_today.boolean = True
def mark_as_paid(self, request, queryset):
count = queryset.update(paid=True)
if count == 1:
msg = '{} inscrição foi marcada como paga.'
else:
msg = '{} inscrições foram marcadas como pagas.'
self.message_user(request, msg.format(count))
mark_as_paid.short_description = 'Marcar como pago'
admin.site.register(Subscription, SubscriptionModelAdmin)
|
[
"[email protected]"
] | |
3107dbe3bafdd15431f25770a3c8691696fc20bd
|
cdd9649499cd2aa7dcaaf6e699a6f460df56fc03
|
/products/extra_utilities.py
|
8747d9762b5b7bcb29e201399a6c7166f516e012
|
[] |
no_license
|
maxibesso11/django-shop-v2.1
|
2d29a299cae118ffeaaa36da6b4be6d093301697
|
af83f7ea7e871db42c4bddbf34d6806b9648bd92
|
refs/heads/master
| 2022-12-16T16:52:32.087230 | 2020-09-16T18:03:38 | 2020-09-16T18:03:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 252 |
py
|
def get_range(list):
y = -1
list_final = []
url_list = []
for x in list:
y+=1
list_final.append(y)
for x in list_final:
url_list.append({"id":x,"url":list[x]["url"]})
return url_list
|
[
"[email protected]"
] | |
6085667ce991868716dea4c4d42778e766fb8ca4
|
37753c621d76336ecca839caa8864ff17fc9f1c3
|
/Array/Largest_element_in_an_array.py
|
5650862e3e08f9111d17fe6554250617896c5698
|
[] |
no_license
|
NidhiSaluja12/GeeksForGeeks
|
08b8c84d789c5ccd365c39d2f5403e4dbe1bcb26
|
0f8d6e271fbffb0c970043f19fa8b107d49fb879
|
refs/heads/main
| 2023-08-17T11:08:34.849744 | 2021-10-02T18:16:20 | 2021-10-02T18:16:20 | 386,713,653 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,113 |
py
|
'''
Given an array A[] of size n. The task is to find the largest element in it.
Example 1:
Input:
n = 5
A[] = {1, 8, 7, 56, 90}
Output:
90
Explanation:
The largest element of given array is 90.
Example 2:
Input:
n = 7
A[] = {1, 2, 0, 3, 2, 4, 5}
Output:
5
Explanation:
The largest element of given array is 5.
Your Task:
You don't need to read input or print anything. Your task is to complete the function largest() which takes the array A[] and its size n as inputs and returns the maximum element in the array.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= n<= 103
0 <= A[i] <= 103
Array may contain duplicate elements.
'''
# User function Template for python3
def largest(arr, n):
arr.sort()
largest_element = arr[n - 1]
return largest_element
# {
# Driver Code Starts
# Initial Template for Python 3
def main():
T = int(input())
while (T > 0):
n = int(input())
a = [int(x) for x in input().strip().split()]
print(largest(a, n))
T -= 1
if __name__ == "__main__":
main()
# } Driver Code Ends
|
[
"[email protected]"
] | |
f02037b69640ebce69ea028aff378e524d13a6e1
|
484f2b6ed2a51a78978a4b6450f97a3cbefcd087
|
/group/api.py
|
34820ed4e921bf24ad6291684117c8be6a49f01f
|
[] |
no_license
|
ivan371/technotrack-web2-spring-2017
|
31d0a937f1b6342bd70432cbebd37bb68c1dd8df
|
92e9fd9040984eef66b6bab45bb4d6918e178d41
|
refs/heads/master
| 2021-01-11T14:27:04.717314 | 2017-05-22T18:55:22 | 2017-05-22T18:55:22 | 81,424,353 | 0 | 0 | null | 2017-02-09T07:54:27 | 2017-02-09T07:54:27 | null |
UTF-8
|
Python
| false | false | 3,347 |
py
|
from group.models import Groupp, GroupUser, PostGroup
from rest_framework import serializers, viewsets, permissions
from application.api import router
from django.shortcuts import get_object_or_404
from core.api import UserSerializer
from django.db.models import Q
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj == request.user
class PostGroupSerializer(serializers.ModelSerializer):
author = UserSerializer(read_only=True)
comment_count = serializers.ReadOnlyField()
like_count = serializers.ReadOnlyField()
short_content = serializers.ReadOnlyField()
class Meta:
model = PostGroup
fields = ('id',
'title',
'content',
'author',
'short_content',
'comment_count',
'like_count',
)
class PostGroupViewSet(viewsets.ModelViewSet):
queryset = PostGroup.objects.all()
serializer_class = PostGroupSerializer
permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly)
def perform_create(self, serializer):
if 'group' in self.request.query_params:
serializer.save(author=self.request.user, group_id=self.request.query_params['group'])
def get_queryset(self):
queryset = super(PostGroupViewSet, self).get_queryset()
if 'group' in self.request.query_params:
queryset = queryset.filter(group=self.request.query_params['group']).order_by('-id')
return queryset
class GroupUserSerializer(serializers.ModelSerializer):
author = UserSerializer()
class Meta:
model = GroupUser
fields = ('author', 'id',)
class GroupUserViewSet(viewsets.ModelViewSet):
queryset = GroupUser.objects.all()
serializer_class = GroupUserSerializer
def perform_create(self, serializer):
if 'group' in self.request.query_params:
chat = Group.objects.get(id = self.request.query_params['group'])
serializer.save(group=group)
def get_queryset(self):
queryset = super(GroupUserViewSet, self).get_queryset()
if 'group' in self.request.query_params:
queryset = queryset.filter(group=self.request.query_params['group'])
return queryset
class GroupSerializer(serializers.ModelSerializer):
groupuser_set = GroupUserSerializer(many=True, read_only=True)
author = UserSerializer(read_only=True)
class Meta:
model = Groupp
fields = ('name', 'groupuser_set', 'id', 'author')
class GroupViewSet(viewsets.ModelViewSet):
queryset = Groupp.objects.all()
serializer_class = GroupSerializer
permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly)
def perform_create(self, serializer):
serializer.save(author=self.request.user)
def get_queryset(self):
queryset = super(GroupViewSet, self).get_queryset()
return queryset.filter(Q(groupuser__author=self.request.user) | Q(author=self.request.user)).distinct().order_by('id')
router.register(r'groups', GroupViewSet)
router.register(r'postgroup', PostGroupViewSet)
router.register(r'groupuser', GroupUserViewSet)
|
[
"[email protected]"
] | |
0a1c792fba067f7ebbb87291e1536e055e5adcc0
|
a5e06360397a51a499974c24b587e39ef98b12cb
|
/2爬虫/7、json数据解析.py
|
02ffe08dd4434d9c374b2c16021bc319485edc60
|
[] |
no_license
|
songjiabin/PyDemo
|
3c89b03f009a6f72813099e61c1a9e2d5d16fb87
|
afc2d98521b2d158ef2b54cf887502a3b1568aec
|
refs/heads/master
| 2022-10-29T00:18:31.887522 | 2018-09-12T16:23:09 | 2018-09-12T16:23:09 | 142,775,346 | 0 | 1 | null | 2022-10-22T18:33:14 | 2018-07-29T16:06:41 |
Python
|
UTF-8
|
Python
| false | false | 1,426 |
py
|
import json
jsonStr = '{"result":[["卫衣女春2018","8.092529385849389"],["卫衣上衣春 春秋","8.022499133719828"],["卫衣 秋 女","7.963854696462119"],["卫衣2017女秋","8.033525396543094"],["卫衣不带帽子女","8.036049751550866"],["卫衣外套宽松女","8.036109676892297"],["卫衣女长袖宽松上衣","8.016274388878704"],["卫衣女春秋不收边","8.056971186377892"],["卫衣女长袖 秋薄","8.048634073251334"],["卫衣女2018 新","8.064379456712274"]]}'
# 将json格式转为 python数据类型对象
jsonData = json.loads(jsonStr)
print(jsonData)
# 类型 类型是 dict 字典
print(type(jsonData))
result = jsonData["result"]
print(result)
# 将字典格式的转为json字符串
jsonData2 = {
"result": [["卫衣女春2018", "8.092529385849389"], ["卫衣上衣春 春秋", "8.022499133719828"], ["卫衣 秋 女", "7.963854696462119"],
["卫衣2017女秋", "8.033525396543094"], ["卫衣不带帽子女", "8.036049751550866"], ["卫衣外套宽松女", "8.036109676892297"],
["卫衣女长袖宽松上衣", "8.016274388878704"], ["卫衣女春秋不收边", "8.056971186377892"], ["卫衣女长袖 秋薄", "8.048634073251334"],
["卫衣女2018 新", "8.064379456712274"]]}
# 字典格式
print(type(jsonData2))
# 将字典格式的数据转为了 str格式的
jsonStr2 = json.dumps(jsonData2)
print(jsonStr2)
print(type(jsonStr2))
|
[
"[email protected]"
] | |
5790747bf3bb59cf374317ac2044970705d035fb
|
3213373f90f10c60667c26a56d30a9202e1b9ae3
|
/language/orqa/predict/orqa_eval.py
|
1fe260eb6edd190f0e5df545f0ad78f7fc8a06b0
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
Mistobaan/language
|
59a481b3ff6a7c7beada2361aef7173fbfd355a4
|
394675a831ae45ea434abb50655e7975c68a7121
|
refs/heads/master
| 2022-11-29T14:10:37.590205 | 2020-08-13T22:28:13 | 2020-08-13T22:31:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,448 |
py
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""ORQA evaluation."""
import json
import os
from absl import flags
from language.orqa.models import orqa_model
from language.orqa.utils import eval_utils
import six
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
flags.DEFINE_string("model_dir", None, "Model directory.")
flags.DEFINE_string("dataset_path", None, "Data path.")
def main(_):
predictor = orqa_model.get_predictor(FLAGS.model_dir)
example_count = 0
correct_count = 0
predictions_path = os.path.join(FLAGS.model_dir, "predictions.jsonl")
with tf.io.gfile.GFile(predictions_path, "w") as predictions_file:
with tf.io.gfile.GFile(FLAGS.dataset_path) as dataset_file:
for line in dataset_file:
example = json.loads(line)
question = example["question"]
answers = example["answer"]
predictions = predictor(question)
predicted_answer = six.ensure_text(
predictions["answer"], errors="ignore")
is_correct = eval_utils.is_correct(
answers=[six.ensure_text(a) for a in answers],
prediction=predicted_answer,
is_regex=False)
predictions_file.write(
json.dumps(
dict(
question=question,
prediction=predicted_answer,
predicted_context=six.ensure_text(
predictions["orig_block"], errors="ignore"),
correct=is_correct,
answer=answers)))
predictions_file.write("\n")
correct_count += int(is_correct)
example_count += 1
tf.logging.info("Accuracy: %.4f (%d/%d)",
correct_count/float(example_count),
correct_count,
example_count)
if __name__ == "__main__":
tf.disable_v2_behavior()
tf.app.run()
|
[
"[email protected]"
] | |
fd5c1bace80b13e13c1a052dd0dcd6ce9afea215
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_340/ch4_2020_03_23_19_22_41_022512.py
|
4f38805b970b740b4a241620cdc59197c4c64017
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 174 |
py
|
def idade(x):
x=int(input('digite sua idade'))
return idade
if (idade=<11):
print('crianca')
if (12<=idade<=17):
print('adolescente')
if (idade>=18):
print ('adulto')
|
[
"[email protected]"
] | |
ed6a9ed22ef18d86ebcb7492dceb5f636c891769
|
10d615680114a31a3611ae03f86b7d0b756243cb
|
/dataScienceFinancialProjectExtractTickers.py
|
90596f2fbdc4c02d1775cd32397ab217b4505f4c
|
[] |
no_license
|
AdrienKamdem/DataScience
|
3aa8ddbb064cb82e753154bbc62ca0483fbb4ee3
|
350ca9ae08b72809877f8535d8a0177da4b96272
|
refs/heads/main
| 2023-08-22T09:25:19.266670 | 2021-10-03T09:30:21 | 2021-10-03T09:30:21 | 412,636,613 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 12,470 |
py
|
import json
import requests
import csv
import time
class tickersFinancialCrawler:
def __init__ (self):
self.session = requests.Session()
self.tickersListNames = []
self.dictTickersDetailsList = []
self.final_tickers_dict_list = []
def _go_tickers(self,url):
tickersRequest = requests.get(url)
#assert tickersRequest.status_code == 200
#time.sleep(12)
return tickersRequest
def _get_tickers(self,tickersRequest):
dictTickers = json.loads(tickersRequest.text)
return dictTickers
def _go_ticker_details(self,i):
tickerDetailsRequest = requests.get("https://api.polygon.io/v1/meta/symbols/"+str(i)+"/company?&apiKey=fXeNsEuF5_RYIgNgFae7LsdpGSz_jAxn").text
#assert tickerDetailsRequest.status_code == 200
#time.sleep(12)
return tickerDetailsRequest
def _get_ticker_details(self,tickerDetailsRequest):
dictTickersDetails = json.loads(tickerDetailsRequest)
return dictTickersDetails
def _get_next_cursor(self,ticker_next_request):
print(ticker_next_request.status_code) # status code la requete = 401 => OK
if ticker_next_request.status_code == 200:
next_tickers_result = json.loads(ticker_next_request.text)
tickers = next_tickers_result["results"]
return tickers
else:
return None
def _go_stock_financials_details(self,companyTicker):
stockFinancialsRequest = requests.get("https://api.polygon.io/v2/reference/financials/"+str(companyTicker)+"?limit=3&type=T&apiKey=fXeNsEuF5_RYIgNgFae7LsdpGSz_jAxn")
#assert stockFinancialsRequest.status_code == 200
#time.sleep(12)
return stockFinancialsRequest
def _get_stock_financials_details(self,stockFinancialsRequest):
dictstockFinancials = json.loads(stockFinancialsRequest.text)
return dictstockFinancials
def _go_aggregates_details(self,companyTicker):
url = "https://api.polygon.io/v2/aggs/ticker/"+str(companyTicker)+"/range/1/week/2020-08-19/2021-08-19?adjusted=true&sort=asc&limit=120&apiKey=fXeNsEuF5_RYIgNgFae7LsdpGSz_jAxn"
aggreagatesRequests = requests.get(url)
#assert aggreagatesRequests.status_code == 200
#time.sleep(12)
print(url)
return aggreagatesRequests
def _get_aggregates_details(self,aggreagatesRequests):
dictAggregates = json.loads(aggreagatesRequests.text) # sous la forme {.... results:{ {v:..}, {v:..}, {v:..} }}
return dictAggregates
def _import_features_into_csv(self,final_tickers_dict_list):
with open("C:\\Users\\CYTech Student\\AppData\\Local\\Programs\\Python\\Python39\\Scripts\\tickersInformation.csv",'w', encoding='utf-8') as tickerInfo:
featuresNames = ["Id","ticker","name","market","locale","Active", "currency_name", "cik", "composite_figi", "share_class_figi", "last_updated_utc",
'logo', 'listdate', 'bloomberg', 'figi', 'lei', 'sic', 'country', 'industry', 'sector', 'marketcap', 'employees', 'phone', 'ceo', 'url', 'description', 'exchange', 'name', 'symbol', 'exchangeSymbol', 'hq_address', 'hq_state', 'hq_country', 'type', 'updated']
writer = csv.DictWriter(tickerInfo, fieldnames=featuresNames)
writer.writeheader()
print(len(final_tickers_dict_list)) #taille de 1000
print(final_tickers_dict_list)
for ticker in final_tickers_dict_list:
writer.writerow({'Id': ticker.get("Id"),'ticker' : ticker.get('tickerName'),'name': ticker.get('name'),'market': ticker.get('market'),'locale': ticker.get('locale'),'Active': ticker.get('Active'),'currency_name': ticker.get('currency_name'), 'cik': ticker.get('cik'), 'composite_figi': ticker.get('composite_figi'), 'share_class_figi': ticker.get('share_class_figi') , 'last_updated_utc': ticker.get('last_updated_utc'),
'logo': ticker.get("logo"), 'listdate': ticker.get("listdate"), 'bloomberg' :ticker.get("bloomberg"), 'figi' :ticker.get("fig"), 'lei' :ticker.get("lei"), 'sic' :ticker.get("si"), 'country' :ticker.get("country"), 'industry' :ticker.get("industry"), 'sector' :ticker.get("secto"), 'marketcap' :ticker.get("marketca"), 'employees' :ticker.get("employee"), 'phone' :ticker.get("phone"), 'ceo' :ticker.get("ce"), 'url' :ticker.get("ur"), 'description' :ticker.get("description"), 'exchange' :ticker.get("exchange"), 'name' :ticker.get("name"), 'symbol' :ticker.get("symbol"), 'exchangeSymbol' :ticker.get("exchangeSymbol"), 'hq_address' :ticker.get("hq_address"), 'hq_state' :ticker.get("hq_state"), 'hq_country' :ticker.get("hq_country"), 'type' :ticker.get("type"), 'updated' :ticker.get("update")})
def execute(self,financialCrawler):
counter = 0
firstUrl = "https://api.polygon.io/v3/reference/tickers?active=true&sort=ticker&order=asc&limit=1000&apiKey=fXeNsEuF5_RYIgNgFae7LsdpGSz_jAxn"
ticker_request = financialCrawler._go_tickers(firstUrl)
tickers_result = financialCrawler._get_tickers(ticker_request)
tickers = tickers_result["results"]
for ticker in tickers: # remplissage du ticker dict pour la premiere page
print(counter)
ticker_dict = {}
print(ticker)
ticker_dict.update(Id= counter ,tickerName=ticker.get('ticker'),name = ticker.get('name'), market=ticker.get('market'), locale = ticker.get('locale'), Active = ticker.get('active'), currency_name = ticker.get('currency_name'), cik = ticker.get('cik'), composite_figi = ticker.get('composite_figi'), share_class_figi = ticker.get('share_class_figi') , last_updated_utc = ticker.get('last_updated_utc'))
tickerDetailsRequest = financialCrawler._go_ticker_details(ticker.get('ticker'))
dictTickerDetails = financialCrawler._get_ticker_details(tickerDetailsRequest)
ticker_dict.update( logo = dictTickerDetails.get("logo"), listdate = dictTickerDetails.get("listdate"), bloomberg = dictTickerDetails.get("bloomberg"), fig = dictTickerDetails.get("figi"), lei = dictTickerDetails.get("lei"), si = dictTickerDetails.get("sic"), country = dictTickerDetails.get("country"), industry = dictTickerDetails.get("industry"), secto = dictTickerDetails.get("lsector"), marketca = dictTickerDetails.get("marketcap"), employee = dictTickerDetails.get("employees"), phone = dictTickerDetails.get("phone"), ce = dictTickerDetails.get("ceo"), ur = dictTickerDetails.get("url"), description = dictTickerDetails.get("description"), exchange = dictTickerDetails.get("exchange"), name = dictTickerDetails.get("name"), symbol = dictTickerDetails.get("symbol"), exchangeSymbol = dictTickerDetails.get("exchangeSymbol"), hq_address = dictTickerDetails.get("hq_adress"), hq_state = dictTickerDetails.get("hq_state"), hq_country = dictTickerDetails.get("hq_country"), type = dictTickerDetails.get("type"), update = dictTickerDetails.get("updated"))
counter=counter+1
self.final_tickers_dict_list.append(ticker_dict)
""" if counter == 2:
break """
next_url = tickers_result["next_url"]
#print(next_url) #OK verification de l'url pour voir si ma requete est fonctionnelle ou pas
if requests.get(next_url).status_code == 200:
ticker_next_request = financialCrawler._go_tickers(next_url)
tickers_next = financialCrawler._get_next_cursor(ticker_next_request)
if tickers_next != None:
_has_next_page = True
print("Ticker is different of 'None'")
for ticker in tickers: # remplissage du ticker dict pour la premiere page
print(counter)
ticker_dict = {}
print(ticker)
ticker_dict.update(Id= counter ,tickerName=ticker.get('ticker'),name = ticker.get('name'), market=ticker.get('market'), locale = ticker.get('locale'), Active = ticker.get('active'), currency_name = ticker.get('currency_name'), cik = ticker.get('cik'), composite_figi = ticker.get('composite_figi'), share_class_figi = ticker.get('share_class_figi') , last_updated_utc = ticker.get('last_updated_utc'))
tickerDetailsRequest = financialCrawler._go_ticker_details(ticker.get('ticker'))
dictTickerDetails = financialCrawler._get_ticker_details(tickerDetailsRequest)
ticker_dict.update( logo = dictTickerDetails.get("logo"), listdate = dictTickerDetails.get("listdate"), bloomberg = dictTickerDetails.get("bloomberg"), fig = dictTickerDetails.get("figi"), lei = dictTickerDetails.get("lei"), si = dictTickerDetails.get("sic"), country = dictTickerDetails.get("country"), industry = dictTickerDetails.get("industry"), secto = dictTickerDetails.get("lsector"), marketca = dictTickerDetails.get("marketcap"), employee = dictTickerDetails.get("employees"), phone = dictTickerDetails.get("phone"), ce = dictTickerDetails.get("ceo"), ur = dictTickerDetails.get("url"), description = dictTickerDetails.get("description"), exchange = dictTickerDetails.get("exchange"), name = dictTickerDetails.get("name"), symbol = dictTickerDetails.get("symbol"), exchangeSymbol = dictTickerDetails.get("exchangeSymbol"), hq_address = dictTickerDetails.get("hq_adress"), hq_state = dictTickerDetails.get("hq_state"), hq_country = dictTickerDetails.get("hq_country"), type = dictTickerDetails.get("type"), update = dictTickerDetails.get("updated"))
counter=counter+1
self.final_tickers_dict_list.append(ticker_dict)
else:
_has_next_page = False
print("Ticker is equal to 'None'")
counter = 3 # pour connaitre le nombre de page prise
while _has_next_page == True:
print("I am in "+str(counter)+"next_url")
tickers_next = financialCrawler._get_next_cursor(ticker_next_request)
for ticker in tickers: # remplissage du ticker dict pour la premiere page
print(counter)
ticker_dict = {}
print(ticker)
ticker_dict.update(Id= counter ,tickerName=ticker.get('ticker'),name = ticker.get('name'), market=ticker.get('market'), locale = ticker.get('locale'), Active = ticker.get('active'), currency_name = ticker.get('currency_name'), cik = ticker.get('cik'), composite_figi = ticker.get('composite_figi'), share_class_figi = ticker.get('share_class_figi') , last_updated_utc = ticker.get('last_updated_utc'))
tickerDetailsRequest = financialCrawler._go_ticker_details(ticker.get('ticker'))
dictTickerDetails = financialCrawler._get_ticker_details(tickerDetailsRequest)
ticker_dict.update( logo = dictTickerDetails.get("logo"), listdate = dictTickerDetails.get("listdate"), bloomberg = dictTickerDetails.get("bloomberg"), fig = dictTickerDetails.get("figi"), lei = dictTickerDetails.get("lei"), si = dictTickerDetails.get("sic"), country = dictTickerDetails.get("country"), industry = dictTickerDetails.get("industry"), secto = dictTickerDetails.get("lsector"), marketca = dictTickerDetails.get("marketcap"), employee = dictTickerDetails.get("employees"), phone = dictTickerDetails.get("phone"), ce = dictTickerDetails.get("ceo"), ur = dictTickerDetails.get("url"), description = dictTickerDetails.get("description"), exchange = dictTickerDetails.get("exchange"), name = dictTickerDetails.get("name"), symbol = dictTickerDetails.get("symbol"), exchangeSymbol = dictTickerDetails.get("exchangeSymbol"), hq_address = dictTickerDetails.get("hq_adress"), hq_state = dictTickerDetails.get("hq_state"), hq_country = dictTickerDetails.get("hq_country"), type = dictTickerDetails.get("type"), update = dictTickerDetails.get("updated"))
counter=counter+1
self.final_tickers_dict_list.append(ticker_dict)
next_url = tickers_result["next_url"]
ticker_next_request = requests.get(next_url)
else:
pass
final_tickers_dict_list = self.final_tickers_dict_list
financialCrawler._import_features_into_csv(final_tickers_dict_list)
def main():
financialCrawler = tickersFinancialCrawler()
financialCrawler.execute(financialCrawler)
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
8e93033e3fda24c0d02373689cd2ffdcb8f11934
|
f06ffc869fddaa351a1b8e1bc2f4eadd82a022cf
|
/2013-milgram-project-new/make_gowalla_us_states.py
|
0f1eda9742ce4b6c845a3db7834cc072e79bcb70
|
[] |
no_license
|
thornb/FoFSimulation
|
dd5de09e6be3984174aaad52127bff81c1d6f42b
|
ed7e13dff6e08af7e519791fbbb17c6a2ecef937
|
refs/heads/master
| 2021-01-21T13:08:30.650244 | 2016-05-18T18:50:58 | 2016-05-18T18:50:58 | 55,800,780 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 561 |
py
|
import cPickle
locdata = cPickle.load(open('data/gowalla_users_locationmap.pck','rb'))
udata = cPickle.load(open('data/gowalla_users_locations.pck','rb'))
states_data = {}
mapcount = 0
for uid,latlong in udata.items():
if latlong not in locdata.keys():
continue
mapcount = mapcount+1
state = locdata[latlong]
if state not in states_data.keys():
states_data[state] = set()
states_data[state].add(uid)
cPickle.dump(states_data,open('data/gowalla_us_states.pck','wb'))
print "Succesfully added",mapcount,"of",len(udata),"users"
|
[
"[email protected]"
] | |
3943484a0d61c50b4405bc497457b811c4b22f96
|
8adead984d1e2fd4f36ae4088a0363597fbca8a3
|
/venv/lib/python3.7/site-packages/gevent/testing/patched_tests_setup.py
|
3fdef75043869db42b012f8ad15407c4d116d9e0
|
[] |
no_license
|
ravisjoshi/python_snippets
|
2590650c673763d46c16c9f9b8908997530070d6
|
f37ed822b5863a5a11b09550dd32a73d68e7070b
|
refs/heads/master
| 2022-11-05T03:48:10.842858 | 2020-06-14T09:19:46 | 2020-06-14T09:19:46 | 256,961,137 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 59,511 |
py
|
# pylint:disable=missing-docstring,invalid-name,too-many-lines
from __future__ import print_function, absolute_import, division
import collections
import contextlib
import functools
import sys
import os
# At least on 3.6+, importing platform
# imports subprocess, which imports selectors. That
# can expose issues with monkey patching. We don't need it
# though.
# import platform
import re
from .sysinfo import RUNNING_ON_APPVEYOR as APPVEYOR
from .sysinfo import RUNNING_ON_TRAVIS as TRAVIS
from .sysinfo import RESOLVER_NOT_SYSTEM as ARES
from .sysinfo import RUN_COVERAGE
from .sysinfo import PYPY
from .sysinfo import PYPY3
from .sysinfo import PY3
from .sysinfo import PY2
from .sysinfo import PY35
from .sysinfo import PY36
from .sysinfo import PY37
from .sysinfo import PY38
from .sysinfo import WIN
from .sysinfo import OSX
from .sysinfo import LIBUV
from .sysinfo import CFFI_BACKEND
from . import flaky
CPYTHON = not PYPY
# By default, test cases are expected to switch and emit warnings if there was none
# If a test is found in this list, it's expected not to switch.
no_switch_tests = '''test_patched_select.SelectTestCase.test_error_conditions
test_patched_ftplib.*.test_all_errors
test_patched_ftplib.*.test_getwelcome
test_patched_ftplib.*.test_sanitize
test_patched_ftplib.*.test_set_pasv
#test_patched_ftplib.TestIPv6Environment.test_af
test_patched_socket.TestExceptions.testExceptionTree
test_patched_socket.Urllib2FileobjectTest.testClose
test_patched_socket.TestLinuxAbstractNamespace.testLinuxAbstractNamespace
test_patched_socket.TestLinuxAbstractNamespace.testMaxName
test_patched_socket.TestLinuxAbstractNamespace.testNameOverflow
test_patched_socket.FileObjectInterruptedTestCase.*
test_patched_urllib.*
test_patched_asyncore.HelperFunctionTests.*
test_patched_httplib.BasicTest.*
test_patched_httplib.HTTPSTimeoutTest.test_attributes
test_patched_httplib.HeaderTests.*
test_patched_httplib.OfflineTest.*
test_patched_httplib.HTTPSTimeoutTest.test_host_port
test_patched_httplib.SourceAddressTest.testHTTPSConnectionSourceAddress
test_patched_select.SelectTestCase.test_error_conditions
test_patched_smtplib.NonConnectingTests.*
test_patched_urllib2net.OtherNetworkTests.*
test_patched_wsgiref.*
test_patched_subprocess.HelperFunctionTests.*
'''
ignore_switch_tests = '''
test_patched_socket.GeneralModuleTests.*
test_patched_httpservers.BaseHTTPRequestHandlerTestCase.*
test_patched_queue.*
test_patched_signal.SiginterruptTest.*
test_patched_urllib2.*
test_patched_ssl.*
test_patched_signal.BasicSignalTests.*
test_patched_threading_local.*
test_patched_threading.*
'''
def make_re(tests):
tests = [x.strip().replace(r'\.', r'\\.').replace('*', '.*?')
for x in tests.split('\n') if x.strip()]
return re.compile('^%s$' % '|'.join(tests))
no_switch_tests = make_re(no_switch_tests)
ignore_switch_tests = make_re(ignore_switch_tests)
def get_switch_expected(fullname):
"""
>>> get_switch_expected('test_patched_select.SelectTestCase.test_error_conditions')
False
>>> get_switch_expected('test_patched_socket.GeneralModuleTests.testCrucialConstants')
False
>>> get_switch_expected('test_patched_socket.SomeOtherTest.testHello')
True
>>> get_switch_expected("test_patched_httplib.BasicTest.test_bad_status_repr")
False
"""
# certain pylint versions mistype the globals as
# str, not re.
# pylint:disable=no-member
if ignore_switch_tests.match(fullname) is not None:
return None
if no_switch_tests.match(fullname) is not None:
return False
return True
disabled_tests = [
# The server side takes awhile to shut down
'test_httplib.HTTPSTest.test_local_bad_hostname',
# These were previously 3.5+ issues (same as above)
# but have been backported.
'test_httplib.HTTPSTest.test_local_good_hostname',
'test_httplib.HTTPSTest.test_local_unknown_cert',
'test_threading.ThreadTests.test_PyThreadState_SetAsyncExc',
# uses some internal C API of threads not available when threads are emulated with greenlets
'test_threading.ThreadTests.test_join_nondaemon_on_shutdown',
# asserts that repr(sleep) is '<built-in function sleep>'
'test_urllib2net.TimeoutTest.test_ftp_no_timeout',
'test_urllib2net.TimeoutTest.test_ftp_timeout',
'test_urllib2net.TimeoutTest.test_http_no_timeout',
'test_urllib2net.TimeoutTest.test_http_timeout',
# accesses _sock.gettimeout() which is always in non-blocking mode
'test_urllib2net.OtherNetworkTests.test_ftp',
# too slow
'test_urllib2net.OtherNetworkTests.test_urlwithfrag',
# fails dues to some changes on python.org
'test_urllib2net.OtherNetworkTests.test_sites_no_connection_close',
# flaky
'test_socket.UDPTimeoutTest.testUDPTimeout',
# has a bug which makes it fail with error: (107, 'Transport endpoint is not connected')
# (it creates a TCP socket, not UDP)
'test_socket.GeneralModuleTests.testRefCountGetNameInfo',
# fails with "socket.getnameinfo loses a reference" while the reference is only "lost"
# because it is referenced by the traceback - any Python function would lose a reference like that.
# the original getnameinfo does not "lose" it because it's in C.
'test_socket.NetworkConnectionNoServer.test_create_connection_timeout',
# replaces socket.socket with MockSocket and then calls create_connection.
# this unfortunately does not work with monkey patching, because gevent.socket.create_connection
# is bound to gevent.socket.socket and updating socket.socket does not affect it.
# this issues also manifests itself when not monkey patching DNS: http://code.google.com/p/gevent/issues/detail?id=54
# create_connection still uses gevent.socket.getaddrinfo while it should be using socket.getaddrinfo
'test_asyncore.BaseTestAPI.test_handle_expt',
# sends some OOB data and expect it to be detected as such; gevent.select.select does not support that
# This one likes to check its own filename, but we rewrite
# the file to a temp location during patching.
'test_asyncore.HelperFunctionTests.test_compact_traceback',
# expects time.sleep() to return prematurely in case of a signal;
# gevent.sleep() is better than that and does not get interrupted
# (unless signal handler raises an error)
'test_signal.WakeupSignalTests.test_wakeup_fd_early',
# expects select.select() to raise select.error(EINTR'interrupted
# system call') gevent.select.select() does not get interrupted
# (unless signal handler raises an error) maybe it should?
'test_signal.WakeupSignalTests.test_wakeup_fd_during',
'test_signal.SiginterruptTest.test_without_siginterrupt',
'test_signal.SiginterruptTest.test_siginterrupt_on',
# these rely on os.read raising EINTR which never happens with gevent.os.read
'test_subprocess.ProcessTestCase.test_leak_fast_process_del_killed',
'test_subprocess.ProcessTestCase.test_zombie_fast_process_del',
# relies on subprocess._active which we don't use
# Very slow, tries to open lots and lots of subprocess and files,
# tends to timeout on CI.
'test_subprocess.ProcessTestCase.test_no_leaking',
# This test is also very slow, and has been timing out on Travis
# since November of 2016 on Python 3, but now also seen on Python 2/Pypy.
'test_subprocess.ProcessTestCase.test_leaking_fds_on_error',
# Added between 3.6.0 and 3.6.3, uses _testcapi and internals
# of the subprocess module. Backported to Python 2.7.16.
'test_subprocess.POSIXProcessTestCase.test_stopped',
'test_ssl.ThreadedTests.test_default_ciphers',
'test_ssl.ThreadedTests.test_empty_cert',
'test_ssl.ThreadedTests.test_malformed_cert',
'test_ssl.ThreadedTests.test_malformed_key',
'test_ssl.NetworkedTests.test_non_blocking_connect_ex',
# XXX needs investigating
'test_ssl.NetworkedTests.test_algorithms',
# The host this wants to use, sha256.tbs-internet.com, is not resolvable
# right now (2015-10-10), and we need to get Windows wheels
# This started timing out randomly on Travis in oct/nov 2018. It appears
# to be something with random number generation taking too long.
'test_ssl.BasicSocketTests.test_random_fork',
# Relies on the repr of objects (Py3)
'test_ssl.BasicSocketTests.test_dealloc_warn',
'test_urllib2.HandlerTests.test_cookie_redirect',
# this uses cookielib which we don't care about
'test_thread.ThreadRunningTests.test__count',
'test_thread.TestForkInThread.test_forkinthread',
# XXX needs investigating
'test_subprocess.POSIXProcessTestCase.test_preexec_errpipe_does_not_double_close_pipes',
# Does not exist in the test suite until 2.7.4+. Subclasses Popen, and overrides
# _execute_child. But our version has a different parameter list than the
# version that comes with PyPy/CPython, so fails with a TypeError.
# This one crashes the interpreter if it has a bug parsing the
# invalid data.
'test_ssl.BasicSocketTests.test_parse_cert_CVE_2019_5010',
# We had to copy in a newer version of the test file for SSL fixes
# and this doesn't work reliably on all versions.
'test_httplib.HeaderTests.test_headers_debuglevel',
# These depend on the exact error message produced by the interpreter
# when too many arguments are passed to functions. We can't match
# the exact signatures (because Python 2 doesn't support the syntax)
'test_context.ContextTest.test_context_new_1',
'test_context.ContextTest.test_context_var_new_1',
]
if 'thread' in os.getenv('GEVENT_FILE', ''):
disabled_tests += [
'test_subprocess.ProcessTestCase.test_double_close_on_error'
# Fails with "OSError: 9 invalid file descriptor"; expect GC/lifetime issues
]
if PY2 and PYPY:
disabled_tests += [
# These appear to hang or take a long time for some reason?
# Likely a hostname/binding issue or failure to properly close/gc sockets.
'test_httpservers.BaseHTTPServerTestCase.test_head_via_send_error',
'test_httpservers.BaseHTTPServerTestCase.test_head_keep_alive',
'test_httpservers.BaseHTTPServerTestCase.test_send_blank',
'test_httpservers.BaseHTTPServerTestCase.test_send_error',
'test_httpservers.BaseHTTPServerTestCase.test_command',
'test_httpservers.BaseHTTPServerTestCase.test_handler',
'test_httpservers.CGIHTTPServerTestcase.test_post',
'test_httpservers.CGIHTTPServerTestCase.test_query_with_continuous_slashes',
'test_httpservers.CGIHTTPServerTestCase.test_query_with_multiple_question_mark',
'test_httpservers.CGIHTTPServerTestCase.test_os_environ_is_not_altered',
# This one sometimes results on connection refused
'test_urllib2_localnet.TestUrlopen.test_info',
# Sometimes hangs
'test_ssl.ThreadedTests.test_socketserver',
# We had to update 'CERTFILE' to continue working, but
# this test hasn't been updated yet (the CPython tests
# are also too new to run on PyPy).
'test_ssl.BasicSocketTests.test_parse_cert',
]
if LIBUV:
# epoll appears to work with these just fine in some cases;
# kqueue (at least on OS X, the only tested kqueue system)
# never does (failing with abort())
# (epoll on Raspbian 8.0/Debian Jessie/Linux 4.1.20 works;
# on a VirtualBox image of Ubuntu 15.10/Linux 4.2.0 both tests fail;
# Travis CI Ubuntu 12.04 precise/Linux 3.13 causes one of these tests to hang forever)
# XXX: Retry this with libuv 1.12+
disabled_tests += [
# A 2.7 test. Tries to fork, and libuv cannot fork
'test_signal.InterProcessSignalTests.test_main',
# Likewise, a forking problem
'test_signal.SiginterruptTest.test_siginterrupt_off',
]
if PY2:
if TRAVIS:
if CPYTHON:
disabled_tests += [
# This appears to crash the process, for some reason,
# but only on CPython 2.7.14 on Travis. Cannot reproduce in
# 2.7.14 on macOS or 2.7.12 in local Ubuntu 16.04
'test_subprocess.POSIXProcessTestCase.test_close_fd_0',
'test_subprocess.POSIXProcessTestCase.test_close_fds_0_1',
'test_subprocess.POSIXProcessTestCase.test_close_fds_0_2',
]
if PYPY:
disabled_tests += [
# This seems to crash the interpreter. I cannot reproduce
# on macOS or local Linux VM.
# See https://travis-ci.org/gevent/gevent/jobs/348661604#L709
'test_smtplib.TooLongLineTests.testLineTooLong',
]
if ARES:
disabled_tests += [
# This can timeout with a socket timeout in ssl.wrap_socket(c)
# on Travis. I can't reproduce locally.
'test_ssl.ThreadedTests.test_handshake_timeout',
]
if PY3:
disabled_tests += [
# This test wants to pass an arbitrary fileno
# to a socket and do things with it. libuv doesn't like this,
# it raises EPERM. It is disabled on windows already.
# It depends on whether we had a fd already open and multiplexed with
'test_socket.GeneralModuleTests.test_unknown_socket_family_repr',
# And yes, there's a typo in some versions.
'test_socket.GeneralModuleTests.test_uknown_socket_family_repr',
]
if PY37:
disabled_tests += [
# This test sometimes fails at line 358. It's apparently
# extremely sensitive to timing.
'test_selectors.PollSelectorTestCase.test_timeout',
]
if OSX:
disabled_tests += [
# XXX: Starting when we upgraded from libuv 1.18.0
# to 1.19.2, this sometimes (usually) started having
# a series of calls ('select.poll(0)', 'select.poll(-1)')
# take longer than the allowed 0.5 seconds. Debugging showed that
# it was the second call that took longer, for no apparent reason.
# There doesn't seem to be a change in the source code to libuv that
# would affect this.
# XXX-XXX: This actually disables too many tests :(
'test_selectors.PollSelectorTestCase.test_timeout',
]
if RUN_COVERAGE:
disabled_tests += [
# Starting with #1145 this test (actually
# TestTLS_FTPClassMixin) becomes sensitive to timings
# under coverage.
'test_ftplib.TestFTPClass.test_storlines',
]
if sys.platform.startswith('linux'):
disabled_tests += [
# crashes with EPERM, which aborts the epoll loop, even
# though it was allowed in in the first place.
'test_asyncore.FileWrapperTest.test_dispatcher',
]
if WIN and PY2:
# From PyPy2-v5.9.0 and CPython 2.7.14, using its version of tests,
# which do work on darwin (and possibly linux?)
# I can't produce them in a local VM running Windows 10
# and the same pypy version.
disabled_tests += [
# These, which use asyncore, fail with
# 'NoneType is not iterable' on 'conn, addr = self.accept()'
# That returns None when the underlying socket raises
# EWOULDBLOCK, which it will do because it's set to non-blocking
# both by gevent and by libuv (at the level below python's knowledge)
# I can *usually* reproduce these locally; it seems to be some sort
# of race condition.
'test_ftplib.TestFTPClass.test_acct',
'test_ftplib.TestFTPClass.test_all_errors',
'test_ftplib.TestFTPClass.test_cwd',
'test_ftplib.TestFTPClass.test_delete',
'test_ftplib.TestFTPClass.test_dir',
'test_ftplib.TestFTPClass.test_exceptions',
'test_ftplib.TestFTPClass.test_getwelcome',
'test_ftplib.TestFTPClass.test_line_too_long',
'test_ftplib.TestFTPClass.test_login',
'test_ftplib.TestFTPClass.test_makepasv',
'test_ftplib.TestFTPClass.test_mkd',
'test_ftplib.TestFTPClass.test_nlst',
'test_ftplib.TestFTPClass.test_pwd',
'test_ftplib.TestFTPClass.test_quit',
'test_ftplib.TestFTPClass.test_makepasv',
'test_ftplib.TestFTPClass.test_rename',
'test_ftplib.TestFTPClass.test_retrbinary',
'test_ftplib.TestFTPClass.test_retrbinary_rest',
'test_ftplib.TestFTPClass.test_retrlines',
'test_ftplib.TestFTPClass.test_retrlines_too_long',
'test_ftplib.TestFTPClass.test_rmd',
'test_ftplib.TestFTPClass.test_sanitize',
'test_ftplib.TestFTPClass.test_set_pasv',
'test_ftplib.TestFTPClass.test_size',
'test_ftplib.TestFTPClass.test_storbinary',
'test_ftplib.TestFTPClass.test_storbinary_rest',
'test_ftplib.TestFTPClass.test_storlines',
'test_ftplib.TestFTPClass.test_storlines_too_long',
'test_ftplib.TestFTPClass.test_voidcmd',
'test_ftplib.TestTLS_FTPClass.test_data_connection',
'test_ftplib.TestTLS_FTPClass.test_control_connection',
'test_ftplib.TestTLS_FTPClass.test_context',
'test_ftplib.TestTLS_FTPClass.test_check_hostname',
'test_ftplib.TestTLS_FTPClass.test_auth_ssl',
'test_ftplib.TestTLS_FTPClass.test_auth_issued_twice',
# This one times out, but it's still a non-blocking socket
'test_ftplib.TestFTPClass.test_makeport',
# A timeout, possibly because of the way we handle interrupts?
'test_socketserver.SocketServerTest.test_InterruptedServerSelectCall',
'test_socketserver.SocketServerTest.test_InterruptServerSelectCall',
# times out with something about threading?
# The apparent hang is just after the print of "waiting for server"
'test_socketserver.SocketServerTest.test_ThreadingTCPServer',
'test_socketserver.SocketServerTest.test_ThreadingUDPServer',
'test_socketserver.SocketServerTest.test_TCPServer',
'test_socketserver.SocketServerTest.test_UDPServer',
# This one might be like 'test_urllib2_localnet.TestUrlopen.test_https_with_cafile'?
# XXX: Look at newer pypy and verify our usage of drop/reuse matches
# theirs.
'test_httpservers.BaseHTTPServerTestCase.test_command',
'test_httpservers.BaseHTTPServerTestCase.test_handler',
'test_httpservers.BaseHTTPServerTestCase.test_head_keep_alive',
'test_httpservers.BaseHTTPServerTestCase.test_head_via_send_error',
'test_httpservers.BaseHTTPServerTestCase.test_header_close',
'test_httpservers.BaseHTTPServerTestCase.test_internal_key_error',
'test_httpservers.BaseHTTPServerTestCase.test_request_line_trimming',
'test_httpservers.BaseHTTPServerTestCase.test_return_custom_status',
'test_httpservers.BaseHTTPServerTestCase.test_send_blank',
'test_httpservers.BaseHTTPServerTestCase.test_send_error',
'test_httpservers.BaseHTTPServerTestCase.test_version_bogus',
'test_httpservers.BaseHTTPServerTestCase.test_version_digits',
'test_httpservers.BaseHTTPServerTestCase.test_version_invalid',
'test_httpservers.BaseHTTPServerTestCase.test_version_none',
'test_httpservers.SimpleHTTPServerTestCase.test_get',
'test_httpservers.SimpleHTTPServerTestCase.test_head',
'test_httpservers.SimpleHTTPServerTestCase.test_invalid_requests',
'test_httpservers.SimpleHTTPServerTestCase.test_path_without_leading_slash',
'test_httpservers.CGIHTTPServerTestCase.test_invaliduri',
'test_httpservers.CGIHTTPServerTestCase.test_issue19435',
# Unexpected timeouts sometimes
'test_smtplib.TooLongLineTests.testLineTooLong',
'test_smtplib.GeneralTests.testTimeoutValue',
# This sometimes crashes, which can't be our fault?
'test_ssl.BasicSocketTests.test_parse_cert_CVE_2019_5010',
]
if PYPY:
disabled_tests += [
# appears to timeout?
'test_threading.ThreadTests.test_finalize_with_trace',
'test_asyncore.DispatcherWithSendTests_UsePoll.test_send',
'test_asyncore.DispatcherWithSendTests.test_send',
# More unexpected timeouts
'test_ssl.ContextTests.test__https_verify_envvar',
'test_subprocess.ProcessTestCase.test_check_output',
'test_telnetlib.ReadTests.test_read_eager_A',
# But on Windows, our gc fix for that doesn't work anyway
# so we have to disable it.
'test_urllib2_localnet.TestUrlopen.test_https_with_cafile',
# These tests hang. see above.
'test_threading.ThreadJoinOnShutdown.test_1_join_on_shutdown',
'test_threading.ThreadingExceptionTests.test_print_exception',
# Our copy of these in test__subprocess.py also hangs.
# Anything that uses Popen.communicate or directly uses
# Popen.stdXXX.read hangs. It's not clear why.
'test_subprocess.ProcessTestCase.test_communicate',
'test_subprocess.ProcessTestCase.test_cwd',
'test_subprocess.ProcessTestCase.test_env',
'test_subprocess.ProcessTestCase.test_stderr_pipe',
'test_subprocess.ProcessTestCase.test_stdout_pipe',
'test_subprocess.ProcessTestCase.test_stdout_stderr_pipe',
'test_subprocess.ProcessTestCase.test_stderr_redirect_with_no_stdout_redirect',
'test_subprocess.ProcessTestCase.test_stdout_filedes_of_stdout',
'test_subprocess.ProcessTestcase.test_stdout_none',
'test_subprocess.ProcessTestcase.test_universal_newlines',
'test_subprocess.ProcessTestcase.test_writes_before_communicate',
'test_subprocess.Win32ProcessTestCase._kill_process',
'test_subprocess.Win32ProcessTestCase._kill_dead_process',
'test_subprocess.Win32ProcessTestCase.test_shell_sequence',
'test_subprocess.Win32ProcessTestCase.test_shell_string',
'test_subprocess.CommandsWithSpaces.with_spaces',
]
if WIN:
disabled_tests += [
# This test winds up hanging a long time.
# Inserting GCs doesn't fix it.
'test_ssl.ThreadedTests.test_handshake_timeout',
# These sometimes raise LoopExit, for no apparent reason,
# mostly but not exclusively on Python 2. Sometimes (often?)
# this happens in the setUp() method when we attempt to get a client
# connection
'test_socket.BufferIOTest.testRecvFromIntoBytearray',
'test_socket.BufferIOTest.testRecvFromIntoArray',
'test_socket.BufferIOTest.testRecvIntoArray',
'test_socket.BufferIOTest.testRecvIntoMemoryview',
'test_socket.BufferIOTest.testRecvFromIntoEmptyBuffer',
'test_socket.BufferIOTest.testRecvFromIntoMemoryview',
'test_socket.BufferIOTest.testRecvFromIntoSmallBuffer',
'test_socket.BufferIOTest.testRecvIntoBytearray',
]
if PY3:
disabled_tests += [
]
if APPVEYOR:
disabled_tests += [
]
if PYPY:
if TRAVIS:
disabled_tests += [
# This sometimes causes a segfault for no apparent reason.
# See https://travis-ci.org/gevent/gevent/jobs/327328704
# Can't reproduce locally.
'test_subprocess.ProcessTestCase.test_universal_newlines_communicate',
]
if RUN_COVERAGE and CFFI_BACKEND:
disabled_tests += [
# This test hangs in this combo for some reason
'test_socket.GeneralModuleTests.test_sendall_interrupted',
# This can get a timeout exception instead of the Alarm
'test_socket.TCPTimeoutTest.testInterruptedTimeout',
# This test sometimes gets the wrong answer (due to changed timing?)
'test_socketserver.SocketServerTest.test_ForkingUDPServer',
# Timing and signals are off, so a handler exception doesn't get raised.
# Seen under libev
'test_signal.InterProcessSignalTests.test_main',
]
if PY2:
if TRAVIS:
disabled_tests += [
# When we moved to group:travis_latest and dist:xenial,
# this started returning a value (33554432L) != 0; presumably
# because of updated SSL library? Only on CPython.
'test_ssl.ContextTests.test_options',
# When we moved to group:travis_latest and dist:xenial,
# one of the values used started *working* when it was expected to fail.
# The list of values and systems is long and complex, so
# presumably something needs to be updated. Only on PyPy.
'test_ssl.ThreadedTests.test_alpn_protocols',
]
disabled_tests += [
# At least on OSX, this results in connection refused
'test_urllib2_localnet.TestUrlopen.test_https_sni',
]
if sys.version_info[:3] < (2, 7, 16):
# We have 2.7.16 tests; older versions can fail
# to validate some SSL things or are missing important support functions
disabled_tests += [
# Support functions
'test_thread.ThreadRunningTests.test_nt_and_posix_stack_size',
'test_thread.ThreadRunningTests.test_save_exception_state_on_error',
'test_thread.ThreadRunningTests.test_starting_threads',
'test_thread.BarrierTest.test_barrier',
# Broken SSL
'test_urllib2_localnet.TestUrlopen.test_https',
'test_ssl.ContextTests.test__create_stdlib_context',
'test_ssl.ContextTests.test_create_default_context',
'test_ssl.ContextTests.test_options',
]
if PYPY and sys.pypy_version_info[:3] == (7, 3, 0): # pylint:disable=no-member
if OSX:
disabled_tests += [
# This is expected to produce an SSLError, but instead it appears to
# actually work. See above for when it started failing the same on
# Travis.
'test_ssl.ThreadedTests.test_alpn_protocols',
# This fails, presumably due to the OpenSSL it's compiled with.
'test_ssl.ThreadedTests.test_default_ecdh_curve',
]
def _make_run_with_original(mod_name, func_name):
@contextlib.contextmanager
def with_orig():
mod = __import__(mod_name)
now = getattr(mod, func_name)
from gevent.monkey import get_original
orig = get_original(mod_name, func_name)
try:
setattr(mod, func_name, orig)
yield
finally:
setattr(mod, func_name, now)
return with_orig
@contextlib.contextmanager
def _gc_at_end():
try:
yield
finally:
import gc
gc.collect()
gc.collect()
@contextlib.contextmanager
def _flaky_socket_timeout():
import socket
try:
yield
except socket.timeout:
flaky.reraiseFlakyTestTimeout()
# Map from FQN to a context manager that will be wrapped around
# that test.
wrapped_tests = {
}
class _PatchedTest(object):
def __init__(self, test_fqn):
self._patcher = wrapped_tests[test_fqn]
def __call__(self, orig_test_fn):
@functools.wraps(orig_test_fn)
def test(*args, **kwargs):
with self._patcher():
return orig_test_fn(*args, **kwargs)
return test
if sys.version_info[:3] <= (2, 7, 11):
disabled_tests += [
# These were added/fixed in 2.7.12+
'test_ssl.ThreadedTests.test__https_verify_certificates',
'test_ssl.ThreadedTests.test__https_verify_envvar',
]
if OSX:
disabled_tests += [
'test_subprocess.POSIXProcessTestCase.test_run_abort',
# causes Mac OS X to show "Python crashes" dialog box which is annoying
]
if WIN:
disabled_tests += [
# Issue with Unix vs DOS newlines in the file vs from the server
'test_ssl.ThreadedTests.test_socketserver',
# On appveyor, this sometimes produces 'A non-blocking socket
# operation could not be completed immediately', followed by
# 'No connection could be made because the target machine
# actively refused it'
'test_socket.NonBlockingTCPTests.testAccept',
]
# These are a problem on 3.5; on 3.6+ they wind up getting (accidentally) disabled.
wrapped_tests.update({
'test_socket.SendfileUsingSendTest.testWithTimeout': _flaky_socket_timeout,
'test_socket.SendfileUsingSendTest.testOffset': _flaky_socket_timeout,
'test_socket.SendfileUsingSendTest.testRegularFile': _flaky_socket_timeout,
'test_socket.SendfileUsingSendTest.testCount': _flaky_socket_timeout,
})
if PYPY:
disabled_tests += [
# Does not exist in the CPython test suite, tests for a specific bug
# in PyPy's forking. Only runs on linux and is specific to the PyPy
# implementation of subprocess (possibly explains the extra parameter to
# _execut_child)
'test_subprocess.ProcessTestCase.test_failed_child_execute_fd_leak',
# On some platforms, this returns "zlib_compression", but the test is looking for
# "ZLIB"
'test_ssl.ThreadedTests.test_compression',
# These are flaxy, apparently a race condition? Began with PyPy 2.7-7 and 3.6-7
'test_asyncore.TestAPI_UsePoll.test_handle_error',
'test_asyncore.TestAPI_UsePoll.test_handle_read',
]
if WIN:
disabled_tests += [
# Starting in 7.3.1 on Windows, this stopped raising ValueError; it appears to
# be a bug in PyPy.
'test_signal.WakeupFDTests.test_invalid_fd',
# Likewise for 7.3.1. See the comments for PY35
'test_socket.GeneralModuleTests.test_sock_ioctl',
]
if PY36:
disabled_tests += [
# These are flaky, beginning in 3.6-alpha 7.0, not finding some flag
# set, apparently a race condition
'test_asyncore.TestAPI_UveIPv6Poll.test_handle_accept',
'test_asyncore.TestAPI_UveIPv6Poll.test_handle_accepted',
'test_asyncore.TestAPI_UveIPv6Poll.test_handle_close',
'test_asyncore.TestAPI_UveIPv6Poll.test_handle_write',
'test_asyncore.TestAPI_UseIPV6Select.test_handle_read',
# These are reporting 'ssl has no attribute ...'
# This could just be an OSX thing
'test_ssl.ContextTests.test__create_stdlib_context',
'test_ssl.ContextTests.test_create_default_context',
'test_ssl.ContextTests.test_get_ciphers',
'test_ssl.ContextTests.test_options',
'test_ssl.ContextTests.test_constants',
# These tend to hang for some reason, probably not properly
# closed sockets.
'test_socketserver.SocketServerTest.test_write',
# This uses ctypes to do funky things including using ptrace,
# it hangs
'test_subprocess.ProcessTestcase.test_child_terminated_in_stopped_state',
# Certificate errors; need updated test
'test_urllib2_localnet.TestUrlopen.test_https',
]
# Generic Python 3
if PY3:
disabled_tests += [
# Triggers the crash reporter
'test_threading.SubinterpThreadingTests.test_daemon_threads_fatal_error',
# Relies on an implementation detail, Thread._tstate_lock
'test_threading.ThreadTests.test_tstate_lock',
# Relies on an implementation detail (reprs); we have our own version
'test_threading.ThreadTests.test_various_ops',
'test_threading.ThreadTests.test_various_ops_large_stack',
'test_threading.ThreadTests.test_various_ops_small_stack',
# Relies on Event having a _cond and an _reset_internal_locks()
# XXX: These are commented out in the source code of test_threading because
# this doesn't work.
# 'lock_tests.EventTests.test_reset_internal_locks',
# Python bug 13502. We may or may not suffer from this as its
# basically a timing race condition.
# XXX Same as above
# 'lock_tests.EventTests.test_set_and_clear',
# These tests want to assert on the type of the class that implements
# `Popen.stdin`; we use a FileObject, but they expect different subclasses
# from the `io` module
'test_subprocess.ProcessTestCase.test_io_buffered_by_default',
'test_subprocess.ProcessTestCase.test_io_unbuffered_works',
# 3.3 exposed the `endtime` argument to wait accidentally.
# It is documented as deprecated and not to be used since 3.4
# This test in 3.6.3 wants to use it though, and we don't have it.
'test_subprocess.ProcessTestCase.test_wait_endtime',
# These all want to inspect the string value of an exception raised
# by the exec() call in the child. The _posixsubprocess module arranges
# for better exception handling and printing than we do.
'test_subprocess.POSIXProcessTestCase.test_exception_bad_args_0',
'test_subprocess.POSIXProcessTestCase.test_exception_bad_executable',
'test_subprocess.POSIXProcessTestCase.test_exception_cwd',
# Relies on a 'fork_exec' attribute that we don't provide
'test_subprocess.POSIXProcessTestCase.test_exception_errpipe_bad_data',
'test_subprocess.POSIXProcessTestCase.test_exception_errpipe_normal',
# Python 3 fixed a bug if the stdio file descriptors were closed;
# we still have that bug
'test_subprocess.POSIXProcessTestCase.test_small_errpipe_write_fd',
# Relies on implementation details (some of these tests were added in 3.4,
# but PyPy3 is also shipping them.)
'test_socket.GeneralModuleTests.test_SocketType_is_socketobject',
'test_socket.GeneralModuleTests.test_dealloc_warn',
'test_socket.GeneralModuleTests.test_repr',
'test_socket.GeneralModuleTests.test_str_for_enums',
'test_socket.GeneralModuleTests.testGetaddrinfo',
]
if TRAVIS:
disabled_tests += [
# test_cwd_with_relative_executable tends to fail
# on Travis...it looks like the test processes are stepping
# on each other and messing up their temp directories. We tend to get things like
# saved_dir = os.getcwd()
# FileNotFoundError: [Errno 2] No such file or directory
'test_subprocess.ProcessTestCase.test_cwd_with_relative_arg',
'test_subprocess.ProcessTestCaseNoPoll.test_cwd_with_relative_arg',
'test_subprocess.ProcessTestCase.test_cwd_with_relative_executable',
# In 3.7 and 3.8 on Travis CI, this appears to take the full 3 seconds.
# Can't reproduce it locally. We have our own copy of this that takes
# timing on CI into account.
'test_subprocess.RunFuncTestCase.test_run_with_shell_timeout_and_capture_output',
]
disabled_tests += [
# XXX: BUG: We simply don't handle this correctly. On CPython,
# we wind up raising a BlockingIOError and then
# BrokenPipeError and then some random TypeErrors, all on the
# server. CPython 3.5 goes directly to socket.send() (via
# socket.makefile), whereas CPython 3.6 uses socket.sendall().
# On PyPy, the behaviour is much worse: we hang indefinitely, perhaps exposing a problem
# with our signal handling.
# In actuality, though, this test doesn't fully test the EINTR it expects
# to under gevent (because if its EWOULDBLOCK retry behaviour.)
# Instead, the failures were all due to `pthread_kill` trying to send a signal
# to a greenlet instead of a real thread. The solution is to deliver the signal
# to the real thread by letting it get the correct ID, and we previously
# used make_run_with_original to make it do that.
#
# But now that we have disabled our wrappers around Thread.join() in favor
# of the original implementation, that causes problems:
# background.join() thinks that it is the current thread, and won't let it
# be joined.
'test_wsgiref.IntegrationTests.test_interrupted_write',
]
# PyPy3 3.5.5 v5.8-beta
if PYPY3:
disabled_tests += [
# This raises 'RuntimeError: reentrant call' when exiting the
# process tries to close the stdout stream; no other platform does this.
# Seen in both 3.3 and 3.5 (5.7 and 5.8)
'test_signal.SiginterruptTest.test_siginterrupt_off',
]
if PYPY and PY3:
disabled_tests += [
# This fails to close all the FDs, at least on CI. On OS X, many of the
# POSIXProcessTestCase fd tests have issues.
'test_subprocess.POSIXProcessTestCase.test_close_fds_when_max_fd_is_lowered',
# This has the wrong constants in 5.8 (but worked in 5.7), at least on
# OS X. It finds "zlib compression" but expects "ZLIB".
'test_ssl.ThreadedTests.test_compression',
# The below are new with 5.10.1
# This gets an EOF in violation of protocol; again, even without gevent
# (at least on OS X; it's less consistent about that on travis)
'test_ssl.NetworkedBIOTests.test_handshake',
# This passes various "invalid" strings and expects a ValueError. not sure why
# we don't see errors on CPython.
'test_subprocess.ProcessTestCase.test_invalid_env',
]
if OSX:
disabled_tests += [
# These all fail with "invalid_literal for int() with base 10: b''"
'test_subprocess.POSIXProcessTestCase.test_close_fds',
'test_subprocess.POSIXProcessTestCase.test_close_fds_after_preexec',
'test_subprocess.POSIXProcessTestCase.test_pass_fds',
'test_subprocess.POSIXProcessTestCase.test_pass_fds_inheritable',
'test_subprocess.POSIXProcessTestCase.test_pipe_cloexec',
# The below are new with 5.10.1
# These fail with 'OSError: received malformed or improperly truncated ancillary data'
'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen0',
'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen0Plus1',
'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen1',
'test_socket.RecvmsgSCMRightsStreamTest.testCmsgTruncLen2Minus1',
# Using the provided High Sierra binary, these fail with
# 'ValueError: invalid protocol version _SSLMethod.PROTOCOL_SSLv3'.
# gevent code isn't involved and running them unpatched has the same issue.
'test_ssl.ContextTests.test_constructor',
'test_ssl.ContextTests.test_protocol',
'test_ssl.ContextTests.test_session_stats',
'test_ssl.ThreadedTests.test_echo',
'test_ssl.ThreadedTests.test_protocol_sslv23',
'test_ssl.ThreadedTests.test_protocol_sslv3',
'test_ssl.ThreadedTests.test_protocol_tlsv1',
'test_ssl.ThreadedTests.test_protocol_tlsv1_1',
# Similar, they fail without monkey-patching.
'test_ssl.TestPostHandshakeAuth.test_pha_no_pha_client',
'test_ssl.TestPostHandshakeAuth.test_pha_optional',
'test_ssl.TestPostHandshakeAuth.test_pha_required',
# This gets None instead of http1.1, even without gevent
'test_ssl.ThreadedTests.test_npn_protocols',
# This fails to decode a filename even without gevent,
# at least on High Sierra. Newer versions of the tests actually skip this.
'test_httpservers.SimpleHTTPServerTestCase.test_undecodable_filename',
]
disabled_tests += [
# This seems to be a buffering issue? Something isn't
# getting flushed. (The output is wrong). Under PyPy3 5.7,
# I couldn't reproduce locally in Ubuntu 16 in a VM
# or a laptop with OS X. Under 5.8.0, I can reproduce it, but only
# when run by the testrunner, not when run manually on the command line,
# so something is changing in stdout buffering in those situations.
'test_threading.ThreadJoinOnShutdown.test_2_join_in_forked_process',
'test_threading.ThreadJoinOnShutdown.test_1_join_in_forked_process',
]
if TRAVIS:
disabled_tests += [
# Likewise, but I haven't produced it locally.
'test_threading.ThreadJoinOnShutdown.test_1_join_on_shutdown',
]
if PYPY:
wrapped_tests.update({
# XXX: gevent: The error that was raised by that last call
# left a socket open on the server or client. The server gets
# to http/server.py(390)handle_one_request and blocks on
# self.rfile.readline which apparently is where the SSL
# handshake is done. That results in the exception being
# raised on the client above, but apparently *not* on the
# server. Consequently it sits trying to read from that
# socket. On CPython, when the client socket goes out of scope
# it is closed and the server raises an exception, closing the
# socket. On PyPy, we need a GC cycle for that to happen.
# Without the socket being closed and exception being raised,
# the server cannot be stopped (it runs each request in the
# same thread that would notice it had been stopped), and so
# the cleanup method added by start_https_server to stop the
# server blocks "forever".
# This is an important test, so rather than skip it in patched_tests_setup,
# we do the gc before we return.
'test_urllib2_localnet.TestUrlopen.test_https_with_cafile': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_command': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_handler': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_head_keep_alive': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_head_via_send_error': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_header_close': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_internal_key_error': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_request_line_trimming': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_return_custom_status': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_return_header_keep_alive': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_send_blank': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_send_error': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_version_bogus': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_version_digits': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_version_invalid': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_version_none': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_version_none_get': _gc_at_end,
'test_httpservers.BaseHTTPServerTestCase.test_get': _gc_at_end,
'test_httpservers.SimpleHTTPServerTestCase.test_get': _gc_at_end,
'test_httpservers.SimpleHTTPServerTestCase.test_head': _gc_at_end,
'test_httpservers.SimpleHTTPServerTestCase.test_invalid_requests': _gc_at_end,
'test_httpservers.SimpleHTTPServerTestCase.test_path_without_leading_slash': _gc_at_end,
'test_httpservers.CGIHTTPServerTestCase.test_invaliduri': _gc_at_end,
'test_httpservers.CGIHTTPServerTestCase.test_issue19435': _gc_at_end,
'test_httplib.TunnelTests.test_connect': _gc_at_end,
'test_httplib.SourceAddressTest.testHTTPConnectionSourceAddress': _gc_at_end,
# Unclear
'test_urllib2_localnet.ProxyAuthTests.test_proxy_with_bad_password_raises_httperror': _gc_at_end,
'test_urllib2_localnet.ProxyAuthTests.test_proxy_with_no_password_raises_httperror': _gc_at_end,
})
if PY35:
disabled_tests += [
'test_subprocess.ProcessTestCase.test_threadsafe_wait',
# XXX: It seems that threading.Timer is not being greened properly, possibly
# due to a similar issue to what gevent.threading documents for normal threads.
# In any event, this test hangs forever
'test_subprocess.POSIXProcessTestCase.test_preexec_errpipe_does_not_double_close_pipes',
# Subclasses Popen, and overrides _execute_child. Expects things to be done
# in a particular order in an exception case, but we don't follow that
# exact order
'test_selectors.PollSelectorTestCase.test_above_fd_setsize',
# This test attempts to open many many file descriptors and
# poll on them, expecting them all to be ready at once. But
# libev limits the number of events it will return at once. Specifically,
# on linux with epoll, it returns a max of 64 (ev_epoll.c).
# XXX: Hangs (Linux only)
'test_socket.NonBlockingTCPTests.testInitNonBlocking',
# We don't handle the Linux-only SOCK_NONBLOCK option
'test_socket.NonblockConstantTest.test_SOCK_NONBLOCK',
# Tries to use multiprocessing which doesn't quite work in
# monkey_test module (Windows only)
'test_socket.TestSocketSharing.testShare',
# Windows-only: Sockets have a 'ioctl' method in Python 3
# implemented in the C code. This test tries to check
# for the presence of the method in the class, which we don't
# have because we don't inherit the C implementation. But
# it should be found at runtime.
'test_socket.GeneralModuleTests.test_sock_ioctl',
# XXX This fails for an unknown reason
'test_httplib.HeaderTests.test_parse_all_octets',
]
if OSX:
disabled_tests += [
# These raise "OSError: 12 Cannot allocate memory" on both
# patched and unpatched runs
'test_socket.RecvmsgSCMRightsStreamTest.testFDPassEmpty',
]
if TRAVIS:
# This has been seen to produce "Inconsistency detected by
# ld.so: dl-open.c: 231: dl_open_worker: Assertion
# `_dl_debug_initialize (0, args->nsid)->r_state ==
# RT_CONSISTENT' failed!" and fail.
disabled_tests += [
'test_threading.ThreadTests.test_is_alive_after_fork',
]
if TRAVIS:
disabled_tests += [
'test_subprocess.ProcessTestCase.test_double_close_on_error',
# This test is racy or OS-dependent. It passes locally (sufficiently fast machine)
# but fails under Travis
]
if PY35:
disabled_tests += [
# XXX: Hangs
'test_ssl.ThreadedTests.test_nonblocking_send',
'test_ssl.ThreadedTests.test_socketserver',
# Uses direct sendfile, doesn't properly check for it being enabled
'test_socket.GeneralModuleTests.test__sendfile_use_sendfile',
# Relies on the regex of the repr having the locked state (TODO: it'd be nice if
# we did that).
# XXX: These are commented out in the source code of test_threading because
# this doesn't work.
# 'lock_tests.LockTests.lest_locked_repr',
# 'lock_tests.LockTests.lest_repr',
# This test opens a socket, creates a new socket with the same fileno,
# closes the original socket (and hence fileno) and then
# expects that the calling setblocking() on the duplicate socket
# will raise an error. Our implementation doesn't work that way because
# setblocking() doesn't actually touch the file descriptor.
# That's probably OK because this was a GIL state error in CPython
# see https://github.com/python/cpython/commit/fa22b29960b4e683f4e5d7e308f674df2620473c
'test_socket.TestExceptions.test_setblocking_invalidfd',
]
if ARES:
disabled_tests += [
# These raise different errors or can't resolve
# the IP address correctly
'test_socket.GeneralModuleTests.test_host_resolution',
'test_socket.GeneralModuleTests.test_getnameinfo',
]
if sys.version_info[1] == 5:
disabled_tests += [
# This test tends to time out, but only under 3.5, not under
# 3.6 or 3.7. Seen with both libev and libuv
'test_socket.SendfileUsingSendTest.testWithTimeoutTriggeredSend',
]
if sys.version_info[:3] <= (3, 5, 1):
# Python issue 26499 was fixed in 3.5.2 and these tests were added.
disabled_tests += [
'test_httplib.BasicTest.test_mixed_reads',
'test_httplib.BasicTest.test_read1_bound_content_length',
'test_httplib.BasicTest.test_read1_content_length',
'test_httplib.BasicTest.test_readline_bound_content_length',
'test_httplib.BasicTest.test_readlines_content_length',
]
if PY36:
disabled_tests += [
'test_threading.MiscTestCase.test__all__',
]
# We don't actually implement socket._sendfile_use_sendfile,
# so these tests, which think they're using that and os.sendfile,
# fail.
disabled_tests += [
'test_socket.SendfileUsingSendfileTest.testCount',
'test_socket.SendfileUsingSendfileTest.testCountSmall',
'test_socket.SendfileUsingSendfileTest.testCountWithOffset',
'test_socket.SendfileUsingSendfileTest.testOffset',
'test_socket.SendfileUsingSendfileTest.testRegularFile',
'test_socket.SendfileUsingSendfileTest.testWithTimeout',
'test_socket.SendfileUsingSendfileTest.testEmptyFileSend',
'test_socket.SendfileUsingSendfileTest.testNonBlocking',
'test_socket.SendfileUsingSendfileTest.test_errors',
]
# Ditto
disabled_tests += [
'test_socket.GeneralModuleTests.test__sendfile_use_sendfile',
]
disabled_tests += [
# This test requires Linux >= 4.3. When we were running 'dist:
# trusty' on the 4.4 kernel, it passed (~July 2017). But when
# trusty became the default dist in September 2017 and updated
# the kernel to 4.11.6, it begain failing. It fails on `res =
# op.recv(assoclen + len(plain) + taglen)` (where 'op' is the
# client socket) with 'OSError: [Errno 22] Invalid argument'
# for unknown reasons. This is *after* having successfully
# called `op.sendmsg_afalg`. Post 3.6.0, what we test with,
# the test was changed to require Linux 4.9 and the data was changed,
# so this is not our fault. We should eventually update this when we
# update our 3.6 version.
# See https://bugs.python.org/issue29324
'test_socket.LinuxKernelCryptoAPI.test_aead_aes_gcm',
]
if PY37:
disabled_tests += [
# These want to use the private '_communicate' method, which
# our Popen doesn't have.
'test_subprocess.MiscTests.test_call_keyboardinterrupt_no_kill',
'test_subprocess.MiscTests.test_context_manager_keyboardinterrupt_no_kill',
'test_subprocess.MiscTests.test_run_keyboardinterrupt_no_kill',
# This wants to check that the underlying fileno is blocking,
# but it isn't.
'test_socket.NonBlockingTCPTests.testSetBlocking',
# 3.7b2 made it impossible to instantiate SSLSocket objects
# directly, and this tests for that, but we don't follow that change.
'test_ssl.BasicSocketTests.test_private_init',
# 3.7b2 made a change to this test that on the surface looks incorrect,
# but it passes when they run it and fails when we do. It's not
# clear why.
'test_ssl.ThreadedTests.test_check_hostname_idn',
# These appear to hang, haven't investigated why
'test_ssl.SimpleBackgroundTests.test_get_server_certificate',
# Probably the same as NetworkConnectionNoServer.test_create_connection_timeout
'test_socket.NetworkConnectionNoServer.test_create_connection',
# Internals of the threading module that change.
'test_threading.ThreadTests.test_finalization_shutdown',
'test_threading.ThreadTests.test_shutdown_locks',
# Expects a deprecation warning we don't raise
'test_threading.ThreadTests.test_old_threading_api',
# This tries to use threading.interrupt_main() from a new Thread;
# but of course that's actually the same thread and things don't
# work as expected.
'test_threading.InterruptMainTests.test_interrupt_main_subthread',
'test_threading.InterruptMainTests.test_interrupt_main_noerror',
# TLS1.3 seems flaky
'test_ssl.ThreadedTests.test_wrong_cert_tls13',
]
if sys.version_info < (3, 7, 6):
disabled_tests += [
# Earlier versions parse differently so the newer test breaks
'test_ssl.BasicSocketTests.test_parse_all_sans',
'test_ssl.BasicSocketTests.test_parse_cert_CVE_2013_4238',
]
if APPVEYOR:
disabled_tests += [
]
if PY38:
disabled_tests += [
# This one seems very strict: doesn't want a pathlike
# first argument when shell is true.
'test_subprocess.RunFuncTestCase.test_run_with_pathlike_path',
# This tests for a warning we don't raise.
'test_subprocess.RunFuncTestCase.test_bufsize_equal_one_binary_mode',
# This compares the output of threading.excepthook with
# data constructed in Python. But excepthook is implemented in C
# and can't see the patched threading.get_ident() we use, so the
# output doesn't match.
'test_threading.ExceptHookTests.test_excepthook_thread_None',
]
if sys.version_info < (3, 8, 1):
disabled_tests += [
# Earlier versions parse differently so the newer test breaks
'test_ssl.BasicSocketTests.test_parse_all_sans',
'test_ssl.BasicSocketTests.test_parse_cert_CVE_2013_4238',
]
# if 'signalfd' in os.environ.get('GEVENT_BACKEND', ''):
# # tests that don't interact well with signalfd
# disabled_tests.extend([
# 'test_signal.SiginterruptTest.test_siginterrupt_off',
# 'test_socketserver.SocketServerTest.test_ForkingTCPServer',
# 'test_socketserver.SocketServerTest.test_ForkingUDPServer',
# 'test_socketserver.SocketServerTest.test_ForkingUnixStreamServer'])
# LibreSSL reports OPENSSL_VERSION_INFO (2, 0, 0, 0, 0) regardless of its version,
# so this is known to fail on some distros. We don't want to detect this because we
# don't want to trigger the side-effects of importing ssl prematurely if we will
# be monkey-patching, so we skip this test everywhere. It doesn't do much for us
# anyway.
disabled_tests += [
'test_ssl.BasicSocketTests.test_openssl_version'
]
if OSX:
disabled_tests += [
# This sometimes produces OSError: Errno 40: Message too long
'test_socket.RecvmsgIntoTCPTest.testRecvmsgIntoGenerator',
]
# Now build up the data structure we'll use to actually find disabled tests
# to avoid a linear scan for every file (it seems the list could get quite large)
# (First, freeze the source list to make sure it isn't modified anywhere)
def _build_test_structure(sequence_of_tests):
_disabled_tests = frozenset(sequence_of_tests)
disabled_tests_by_file = collections.defaultdict(set)
for file_case_meth in _disabled_tests:
file_name, _case, _meth = file_case_meth.split('.')
by_file = disabled_tests_by_file[file_name]
by_file.add(file_case_meth)
return disabled_tests_by_file
_disabled_tests_by_file = _build_test_structure(disabled_tests)
_wrapped_tests_by_file = _build_test_structure(wrapped_tests)
def disable_tests_in_source(source, filename):
# Source and filename are both native strings.
if filename.startswith('./'):
# turn "./test_socket.py" (used for auto-complete) into "test_socket.py"
filename = filename[2:]
if filename.endswith('.py'):
filename = filename[:-3]
# XXX ignoring TestCase class name (just using function name).
# Maybe we should do this with the AST, or even after the test is
# imported.
my_disabled_tests = _disabled_tests_by_file.get(filename, ())
my_wrapped_tests = _wrapped_tests_by_file.get(filename, {})
if my_disabled_tests or my_wrapped_tests:
# Insert our imports early in the file.
# If we do it on a def-by-def basis, we can break syntax
# if the function is already decorated
pattern = r'^import .*'
replacement = r'from gevent.testing import patched_tests_setup as _GEVENT_PTS;'
replacement += r'import unittest as _GEVENT_UTS;'
replacement += r'\g<0>'
source, n = re.subn(pattern, replacement, source, 1, re.MULTILINE)
print("Added imports", n)
# Test cases will always be indented some,
# so use [ \t]+. Without indentation, test_main, commonly used as the
# __main__ function at the top level, could get matched. \s matches
# newlines even in MULTILINE mode so it would still match that.
my_disabled_testcases = set()
for test in my_disabled_tests:
testcase = test.split('.')[-1]
my_disabled_testcases.add(testcase)
# def foo_bar(self)
# ->
# @_GEVENT_UTS.skip('Removed by patched_tests_setup')
# def foo_bar(self)
pattern = r"^([ \t]+)def " + testcase
replacement = r"\1@_GEVENT_UTS.skip('Removed by patched_tests_setup: %s')\n" % (test,)
replacement += r"\g<0>"
source, n = re.subn(pattern, replacement, source, 0, re.MULTILINE)
print('Skipped %s (%d)' % (testcase, n), file=sys.stderr)
for test in my_wrapped_tests:
testcase = test.split('.')[-1]
if testcase in my_disabled_testcases:
print("Not wrapping %s because it is skipped" % (test,))
continue
# def foo_bar(self)
# ->
# @_GEVENT_PTS._PatchedTest('file.Case.name')
# def foo_bar(self)
pattern = r"^([ \t]+)def " + testcase
replacement = r"\1@_GEVENT_PTS._PatchedTest('%s')\n" % (test,)
replacement += r"\g<0>"
source, n = re.subn(pattern, replacement, source, 0, re.MULTILINE)
print('Wrapped %s (%d)' % (testcase, n), file=sys.stderr)
return source
|
[
"[email protected]"
] | |
2e7d4646e442f507f545946684908d679bc89a25
|
b9a843c18bc0806ffcf49bb4af9a32d7c5b7e5d8
|
/test_get_average_club_count.py
|
df5e8b0b263947e665cc4702cdd8db340d38b714
|
[] |
no_license
|
serhatgktp/club-finder-in-python
|
ee6d5241f746655cd96c3cab2d60950e23f69869
|
f08da62c139d693f9393a39e6e13af55c57a4cbd
|
refs/heads/main
| 2023-03-12T08:39:33.476797 | 2021-02-23T19:56:55 | 2021-02-23T19:56:55 | 341,646,998 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,649 |
py
|
"""Test cases"""
import unittest
import club_functions
class TestGetAverageClubCount(unittest.TestCase):
"""Test cases for function club_functions.get_average_club_count.
"""
def test_00_empty(self):
param = {}
actual = club_functions.get_average_club_count(param)
expected = 0.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_one_person_one_club(self):
param = {'Claire Dunphy': ['Parent Teacher Association']}
actual = club_functions.get_average_club_count(param)
expected = 1.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_one_person_odd_clubs(self):
param = {'Claire Dunphy': ['Parent Teacher Association', \
'Rock N Rollers', 'Chess Club']}
actual = club_functions.get_average_club_count(param)
expected = 3.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_one_person_no_clubs(self):
param = {'Claire Dunphy': []}
actual = club_functions.get_average_club_count(param)
expected = 0.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_one_person_even_clubs(self):
param = {'Claire Dunphy': ['Parent Teacher Association', \
'Rock N Rollers']}
actual = club_functions.get_average_club_count(param)
expected = 2.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_one_person_longer_even_clubs(self):
param = {'Claire Dunphy': ['Parent Teacher Association', \
'Wizard of Oz Fan Club', 'Rock N Rollers', \
'Smash Club', 'Comics R Us', 'Comet Club']}
actual = club_functions.get_average_club_count(param)
expected = 6.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_one_person_longer_odd_clubs(self):
param = {'Claire Dunphy': ['Parent Teacher Association', \
'Wizard of Oz Fan Club', 'Rock N Rollers', \
'Smash Club', 'Comics R Us', 'Comet Club', \
'Chess Club']}
actual = club_functions.get_average_club_count(param)
expected = 7.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_even_people_both_one_club(self):
param = {'Claire Dunphy': ['Parent Teacher Association'], 'Jack \
Sparrow': ['Movie Club']}
actual = club_functions.get_average_club_count(param)
expected = 1.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_even_people_odd_and_even_clubs(self):
param = {'Claire Dunphy': ['Parent Teacher Association'], 'Jack \
Sparrow': ['Movie Club', 'Chess Club']}
actual = club_functions.get_average_club_count(param)
expected = 1.5
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_odd_people_all_one_club(self):
param = {'Claire Dunphy': ['Parent Teacher Association'], 'Jack \
Sparrow': ['Movie Club'], 'Matt Hughes': ['Movie Club']}
actual = club_functions.get_average_club_count(param)
expected = 1.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
def test_01_odd_people_all_even_clubs(self):
param = {'Claire Dunphy': ['Parent Teacher Association', 'Chess Club'],\
'Jack Sparrow': ['Movie Club', 'Chess Club'], \
'Matt Hughes': ['Movie Club', 'Chess Club']}
actual = club_functions.get_average_club_count(param)
expected = 2.0
msg = "Expected {}, but returned {}".format(expected, actual)
self.assertAlmostEqual(actual, expected, msg=msg)
if __name__ == '__main__':
unittest.main(exit=False)
|
[
"[email protected]"
] | |
1204884c0f76b2d403acbc11ca7c272f6ef259db
|
10f068d3ac95b3c072a1ddcc9b91a0dc41a7fd62
|
/customer/migrations/0004_auto_20200612_1751.py
|
9d380328dc36a67f53fc80f496d94f4c1975f6c2
|
[] |
no_license
|
sabirAIE/Django-FlyLight-CRM
|
60915e62ef70723dc958758df13b564ff4b9c954
|
3fbfa131c83ce55b812e3047b319ac9ae878943e
|
refs/heads/master
| 2022-10-30T02:34:18.208052 | 2020-06-13T16:05:42 | 2020-06-13T16:05:42 | 269,138,905 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 535 |
py
|
# Generated by Django 3.0.4 on 2020-06-12 17:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20200612_0602'),
('customer', '0003_auto_20200612_0602'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='user',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='users.adminUsers'),
),
]
|
[
"[email protected]"
] | |
549ee267634c9ffaee6dd29b1bc8292291f89241
|
3f40f963f017283c16cadb13bf5341a9df33ecfe
|
/ScrapePython.py
|
363b3665029213108cc3a330e411558fc6f9872b
|
[] |
no_license
|
sumon062/ScrapePython
|
885fc0b1cc25b5f8e36ecc72848734d7cf9105a6
|
e456099b787b9fb5869b428787a0b4f9c9b0a63e
|
refs/heads/master
| 2020-07-30T04:41:26.168888 | 2019-09-22T04:27:39 | 2019-09-22T04:27:39 | 210,089,710 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,629 |
py
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 16:00:10 2019
@author: Towfik
"""
# Here, I am importing Beautiful Soup,csv and the Requests library
import requests as r
from bs4 import BeautifulSoup
import csv
# this is the url that we've already determined to scrape from.
urltoget = 'http://drd.ba.ttu.edu/2019c/isqs6339/hw1'
#this is the filepath to copy
filepath = 'C:\\users\\Sumon\\Desktop\\dataout.csv'
# here,I fetch the content from the url, using the requests library
res = r.get(urltoget)
#Check if we have a good request
if res.status_code == 200:
print('request is good')
else:
print('bad request, received code ' + str(res.status_code))
#Soup Object
soup = BeautifulSoup(res.content,'lxml')
#Let's find the table. Note, there is only 1 table so this works well.
results = soup.find("table")
#print (results)
#Now, let's find all rows within the table
rowresults = results.find_all("tr")
#print (rowresults)
#Opening the csv file to write and providing the column names
with open(filepath, 'w') as dataout:
datawriter = csv.writer(dataout, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
datawriter.writerow(['id','quality', 'name', 'hp','level','elite','damage','money_drop','drop_mask'])
#Now, let's iterate on all the rows within the table.
for row in rowresults:
#Locate the cells in the row
cells = row.find_all("td")
#This checks to see if we have a header row. Notice the first row of the
#table is using <th> instead of <td> tags.
if len(cells) != 0:
#Access the data. Note, the cells[#] syntax.
#print these on console
#print('\n*************MOBS INFO************\n')
#print("Quality: " + cells[1].text)
#print(cells[0].find('a')['href'])
find_id = cells[0].find('a')['href']
id=find_id[15:]
#checking the extended link, put it in an object
link= ('/' + cells[0].find('a')['href'])
# creating the link by concetanating with the extended link
new_link= urltoget+link
# here,I fetch the content from the updated url, using the requests library
mobs = r.get(new_link)
#soup Object from the updated url
mobssoup = BeautifulSoup(mobs.content,'lxml')
#finding the mobcard id
mobs_all = mobssoup.find_all('div', attrs={'id' : 'mobcard'})
#print (mobs_all)
#print('\mobcard INFORMATION\n ')
#Iterate on all the values within the table where id is not blank(as here we have a blank id) and writing into the csv file
for item in mobs_all:
if id!='':
mobstats = item.findAll('span', attrs={'class' : 'val'})
#print on console
#print('name: ' + mobstats[0].text)
#print('hp: ' + mobstats[3].text)
#print('level: ' + mobstats[2].text)
#print('elite: ' + mobstats[1].text)
#print('manage: ' + mobstats[6].text)
#print('money_frop: ' + mobstats[5].text)
#print('drop_mask: ' + mobstats[4].text)
#print('------------------------------')
datawriter.writerow([id,cells[1].text,mobstats[0].text,mobstats[3].text,mobstats[2].text,
'0'if mobstats[1].text=='Normal' else '1',mobstats[6].text,mobstats[5].text,
mobstats[4].text.strip()])
|
[
"[email protected]"
] | |
9a6939baf3aeccf90e9bd609a773f0dd99b7a3f1
|
fcbe275aececcc844eaeedb00358ffd3da6bd3c1
|
/Project/ml_creator.py
|
bcdc7a76e5e59a05b116b23f310abb69e7b0664d
|
[] |
no_license
|
geffenbrenman/Link-a-Pix-AI-final-project
|
da56edf0cbb6bd4435dee4b935a7746143268b07
|
427dea80db0afb06415f538d69f00ae873baddca
|
refs/heads/master
| 2023-08-28T09:42:35.831196 | 2021-11-06T14:32:11 | 2021-11-06T14:32:11 | 286,984,295 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,159 |
py
|
# import csv
import os
import pickle
import numpy as np
import pandas as pd
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import OneHotEncoder
import xml_parser as ag
from game import Game
from ml import normalize_path, PATH_TO_TRAIN_SET, PATH_TO_PREDICTOR, PATH_TO_ONE_HOT_ENCODER
# *** Create train set *** #
def convert_xml_dict_to_rows(xml_dict):
w = xml_dict['width']
h = xml_dict['height']
number_of_colors = len(xml_dict['colors'])
number_of_cells = w * h
number_of_filled_cells = sum(
[len(path) for color, paths in xml_dict['paths'].items() for path in paths])
percent_of_filled_cells = round((number_of_filled_cells / number_of_cells) * 100, 2)
rows = []
solution_paths = []
# Get least of solution paths, score them 100
for color, paths in xml_dict['paths'].items():
for path in paths:
solution_paths += paths
path_start_x, path_start_y = path[0]
path_end_x, path_end_y = path[-1]
rows += [[
w, h,
number_of_colors,
percent_of_filled_cells,
path_start_x, path_start_y,
path_end_x, path_end_y,
str(normalize_path(path)),
100
]]
# Get list of wrong paths, score them 0
game = Game(xml_dict)
for cell in game.initial_board.get_list_of_numbered_cells():
paths = game.board.get_possible_moves(cell[0], cell[1])
for path in paths:
path_start_x, path_start_y = path[0]
path_end_x, path_end_y = path[-1]
if path not in solution_paths:
rows += [[
w, h,
number_of_colors,
percent_of_filled_cells,
path_start_x, path_start_y,
path_end_x, path_end_y,
str(normalize_path(path)),
0
]]
return rows
def create_train_file():
path_puzzles = './boards'
train_set = [['w', 'h', 'number_of_colors', 'percent_of_filled_cells', 'path_start_x',
'path_start_y', 'path_end_x', 'path_end_y', 'normalize_path', 'label']]
puzzles = [f for f in os.listdir(path_puzzles)]
with open('learner/train_set.csv', 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerows(train_set)
for i, puzzle in enumerate(puzzles[:-2]):
print(f'{i} out of {len(puzzles[:-2])}')
xml_dict = ag.get_xml_from_path(path_puzzles + '/' + puzzle)
train_set = convert_xml_dict_to_rows(xml_dict)
writer.writerows(train_set)
print('Train set is written to disk')
# *** Create predictor *** #
def create_predictor():
# Read from train_set.csv
train_set = pd.read_csv(PATH_TO_TRAIN_SET)
train_label = train_set['label']
del train_set['label']
print('1) Create one hot matrix')
ohe = OneHotEncoder(sparse=False, handle_unknown='ignore')
one_hot_data_set = ohe.fit_transform(train_set['normalize_path'].to_numpy().reshape(-1, 1))
print('2) Delete path strings and convert data frame to uint8')
del train_set['normalize_path']
train_set = train_set.astype(np.uint8)
print('3) Convert one hot matrix to data frame of booleans')
pd_one_hot_data_set = pd.DataFrame(one_hot_data_set, dtype='bool')
print('4) Join to existing data')
train_set = train_set.join(pd_one_hot_data_set)
print('5) Train model on data')
model = MLPRegressor(hidden_layer_sizes=(10,), activation='logistic')
predictor = model.fit(train_set, train_label)
with open(PATH_TO_PREDICTOR, 'wb') as file:
pickle.dump(predictor, file)
print('6) Predictor is written to disk')
with open(PATH_TO_ONE_HOT_ENCODER, 'wb') as file:
pickle.dump(ohe, file)
print('7) Encoder is written to disk')
# *** Main *** #
if __name__ == '__main__':
create_train_file()
create_predictor()
|
[
"[email protected]"
] | |
81dbc6da5a67a3c9d1cf4e3e4013b93416329c60
|
aef08a7c30c80d24a1ba5708f316153541b841d9
|
/Leetcode 0071. Simplify Path.py
|
7f9fbb46989a724cd62a68c8396c195fbacddb48
|
[] |
no_license
|
Chaoran-sjsu/leetcode
|
65b8f9ba44c074f415a25989be13ad94505d925f
|
6ff1941ff213a843013100ac7033e2d4f90fbd6a
|
refs/heads/master
| 2023-03-19T02:43:29.022300 | 2020-11-03T02:33:25 | 2020-11-03T02:33:25 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,539 |
py
|
"""
71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: "/a/./b/../../c/"
Output: "/c"
Example 5:
Input: "/a/../../b/../c//.//"
Output: "/c"
Example 6:
Input: "/a//b////c/d//././/.."
Output: "/a/b/c"
"""
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for s in path.split("/"):
if len(s) == 0 or s == ".":
continue
elif s == "..":
if len(stack) > 0:
stack.pop()
else:
stack.append(s)
return "/" + "/".join(stack)
|
[
"[email protected]"
] | |
19e9b0e029eb9fb62e6b451f360684c8ccff761e
|
b028a4b5f3fd54b7b64cd9785567cdcb5404b71f
|
/class12/12_titanic_confusion_nb.py
|
a52a9b391036a76628cd8e6199472ef823d3800e
|
[] |
no_license
|
JAStark/GA_DataScience
|
3ba39de4d5d50a1fcc24feafac9f5f5f58bb397b
|
312ad980f355d3186217078b9fb0163c8b1d777b
|
refs/heads/master
| 2021-01-01T18:18:37.446596 | 2015-10-30T15:33:17 | 2015-10-30T15:33:17 | 41,229,970 | 2 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 912 |
py
|
# # Logistic regression exercise with Titanic data
# ## Introduction
#
# - Data from Kaggle's Titanic competition: [data](https://github.com/justmarkham/DAT8/blob/master/data/titanic.csv), [data dictionary](https://www.kaggle.com/c/titanic/data)
# - **Goal**: Predict survival based on passenger characteristics
# - `titanic.csv` is already in our repo, so there is no need to download the data from the Kaggle website
# ## Step 1: Read the data into Pandas
# ## Step 2: Create X and y
#
# Define **Pclass** and **Parch** as the features, and **Survived** as the response.
# ## Step 3: Split the data into training and testing sets
# ## Step 4: Fit a logistic regression model and examine the coefficients
#
# Confirm that the coefficients make intuitive sense.
# ## Step 5: Make predictions on the testing set and calculate the accuracy
# ## Step 6: Compare your testing accuracy to the null accuracy
|
[
"[email protected]"
] | |
40049526245605797741259cdc585bd03091314e
|
bf5c4cd484153e9c36f12e574af6ff3101293688
|
/Web Server and Client/smart_stove/stove/admin.py
|
201e1e7918368e1f4a147363e255a6e6920f135e
|
[] |
no_license
|
rohanmanatkar/Smart-Stove
|
4f78964a39c14eccc229867c07b2a6f34e6d30e0
|
b52c0e8933b19315ce5df3fddfb358bad1850db4
|
refs/heads/master
| 2021-01-26T17:45:06.465792 | 2020-02-27T07:50:21 | 2020-02-27T07:50:21 | 243,459,678 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 118 |
py
|
from django.contrib import admin
from stove.models import *
# Register your models here.
admin.site.register([State])
|
[
"[email protected]"
] | |
696b87b0bff7a5bcf494441ef9ff10dbad893cd4
|
8fd07ea363ba4263bafe25d213c72cc9a93e2b3e
|
/devops/Day4_json_requests_zabbix-api/zabbix/dingtalk.py
|
2112181a91ce4aaf534cba9d5b2bc2035ec13296
|
[] |
no_license
|
ml758392/python_tedu
|
82e12ae014f0fc81230386fab07f901510fc8837
|
9f20798604db0ac8cd7b69d8c7a52ee361ebc7a7
|
refs/heads/master
| 2020-04-12T08:30:42.354663 | 2019-03-29T11:55:30 | 2019-03-29T11:55:30 | 162,386,878 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 821 |
py
|
# -*-coding:utf-8-*-
import json
import requests
import sys
def send_msg(url, reminders, msg):
headers = {'Content-Type': 'application/json;charset=utf-8'}
data = {
"msgtype": "text", # 发送消息类型为文本
"at": {
"atMobiles": reminders,
"isAtAll": False, # 不@所有人
},
"text": {
"content": msg, # 消息正文
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
return r.text
if __name__ == '__main__':
msg = sys.argv[1]
reminders = ['15937762237'] # 特别提醒要查看的人,就是@某人一下
url = 'https://oapi.dingtalk.com/robot/send?access_token=f62936c2eb31a053f422b5fdea9ea4748ce873a399ab521ccbf3ec\
29fefce9d1'
print(send_msg(url, reminders, msg))
|
[
"yy.tedu.cn"
] |
yy.tedu.cn
|
41561d116cf061f86b5406261d48b42a2048354b
|
54cdb0023d99a77ece44119298e9536798b81dec
|
/games.py
|
bf9e270ee3a1a7ffd1d7c6a27dd64d8bc2592a62
|
[] |
no_license
|
renzon/sudoku
|
8a36f1e3d488cf1d27f9131cea8c3255ef0be863
|
aca8a1a867bb7b77c7f998c9b6a8d641239b715f
|
refs/heads/master
| 2020-05-30T17:36:05.235259 | 2013-02-02T14:34:29 | 2013-02-02T14:34:29 | 7,976,685 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,395 |
py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from sudoku import Sudoku, EMPTY
#game=[[5,8,EMPTY,EMPTY,EMPTY,7,EMPTY,EMPTY,EMPTY],
# [EMPTY,EMPTY,6,4,5,EMPTY,8,EMPTY,EMPTY],
# [EMPTY,EMPTY,7,EMPTY,3,EMPTY,EMPTY,EMPTY,1],
# [1,EMPTY,EMPTY,EMPTY,EMPTY,9,EMPTY,2,EMPTY],
# [8,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,6],
# [EMPTY,6,EMPTY,2,EMPTY,EMPTY,EMPTY,EMPTY,4],
# [7,EMPTY,EMPTY,EMPTY,9,EMPTY,2,EMPTY,EMPTY],
# [EMPTY,EMPTY,1,EMPTY,2,3,9,EMPTY,EMPTY],
# [EMPTY,EMPTY,EMPTY,8,EMPTY,EMPTY,EMPTY,1,3]]
#
#sudoku=Sudoku(game)
#sudoku=sudoku.solve()
#print sudoku.game_state()
#lets try the most difficult: http://news.yahoo.com/solve-hardest-ever-sudoku-133055603--abc-news-topstories.html
# It take a while ;)
difficult=[[8,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY],
[EMPTY,EMPTY,3,6,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY],
[EMPTY,7,EMPTY,EMPTY,9,EMPTY,2,EMPTY,EMPTY],
[EMPTY,5,EMPTY,EMPTY,EMPTY,7,EMPTY,EMPTY,EMPTY],
[EMPTY,EMPTY,EMPTY,EMPTY,4,5,7,EMPTY,EMPTY],
[EMPTY,EMPTY,EMPTY,1,EMPTY,EMPTY,EMPTY,3,EMPTY],
[EMPTY,EMPTY,1,EMPTY,EMPTY,EMPTY,EMPTY,6,8],
[EMPTY,EMPTY,8,5,EMPTY,EMPTY,EMPTY,1,EMPTY],
[EMPTY,9,EMPTY,EMPTY,EMPTY,EMPTY,4,EMPTY,EMPTY]]
sudoku=Sudoku(difficult)
sudoku=sudoku.solve(True)
print sudoku.game_state()
|
[
"[email protected]"
] | |
da581130e8f6f6a50f13b8bec168a81a02799f1e
|
e6ea5bf7db2eb6edd10983b8101fa3e2960026c5
|
/main.py
|
e45aae52a4170dc3a9c94707e1181a7a377d2009
|
[] |
no_license
|
ZamanovArslan/11_703_ZAMANOV
|
3d618afaedd3bbf71a87dd57bf2f87a57d08f6d0
|
66af7b49146ce96c6eac11810b838e3301df32c1
|
refs/heads/master
| 2023-02-08T09:43:05.821587 | 2020-12-28T08:21:58 | 2020-12-28T08:21:58 | 294,627,339 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 546 |
py
|
import pandas as pd
import matplotlib.pyplot as plt
def draw(dataset):
numb = list(data.PassengerId)
p_class = list(dataset.Pclass)
ages = list(dataset.Age)
colors = []
for i in range(0, len(numb)):
if p_class[i] == 1:
colors.append('r')
elif p_class[i] == 2:
colors.append('g')
else:
colors.append('b')
fig, ax = plt.subplots()
ax.bar(numb, ages, color=colors)
plt.show()
data = pd.read_csv("titanic/test.csv")
draw(data)
|
[
"[email protected]"
] | |
ca31e749dfd6ef7361d874037485c67a5ef83fc9
|
e93ef436dd2cfdd8e3badefd721b639838fd9ef5
|
/accounts/views.py
|
67f4ee3dce5fcc597638045a0225282da165e355
|
[] |
no_license
|
sphere-net/spnintra
|
38b2384d43bf73842b59c8b30fd4aa6c1a025651
|
be2edf021733a239bfc3df5da86e1ac372ff4431
|
refs/heads/master
| 2023-08-11T02:57:36.772923 | 2021-10-12T01:22:57 | 2021-10-12T01:22:57 | 414,019,257 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 108 |
py
|
from django.views import generic
class IndexView(generic.TemplateView):
template_name = "accounts.html"
|
[
"[email protected]"
] | |
0f839b18d8c2ddf2a816581790ffe3ed05a65e65
|
da58d7e2296fa2c99b06f88375f723227bed0b39
|
/board.py
|
1de8191fefac6d853bf6c76bb6bc8ca7b105e353
|
[] |
no_license
|
gmiller148/ChessEngine
|
73e30d22e8f237f172129269823708b556779a6d
|
d47ab3ccb7ee15ad66f796eb4b84e3204095646f
|
refs/heads/master
| 2022-03-23T08:12:13.965393 | 2019-12-27T18:57:32 | 2019-12-27T18:57:32 | 48,001,167 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 12,045 |
py
|
from bitstring import BitArray
from textwrap import wrap
import json
with open('resources/bitboards/clear_file.json') as f:
d = json.load(f)
clear_file = {f:BitArray('0x'+h) for f,h in d.items()}
with open('resources/bitboards/clear_rank.json') as f:
d = json.load(f)
clear_rank = {int(r):BitArray('0x'+h) for r,h in d.items()}
with open('resources/bitboards/knight_moves.json') as f:
d = json.load(f)
knight_moves = {int(k):BitArray('0x'+h) for k,h in d.items()}
with open('resources/bitboards/mask_file.json') as f:
d = json.load(f)
mask_file = {f:BitArray('0x'+h) for f,h in d.items()}
with open('resources/bitboards/mask_rank.json') as f:
d = json.load(f)
mask_rank = {int(r):BitArray('0x'+h) for r,h in d.items()}
with open('resources/bitboards/piece.json') as f:
d = json.load(f)
piece = {int(f):BitArray('0x'+h) for f,h in d.items()}
with open('resources/bitboards/king_moves.json') as f:
d = json.load(f)
king_moves = {int(f):BitArray('0x'+h) for f,h in d.items()}
with open('resources/bitboards/rays.json') as f:
d = json.load(f)
rays = {}
for key,sub_d in d.items():
rays[key] = {int(i): BitArray('0x'+j) for i,j in sub_d.items()}
class Board:
def __init__(self, fen=None):
self.fen = fen if fen else 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
self.castling = 'KQkq'
self.white_to_move = True
self.en_passant = '-'
self.half_move = 0
self.full_move = 0
self.make_bitboards()
def make_bitboards(self): # Setup bitboards
self.wpawn = BitArray('0x0000000000000000')
self.bpawn = BitArray('0x0000000000000000')
self.wrook = BitArray('0x0000000000000000')
self.brook = BitArray('0x0000000000000000')
self.wknight = BitArray('0x0000000000000000')
self.bknight = BitArray('0x0000000000000000')
self.wbishop = BitArray('0x0000000000000000')
self.bbishop = BitArray('0x0000000000000000')
self.wqueen = BitArray('0x0000000000000000')
self.bqueen = BitArray('0x0000000000000000')
self.wking = BitArray('0x0000000000000000')
self.bking = BitArray('0x0000000000000000')
setup = self.fen.split(' ')[0]
ranks = setup.split('/')
for i,rank in enumerate(ranks):
j = 0
for char in rank:
if char.isdigit():
j += int(char)
else:
if char == 'r':
self.brook[8*i+j] = 1
elif char == 'n':
self.bknight[8*i+j] = 1
elif char == 'b':
self.bbishop[8*i+j] = 1
elif char == 'q':
self.bqueen[8*i+j] = 1
elif char == 'k':
self.bking[8*i+j] = 1
elif char == 'p':
self.bpawn[8*i+j] = 1
elif char == 'R':
self.wrook[8*i+j] = 1
elif char == 'N':
self.wknight[8*i+j] = 1
elif char == 'B':
self.wbishop[8*i+j] = 1
elif char == 'Q':
self.wqueen[8*i+j] = 1
elif char == 'K':
self.wking[8*i+j] = 1
elif char == 'P':
self.wpawn[8*i+j] = 1
j += 1
self.allwhite = self.wpawn | self.wrook | self.wknight | self.wbishop | self.wqueen | self.wking
self.allblack = self.bpawn | self.brook | self.bknight | self.bbishop | self.bqueen | self.bking
self.all_pieces = self.allwhite | self.allblack
def print_bitboard(self,b): # print a particular bitboard for debugging purposes
print('\n'.join([' '.join(wrap(line, 1)) for line in wrap(b.bin, 8)]))
def make_move(self,move):
if len(move) != 4:
raise IllegalMove(move)
start = move[:2]
end = move[2:]
start_index = self.convert_spot_to_index(start)
end_index = self.convert_spot_to_index(end)
if self.white_to_move:
for piece in self.white:
if piece[start_index]:
piece[start_index] = 0
piece[end_index] = 1
# self.white_to_move = False
def convert_spot_to_index(self,loc):
r = int(loc[1])
f = ord(loc[0]) - 97
return (8-r) * 8 + f
def get_pawn_attacks(self, color):
pawns = self.wpawn if color == 'w' else self.bpawn
if color == 'w':
west_attack = pawns.copy()
west_attack.rol(9)
west_attack = west_attack & (clear_file['h'])
east_attack = pawns.copy()
east_attack.rol(7)
east_attack = east_attack & (clear_file['a'])
return east_attack | west_attack
else:
west_attack = pawns.copy()
west_attack.ror(7)
west_attack = west_attack & (clear_file['h'])
east_attack = pawns.copy()
east_attack.ror(9)
east_attack = east_attack & (clear_file['a'])
return east_attack | west_attack
def get_bishop_moves(self, square, blockers):
attacks = BitArray('0x0000000000000000')
attacks |= rays['NW'][square]
if rays['NW'][square] & blockers:
blockerIndex = bitscan_forward(rays['NW'][square] & blockers)
attacks &= ~rays['NW'][blockerIndex]
attacks |= rays['NE'][square]
if rays['NE'][square] & blockers:
blockerIndex = bitscan_forward(rays['NE'][square] & blockers)
attacks &= ~rays['NE'][blockerIndex]
attacks |= rays['SE'][square]
if rays['SE'][square] & blockers:
blockerIndex = bitscan_reverse(rays['SE'][square] & blockers)
attacks &= ~rays['SE'][blockerIndex]
attacks |= rays['SW'][square]
if rays['SW'][square] & blockers:
blockerIndex = bitscan_reverse(rays['SW'][square] & blockers)
attacks &= ~rays['SW'][blockerIndex]
return attacks
def get_rook_moves(self, square, blockers):
attacks = BitArray('0x0000000000000000')
attacks |= rays['N'][square]
if rays['N'][square] & blockers:
blockerIndex = bitscan_forward(rays['N'][square] & blockers)
attacks &= ~rays['N'][blockerIndex]
attacks |= rays['W'][square]
if rays['W'][square] & blockers:
blockerIndex = bitscan_forward(rays['W'][square] & blockers)
attacks &= ~rays['W'][blockerIndex]
attacks |= rays['E'][square]
if rays['E'][square] & blockers:
blockerIndex = bitscan_reverse(rays['E'][square] & blockers)
attacks &= ~rays['E'][blockerIndex]
attacks |= rays['S'][square]
if rays['S'][square] & blockers:
blockerIndex = bitscan_reverse(rays['S'][square] & blockers)
attacks &= ~rays['S'][blockerIndex]
return attacks
def get_queen_moves(self, square, blockers):
return self.get_bishop_moves(square,blockers) | self.get_rook_moves(square,blockers)
def get_knight_moves(self, square, blockers):
return knight_moves[square] & ~blockers
def get_king_moves(self, color):
if color == 'w':
king_loc = bitscan_forward(self.wking)
bishop_locs = bitscan_all(self.bbishop)
rook_locs = bitscan_all(self.brook)
queen_locs = bitscan_all(self.bqueen)
knight_locs = bitscan_all(self.bknight)
pawn_attacks = self.get_pawn_attacks('b')
all_except_king = self.all_pieces & ~self.wking
opp_king_loc = bitscan_forward(self.bking)
attacks = BitArray('0x0000000000000000')
for bishop_loc in bishop_locs:
attacks |= self.get_bishop_moves(bishop_loc,all_except_king)
for rook_loc in rook_locs:
attacks |= self.get_rook_moves(rook_loc,all_except_king)
for queen_loc in queen_locs:
attacks |= self.get_queen_moves(queen_loc,all_except_king)
for knight_loc in knight_locs:
attacks |= self.get_knight_moves(knight,all_except_king)
attacks |= king_moves[opp_king_loc] & ~all_except_king
attacks |= pawn_attacks
print_bitboard(attacks)
return king_moves[king_loc] & ~attacks
def king_evasions(self, color):
if color == 'w':
king_loc = self.bitscan_forward(self.wking)
opp_bishops = self.bbishop.copy()
opp_knights = self.bknight.copy()
opp_rooks = self.brook.copy()
opp_queens = self.bqueen.copy()
else:
king_loc = self.bitscan_forward(self.bking)
opp_bishops = self.wbishop.copy()
opp_knights = self.wknight.copy()
opp_rooks = self.wrook.copy()
opp_queens = self.wqueen.copy()
blockers = self.all_pieces.copy()
attackers = BitArray('0x0000000000000000')
attackers |= knight_moves[king_loc] & opp_knights
attackers |= self.get_bishop_moves(king_loc, blockers) & opp_bishops
attackers |= self.get_rook_moves(king_loc, blockers) & opp_rooks
attackers |= self.get_queen_moves(king_loc, blockers) & opp_queens
def bitscan_forward(bs): # start at h1 and scan toward a8
return 63 - bs.rfind('0b1')[0]
def bitscan_reverse(bs): # start at a8 and scan toward h1
return 63 - bs.find('0b1')[0]
def bitscan_all(bs):
return [63 - x for x in bs.findall('0b1')]
def print_bitboard(b): # print a particular bitboard for debugging purposes
print('\n'.join([' '.join(wrap(line, 1)) for line in wrap(b.bin.replace('0','.'), 8)]))
def compute_king(king_loc):
king_clip_h = king_loc & clear_file['h']
king_clip_a = king_loc & clear_file['a']
spot_1 = king_clip_a << 9
spot_2 = king_loc << 8
spot_3 = king_clip_h << 7
spot_4 = king_clip_h >> 1
spot_5 = king_clip_h >> 9
spot_6 = king_loc >> 8
spot_7 = king_clip_a >> 7
spot_8 = king_clip_a << 1
return spot_1 | spot_2 | spot_3 | spot_4 | spot_5 | spot_6 | spot_7 | spot_8
def compute_knight(knight_loc):
"""
. 2 . 3 .
1 . . . 4
. . N . .
8 . . . 5
. 7 . 6 .
"""
spot_1_clip = clear_file['a'] & clear_file['b'] & clear_rank[8]
spot_2_clip = clear_file['a'] & clear_rank[8] & clear_rank[7]
spot_3_clip = clear_file['h'] & clear_rank[8] & clear_rank[7]
spot_4_clip = clear_file['h'] & clear_file['g'] & clear_rank[8]
spot_5_clip = clear_file['h'] & clear_file['g'] & clear_rank[1]
spot_6_clip = clear_file['h'] & clear_rank[1] & clear_rank[2]
spot_7_clip = clear_file['a'] & clear_rank[1] & clear_rank[2]
spot_8_clip = clear_file['a'] & clear_file['b'] & clear_rank[1]
spot_1 = (knight_loc & spot_1_clip) << 10
spot_2 = (knight_loc & spot_2_clip) << 17
spot_3 = (knight_loc & spot_3_clip) << 15
spot_4 = (knight_loc & spot_4_clip) << 6
spot_5 = (knight_loc & spot_5_clip) >> 10
spot_6 = (knight_loc & spot_6_clip) >> 17
spot_7 = (knight_loc & spot_7_clip) >> 15
spot_8 = (knight_loc & spot_8_clip) >> 6
return spot_1 | spot_2 | spot_3 | spot_4 | spot_5 | spot_6 | spot_7 | spot_8
class Error(Exception):
pass
class IllegalMove(Error):
pass
if __name__ == '__main__':
k = BitArray('0x0000010000000000')
fen = '4k3/8/8/8/2b1r3/8/4K3/8 w - - 0 1'
b = Board(fen)
print()
print_bitboard(b.all_pieces)
print()
a = b.get_king_moves('w')
print_bitboard(a)
print(a.int)
# print_bitboard()
# k = rays['NE'][2]
# print_bitboard(k)
# print([63 - x for x in k.findall('0b1')])
|
[
"[email protected]"
] | |
616469de1aec009732d1ae11d1d7737bda848a16
|
75a2d464d10c144a6226cb5941c86423a1f769cf
|
/users/views.py
|
21cc73b926aab722ac47e1f4965cdb0561c47aff
|
[] |
no_license
|
Swiftkind/invoice
|
f5543cbe81b6d42e9938470265d7affb56ab83dd
|
17615ea9bfb1edebe41d60dbf2e977f0018d5339
|
refs/heads/master
| 2021-09-07T18:16:01.647083 | 2018-02-08T08:13:18 | 2018-02-08T08:13:18 | 115,474,697 | 0 | 3 | null | 2018-02-27T06:58:42 | 2017-12-27T02:55:40 |
Python
|
UTF-8
|
Python
| false | false | 5,494 |
py
|
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.http import Http404
from django.shortcuts import get_object_or_404, render, redirect
from django.views.generic import TemplateView
from django.views import View
from users.forms import CompanyForm, UserChangePasswordForm, UserUpdateForm, SigninForm, SignupForm
from users.mixins import UserIsOwnerMixin
from users.models import Company, User
class SigninView(TemplateView):
"""Signin user
"""
template_name = 'users/signin.html'
def get(self, *args, **kwargs):
"""Get signin form
"""
if self.request.user.is_authenticated:
return redirect('index')
form = SigninForm()
return render(self.request, self.template_name,{'form':form})
def post(self, *args, **kwargs):
"""Signin user
"""
form = SigninForm(data=self.request.POST)
if form.is_valid():
login(self.request, form.user_cache)
return redirect('index')
else:
context={ 'form':form,}
return render(self.request, self.template_name, context)
class SignupView(TemplateView):
"""Signup user
"""
template_name = 'users/signup.html'
def get(self, *args, **kwargs):
"""Display signup form
"""
context = { 'company_form' : CompanyForm(),
'signup_form' : SignupForm(),
}
return render(self.request, self.template_name, context)
def post(self, *args, **kwargs):
company_form = CompanyForm(self.request.POST, self.request.FILES)
signup_form = SignupForm(self.request.POST, self.request.FILES)
if signup_form.is_valid() and company_form.is_valid():
company = company_form.save(commit=False)
user = signup_form.save(commit=False)
company.save()
user.company = company
user.save()
messages.error(self.request, 'Account successfully created. Activate your account from the admin.')
return redirect('index')
else:
context = { 'company_form' : CompanyForm(self.request.POST),
'signup_form' : SignupForm(self.request.POST),
}
return render(self.request, self.template_name, context)
class SignoutView(LoginRequiredMixin, View):
"""Signout a user
"""
def get(self, *args, **kwargs):
"""Logout user and redirect to signin
"""
logout(self.request)
return redirect('signin')
class UserProfileView(UserIsOwnerMixin, TemplateView):
"""User profile
"""
template_name = 'users/profile.html'
def get(self, *args, **kwargs):
"""View user details
"""
context = {'user': get_object_or_404(User, pk=kwargs['user_id'])}
return render(self.request, self.template_name, context=context)
class UserUpdateView(UserIsOwnerMixin, TemplateView):
"""Update User
"""
template_name = 'users/update_user.html'
def get(self, *args, **kwargs):
"""Display form
"""
user = get_object_or_404(User, pk=kwargs['user_id'])
if self.request.user == user:
context = { 'company_form':CompanyForm(instance=user.company),
'user_form': UserUpdateForm(instance=user),
}
return render(self.request, self.template_name, context=context)
else:
raise Http404("Does not exist")
def post(self, request, *args, **kwargs):
"""Update a user
"""
user = get_object_or_404(User, pk=kwargs['user_id'])
user_form = UserUpdateForm(self.request.POST, self.request.FILES,instance=user)
company_form = CompanyForm(self.request.POST, self.request.FILES,instance=user.company)
if user_form.is_valid() and company_form.is_valid():
company_form.save()
user_form.save()
messages.success(self.request, 'User is successfully updated')
return redirect('index' )
else:
context = { 'company_form': company_form,
'user_form' : user_form,
}
return render(self.request, self.template_name, context=context)
class UserSettingView(UserIsOwnerMixin, TemplateView):
""" User settings
"""
template_name = 'users/setting.html'
def get(self, *args, **kwargs):
""" View setting
"""
return render(self.request, self.template_name)
class UserChangePassword(UserIsOwnerMixin, TemplateView):
""" User change password
"""
template_name = 'users/change_password.html'
def get(self, *args, **kwargs):
""" Change password form
"""
context = {}
context['form'] = UserChangePasswordForm()
return render(self.request, self.template_name, context)
def post(self, *args, **kwargs):
""" Check old and new password match
"""
form = UserChangePasswordForm(self.request.POST, user=self.request.user)
if form.is_valid():
form.save()
return redirect('index')
else:
context = {}
context['form'] = UserChangePasswordForm(self.request.POST, user=self.request.user)
return render(self.request, self.template_name, context)
|
[
"[email protected]"
] | |
9cdc3025395648558462f4da510485dbf2aeaf70
|
54a8bb0d3ea49bbbdebc6deb7db8cbdb6f3063f2
|
/Node.py
|
c9ff286d2bc6dc5e8bbb3a1af21ce884f009731e
|
[] |
no_license
|
adolfdcosta91/CSMASimulator
|
beaf9f4aad7fe83b25cb058669e81ab925fb31eb
|
be7bc2a186801685072beb4f2056f35f72d4c0c8
|
refs/heads/master
| 2020-05-15T20:06:46.482776 | 2020-05-07T07:17:05 | 2020-05-07T07:17:05 | 182,473,249 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,494 |
py
|
from random import *
from collections import deque
import Packet
class Node:
def __init__(self, identity_ip, buffer_size, gen_prob, total_nodes_in_system, randomization_ceiling, max_retrans_count_until_drop):
self.identity_ip = identity_ip
self.buffer_size = buffer_size
self.buffer = deque([], buffer_size) # initialize all the elements with -1
self.gen_prob = gen_prob
self.total_nodes_in_system = total_nodes_in_system
self.max_retrans_count_until_drop = max_retrans_count_until_drop
self.randomization_ceiling = randomization_ceiling
self.back_off_time = 0
self.num_of_collisions = 0
self.lost_packet_count = 0 # due to buffer overflows
self.num_of_gen_packets = 0
self.num_of_retrans_packets = 0
self.success_trans_packet_count = 0
self.num_of_retrans_attempts = 0
self.facedCollision = False
self.num_of_delayed_slots = 0
self.consecutive_collisions = 0
def gen_packet_with_prob(self, generation_timeslot):
allowable_upper_bound = (self.gen_prob * 100)
rand_int = randint(1, 100)
if rand_int <= allowable_upper_bound:
# packet generated
self.num_of_gen_packets += 1
identity = 'Node '
identity += str(randint(1, self.total_nodes_in_system))
new_packet = Packet.Packet(self.identity_ip, identity, generation_timeslot)
# insert in buffer if not full
if len(self.buffer) == self.buffer.maxlen:
# buffer size is full, so the packet is dropped, increase dropped packet count
self.lost_packet_count += 1
else:
self.buffer.append(new_packet)
def book_keeping_after_suc_trans(self, trans_timeslot):
# packet transmitted
print("successful transmission")
self.success_trans_packet_count += 1
# turn off faced collision flag
if self.facedCollision:
self.facedCollision = False
self.num_of_retrans_packets += 1
# remove from buffer
transmitted_packet = self.buffer.popleft()
# update packet retransmission attempts
self.num_of_retrans_attempts += transmitted_packet.retrans_count
# update delay variable
self.num_of_delayed_slots += trans_timeslot - transmitted_packet.gen_time_slot
# update consecutive collisions variable
self.consecutive_collisions = 0
def book_keeping_after_collision(self):
# increase collision count
self.num_of_collisions += 1
# turn on faced collision flag
self.facedCollision = True
# change retransmission count for the collided packet
self.buffer[0].retrans_count += 1
# change backoff time
exp = min(self.randomization_ceiling, self.num_of_collisions)
result = (2 ** exp) - 1
self.back_off_time = randint(0, result)
# change consecutive collisions count
if self.consecutive_collisions > 0:
self.consecutive_collisions += 1
if self.consecutive_collisions == self.max_retrans_count_until_drop:
# packet is dropped due to consecutive collisions
# remove from buffer
self.buffer.popleft()
# update consecutive collisions variable
self.consecutive_collisions = 0
# update lost packet count
self.lost_packet_count += 1
|
[
"[email protected]"
] | |
a43370084f8aed4b85f5604907aaff3a544de79d
|
d77d799cf6c72e1299701f45693e146c338e4064
|
/blog/views.py
|
2462594f06079b0a2fd91af472b47b712ec8eb71
|
[] |
no_license
|
Jonathanifpe/my-first-blog
|
257c6c6a4972712b9ba4749b9160c58fb7b48df5
|
c03c571207a61924888d27f8a48d7a1d0b660879
|
refs/heads/master
| 2021-04-12T05:50:15.911921 | 2017-06-28T21:59:44 | 2017-06-28T21:59:44 | 95,694,568 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 709 |
py
|
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
# Como views.py e models.py estão no mesmo diretório podemos simplesmente usar . e o nome do arquivo (sem .py).
from .models import Post
# Create your views here.
def post_list(request):
#Pegar a lista de posts que foram publicados
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
#Retornar os posts publicados (passando o resultado para o template)
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail (request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
|
[
"[email protected]"
] | |
deceaf4cc9be6fae32b19e5d1db623f9aef157be
|
462b971c675aa7a0476f645a9f29f21da4612f75
|
/src/canny.py
|
92b9cd4c74f6897d9be983f2960fe650eb503eb3
|
[] |
no_license
|
CDDzhang/horizon_
|
ddc048e9d0352f20a2e835390ac1b9470f25c131
|
79c0676bde875f3309d2c3c7460f3afb2e766554
|
refs/heads/master
| 2022-11-14T02:25:05.661980 | 2020-06-29T08:08:42 | 2020-06-29T08:08:42 | 275,770,010 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 682 |
py
|
import cv2
import numpy as np
import src.blur as blur
def img_canny(img):
img = img
# img = img[100:1600,375:1500]
img1 = cv2.resize(img, (640, 480))
img = img1
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# filter:
img = blur.blur(img, Blurnum=3)
ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
sure_bg = cv2.dilate(opening, kernel, iterations=5)
sure_bg = cv2.erode(sure_bg,kernel,iterations=3)
img = sure_bg
# canny_extra
img = cv2.Canny(img, 50, 150)
return img,img1
|
[
"[email protected]"
] | |
631e33fe35bf9b382cc076142b56410f9f925c6f
|
e60a342f322273d3db5f4ab66f0e1ffffe39de29
|
/parts/zodiac/pyramid/tests/pkgs/fixtureapp/views.py
|
a42b58217f01e42d42c80a658be0d1bc8c543933
|
[] |
no_license
|
Xoting/GAExotZodiac
|
6b1b1f5356a4a4732da4c122db0f60b3f08ff6c1
|
f60b2b77b47f6181752a98399f6724b1cb47ddaf
|
refs/heads/master
| 2021-01-15T21:45:20.494358 | 2014-01-13T15:29:22 | 2014-01-13T15:29:22 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 89 |
py
|
/home/alex/myenv/zodiac/eggs/pyramid-1.4-py2.7.egg/pyramid/tests/pkgs/fixtureapp/views.py
|
[
"[email protected]"
] | |
531a0f2971c9916a90111d7a3a60c5b3108c54c3
|
f8ac7433544a364b5da918c7c3d64289600a92be
|
/notebooks/mean_field_model.py
|
23b1ae32fccf08a8608a1a39c0ca269f37f82ad7
|
[] |
no_license
|
btel/ei_ephaptic_model
|
c2af9e48349124051c4240e588ad3a220a694999
|
a2dee563b99c76202335031cacd846f083996db1
|
refs/heads/master
| 2023-02-20T22:22:33.829700 | 2021-01-08T09:44:17 | 2021-01-08T09:44:17 | 154,492,711 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,580 |
py
|
#!/usr/bin/env python
#coding=utf-8
import numpy as np
from scipy import special
from scipy import optimize
#SI base units
s = 1
kg = 1
m = 1
A = 1
#derived units
S = s**3*A**2/(kg*m**2)
V = kg*m**2*s**-3*A**-1
F = s**4 * A**2 * m**-2 * kg ** -1
Hz = 1/s
#with prefixes
nS = 1e-9 * S
uS = 1e-6 * S
mV = 1e-3 * V
pF = 1e-12 * F
ms = 1e-3 * s
nA = 1e-9 * A
pA = 1e-12 * A
# constants
dt = 10 * ms
E_e = 0*mV
E_i = -75*mV
E_l = -70*mV
g_l = 1./60*uS
C = 250*pF
v_reset = -60*mV
threshold = -50*mV
threshold_inh = -53 * mV
tau_ref = 2*ms
tau_e = 0.2 * ms # width of excitatory PSC (ms)
tau_i = 2 * ms # width of inhibitory PSC (ms)
B_e = 7.1 * nS # peak excitatory conductance (nS)
B_i = 3.7 * nS # peak inhibitory conductance (nS)
fr_e = 9655 * Hz # total firing rate of excitatory population (Hz)
fr_i = 4473 * Hz # total firing rate of excitatory population (Hz)
f_ext = 5000 * Hz # etracellular_firing_rate
n_e = 350. # number of excitatory neurons
n_i = n_e / 4. # number of inhibitory neurons
def calc_membrane_stats(fr_e=fr_e, fr_i=fr_i):
mu_ge = fr_e * B_e * tau_e * np.exp(1)
mu_gi = fr_i * B_i * tau_i * np.exp(1)
gtot = g_l + mu_ge + mu_gi
mu_u = (E_l * g_l + E_e * mu_ge + E_i * mu_gi) / gtot
tau_eff = C / gtot
epsp_int = (E_e - mu_u) * B_e * tau_e * np.exp(1) * tau_eff / C
ipsp_int = (E_i - mu_u) * (B_i * tau_i * np.exp(1) * tau_eff / C)
epsp_sq = epsp_int ** 2 * (2 * tau_eff + tau_e) /(4 * (tau_eff + tau_e)**2)
ipsp_sq = ipsp_int ** 2 * (2 * tau_eff + tau_i) /(4 * (tau_eff + tau_i)**2)
sigma_sq_u = fr_e * epsp_sq + fr_i * ipsp_sq
return gtot, mu_u, tau_eff, sigma_sq_u
def kuhn_transfer_function(tau_eff, threshold, mu_u, sigma_sq_u):
return 1. /(2 * tau_eff) * special.erfc((threshold - mu_u) / (np.sqrt(2) * np.sqrt(sigma_sq_u)))
def derivative_kuhn_transfer_function(tau_eff, threshold, mu_u, sigma_sq_u):
return 1. /(2 * tau_eff * np.sqrt(2 * sigma_sq_u)) * (2/ np.sqrt(np.pi)) * np.exp(-(threshold - mu_u) ** 2 / (2 * sigma_sq_u))
def calc_output_rate_inh_exc(fr_e, fr_i, n_e, n_i, threshold_exc=-50 * mV, threshold_inh=-50 * mV):
gtot_exc, mu_u_exc, tau_eff_exc, sigma_sq_u_exc = calc_membrane_stats(fr_e=fr_e, fr_i=fr_i)
gtot_inh, mu_u_inh, tau_eff_inh, sigma_sq_u_inh = calc_membrane_stats(fr_e=fr_e, fr_i=fr_i)
rexc = kuhn_transfer_function(tau_eff_exc, threshold_exc, mu_u_exc, sigma_sq_u_exc)
rinh = kuhn_transfer_function(tau_eff_inh, threshold_inh, mu_u_inh, sigma_sq_u_inh)
return rexc * n_e, rinh * n_i
|
[
"[email protected]"
] | |
44e65597c9d09c9e6d7df09034df211ec77c6bb7
|
8083f3819e4dbdd134f6a636020c5e89053c3ad8
|
/shop/migrations/0005_orders_amount.py
|
07bd8afd74822dd1fd4eba16280385b574652a08
|
[] |
no_license
|
vikasmauryaofficial/buyfromhome
|
c0c8ef763202ce04509c2e855c5f34cce177e5b0
|
ed2ab1f64eb1faf07782b5181fb035bcd9bbcc0a
|
refs/heads/master
| 2022-12-05T14:02:09.726222 | 2020-08-19T15:59:07 | 2020-08-19T15:59:07 | 258,971,109 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 380 |
py
|
# Generated by Django 3.0.4 on 2020-04-25 15:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_orders_orderupdate'),
]
operations = [
migrations.AddField(
model_name='orders',
name='amount',
field=models.IntegerField(default=0),
),
]
|
[
"[email protected]"
] | |
f46600e041a9e3fa1eb90c0961f25917ad284329
|
e95fc8c562c050f47ecb6fb2639ce3024271a06d
|
/medium/46.全排列.py
|
60bd223afd3aaf74a76e0693f8cd590cbe521c1d
|
[] |
no_license
|
w940853815/my_leetcode
|
3fb56745b95fbcb4086465ff42ea377c1d9fc764
|
6d39fa76c0def4f1d57840c40ffb360678caa96e
|
refs/heads/master
| 2023-05-25T03:39:32.304242 | 2023-05-22T01:46:43 | 2023-05-22T01:46:43 | 179,017,338 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,032 |
py
|
#
# @lc app=leetcode.cn id=46 lang=python3
#
# [46] 全排列
#
# @lc code=start
from typing import List
"""
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择
"""
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
track = []
def backtrack(track, nums):
if len(track) == len(nums):
# 列表深拷贝
tmp = list(track)
res.append(tmp)
return
for i in range(len(nums)):
if nums[i] in track:
continue
track.append(nums[i])
backtrack(track, nums)
track.pop()
backtrack(track, nums)
return res
if __name__ == "__main__":
s = Solution()
res = s.permute([1, 2, 3])
print(res)
# @lc code=end
|
[
"[email protected]"
] | |
02cdb66616bdde2dfae11f96162149ab105ca015
|
dae129b83f5635e2ded9d6a9f97a15c3953a4c96
|
/project.py
|
69dbb0b76dca3d40ee6f91da7f4a88c9da63a141
|
[] |
no_license
|
barkev2009/Mini-Projects
|
3584e6757595ac96f6a08c9f24e87773858d3a9f
|
57bfc79b44627c433d1d7692b560d43571d5c493
|
refs/heads/master
| 2020-08-11T03:36:36.951408 | 2019-10-20T14:01:05 | 2019-10-20T14:01:05 | 214,483,348 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,394 |
py
|
from datetime import date
# Printing the heading
print('''"Вояджер-1" был запущен 5 сентября 1977 года.
Предлагаем узнать примерное расстояние от зонда до Солнца на выбранную Вами дату,
предполагая, что зонд движется по прямой, с постоянной скоростью.''')
# Setting the velocity
velocity = 38241 # miles/hour
lag_vel = 299792458 # meters/sec
# Recording the current date
input_date = input('\nВведите дату в формате дд.мм.гггг: ')
print('')
now_date = list(input_date)
now_day = int(now_date[0] + now_date[1])
now_mon = int(now_date[3] + now_date[4])
now_year = int(now_date[6] + now_date[7] + now_date[8] + now_date[9])
now_date1 = date(now_year, now_mon, now_day)
# Setting the constant dates
date_init = date(1977, 9, 5)
# Calculating the parameters
days = (now_date1 - date_init).days
miles = velocity * days * 24
kms = miles * 1.609
aster_uns = kms / 149598100
i = 0
while True:
i += 1
if i >= 4:
print('Если хотите закончить программу, нажмите q.')
choice = input('В каком измерении хотите получить расстояние (км/мили/ае)? ')
if days < 0:
print('\nВы ввели дату более раннюю, чем дата запуска "Вояджера".')
else:
if choice == 'км':
print('\nНа {} '.format(input_date) +
'зонд прошел расстояние в {:,.0f} километров.'.format(kms).replace(',', ' '))
break
elif choice == 'мили':
print('\nНа {} '.format(input_date) +
'зонд прошел расстояние в {:,.0f} миль.'.format(miles).replace(',', ' '))
break
elif choice == 'ае':
print('\nНа {} '.format(input_date) +
'зонд прошел расстояние в {:,.0f} астрономических единиц.'.format(aster_uns).replace(',', ' '))
break
elif choice == 'q' or choice == 'й':
break
else:
print('\nВы ввели неправильное измерение.')
|
[
"[email protected]"
] | |
9e14947217a3b89187ed7b08faf9ab8095a03563
|
85a03f8c79cc2092709e7be55f8d63db1949df92
|
/oldmain.py
|
7e3912019f097631c654eca810519fef10c0f987
|
[] |
no_license
|
GeraAlcantara/pinchef
|
f3570664929a506cc4810598bc42b19081cd058d
|
2379820a50cef6687e3905e14cc7f6f0a34ec65f
|
refs/heads/master
| 2023-08-11T06:30:38.811606 | 2021-10-10T17:38:44 | 2021-10-10T17:38:44 | 412,414,537 | 1 | 1 | null | 2021-10-06T19:07:29 | 2021-10-01T10:00:26 |
Python
|
UTF-8
|
Python
| false | false | 4,126 |
py
|
# proceso de Oauth2 login
from datetime import datetime, timedelta
from typing import Optional
import os
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
# read env variables
load_dotenv()
SECRET_KEY = os.getenv("SECRET_KEY")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "[email protected]",
"hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
"disabled": False,
}
}
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None
class User(BaseModel):
username: str
email: Optional[str] = None
full_name: Optional[str] = None
disabled: Optional[bool] = None
class UserInDB(User):
hashed_password: str
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def get_user(db, username: str):
if username in db:
user_dict = db[username]
return UserInDB(**user_dict)
def authenticate_user(fake_db, username: str, password: str):
user = get_user(fake_db, username)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenData(username=username)
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: User = Depends(get_current_user)):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(
fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me/", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
return current_user
@app.get("/users/me/items/")
async def read_own_items(current_user: User = Depends(get_current_active_user)):
return [{"item_id": "Foo", "owner": current_user.username}]
|
[
"[email protected]"
] | |
b259e075e6f57daf45d84ef30bc00fdb2c29c3b9
|
3dac960cd8cb0efa6ae726fc96e0748234f5437d
|
/03python-books/python3-cookbook/第一章:数据结构和算法/1.7 字典排序.py
|
f6ab72e2bcd24eb2abd367f59900b072ef6e994f
|
[] |
no_license
|
nebofeng/python-study
|
352b805163b3c81bee3d37f9240e336b6b5bd246
|
18c07f4ba44c9f35325e07a1c8c2984cab9abd34
|
refs/heads/master
| 2020-03-27T08:52:50.669866 | 2019-11-18T05:18:30 | 2019-11-18T05:18:30 | 146,294,997 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,413 |
py
|
#你想创建一个字典,并且在迭代或序列化这个字典的时候能够控制元素的顺序。
#为了能控制一个字典中元素的顺序,你可以使用 collections 模块中的 OrderedDict 类。
#在迭代操作的时候它会保持元素被插入时的顺序,示例如下
from collections import OrderedDict
d=OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 5
d['grok'] = 4
# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
for key in d:
print(key, d[key])
#当你想要构建一个将来需要序列化或编码成其他格式的映射的时候, OrderedDict 是非常有用的。
# 比如,你想精确控制以 JSON 编码后字段的顺序,你可以先使用 OrderedDict 来构建这样的数据
import json
json.dumps(d)
'''
OrderedDict 内部维护着一个根据键插入顺序排序的双向链表。每次当一个新的元素插入进来的时候,
它会被放到链表的尾部。对于一个已经存在的键的重复赋值不会改变键的顺序。需要注意的是,一个
OrderedDict 的大小是一个普通字典的两倍,因为它内部维护着另外一个链表。所以如果你要构建一个
需要大量 OrderedDict 实例的数据结构的时候(比如读取 100,000 行 CSV 数据到一个 OrderedDict 列表中去),
那么你就得仔细权衡一下是否使用 OrderedDict 带来的好处要大过额外内存消耗的影响。
'''
|
[
"[email protected]"
] | |
eb4dcb0695216b1e4c121149f2ed15f123a1e73f
|
5e6df6fe5430728428339fba5f4cc1b3bada3912
|
/matcherScriptTwo.py
|
aced1d930aa337f5ec9e1fa67555a97765a72f0f
|
[] |
no_license
|
MFredX/Honours-Scripts
|
0f411f3620d1ffd508feea17f66f4a1843924e5e
|
7a9b4e17472e0cd10c755d7571b5e889deb8aeef
|
refs/heads/master
| 2022-10-16T13:43:02.726561 | 2020-06-12T13:24:45 | 2020-06-12T13:24:45 | 271,802,743 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,900 |
py
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 21:43:13 2020
@author: sachi
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 10
img1 = cv2.imread('./Training/croppedDrive.jpg',0) # queryImage
img2 = cv2.imread('./Training/croppedLob.jpg',0) # trainImage
# Initiate SIFT detector
sift = cv2.xfeatures2d.SIFT_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1,des2,k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
if len(good)>MIN_MATCH_COUNT:
src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
matchesMask = mask.ravel().tolist()
h,w = img1.shape
pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
dst = cv2.perspectiveTransform(pts,M)
img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA)
print ("Enough matches are found. COUNT:", len(good)," MIN:",MIN_MATCH_COUNT)
else:
print ("Not enough matches are found. COUNT:", len(good)," MIN:",MIN_MATCH_COUNT)
matchesMask = None
draw_params = dict(matchColor = (0,255,0), # draw matches in green color
singlePointColor = None,
matchesMask = matchesMask, # draw only inliers
flags = 2)
img3 = cv2.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)
plt.imshow(img3, 'gray'),plt.show()
|
[
"[email protected]"
] | |
07f3f67d6f6f29eb55237b53dbf86e7f620319bd
|
aae1a200625dc357f8906f6b4532e041bd13e638
|
/paml_parser.py
|
1212bb9df23b121d129f5e44e5bb4da4c1165328
|
[
"MIT"
] |
permissive
|
prakashraaz/bootcamp_test
|
1b2473c41f54a2b2f921efce9684a46b4cde4e2b
|
c664b4b6ff304009924c5680cc6f0c84c75833d3
|
refs/heads/master
| 2021-01-09T20:32:18.313764 | 2016-06-10T13:54:47 | 2016-06-10T13:54:47 | 60,851,030 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,814 |
py
|
# PAMLparser. Outputs useful data from PAML outputs (baseml and codeml) in a
# tab-delimited form, readable by Excel, etc.
#! /usr/bin/env python
import sys
import re
Usage = """
You must give a file, and provide an output file name.
E.g., "paml_parser.py examplebaseml.output > cleanSummary.txt"
"""
# User inputs file name at time the program is called
if len(sys.argv)<2:
sys.stderr.write(Usage)
exit()
InFileName= sys.argv[1]
trees = []
text = ""
InFile = open(InFileName, 'r')
for line in InFile:
if (re.match('^TREE', line)):
trees.append(text)
text = ""
text = text + line
trees.pop(0)
# The following list contains regular expressions for the parts of the paml
# outputs that were of interest to
# Rothfels & Schuettpelz 2013 -- Accelerated Rate of Molecular Evolution for
# Vittarioid Ferns is Strong and Not Due to Selection. Sys Bio.
# Users should add or remove items to suit their specific needs.
SearchStr_TREE='^(TREE) #\s*(\d*)'
SearchStr_GeneNum='(Gene .+)'
SearchStr_Ln='lnL\(ntime: (\d\d) np:\s+(\d\d)\):\s+(-\d+\.\d+)'
SearchStr_rates='(rates.*)\:\s+(1)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)' #The number of repeats here needs to be changed to match the
# number of partitions...
SearchStr_prop='(proportion)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)'
SearchStr_branch='(branch type \d:)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)'
SearchStr_bgRates3='Rates for branch groups\n*\r*\s\s\s\s([\d\.]+)\s\s\s\s([\d\.]+)\s\s\s\s([\d\.]+)' #There are two
# of these because some of my runs have three clocks and some have four
SearchStr_bgRates4='Rates for branch groups\n*\r*\s\s\s\s([\d\.]+)\s\s\s\s([\d\.]+)\s\s\s\s([\d\.]+)\s\s\s\s([\d\.]+)'
SearchStr_ps='p:\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)'
SearchStr_ws='w:\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)'
SearchStr_wBnchMod3='w\s.+for branches: ([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\n'
SearchStr_wBnchMod4='w\s.+for branches: ([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)'
outputstring=""
for tree in trees:
#print "TREE RECORD"
#Tree Number
Result = re.search(SearchStr_TREE, tree) # Get the (captured) character
# groups from the search
if Result:
outputstring = outputstring + '\n\t\t%s %s\t\t\t' % (Result.group(1),Result.group(2))
#Likelihood and parameter number, etc
Result = re.search(SearchStr_Ln, tree)
if Result:
outputstring = outputstring + '%s\t%s\t\t%s\t\t\t' % (Result.group(1),Result.group(2),Result.group(3))
# I can't get these Branchgroup ones to work, for some reason. A
# complication in how python deals with \n and/or \r?
#Branchgroup rates for three clocks
Result = re.search(SearchStr_bgRates3, tree)
if Result:
outputstring = outputstring + '%s\t%s\t%s\t' % (Result.group(1),Result.group(2),Result.group(3))
#Branchgroup rates for four clocks
Result = re.search(SearchStr_bgRates4, tree)
if Result:
outputstring = outputstring + '%s\t%s\t%s\t%s\t' % (Result.group(1),Result.group(2),Result.group(3),Result.group(4))
#Rates
Result = re.search(SearchStr_rates, tree)
if Result:
outputstring = outputstring + '%s\t%s\t%s\t%s\t%s\t%s\t%s\t\t' % (Result.group(1),Result.group(2),Result.group(3),Result.group(4),Result.group(5),Result.group(6),Result.group(7)) #again, needs to match the number of
# partitions
#Proportions
Result = re.search(SearchStr_prop, tree)
if Result:
outputstring = outputstring + '%s\t%s\t%s\t%s\t' % (Result.group(1),Result.group(2),Result.group(3),Result.group(4))
#Proportions for codeml model 2a
Result = re.search(SearchStr_ps, tree)
if Result:
outputstring = outputstring + 'proportions\t%s\t%s\t%s\t' % (Result.group(1),Result.group(2),Result.group(3))
#Omegas for codeml model 2a
Result = re.search(SearchStr_ws, tree)
if Result:
outputstring = outputstring + '\t%s\t%s\t%s\t' % (Result.group(1),Result.group(2),Result.group(3))
#Omegas for codeml branch models, three clades
Result = re.search(SearchStr_wBnchMod3, tree)
if Result:
outputstring = outputstring + '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t%s\t%s\t%s\t' % (Result.group(1),Result.group(2),Result.group(3))
#Omegas for codeml branch models, four clades
Result = re.search(SearchStr_wBnchMod4, tree)
if Result:
outputstring = outputstring + '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t%s\t%s\t%s\t%s\t' % (Result.group(1),Result.group(2),Result.group(3),Result.group(4))
#Branch Types --This one is slightly different from the others (it has the
# .join(x), etc.) because there are multiple lines starting with
" # branch type" within each "TREE" loop, and they need to
# get concatenated together
Result = re.findall(SearchStr_branch, tree)
if Result:
for x in Result:
outputstring = outputstring + "\t".join(x) + "\t"
print outputstring
|
[
"[email protected]"
] | |
40d415f635b35add767833905aef591e6990c7bb
|
3c000380cbb7e8deb6abf9c6f3e29e8e89784830
|
/venv/Lib/site-packages/cobra/modelimpl/bgp/bgprtprefixcounthist1year.py
|
71ca4307f2d3906eb50252edabe8f510d7043377
|
[] |
no_license
|
bkhoward/aciDOM
|
91b0406f00da7aac413a81c8db2129b4bfc5497b
|
f2674456ecb19cf7299ef0c5a0887560b8b315d0
|
refs/heads/master
| 2023-03-27T23:37:02.836904 | 2021-03-26T22:07:54 | 2021-03-26T22:07:54 | 351,855,399 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 26,082 |
py
|
# coding=UTF-8
# **********************************************************************
# Copyright (c) 2013-2020 Cisco Systems, Inc. All rights reserved
# written by zen warriors, do not modify!
# **********************************************************************
from cobra.mit.meta import ClassMeta
from cobra.mit.meta import StatsClassMeta
from cobra.mit.meta import CounterMeta
from cobra.mit.meta import PropMeta
from cobra.mit.meta import Category
from cobra.mit.meta import SourceRelationMeta
from cobra.mit.meta import NamedSourceRelationMeta
from cobra.mit.meta import TargetRelationMeta
from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory
from cobra.model.category import MoCategory, PropCategory, CounterCategory
from cobra.mit.mo import Mo
# ##################################################
class BgpRtPrefixCountHist1year(Mo):
"""
Mo doc not defined in techpub!!!
"""
meta = StatsClassMeta("cobra.model.bgp.BgpRtPrefixCountHist1year", "BGP Route Prefix Count")
counter = CounterMeta("pfxSaved", CounterCategory.COUNTER, "routecount", "Prefixes Saved")
counter._propRefs[PropCategory.IMPLICIT_CUMULATIVE] = "pfxSavedCum"
counter._propRefs[PropCategory.IMPLICIT_PERIODIC] = "pfxSavedPer"
counter._propRefs[PropCategory.IMPLICIT_MIN] = "pfxSavedMin"
counter._propRefs[PropCategory.IMPLICIT_MAX] = "pfxSavedMax"
counter._propRefs[PropCategory.IMPLICIT_AVG] = "pfxSavedAvg"
counter._propRefs[PropCategory.IMPLICIT_SUSPECT] = "pfxSavedSpct"
counter._propRefs[PropCategory.IMPLICIT_THRESHOLDED] = "pfxSavedThr"
counter._propRefs[PropCategory.IMPLICIT_TREND] = "pfxSavedTr"
counter._propRefs[PropCategory.IMPLICIT_RATE] = "pfxSavedRate"
meta._counters.append(counter)
counter = CounterMeta("pfxSent", CounterCategory.COUNTER, "routecount", "Prefixes Sent")
counter._propRefs[PropCategory.IMPLICIT_CUMULATIVE] = "pfxSentCum"
counter._propRefs[PropCategory.IMPLICIT_PERIODIC] = "pfxSentPer"
counter._propRefs[PropCategory.IMPLICIT_MIN] = "pfxSentMin"
counter._propRefs[PropCategory.IMPLICIT_MAX] = "pfxSentMax"
counter._propRefs[PropCategory.IMPLICIT_AVG] = "pfxSentAvg"
counter._propRefs[PropCategory.IMPLICIT_SUSPECT] = "pfxSentSpct"
counter._propRefs[PropCategory.IMPLICIT_THRESHOLDED] = "pfxSentThr"
counter._propRefs[PropCategory.IMPLICIT_TREND] = "pfxSentTr"
counter._propRefs[PropCategory.IMPLICIT_RATE] = "pfxSentRate"
meta._counters.append(counter)
counter = CounterMeta("acceptedPaths", CounterCategory.COUNTER, "routecount", "Accepted Paths")
counter._propRefs[PropCategory.IMPLICIT_CUMULATIVE] = "acceptedPathsCum"
counter._propRefs[PropCategory.IMPLICIT_PERIODIC] = "acceptedPathsPer"
counter._propRefs[PropCategory.IMPLICIT_MIN] = "acceptedPathsMin"
counter._propRefs[PropCategory.IMPLICIT_MAX] = "acceptedPathsMax"
counter._propRefs[PropCategory.IMPLICIT_AVG] = "acceptedPathsAvg"
counter._propRefs[PropCategory.IMPLICIT_SUSPECT] = "acceptedPathsSpct"
counter._propRefs[PropCategory.IMPLICIT_THRESHOLDED] = "acceptedPathsThr"
counter._propRefs[PropCategory.IMPLICIT_TREND] = "acceptedPathsTr"
counter._propRefs[PropCategory.IMPLICIT_RATE] = "acceptedPathsRate"
meta._counters.append(counter)
meta.moClassName = "bgpBgpRtPrefixCountHist1year"
meta.rnFormat = "HDbgpBgpRtPrefixCount1year-%(index)s"
meta.category = MoCategory.STATS_HISTORY
meta.label = "historical BGP Route Prefix Count stats in 1 year"
meta.writeAccessMask = 0x8008020040001
meta.readAccessMask = 0x8008020040001
meta.isDomainable = False
meta.isReadOnly = True
meta.isConfigurable = False
meta.isDeletable = False
meta.isContextRoot = True
meta.parentClasses.add("cobra.model.bgp.PeerEntryStats")
meta.superClasses.add("cobra.model.bgp.BgpRtPrefixCountHist")
meta.superClasses.add("cobra.model.stats.Item")
meta.superClasses.add("cobra.model.stats.Hist")
meta.rnPrefixes = [
('HDbgpBgpRtPrefixCount1year-', True),
]
prop = PropMeta("str", "acceptedPathsAvg", "acceptedPathsAvg", 53822, PropCategory.IMPLICIT_AVG)
prop.label = "Accepted Paths average value"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsAvg", prop)
prop = PropMeta("str", "acceptedPathsCum", "acceptedPathsCum", 53818, PropCategory.IMPLICIT_CUMULATIVE)
prop.label = "Accepted Paths cumulative"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsCum", prop)
prop = PropMeta("str", "acceptedPathsMax", "acceptedPathsMax", 53821, PropCategory.IMPLICIT_MAX)
prop.label = "Accepted Paths maximum value"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsMax", prop)
prop = PropMeta("str", "acceptedPathsMin", "acceptedPathsMin", 53820, PropCategory.IMPLICIT_MIN)
prop.label = "Accepted Paths minimum value"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsMin", prop)
prop = PropMeta("str", "acceptedPathsPer", "acceptedPathsPer", 53819, PropCategory.IMPLICIT_PERIODIC)
prop.label = "Accepted Paths periodic"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsPer", prop)
prop = PropMeta("str", "acceptedPathsRate", "acceptedPathsRate", 53826, PropCategory.IMPLICIT_RATE)
prop.label = "Accepted Paths rate"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsRate", prop)
prop = PropMeta("str", "acceptedPathsSpct", "acceptedPathsSpct", 53823, PropCategory.IMPLICIT_SUSPECT)
prop.label = "Accepted Paths suspect count"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsSpct", prop)
prop = PropMeta("str", "acceptedPathsThr", "acceptedPathsThr", 53824, PropCategory.IMPLICIT_THRESHOLDED)
prop.label = "Accepted Paths thresholded flags"
prop.isOper = True
prop.isStats = True
prop.defaultValue = 0
prop.defaultValueStr = "unspecified"
prop._addConstant("avgCrit", "avg-severity-critical", 2199023255552)
prop._addConstant("avgHigh", "avg-crossed-high-threshold", 68719476736)
prop._addConstant("avgLow", "avg-crossed-low-threshold", 137438953472)
prop._addConstant("avgMajor", "avg-severity-major", 1099511627776)
prop._addConstant("avgMinor", "avg-severity-minor", 549755813888)
prop._addConstant("avgRecovering", "avg-recovering", 34359738368)
prop._addConstant("avgWarn", "avg-severity-warning", 274877906944)
prop._addConstant("cumulativeCrit", "cumulative-severity-critical", 8192)
prop._addConstant("cumulativeHigh", "cumulative-crossed-high-threshold", 256)
prop._addConstant("cumulativeLow", "cumulative-crossed-low-threshold", 512)
prop._addConstant("cumulativeMajor", "cumulative-severity-major", 4096)
prop._addConstant("cumulativeMinor", "cumulative-severity-minor", 2048)
prop._addConstant("cumulativeRecovering", "cumulative-recovering", 128)
prop._addConstant("cumulativeWarn", "cumulative-severity-warning", 1024)
prop._addConstant("lastReadingCrit", "lastreading-severity-critical", 64)
prop._addConstant("lastReadingHigh", "lastreading-crossed-high-threshold", 2)
prop._addConstant("lastReadingLow", "lastreading-crossed-low-threshold", 4)
prop._addConstant("lastReadingMajor", "lastreading-severity-major", 32)
prop._addConstant("lastReadingMinor", "lastreading-severity-minor", 16)
prop._addConstant("lastReadingRecovering", "lastreading-recovering", 1)
prop._addConstant("lastReadingWarn", "lastreading-severity-warning", 8)
prop._addConstant("maxCrit", "max-severity-critical", 17179869184)
prop._addConstant("maxHigh", "max-crossed-high-threshold", 536870912)
prop._addConstant("maxLow", "max-crossed-low-threshold", 1073741824)
prop._addConstant("maxMajor", "max-severity-major", 8589934592)
prop._addConstant("maxMinor", "max-severity-minor", 4294967296)
prop._addConstant("maxRecovering", "max-recovering", 268435456)
prop._addConstant("maxWarn", "max-severity-warning", 2147483648)
prop._addConstant("minCrit", "min-severity-critical", 134217728)
prop._addConstant("minHigh", "min-crossed-high-threshold", 4194304)
prop._addConstant("minLow", "min-crossed-low-threshold", 8388608)
prop._addConstant("minMajor", "min-severity-major", 67108864)
prop._addConstant("minMinor", "min-severity-minor", 33554432)
prop._addConstant("minRecovering", "min-recovering", 2097152)
prop._addConstant("minWarn", "min-severity-warning", 16777216)
prop._addConstant("periodicCrit", "periodic-severity-critical", 1048576)
prop._addConstant("periodicHigh", "periodic-crossed-high-threshold", 32768)
prop._addConstant("periodicLow", "periodic-crossed-low-threshold", 65536)
prop._addConstant("periodicMajor", "periodic-severity-major", 524288)
prop._addConstant("periodicMinor", "periodic-severity-minor", 262144)
prop._addConstant("periodicRecovering", "periodic-recovering", 16384)
prop._addConstant("periodicWarn", "periodic-severity-warning", 131072)
prop._addConstant("rateCrit", "rate-severity-critical", 36028797018963968)
prop._addConstant("rateHigh", "rate-crossed-high-threshold", 1125899906842624)
prop._addConstant("rateLow", "rate-crossed-low-threshold", 2251799813685248)
prop._addConstant("rateMajor", "rate-severity-major", 18014398509481984)
prop._addConstant("rateMinor", "rate-severity-minor", 9007199254740992)
prop._addConstant("rateRecovering", "rate-recovering", 562949953421312)
prop._addConstant("rateWarn", "rate-severity-warning", 4503599627370496)
prop._addConstant("trendCrit", "trend-severity-critical", 281474976710656)
prop._addConstant("trendHigh", "trend-crossed-high-threshold", 8796093022208)
prop._addConstant("trendLow", "trend-crossed-low-threshold", 17592186044416)
prop._addConstant("trendMajor", "trend-severity-major", 140737488355328)
prop._addConstant("trendMinor", "trend-severity-minor", 70368744177664)
prop._addConstant("trendRecovering", "trend-recovering", 4398046511104)
prop._addConstant("trendWarn", "trend-severity-warning", 35184372088832)
prop._addConstant("unspecified", None, 0)
meta.props.add("acceptedPathsThr", prop)
prop = PropMeta("str", "acceptedPathsTr", "acceptedPathsTr", 53825, PropCategory.IMPLICIT_TREND)
prop.label = "Accepted Paths trend"
prop.isOper = True
prop.isStats = True
meta.props.add("acceptedPathsTr", prop)
prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("deleteAll", "deleteall", 16384)
prop._addConstant("deleteNonPresent", "deletenonpresent", 8192)
prop._addConstant("ignore", "ignore", 4096)
meta.props.add("childAction", prop)
prop = PropMeta("str", "cnt", "cnt", 16212, PropCategory.REGULAR)
prop.label = "Number of Collections During this Interval"
prop.isImplicit = True
prop.isAdmin = True
meta.props.add("cnt", prop)
prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN)
prop.label = "None"
prop.isDn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("dn", prop)
prop = PropMeta("str", "index", "index", 53426, PropCategory.REGULAR)
prop.label = "History Index"
prop.isConfig = True
prop.isAdmin = True
prop.isCreateOnly = True
prop.isNaming = True
meta.props.add("index", prop)
prop = PropMeta("str", "lastCollOffset", "lastCollOffset", 111, PropCategory.REGULAR)
prop.label = "Collection Length"
prop.isImplicit = True
prop.isAdmin = True
meta.props.add("lastCollOffset", prop)
prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop.defaultValue = 0
prop.defaultValueStr = "never"
prop._addConstant("never", "never", 0)
meta.props.add("modTs", prop)
prop = PropMeta("str", "pfxSavedAvg", "pfxSavedAvg", 53843, PropCategory.IMPLICIT_AVG)
prop.label = "Prefixes Saved average value"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedAvg", prop)
prop = PropMeta("str", "pfxSavedCum", "pfxSavedCum", 53839, PropCategory.IMPLICIT_CUMULATIVE)
prop.label = "Prefixes Saved cumulative"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedCum", prop)
prop = PropMeta("str", "pfxSavedMax", "pfxSavedMax", 53842, PropCategory.IMPLICIT_MAX)
prop.label = "Prefixes Saved maximum value"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedMax", prop)
prop = PropMeta("str", "pfxSavedMin", "pfxSavedMin", 53841, PropCategory.IMPLICIT_MIN)
prop.label = "Prefixes Saved minimum value"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedMin", prop)
prop = PropMeta("str", "pfxSavedPer", "pfxSavedPer", 53840, PropCategory.IMPLICIT_PERIODIC)
prop.label = "Prefixes Saved periodic"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedPer", prop)
prop = PropMeta("str", "pfxSavedRate", "pfxSavedRate", 53847, PropCategory.IMPLICIT_RATE)
prop.label = "Prefixes Saved rate"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedRate", prop)
prop = PropMeta("str", "pfxSavedSpct", "pfxSavedSpct", 53844, PropCategory.IMPLICIT_SUSPECT)
prop.label = "Prefixes Saved suspect count"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedSpct", prop)
prop = PropMeta("str", "pfxSavedThr", "pfxSavedThr", 53845, PropCategory.IMPLICIT_THRESHOLDED)
prop.label = "Prefixes Saved thresholded flags"
prop.isOper = True
prop.isStats = True
prop.defaultValue = 0
prop.defaultValueStr = "unspecified"
prop._addConstant("avgCrit", "avg-severity-critical", 2199023255552)
prop._addConstant("avgHigh", "avg-crossed-high-threshold", 68719476736)
prop._addConstant("avgLow", "avg-crossed-low-threshold", 137438953472)
prop._addConstant("avgMajor", "avg-severity-major", 1099511627776)
prop._addConstant("avgMinor", "avg-severity-minor", 549755813888)
prop._addConstant("avgRecovering", "avg-recovering", 34359738368)
prop._addConstant("avgWarn", "avg-severity-warning", 274877906944)
prop._addConstant("cumulativeCrit", "cumulative-severity-critical", 8192)
prop._addConstant("cumulativeHigh", "cumulative-crossed-high-threshold", 256)
prop._addConstant("cumulativeLow", "cumulative-crossed-low-threshold", 512)
prop._addConstant("cumulativeMajor", "cumulative-severity-major", 4096)
prop._addConstant("cumulativeMinor", "cumulative-severity-minor", 2048)
prop._addConstant("cumulativeRecovering", "cumulative-recovering", 128)
prop._addConstant("cumulativeWarn", "cumulative-severity-warning", 1024)
prop._addConstant("lastReadingCrit", "lastreading-severity-critical", 64)
prop._addConstant("lastReadingHigh", "lastreading-crossed-high-threshold", 2)
prop._addConstant("lastReadingLow", "lastreading-crossed-low-threshold", 4)
prop._addConstant("lastReadingMajor", "lastreading-severity-major", 32)
prop._addConstant("lastReadingMinor", "lastreading-severity-minor", 16)
prop._addConstant("lastReadingRecovering", "lastreading-recovering", 1)
prop._addConstant("lastReadingWarn", "lastreading-severity-warning", 8)
prop._addConstant("maxCrit", "max-severity-critical", 17179869184)
prop._addConstant("maxHigh", "max-crossed-high-threshold", 536870912)
prop._addConstant("maxLow", "max-crossed-low-threshold", 1073741824)
prop._addConstant("maxMajor", "max-severity-major", 8589934592)
prop._addConstant("maxMinor", "max-severity-minor", 4294967296)
prop._addConstant("maxRecovering", "max-recovering", 268435456)
prop._addConstant("maxWarn", "max-severity-warning", 2147483648)
prop._addConstant("minCrit", "min-severity-critical", 134217728)
prop._addConstant("minHigh", "min-crossed-high-threshold", 4194304)
prop._addConstant("minLow", "min-crossed-low-threshold", 8388608)
prop._addConstant("minMajor", "min-severity-major", 67108864)
prop._addConstant("minMinor", "min-severity-minor", 33554432)
prop._addConstant("minRecovering", "min-recovering", 2097152)
prop._addConstant("minWarn", "min-severity-warning", 16777216)
prop._addConstant("periodicCrit", "periodic-severity-critical", 1048576)
prop._addConstant("periodicHigh", "periodic-crossed-high-threshold", 32768)
prop._addConstant("periodicLow", "periodic-crossed-low-threshold", 65536)
prop._addConstant("periodicMajor", "periodic-severity-major", 524288)
prop._addConstant("periodicMinor", "periodic-severity-minor", 262144)
prop._addConstant("periodicRecovering", "periodic-recovering", 16384)
prop._addConstant("periodicWarn", "periodic-severity-warning", 131072)
prop._addConstant("rateCrit", "rate-severity-critical", 36028797018963968)
prop._addConstant("rateHigh", "rate-crossed-high-threshold", 1125899906842624)
prop._addConstant("rateLow", "rate-crossed-low-threshold", 2251799813685248)
prop._addConstant("rateMajor", "rate-severity-major", 18014398509481984)
prop._addConstant("rateMinor", "rate-severity-minor", 9007199254740992)
prop._addConstant("rateRecovering", "rate-recovering", 562949953421312)
prop._addConstant("rateWarn", "rate-severity-warning", 4503599627370496)
prop._addConstant("trendCrit", "trend-severity-critical", 281474976710656)
prop._addConstant("trendHigh", "trend-crossed-high-threshold", 8796093022208)
prop._addConstant("trendLow", "trend-crossed-low-threshold", 17592186044416)
prop._addConstant("trendMajor", "trend-severity-major", 140737488355328)
prop._addConstant("trendMinor", "trend-severity-minor", 70368744177664)
prop._addConstant("trendRecovering", "trend-recovering", 4398046511104)
prop._addConstant("trendWarn", "trend-severity-warning", 35184372088832)
prop._addConstant("unspecified", None, 0)
meta.props.add("pfxSavedThr", prop)
prop = PropMeta("str", "pfxSavedTr", "pfxSavedTr", 53846, PropCategory.IMPLICIT_TREND)
prop.label = "Prefixes Saved trend"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSavedTr", prop)
prop = PropMeta("str", "pfxSentAvg", "pfxSentAvg", 53864, PropCategory.IMPLICIT_AVG)
prop.label = "Prefixes Sent average value"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentAvg", prop)
prop = PropMeta("str", "pfxSentCum", "pfxSentCum", 53860, PropCategory.IMPLICIT_CUMULATIVE)
prop.label = "Prefixes Sent cumulative"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentCum", prop)
prop = PropMeta("str", "pfxSentMax", "pfxSentMax", 53863, PropCategory.IMPLICIT_MAX)
prop.label = "Prefixes Sent maximum value"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentMax", prop)
prop = PropMeta("str", "pfxSentMin", "pfxSentMin", 53862, PropCategory.IMPLICIT_MIN)
prop.label = "Prefixes Sent minimum value"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentMin", prop)
prop = PropMeta("str", "pfxSentPer", "pfxSentPer", 53861, PropCategory.IMPLICIT_PERIODIC)
prop.label = "Prefixes Sent periodic"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentPer", prop)
prop = PropMeta("str", "pfxSentRate", "pfxSentRate", 53868, PropCategory.IMPLICIT_RATE)
prop.label = "Prefixes Sent rate"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentRate", prop)
prop = PropMeta("str", "pfxSentSpct", "pfxSentSpct", 53865, PropCategory.IMPLICIT_SUSPECT)
prop.label = "Prefixes Sent suspect count"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentSpct", prop)
prop = PropMeta("str", "pfxSentThr", "pfxSentThr", 53866, PropCategory.IMPLICIT_THRESHOLDED)
prop.label = "Prefixes Sent thresholded flags"
prop.isOper = True
prop.isStats = True
prop.defaultValue = 0
prop.defaultValueStr = "unspecified"
prop._addConstant("avgCrit", "avg-severity-critical", 2199023255552)
prop._addConstant("avgHigh", "avg-crossed-high-threshold", 68719476736)
prop._addConstant("avgLow", "avg-crossed-low-threshold", 137438953472)
prop._addConstant("avgMajor", "avg-severity-major", 1099511627776)
prop._addConstant("avgMinor", "avg-severity-minor", 549755813888)
prop._addConstant("avgRecovering", "avg-recovering", 34359738368)
prop._addConstant("avgWarn", "avg-severity-warning", 274877906944)
prop._addConstant("cumulativeCrit", "cumulative-severity-critical", 8192)
prop._addConstant("cumulativeHigh", "cumulative-crossed-high-threshold", 256)
prop._addConstant("cumulativeLow", "cumulative-crossed-low-threshold", 512)
prop._addConstant("cumulativeMajor", "cumulative-severity-major", 4096)
prop._addConstant("cumulativeMinor", "cumulative-severity-minor", 2048)
prop._addConstant("cumulativeRecovering", "cumulative-recovering", 128)
prop._addConstant("cumulativeWarn", "cumulative-severity-warning", 1024)
prop._addConstant("lastReadingCrit", "lastreading-severity-critical", 64)
prop._addConstant("lastReadingHigh", "lastreading-crossed-high-threshold", 2)
prop._addConstant("lastReadingLow", "lastreading-crossed-low-threshold", 4)
prop._addConstant("lastReadingMajor", "lastreading-severity-major", 32)
prop._addConstant("lastReadingMinor", "lastreading-severity-minor", 16)
prop._addConstant("lastReadingRecovering", "lastreading-recovering", 1)
prop._addConstant("lastReadingWarn", "lastreading-severity-warning", 8)
prop._addConstant("maxCrit", "max-severity-critical", 17179869184)
prop._addConstant("maxHigh", "max-crossed-high-threshold", 536870912)
prop._addConstant("maxLow", "max-crossed-low-threshold", 1073741824)
prop._addConstant("maxMajor", "max-severity-major", 8589934592)
prop._addConstant("maxMinor", "max-severity-minor", 4294967296)
prop._addConstant("maxRecovering", "max-recovering", 268435456)
prop._addConstant("maxWarn", "max-severity-warning", 2147483648)
prop._addConstant("minCrit", "min-severity-critical", 134217728)
prop._addConstant("minHigh", "min-crossed-high-threshold", 4194304)
prop._addConstant("minLow", "min-crossed-low-threshold", 8388608)
prop._addConstant("minMajor", "min-severity-major", 67108864)
prop._addConstant("minMinor", "min-severity-minor", 33554432)
prop._addConstant("minRecovering", "min-recovering", 2097152)
prop._addConstant("minWarn", "min-severity-warning", 16777216)
prop._addConstant("periodicCrit", "periodic-severity-critical", 1048576)
prop._addConstant("periodicHigh", "periodic-crossed-high-threshold", 32768)
prop._addConstant("periodicLow", "periodic-crossed-low-threshold", 65536)
prop._addConstant("periodicMajor", "periodic-severity-major", 524288)
prop._addConstant("periodicMinor", "periodic-severity-minor", 262144)
prop._addConstant("periodicRecovering", "periodic-recovering", 16384)
prop._addConstant("periodicWarn", "periodic-severity-warning", 131072)
prop._addConstant("rateCrit", "rate-severity-critical", 36028797018963968)
prop._addConstant("rateHigh", "rate-crossed-high-threshold", 1125899906842624)
prop._addConstant("rateLow", "rate-crossed-low-threshold", 2251799813685248)
prop._addConstant("rateMajor", "rate-severity-major", 18014398509481984)
prop._addConstant("rateMinor", "rate-severity-minor", 9007199254740992)
prop._addConstant("rateRecovering", "rate-recovering", 562949953421312)
prop._addConstant("rateWarn", "rate-severity-warning", 4503599627370496)
prop._addConstant("trendCrit", "trend-severity-critical", 281474976710656)
prop._addConstant("trendHigh", "trend-crossed-high-threshold", 8796093022208)
prop._addConstant("trendLow", "trend-crossed-low-threshold", 17592186044416)
prop._addConstant("trendMajor", "trend-severity-major", 140737488355328)
prop._addConstant("trendMinor", "trend-severity-minor", 70368744177664)
prop._addConstant("trendRecovering", "trend-recovering", 4398046511104)
prop._addConstant("trendWarn", "trend-severity-warning", 35184372088832)
prop._addConstant("unspecified", None, 0)
meta.props.add("pfxSentThr", prop)
prop = PropMeta("str", "pfxSentTr", "pfxSentTr", 53867, PropCategory.IMPLICIT_TREND)
prop.label = "Prefixes Sent trend"
prop.isOper = True
prop.isStats = True
meta.props.add("pfxSentTr", prop)
prop = PropMeta("str", "repIntvEnd", "repIntvEnd", 110, PropCategory.REGULAR)
prop.label = "Reporting End Time"
prop.isImplicit = True
prop.isAdmin = True
meta.props.add("repIntvEnd", prop)
prop = PropMeta("str", "repIntvStart", "repIntvStart", 109, PropCategory.REGULAR)
prop.label = "Reporting Start Time"
prop.isImplicit = True
prop.isAdmin = True
meta.props.add("repIntvStart", prop)
prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN)
prop.label = "None"
prop.isRn = True
prop.isImplicit = True
prop.isAdmin = True
prop.isCreateOnly = True
meta.props.add("rn", prop)
prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS)
prop.label = "None"
prop.isImplicit = True
prop.isAdmin = True
prop._addConstant("created", "created", 2)
prop._addConstant("deleted", "deleted", 8)
prop._addConstant("modified", "modified", 4)
meta.props.add("status", prop)
meta.namingProps.append(getattr(meta.props, "index"))
def __init__(self, parentMoOrDn, index, markDirty=True, **creationProps):
namingVals = [index]
Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps)
# End of package file
# ##################################################
|
[
"[email protected]"
] | |
ca161f03be6e6ff891468e06abe663b58ea01712
|
56f027edf5924ef92034ae03682076725b83f31a
|
/company/employeeapi/migrations/0001_initial.py
|
97d575de3ea813da21fab76180944332bb6ed572
|
[] |
no_license
|
pranay-prajapati/Company-Management-System-API
|
08d5bbe6dee3d4bc479df2a625745cc146056a11
|
4ec0098db962935a9db74340e197e2f71e2941df
|
refs/heads/master
| 2022-12-16T22:45:39.905530 | 2020-09-05T14:24:54 | 2020-09-05T14:24:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 673 |
py
|
# Generated by Django 3.0.3 on 2020-09-04 06:51
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Employee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=100)),
('last_name', models.CharField(max_length=100)),
('email', models.EmailField(max_length=254)),
('contact', models.IntegerField()),
],
),
]
|
[
"[email protected]"
] | |
c13756a0ae83f1d431e071abd4b4d72cab702e9b
|
3d5fab0210b4b069042bbf4440d4bdd470c5fa35
|
/morse/stream/decode.py
|
388b75be5c8bf6a328a72f5155bf5b81c9e0a70d
|
[
"MIT"
] |
permissive
|
cheeseywhiz/cheeseywhiz
|
26f7ada10bacd66a92c7664564c7cb698811ecf6
|
51f6651ddbaeebd14d9ce77776bc4cf3a95511c4
|
refs/heads/master
| 2023-02-09T20:58:38.050046 | 2020-07-10T19:06:49 | 2020-07-10T19:06:49 | 91,837,068 | 0 | 0 |
MIT
| 2023-02-02T03:11:25 | 2017-05-19T19:03:51 |
Python
|
UTF-8
|
Python
| false | false | 753 |
py
|
from decode_tree import decode_tree
class BitStream:
def __init__(self, numbers):
self.numbers = iter(numbers)
self.init_bit_range()
def next_number(self):
self.number = next(self.numbers)
self.bit_range = range(self.number.bit_length())
self.next_bit()
def next_bit(self):
try:
self.bit_n = next(self.bit_range)
except StopIteration:
self.next_number()
def __iter__(self):
return self
def __next__(self):
pass
def bit_stream(numbers):
for number in numbers:
for i in range(number.bit_length()):
yield 1 if number & (1 << i) else 0
def decode(byte_seq):
for bit in bit_stream(byte_seq):
pass
|
[
"[email protected]"
] | |
f4b8900ed36ecdfb46767aa1eddfaae0508887d4
|
5cf1b49cf8c6ac048f714cd946aa9476cae2505e
|
/userprofile/migrations/0019_usermain_dob.py
|
a09cb2d81128cf8f4e91958a34ef046985b499d7
|
[] |
no_license
|
vatsv/PanaceiaProgect
|
6e98e7fe9f32ccb2e28a89d182138824d709fcb8
|
b1cbd9ed983e48d3987cc25da2e5ff26772c71c4
|
refs/heads/main
| 2023-03-21T13:09:16.345772 | 2021-03-04T07:05:13 | 2021-03-04T07:05:13 | 344,382,671 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 442 |
py
|
# Generated by Django 3.1.3 on 2020-12-08 11:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userprofile', '0018_auto_20201208_1402'),
]
operations = [
migrations.AddField(
model_name='usermain',
name='dob',
field=models.CharField(blank=True, max_length=100, verbose_name='Дата рождения'),
),
]
|
[
"“[email protected]”"
] | |
e62dab0374051f27143dd9f2e2707e9af79c2218
|
c6f14e539b7fa1e2466bc22c78241ccd99b76447
|
/tests/test_blog.py
|
5c229929e75bc878643073f9dfef0a8d05da2cc5
|
[] |
no_license
|
cofm21/flask-tutorial
|
af8fc45d4835394f05f673fce5cfc9a3d069682d
|
d78cf01a70508da58d27480a2ebb0b32630aceab
|
refs/heads/master
| 2020-04-08T13:21:35.303269 | 2018-12-03T17:27:27 | 2018-12-03T17:27:27 | 159,387,624 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,465 |
py
|
import pytest
from flaskr.db import get_db
def test_index(client, auth):
response = client.get('/')
assert b"Log In" in response.data
assert b"Register" in response.data
auth.login()
response = client.get('/')
assert b'Log Out' in response.data
assert b'test title' in response.data
assert b'by test on 2018-01-01' in response.data
assert b'test\nbody' in response.data
assert b'href="/1/update"' in response.data
@pytest.mark.parametrize('path', (
'/create',
'/1/update',
'/1/delete',
))
def test_login_required(client, path):
response = client.post(path)
assert response.headers['Location'] == 'http://localhost/auth/login'
def test_author_required(app, client, auth):
with app.app_context():
db = get_db()
db.execute('UPDATE post SET author_id = 2 WHERE id = 1')
db.commit()
auth.login()
assert client.post('/1/update').status_code == 403
assert client.post('/1/delete').status_code == 403
assert b'href="/1/update"' not in client.get('/').data
@pytest.mark.parametrize('path', (
'/2/update',
'/2/delete',
))
def test_exists_required(client, auth, path):
auth.login()
assert client.post(path).status_code == 404
def test_create(client, auth, app):
auth.login()
assert client.get('/create').status_code == 200
client.post('/create', data={'title': 'created', 'body': ''})
with app.app_context():
db = get_db()
count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]
assert count == 2
def test_update(client, auth, app):
auth.login()
assert client.get('/1/update').status_code == 200
client.post('/1/update', data={'title': 'updated', 'body': ''})
with app.app_context():
db = get_db()
post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
assert post['title'] == 'updated'
@pytest.mark.parametrize('path', (
'/create',
'/1/update',
))
def test_create_update_valdiate(client, auth, path):
auth.login()
response = client.post(path, data={'title': '', 'body': ''})
assert b'Title is required.' in response.data
def test_delete(client, auth, app):
auth.login()
response = client.post('/1/delete')
assert response.headers['Location'] == 'http://localhost/'
with app.app_context():
db = get_db()
post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
assert post is None
|
[
"[email protected]"
] | |
df7db5f6cf855b9e25fa5feb01494b88573aacf4
|
c5458f2d53d02cb2967434122183ed064e1929f9
|
/sdks/python/test/test_contains_asset_predicate.py
|
4fe42254ff5b1cf16affd36b2f5c261675e7f2ab
|
[] |
no_license
|
ross-weir/ergo-node-api-sdks
|
fd7a32f79784dbd336ef6ddb9702b9dd9a964e75
|
9935ef703b14760854b24045c1307602b282c4fb
|
refs/heads/main
| 2023-08-24T05:12:30.761145 | 2021-11-08T10:28:10 | 2021-11-08T10:28:10 | 425,785,912 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,131 |
py
|
"""
Ergo Node API
API docs for Ergo Node. Models are shared between all Ergo products # noqa: E501
The version of the OpenAPI document: 4.0.15
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import openapi_client
from openapi_client.model.contains_asset_predicate_all_of import ContainsAssetPredicateAllOf
from openapi_client.model.scanning_predicate import ScanningPredicate
globals()['ContainsAssetPredicateAllOf'] = ContainsAssetPredicateAllOf
globals()['ScanningPredicate'] = ScanningPredicate
from openapi_client.model.contains_asset_predicate import ContainsAssetPredicate
class TestContainsAssetPredicate(unittest.TestCase):
"""ContainsAssetPredicate unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testContainsAssetPredicate(self):
"""Test ContainsAssetPredicate"""
# FIXME: construct object with mandatory attributes with example values
# model = ContainsAssetPredicate() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
6d3d98d0120ad6d6ec0dceb5cf86b020ec9a9ecf
|
e2828bdae30efa4fde1894908af6d46a36ae3c15
|
/Twitter-Tool-TRB/assessment/bin/easy_install
|
3c4ba9415002928902d26184c642af9e7e562349
|
[] |
no_license
|
tbacas/Twitter_Django
|
98b0ee13298b26abe436c71e8dc21d4104af17d7
|
6f25d2a91fa7ccb441909f1be94620cb930ed4a8
|
refs/heads/master
| 2020-07-06T17:42:14.791878 | 2020-05-26T20:38:40 | 2020-05-26T20:38:40 | 203,093,867 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 281 |
#!/Users/thomasbacas/Desktop/TwitterTool_TRB/assessment/bin/python
# -*- 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())
|
[
"[email protected]"
] | ||
99027e30edf1a0bcd1aeb0c9f8caa4f0dd5e67be
|
bcc87219fcff3093758bbc4de6e09dfd21b127a8
|
/grape.py
|
342031003e84029f66ada092057b8359ae64cadb
|
[] |
no_license
|
LeoHeller/BitRacer
|
b27ad57cde93c0ced1e89b802e51c73df4ad5906
|
cea0a54a1a93436212598df1446d27ac746edaff
|
refs/heads/master
| 2021-06-25T07:11:57.024327 | 2017-09-11T17:29:04 | 2017-09-11T17:29:04 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 9,764 |
py
|
# 1. make a class that has the atributes of dodged count, position of x and y, trash speed, and class name
# 2. def save (writes the class to a file)
# 3. add save button to pause screen
# 4. add button on intro screen to go to a load save screen.
# 5. add buttons for loading the game
import os
import sys
import pygame
import time
import random
class Game:
def __init__(self, display_width, display_height):
self.display_width = display_width
self.display_height = display_height
self.intro = True
#Colors
self.black = (0,0,0)
self.white = (255,255,255)
self.red = (255,0,0)
self.blue = (20, 20, 255)
self.grey = (55, 55, 55)
self.green = (0,255,0)
self.hotpink = (255,96,96)
self.lightgreen = (96,255,96)
self.light_grey = (145,145,145)
self.guy_x = (display_width*0.45)
#extra variables
self.pause = False
cwd = os.path.dirname(sys.argv[0])
self.guy_width = 73
self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption('BitRacer')
self.clock = pygame.time.Clock()
#importing images
self.bgImg = pygame.image.load(cwd+'\\road.png')
self.guyImg = pygame.image.load(cwd+'\\guy.png')
self.trashImg = pygame.image.load(cwd+'\\trash.png')
self.init()
def init(self,init = True):
if init == True:
self.guy_x = (self.display_width * 0.45)
self.trash_speed = 7
self.count = 0
self.guy_y = (self.display_height * 0.8)
self.trash_start_x = random.randrange(0, self.display_width)
self.trash_start_y = -500
self.gameDisplay.blit(self.bgImg,(0,0))
#block_width = 100
#block_height = 100
self.gameExit = False
def start_game(self):
self.init()
self.game_loop()
def trash_dodged(self, count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
self.gameDisplay.blit(text, (0,0))
def trash(self,trash_x,trash_y):
self.gameDisplay.blit(trashImg,(trash_x,trash_y))
def guy(self,x,y):
self.gameDisplay.blit(guyImg,(x,y))
def text_objects(self, text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',100)
TextSurf, TextRect = self.text_objects(text, largeText)
TextRect.center = ((self.display_width/2), (self.display_height/2))
self.gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
self.game_loop()
def crash(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit
quit()
self.gameDisplay.fill(self.light_grey)
largeText = pygame.font.Font('freesansbold.ttf',100)
TextSurf, TextRect = self.text_objects("You Crashed", largeText)
TextRect.center = ((self.display_width/2), (self.display_height/2))
self.gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
#adds buttons to intro screen
self.button("Play again",150,450,150,50,lightgreen,self.game_loop)
self.button("Exit",550,450,100,50,hotpink,self.quit_game)
#finds mouse position
mouse = pygame.mouse.get_pos()
self.gameDisplay.blit(TextSurf, TextRect)
#updates screen
pygame.display.update()
self.clock.tick(60)
def quit_game(self):
pygame.quit()
quit()
def button(self,msg,x,y,w,h,color,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
ax = x-10
ay = y-10
aw = w+20
ah = h+20
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(self.gameDisplay, color,(ax,ay,aw,ah))
if click[0] == 1 and action != None:
self.intro = False
action()
else:
pygame.draw.rect(self.gameDisplay, color, (x,y,w,h))
smallText = pygame.font.Font('freesansbold.ttf',25)
TextSurf, TextRect = self.text_objects(msg, smallText)
TextRect.center = ((x+(w/2)),y+(h/2))
self.gameDisplay.blit(TextSurf, TextRect)
def unpause(self):
global pause
pause = False
def paused(self):
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit
quit()
self.gameDisplay.fill(self.light_grey)
largeText = pygame.font.Font('freesansbold.ttf',100)
TextSurf, TextRect = self.text_objects("Bitracer", largeText)
TextRect.center = ((self.display_width/2), (self.display_height/2))
self.gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
#adds buttons to intro screen
self.button("Continue",150,450,150,50,lightgreen,self.unpause)
self.button("Exit",550,450,100,50,hotpink,self.quit_game)
self.button("Save",350,450,125,50,hotpink,self.save)
#finds mouse position
mouse = pygame.mouse.get_pos()
self.gameDisplay.blit(TextSurf, TextRect)
#updates screen
pygame.display.update()
self.clock.tick(60)
def game_intro(self):
#intro = True
while self.intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit
quit()
self.gameDisplay.fill(self.light_rey)
largeText = pygame.font.Font('freesansbold.ttf',100)
TextSurf, TextRect = self.text_objects("Bitracer", largeText)
TextRect.center = ((self.display_width/2),(self.display_height/2))
self.gameDisplay.blit(TextSurf, TextRect)
#adds buttons to intro screen
self.button("START",150,450,100,50,lightgreen,self.start_game)
self.button("Exit",550,450,100,50,hotpink, self.quit_game)
self.button("Load Game",350,450,125,50,lightgreen,self.load)
#finds mouse position
mouse = pygame.mouse.get_pos()
self.gameDisplay.blit(TextSurf, TextRect)
#updates screen
pygame.display.update()
self.clock.tick(60)
def game_loop(self, init=True):
while not self.gameExit:
x_change = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
#print(str(event.type))
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.key == pygame.K_p:
pause = True
self.paused()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
self.guy_x += x_change
#print(str(self.x))
self.trash(self.trash_start_x, self.trash_start_y)
self.trash_start_y += trash_speed
trash_speed = trash_speed + 0.001
self.guy(self.guy_x,self.guy_y)
self.trash_dodged(count)
if self.guy_x > self.display_width - guy_width or self.guy_x < 0:
self.crash()
if self.trash_start_y > self.display_height:
self.trash_start_y = 0 - 62
self.trash_start_x = random.randrange(62, self.display_width - 62)
count += 1
if y < self.trash_start_y + 62:
if self.guy_x > self.trash_start_x and self.guy_x < self.trash_start_x + 62 or self.guy_x + guy_width > self.trash_start_x and self.guy_x + guy_width < self.trash_start_x + 62:
self.crash()
pygame.display.update()
self.clock.tick(60)
def save(self):
cwd = os.path.dirname(sys.argv[0])
with open(cwd+"\\text.txt", "w") as f:
print(str(count)+"\n"+str(self.guy_x)+"\n"+str(trash_speed)+"\n",file = f)
def load(self):
cwd = os.path.dirname(sys.argv[0])
with open(cwd+"\\text.txt", "r") as f:
contents = f.readlines()
contents =[l.strip() for l in contents]
count = int(contents[0], base = 10)
self.guy_x = float(contents[1])
self.trash_speed = float(contents[2])
#self.game_loop(False)
print(contents)
#intro = False
#Game_1 = Game(3,500,10)
#print(Game_1.dodged, Game_1.x, Game_1.trash_speed)
|
[
"[email protected]"
] | |
72251e91e7a92f47684862d0a85c43ffa455136f
|
3f0df23d130953dc29b6c7a5c4999ef3bd204dfb
|
/twitterapp/asgi.py
|
42f1a211114274ea6ef27e665b1ec4dfe013c5a8
|
[] |
no_license
|
kaankulac/django-text-app
|
5e4a773d9e644c484d9a5a8cdd9fa97ed5dd08a3
|
cbb0c38c5dd66a787dce41f52ae5f2cd07a1e24e
|
refs/heads/main
| 2023-08-01T02:11:40.424815 | 2021-09-13T08:30:02 | 2021-09-13T08:30:02 | 405,705,944 | 2 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 397 |
py
|
"""
ASGI config for twitterapp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'twitterapp.settings')
application = get_asgi_application()
|
[
"[email protected]"
] | |
92572d40e11aaec728a9177ec310fa9eb822e9f5
|
b6f4e527154b82f4e3fa48f06ca53fc15bf08283
|
/Day02/circle.py
|
020bf65e82244b1110af1fb98f7a1eaca88e783e
|
[] |
no_license
|
Light-City/Python-100-Days
|
74118e36c658db6c897f847e7e554311af036b9d
|
1fe049a1fe1e64082752d2d32cb75c1a4349cded
|
refs/heads/master
| 2020-03-18T12:44:53.191512 | 2018-05-24T09:49:22 | 2018-05-24T09:49:22 | 134,741,794 | 3 | 1 | null | 2018-05-24T16:29:02 | 2018-05-24T16:29:02 | null |
UTF-8
|
Python
| false | false | 288 |
py
|
"""
输入半径计算圆的周长和面积
Version: 0.1
Author: 骆昊
Date: 2018-02-27
"""
import math
radius = float(input('请输入圆的半径: '))
perimeter = 2 * math.pi * radius
area = math.pi * radius * radius
print('周长: %.2f' % perimeter)
print('面积: %.2f' % area)
|
[
"[email protected]"
] | |
ae34784aa1f3972444afd43c466afb94f3e83f8c
|
0d8b08e790fcf57bf72d7afdd5d8afcd3beafa8d
|
/combinato-windows/css-copy-headers.py
|
74d6394c04c9d28e0eb2dc39391f6411acbe3f29
|
[
"MIT"
] |
permissive
|
marijeterwal/combinato
|
94d53375284a70cab7c7729617fe48c3fa0dbf57
|
4ccac676279c1e0bc679d25529849e85323c36df
|
refs/heads/master
| 2020-04-16T03:11:36.693969 | 2019-01-14T14:21:55 | 2019-01-14T14:21:55 | 165,222,989 | 0 | 0 |
MIT
| 2019-01-11T10:10:12 | 2019-01-11T10:10:11 | null |
UTF-8
|
Python
| false | false | 105 |
py
|
#!/usr/bin/env python
# JN 2015-10-27 refactoring
from tools.get_header import parse_args
parse_args()
|
[
"[email protected]"
] | |
c4b95bb1509d20e46c920757aca3ca0e0a656d28
|
cabc6694fa17f356d29e9a7537de69a94f79ca68
|
/calculator.py
|
da7ac9d4352c0c7a5581aba4e41d57c4fa520116
|
[
"MIT"
] |
permissive
|
tejasmorkar/tkinter
|
233c4c1a12141ce1652e596ab295c237a0ec3955
|
488eccade289b37302bb9544a91bb5b661492ae7
|
refs/heads/master
| 2020-12-07T05:51:50.035037 | 2020-01-08T20:40:16 | 2020-01-08T20:40:16 | 232,648,377 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,415 |
py
|
from tkinter import *
root = Tk()
root.title("Simple Calculator")
# root.configure(bg="#242424")
e = Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
def button_click(number):
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(number))
def button_clear():
e.delete(0, END)
def button_add():
first_num = e.get()
global f_num
f_num = int(first_num)
global math
math = "add"
e.delete(0, END)
def button_sub():
first_num = e.get()
global f_num
f_num = int(first_num)
global math
math = "sub"
e.delete(0, END)
def button_mul():
first_num = e.get()
global f_num
f_num = int(first_num)
global math
math = "mul"
e.delete(0, END)
def button_div():
first_num = e.get()
global f_num
f_num = int(first_num)
global math
math = "div"
e.delete(0, END)
def button_equal():
second_num = e.get()
e.delete(0, END)
if math == "add":
e.insert(0, f_num + int(second_num))
if math == "sub":
e.insert(0, f_num - int(second_num))
if math == "mul":
e.insert(0, f_num * int(second_num))
if math == "div":
e.insert(0, f_num / int(second_num))
button_1 = Button(root, bg="#242424", fg="white", text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = Button(root, bg="#242424", fg="white", text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = Button(root, bg="#242424", fg="white", text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = Button(root, bg="#242424", fg="white", text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = Button(root, bg="#242424", fg="white", text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = Button(root, bg="#242424", fg="white", text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = Button(root, bg="#242424", fg="white", text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = Button(root, bg="#242424", fg="white", text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = Button(root, bg="#242424", fg="white", text="9", padx=40, pady=20, command=lambda: button_click(9))
button_0 = Button(root, bg="#242424", fg="white", text="0", padx=40, pady=20, command=lambda: button_click(0))
button_add = Button(root, bg="#242424", fg="white", text="+", padx=39, pady=20, command=button_add)
button_sub = Button(root, bg="#242424", fg="white", text="-", padx=39, pady=20, command=button_sub)
button_mul = Button(root, bg="#242424", fg="white", text="*", padx=40, pady=20, command=button_mul)
button_div = Button(root, bg="#242424", fg="white", text="/", padx=40, pady=20, command=button_div)
button_equal = Button(root, bg="#242424", fg="white", text="=", padx=91, pady=20, command=button_equal)
button_clear = Button(root, bg="#242424", fg="white", text="Clear", padx=79, pady=20, command=button_clear)
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_add.grid(row=5, column=0)
button_sub.grid(row=6, column=0)
button_mul.grid(row=4, column=1)
button_div.grid(row=4, column=2)
button_clear.grid(row=5, column=1, columnspan=2)
button_equal.grid(row=6, column=1, columnspan=2)
root.mainloop()
|
[
"[email protected]"
] | |
0ef74995d488190ad340d026e4e7f73bd2bcc8ba
|
1119f754f57d8ece632866ac6e2e136de77466f4
|
/new_case.py
|
ef4f51e5d0deeb1e10d29b940fe560cd55a95abf
|
[] |
no_license
|
carissasun/HLS
|
2cc0856832df128c6ce7a852cbd54dea0f21c17f
|
2b1ad080b683c61ad345009f8a22e4d358a6b116
|
refs/heads/master
| 2021-06-27T08:53:45.340490 | 2017-09-17T00:37:20 | 2017-09-17T00:37:20 | 103,796,976 | 0 | 0 | null | 2017-09-17T02:18:57 | 2017-09-17T02:18:57 | null |
UTF-8
|
Python
| false | false | 763 |
py
|
import sys
from shutil import copyfile
year = "1L"
term = "Fall Term"
classmap = {
"civpro":"Civil Procedure",
"crim":"Criminal Law",
"lrw":"Legal Reading and Writing",
"legreg":"Legislation and Regulation",
"torts":"Torts"
}
def get_class_name():
for key in classmap:
print "%s - %s" % (key, classmap[key])
return classmap[raw_input("Key: ").lower()]
def main():
casename = raw_input("Case: ") if len(sys.argv) < 2 \
else sys.argv[1]
classname = get_class_name() if len(sys.argv) < 3 \
else classmap[sys.argv[2].lower()]
copyfile("../Brief Template.docx", \
"../%s/%s/%s/Briefs/%s.docx" % (year, term, classname, casename))
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
8a2c9ca2bc9cee05798064ddf9b121627de61573
|
14603d7b42da64c86e05b1495c78dd9451bcf940
|
/test_Subtract.py
|
8347132e2154d742096367dfec7704dfac651c79
|
[] |
no_license
|
Vkutti/Calculator
|
63ffe1fdb764651de6621d2fe0bc99bdceccecef
|
e4b0e2d88db87a0d88dde814bf82be115dfdf4ff
|
refs/heads/master
| 2023-02-12T19:01:57.456528 | 2021-01-11T18:45:55 | 2021-01-11T18:45:55 | 291,496,510 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 837 |
py
|
import pytest
from SubtractFunctions import subtracting
john = 5
dylan = 6
mike = 7
ven = 100
kat = 150
def test_add_elementary():
assert subtracting(1, 2) == -1
def test_add_high_school():
assert subtracting(8000600, 6405006) == 1595594
def test_add_characters():
return_val = subtracting(1, 2)
print(type(return_val))
assert return_val == -1
def test_add_variable():
assert subtracting(john, mike) == -2
def test_add_values_and_vars():
assert subtracting(john, 5) == 0
def test_add_chars_and_vars_and_values():
my_answer = subtracting(mike, 30)
print(type(my_answer))
assert my_answer == -23
def test_add_chars_and_vars():
my_answer = subtracting(ven, kat)
print(type(my_answer))
assert my_answer == -50
|
[
"[email protected]"
] | |
aa59920641826421de01225a970e86152cb78e97
|
1d00bfe48cb30d14eb45d08389d663581f297f49
|
/pdf.py
|
fc8567a8713e9eff61ef560f56069608ac360a36
|
[] |
no_license
|
damirgafic/PDF-Playground
|
10d3a61508747bb79038c942c1ce4542050051dd
|
cef5392e1ddb40d1fa88a487a9ded9ef7121347d
|
refs/heads/master
| 2022-09-20T18:39:13.520431 | 2020-06-04T17:29:29 | 2020-06-04T17:29:29 | 267,965,666 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 520 |
py
|
import PyPDF2
import sys
inputs = sys.argv[1:]
def pdf_combine(pdf_list):
merger = PyPDF2.PdfFileMerger()
for pdf in pdf_list:
print(pdf)
merger.append(pdf)
merger.write('combined.pdf')
pdf_combine(inputs)
#with open('dummy.pdf', 'rb') as file:
# reader = PyPDF2.PdfFileReader(file)
# page = reader.getPage(0)
# page.rotateClockwise(180)
# writer = PyPDF2.PdfFileWriter()
# writer.addPage(page)
# with open('tilt.pdf', 'wb') as new_file:
# writer.write(new_file)
|
[
"[email protected]"
] | |
c201469ab4f413fd8c8302775d79ddbdb90d63b3
|
cd20ef8372134b625989c7e7033118e919d89563
|
/localize/__init__.py
|
3d8473c1b054f158b96b7bf78490455c3e3171a8
|
[] |
no_license
|
adeeps1/Localization
|
f72d84e15e1f9cb195e28f87e7c6f047901524da
|
da672a59f4693881027aa2df6d2460c9c614f59a
|
refs/heads/master
| 2021-08-23T03:06:50.007900 | 2017-12-02T20:26:15 | 2017-12-02T20:26:15 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 140 |
py
|
from __future__ import print_function
# Import all the different filters
from Kalman import *
from Particle import *
from Markov import *
|
[
"[email protected]"
] | |
3f3ffda4e1240e883906405ed000c5e8fbb3ffc6
|
1e61c600193ca26adfa5f667d5f8409028341cc5
|
/TutorialSite/urls.py
|
850e80390364628c2ab5e8ae5980e6e2ccdc8323
|
[] |
no_license
|
jtrinhx33/Django-Sandbox
|
875a8d69516b22f0066d9cae8185f5cdfe8a2d3c
|
b728bd599206e810cc5f85c854a49fdfbfef08b5
|
refs/heads/master
| 2016-09-10T17:51:20.225572 | 2015-06-11T03:11:55 | 2015-06-11T03:11:55 | 37,236,479 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 762 |
py
|
"""TutorialSite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
|
[
"[email protected]"
] | |
b17a76e84bd5b341b2318577b474a833ebec0020
|
782ac271339bbaa317930205e39ce8622be11512
|
/0x05-python-exceptions/3-safe_print_division.py
|
883860b3c2519aa3c4adaf0113138f7be0ca45c4
|
[] |
no_license
|
portableDD/alx-higher_level_programming
|
bc19e2dac6eb5ff079494d8e8dc0d8d00b5241f3
|
a7e08613558ec0dd4b355f863ef9f223d1872100
|
refs/heads/main
| 2023-08-28T15:04:44.949845 | 2021-10-12T15:04:51 | 2021-10-12T15:04:51 | 407,561,939 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 224 |
py
|
#!/usr/bin/python3
def safe_print_division(a, b):
try:
div = a / b
except (TypeError, ZeroDivisionError):
div = None
finally:
print("Inside result: {}".format(div))
return (div)
|
[
"[email protected]"
] | |
6b5be029fd1626d37c9b7f3db3aa07efd58e1011
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_123/627.py
|
28c02feb9a393af2190da5d1cd6130c71872869c
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,171 |
py
|
__author__ = 'jeff'
from collections import deque
base = "A-small-attempt2"
#base = "A1_test"
f = open(base+'.in','r')
fout = open(base+'.out','w')
t = int(f.readline())
def proc( a, motes):
while( len( motes ) and motes[0] < a ):
a += motes.popleft()
return a
max_lev = 100000
for case in range(1,t+1):
[a,n] = f.readline().split(' ')
a=int(a)
n=int(n)
motes = list(map( int, f.readline()[0:-1].split(' ')))
motes.sort()
print(a,motes)
motes = deque( motes )
moves = 0
adds = removes = 0
lev_count = 0
while( len( motes) ):
a=proc(a,motes)
if( not len( motes ) ):
break
a_copy = a
these_adds = 0
while( a>1 and a_copy <= motes[0] ):
these_adds += 1
a_copy += (a_copy - 1)
if( these_adds > 0 and these_adds < len( motes )):
adds += these_adds
a = a_copy
else:
removes += len( motes )
motes = deque([])
moves = moves + adds + removes
out_s = 'Case #{0}: {1}\n'.format(case,moves)
print( out_s )
fout.write(out_s)
f.close()
fout.close()
|
[
"[email protected]"
] | |
0c77dbbd8fb08d26e300e02084f0f0fbd2f1fcfe
|
80c3546d525a05a31d30cc318a44e053efaeb1f1
|
/tensorpack/dataflow/imgaug/misc.py
|
7fc983d4c9de61f53efc05459cca5493fcaca5a5
|
[
"Apache-2.0"
] |
permissive
|
yaroslavvb/tensorpack
|
0f326bef95699f84376465609b631981dc5b68bf
|
271ffad1816132c57baebe8a1aa95479e79f4ef9
|
refs/heads/master
| 2021-05-03T11:02:22.170689 | 2018-02-06T08:18:48 | 2018-02-06T08:18:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 6,419 |
py
|
# -*- coding: UTF-8 -*-
# File: misc.py
import numpy as np
import cv2
from .base import ImageAugmentor
from ...utils import logger
from ...utils.argtools import shape2d
from .transform import ResizeTransform, TransformAugmentorBase
__all__ = ['Flip', 'Resize', 'RandomResize', 'ResizeShortestEdge', 'Transpose']
class Flip(ImageAugmentor):
"""
Random flip the image either horizontally or vertically.
"""
def __init__(self, horiz=False, vert=False, prob=0.5):
"""
Args:
horiz (bool): use horizontal flip.
vert (bool): use vertical flip.
prob (float): probability of flip.
"""
super(Flip, self).__init__()
if horiz and vert:
raise ValueError("Cannot do both horiz and vert. Please use two Flip instead.")
elif horiz:
self.code = 1
elif vert:
self.code = 0
else:
raise ValueError("At least one of horiz or vert has to be True!")
self._init(locals())
def _get_augment_params(self, img):
h, w = img.shape[:2]
do = self._rand_range() < self.prob
return (do, h, w)
def _augment(self, img, param):
do, _, _ = param
if do:
ret = cv2.flip(img, self.code)
if img.ndim == 3 and ret.ndim == 2:
ret = ret[:, :, np.newaxis]
else:
ret = img
return ret
def _augment_coords(self, coords, param):
do, h, w = param
if do:
if self.code == 0:
coords[:, 1] = h - coords[:, 1]
elif self.code == 1:
coords[:, 0] = w - coords[:, 0]
return coords
class Resize(TransformAugmentorBase):
""" Resize image to a target size"""
def __init__(self, shape, interp=cv2.INTER_LINEAR):
"""
Args:
shape: (h, w) tuple or a int
interp: cv2 interpolation method
"""
shape = tuple(shape2d(shape))
self._init(locals())
def _get_augment_params(self, img):
return ResizeTransform(
img.shape[0], img.shape[1],
self.shape[0], self.shape[1], self.interp)
class ResizeShortestEdge(TransformAugmentorBase):
"""
Resize the shortest edge to a certain number while
keeping the aspect ratio.
"""
def __init__(self, size, interp=cv2.INTER_LINEAR):
"""
Args:
size (int): the size to resize the shortest edge to.
"""
size = int(size)
self._init(locals())
def _get_augment_params(self, img):
h, w = img.shape[:2]
scale = self.size * 1.0 / min(h, w)
if h < w:
newh, neww = self.size, int(scale * w + 0.5)
else:
newh, neww = int(scale * h + 0.5), self.size
return ResizeTransform(
h, w, newh, neww, self.interp)
class RandomResize(TransformAugmentorBase):
""" Randomly rescale width and height of the image."""
def __init__(self, xrange, yrange, minimum=(0, 0), aspect_ratio_thres=0.15,
interp=cv2.INTER_LINEAR):
"""
Args:
xrange (tuple): a (min, max) tuple. If is floating point, the
tuple defines the range of scaling ratio of new width, e.g. (0.9, 1.2).
If is integer, the tuple defines the range of new width in pixels, e.g. (200, 350).
yrange (tuple): similar to xrange, but for height.
minimum (tuple): (xmin, ymin) in pixels. To avoid scaling down too much.
aspect_ratio_thres (float): discard samples which change aspect ratio
larger than this threshold. Set to 0 to keep aspect ratio.
interp: cv2 interpolation method
"""
super(RandomResize, self).__init__()
assert aspect_ratio_thres >= 0
self._init(locals())
def is_float(tp):
return isinstance(tp[0], float) or isinstance(tp[1], float)
assert is_float(xrange) == is_float(yrange), "xrange and yrange has different type!"
self._is_scale = is_float(xrange)
if self._is_scale and aspect_ratio_thres == 0:
assert xrange == yrange
def _get_augment_params(self, img):
cnt = 0
h, w = img.shape[:2]
def get_dest_size():
if self._is_scale:
sx = self._rand_range(*self.xrange)
if self.aspect_ratio_thres == 0:
sy = sx
else:
sy = self._rand_range(*self.yrange)
destX = max(sx * w, self.minimum[0])
destY = max(sy * h, self.minimum[1])
else:
sx = self._rand_range(*self.xrange)
if self.aspect_ratio_thres == 0:
sy = sx * 1.0 / w * h
else:
sy = self._rand_range(*self.yrange)
destX = max(sx, self.minimum[0])
destY = max(sy, self.minimum[1])
return (int(destX + 0.5), int(destY + 0.5))
while True:
destX, destY = get_dest_size()
if self.aspect_ratio_thres > 0: # don't check when thres == 0
oldr = w * 1.0 / h
newr = destX * 1.0 / destY
diff = abs(newr - oldr) / oldr
if diff >= self.aspect_ratio_thres + 1e-5:
cnt += 1
if cnt > 50:
logger.warn("RandomResize failed to augment an image")
return ResizeTransform(h, w, h, w, self.interp)
continue
return ResizeTransform(h, w, destY, destX, self.interp)
class Transpose(ImageAugmentor):
"""
Random transpose the image
"""
def __init__(self, prob=0.5):
"""
Args:
prob (float): probability of transpose.
"""
super(Transpose, self).__init__()
self.prob = prob
self._init()
def _get_augment_params(self, img):
return self._rand_range() < self.prob
def _augment(self, img, do):
ret = img
if do:
ret = cv2.transpose(img)
if img.ndim == 3 and ret.ndim == 2:
ret = ret[:, :, np.newaxis]
return ret
def _augment_coords(self, coords, do):
if do:
coords = coords[:, ::-1]
return coords
|
[
"[email protected]"
] | |
6df0e64800da4c8a788cf625ac191169d6db205a
|
5c4852f02b20c5c400c58ff61702a4f35358d78c
|
/editor_orig.py
|
6a4e667273bf50ee0537555a81df701903e3eec4
|
[] |
no_license
|
anovacap/daily_coding_problem
|
6e11f338ad8afc99a702baa6d75ede0c15f02853
|
e64a0e76555addbe3a31fd0ca0bb81e2715766d2
|
refs/heads/master
| 2023-02-23T11:04:30.041455 | 2021-01-29T18:10:36 | 2021-01-29T18:10:36 | 302,237,546 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,992 |
py
|
class SimpleEditor:
def __init__(self, document):
self.document = document
self.dictionary = set()
# On windows, the dictionary can often be found at:
# C:/Users/{username}/AppData/Roaming/Microsoft/Spelling/en-US/default.dic
with open("/usr/share/dict/words") as input_dictionary:
for line in input_dictionary:
words = line.strip().split(" ")
for word in words:
self.dictionary.add(word)
self.paste_text = ""
def cut(self, i, j):
self.paste_text = self.document[i:j]
self.document = self.document[:i] + self.document[j:]
def copy(self, i, j):
self.paste_text = self.document[i:j]
def paste(self, i):
self.document = self.document[:i] + self.paste_text + self.document[i:]
def get_text(self):
return self.document
def misspellings(self):
result = 0
for word in self.document.split(" "):
if word not in self.dictionary:
result = result + 1
return result
import timeit
class EditorBenchmarker:
new_editor_case = """
from __main__ import SimpleEditor
s = SimpleEditor("{}")"""
editor_cut_paste = """
for n in range({}):
if n%2 == 0:
s.cut(1, 3)
else:
s.paste(2)"""
editor_copy_paste = """
for n in range({}):
if n%2 == 0:
s.copy(1, 3)
else:
s.paste(2)"""
editor_get_text = """
for n in range({}):
s.get_text()"""
editor_mispellings = """
for n in range({}):
s.misspellings()"""
def __init__(self, cases, N):
self.cases = cases
self.N = N
self.editor_cut_paste = self.editor_cut_paste.format(N)
self.editor_copy_paste = self.editor_copy_paste.format(N)
self.editor_get_text = self.editor_get_text.format(N)
self.editor_mispellings = self.editor_mispellings.format(N)
def benchmark(self):
for case in self.cases:
print("Evaluating case: {}".format(case))
new_editor = self.new_editor_case.format(case)
cut_paste_time = timeit.repeat(stmt=self.editor_cut_paste,setup=new_editor,repeat=3,number=1)
print("{} cut paste operations took {} s".format(self.N, cut_paste_time))
copy_paste_time = timeit.repeat(stmt=self.editor_copy_paste,setup=new_editor,repeat=3,number=1)
print("{} copy paste operations took {} s".format(self.N, copy_paste_time))
get_text_time = timeit.repeat(stmt=self.editor_get_text,setup=new_editor,repeat=3,number=1)
print("{} text retrieval operations took {} s".format(self.N, get_text_time))
mispellings_time = timeit.repeat(stmt=self.editor_mispellings,setup=new_editor,repeat=3,number=1)
print("{} mispelling operations took {} s".format(self.N, mispellings_time))
if __name__ == "__main__":
b = EditorBenchmarker(["hello friends"], 20)
b.benchmark()
|
[
"[email protected]"
] | |
d045b497d933aa18b4778d7534a892d04146d5e7
|
fd8f3f3d8b9a7f43f2961e290faa53fc29851baf
|
/auth_enj/urls.py
|
e6dc0b88d97a8cb6a12910e97a932da5f987f49f
|
[] |
no_license
|
TwoCatsCanFly/localSite
|
5d629e07183e24cb106612795d5e7bbbeabe8ed4
|
47a91990f6860bed315bb0c5af65c2e349934348
|
refs/heads/master
| 2022-12-06T22:23:07.441937 | 2020-09-01T09:00:00 | 2020-09-01T09:00:00 | 284,434,875 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 855 |
py
|
from django.urls import path
from .views import *
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('register/', UserRegistrationView.as_view(), name='register'),
path('edit-profile/', UserEditView.as_view(), name='edit_profile'),
#path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change_password.html')),
path('password/', PasswordsChangeView.as_view(template_name='registration/change_password.html')),
path('password_success/', views.password_success, name='password_success'),
path('<int:pk>/profile/', ShowProfileView.as_view(), name='show_profile'),
path('<int:pk>/edit_profile_page/', EditProfilePageView.as_view(), name='edit_profile_page'),
path('create_profile_page/', CreateProfilePageView.as_view(), name='create_profile_page'),
]
|
[
"[email protected]"
] | |
d7ce13d83dd278c415907caea2967729f60ed941
|
78a8c8a60b9ebb6c5e01528253971f8464acdc27
|
/python/problem79.py
|
be165c1f7339f7177c38ab3d2d5c3cc45a096b0d
|
[] |
no_license
|
hakver29/project_euler
|
f1b2d19f0bf2c6b842256f961845424cd2dc696f
|
ab356a32d706759531cad7a1a6586534ff92c142
|
refs/heads/master
| 2021-06-03T13:39:22.758018 | 2020-12-01T23:42:35 | 2020-12-01T23:42:35 | 70,273,535 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 559 |
py
|
import pandas as pd
import os
path = './p079_keylog.txt'
data = pd.read_csv(path, header=None)
print(data)
# First letter: [1,3,6,7]
# Only 7 is always first: 7
# Second letter: [1,2,3,6]
# 3 before 1
# 3 before 6
# 3 before 2
# Second letter: 3
# Third letter: [0, 1,2,6,7,8,9]
# 1 before 9 2 8 6 0
# Third letter: 1
# Fourth letter: [0,2,6,8,9]
# 6 before 0,2,8,9
# Fourth letter: 6
# Fifth letter: [0,2,8,9]
# 8 before 0
# 9 before 0
# 8 before 9
# 2 before 9
# 2 before 8
# Fifth letter: 2
# Sixth letter: [0,8,9]
# Remaining: 890
# Answer: 73162890
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.