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
b85a9449dcba5e43a9e775aaff8bc04adbccb40d
67fbc7e92049d81993fbd6011e37bb9de24027c7
/ej8/src/consts.py
c0a739efc1be6bc98ede53d611a2a6882ee8e6e8
[]
no_license
guillermoap/aa-pract6
3102f182cb02e0ef0ea7580f12c906f024759542
0a70826f37b41a4d5862c2f78adee3b3d1a79a2c
refs/heads/master
2020-05-27T05:45:03.791965
2019-06-08T22:58:02
2019-06-08T22:58:02
188,506,629
0
0
null
null
null
null
UTF-8
Python
false
false
387
py
BOARD_WIDTH = 25 BOARD_HEIGHT = 17 INVALID_SPACE = -1 EMPTY_SPACE = 0 RED = 1 GREEN = 4 LEFT = (0, -2) RIGHT = (0, 2) UP_RIGHT = (1, 1) UP_LEFT = (1, -1) DOWN_RIGHT = (-1, 1) DOWN_LEFT = (-1, -1) MOVES = [ LEFT, RIGHT, UP_RIGHT, UP_LEFT, DOWN_LEFT, DOWN_RIGHT ] MAX_PLAYS = 3000 MAX_MATCHES = 10 WIN = 1 TIE = 0 LOSS = -1 NEURAL_TYPE = 0 CLASSIC_TYPE = 1 MODEL_PATH = 'model.h5'
[ "mauricio.irace@pyxis.com.uy" ]
mauricio.irace@pyxis.com.uy
0d66bfb2e2f61e6192594453d928317bed7f64d2
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/MAzBohC2PxchT3wqK_13.py
a37c09d7d848225a334c7b4bb512adb1efefa6cd
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
360
py
def shadow_sentence(a, b): alist, blist = a.split(' '), b.split(' ') if len(alist) != len(blist): return False j = -1 for word in alist: j += 1 if len(word) != len(blist[j]): return False i = -1 for word in blist: i += 1 for letter in word: if letter in alist[i]: return False return True
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
8b3cc35a16fbeebfb02fb67969fc212e5feaaa93
9fc1079a9f679f21c860f4103df2a7f77c451010
/my_project/lib/python2.7/types.py
12aba1aca776e320fe0773084ec82329695d554a
[]
no_license
ramcharangalla/studiegenie
4f7182096d37150b5da32475978b95f5e95c61ca
483df650cc4a2dc3864ce7f4993680780127f253
refs/heads/master
2020-04-07T09:49:06.995233
2018-11-29T08:32:31
2018-11-29T08:32:31
158,266,164
0
0
null
2018-11-29T01:11:16
2018-11-19T17:37:49
Python
UTF-8
Python
false
false
46
py
/Users/Charan/anaconda2/lib/python2.7/types.py
[ "gallaramcharan@gmail.com" ]
gallaramcharan@gmail.com
01eb27b1efe1e94dc35839dd99988ef3512c19f4
6584124fee86f79ce0c9402194d961395583d6c3
/blog/migrations/0005_userprofile.py
741df13e8b0ed00bd33880271c9c54062c148c8f
[]
no_license
janusnic/webman
fdcffb7ed2f36d0951fd18bbaa55d0626cd271e1
2e5eaadec64314fddc19f27d9313317f7a236b9e
refs/heads/master
2018-12-28T18:21:00.291717
2015-06-05T11:49:00
2015-06-05T11:49:00
35,676,834
0
0
null
null
null
null
UTF-8
Python
false
false
796
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog', '0004_auto_20150522_1108'), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('website', models.URLField(blank=True)), ('picture', models.ImageField(upload_to=b'profile_images', blank=True)), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)), ], ), ]
[ "janusnic@gmail.com" ]
janusnic@gmail.com
3232566169f973d936ec35d9dd66eb7a04b3b426
8560680ec56764b93e57b54f603207e94091ee55
/Hackference/Hunger_Management/urls.py
ed64bccd7326de6915fa03310bf1f60e9a04520f
[]
no_license
devikasugathan/Hackferance
f6e13488697f8505a4617dcee05125cc335234dc
1a72daf1a6837ab650cab9a1503c901d7e69871b
refs/heads/master
2020-04-11T05:00:26.462724
2018-12-13T14:23:32
2018-12-13T14:23:32
161,534,831
0
0
null
null
null
null
UTF-8
Python
false
false
679
py
from django.conf.urls import url from django.urls import path, include from . import views from django.views.generic.base import TemplateView urlpatterns = [ url(r'^signup/$', views.signup, name='signup'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), path('',TemplateView.as_view(template_name='index.html'),name='index'), path('about/',TemplateView.as_view(template_name='about-us.html'),name='about'), path('contact/',TemplateView.as_view(template_name='contact.html'),name='contact'), path('',TemplateView.as_view(template_name='index.html'),name='index'), ]
[ "ivvraghavendra1999@gmail.com" ]
ivvraghavendra1999@gmail.com
5c4ddecc079d9e18ad7419ae2086e5021ac6f8e2
fdc7d1ca6d83735f241dfa173b0012a3866ad39e
/barra.py
d515e91e977ab033d5f88bda3bca7995bce0cd20
[]
no_license
Mohamedtareque/joac-python
33b61ff7c3183c2226ce3939b215d95903482fcc
cf0d2829f344bc5f1392d657b5e48924e015d715
refs/heads/master
2020-04-06T04:48:00.311967
2013-03-01T20:29:54
2013-03-01T20:29:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
243
py
import time n = 0 dec = False while True: # print " "*n +"^fg(#FF0000)Hola Mundo^c(%d)" %(n*n) print "mama ^ib(1)^p(10)^fg(#aecf96)^c(10)^p(-15)^fg(grey40)^co(20-%d)" %n n += 3 if n == 360: n = 0 time.sleep(0.5)
[ "joac@gcoop.coop" ]
joac@gcoop.coop
21f960441b8bc9a04eb717d0e9816bcb473adeea
6a8daf093b1f2da1eff86f889184b5c4fe7c8412
/Filters/RoadFilter_WGAN.py
b929975857928dba638346e68b76e1d1dc92adbf
[ "MIT" ]
permissive
PreslavKisyov/RoadFilter
90ab36ec595c21d67f27bc7e41a6f11781c6f24c
a814f61ebf4ebf852d2233aee79d3127a8360d8b
refs/heads/main
2023-07-13T02:16:07.681348
2021-08-22T14:28:59
2021-08-22T14:28:59
366,338,191
0
0
null
null
null
null
UTF-8
Python
false
false
24,055
py
import keras import numpy as np from PIL import Image import cv2.cv2 as cv2 import A_star as star import utilityFunctions as uf from itertools import combinations """ This class creates and processes the Road Network Image. A WGAN Generates a road image and then it is adapted to the selected terrain using Computer Vision techniques. The road is then placed in Minecraft and further processed to resemble a real-like road system. @author: Preslav Kisyov """ class Roads: # A static variable that defines the path for the model path = "stock-filters/Roads/RoadWGAN.h5" # This is the main method of the class # It initializes vital variables # @param n_maps The number of roads to combine # @param n_imgs The number of images generated def __init__(self, n_maps=2, n_imgs=25): self.latent_dim = 100 self.n_imgs = n_imgs self.n_maps = n_maps self.usable_floor = None self.floor = None self.blocks = None # Execute functions imgs = self.load_model() self.road_network = self.get_road_network(imgs) # This method loads a keras model from path # and produces noise to be passed through the model # @return The predicted WGAN images def load_model(self): model = keras.models.load_model(self.path) noise = np.random.random(self.n_imgs * self.latent_dim).reshape(self.n_imgs, self.latent_dim) # Generate n_imgs number of images imgs = model.predict(noise) imgs = (imgs + 1) / 2.0 # Normalize to between 0-1 return imgs # From n_imgs images, perform Preprocessing # and extract one road network image # @param imgs The list of images # @return road_network One generate road image def get_road_network(self, imgs): road_maps = list() image_index = 0 while len(road_maps) != self.n_maps: # If there are no more valid road maps (above the pct) if image_index > self.n_imgs: index_list = np.random.random_integers(self.n_imgs, size=self.n_maps - len(road_maps)) for i in index_list: road_maps.append(imgs[i, :, :, 0]) break # Get the percentage of roads present img = imgs[image_index, :, :, 0] count = np.count_nonzero(img) pct_count = (count/float(img.shape[0]*img.shape[1])) * 100.0 image_index += 1 # Add a road if it contains at least 20% of road infrastructure if pct_count > 20.0: road_maps.append(img) # Combine all road maps into one road_network = road_maps[0] for road_map_index in range(1, self.n_maps): road_network += road_maps[road_map_index] return road_network # This method processes the road image # by applying Computer Vision methods to clean it # @param region_size The size of the selected Minecraft region # @return A processed road image def process_road_network(self, region_size): # Get the required size and convert to grayscale image size = np.mgrid[region_size.minx:region_size.maxx, region_size.minz:region_size.maxz][0].shape min_size, max_size = min(size), max(size) road_network_gray = np.array(self.road_network * 255, dtype=np.uint8) # Perform Closing (Dilation -> Erosion) kernel = np.ones((2, 2), np.uint8) road_network_dilated = cv2.dilate(road_network_gray, kernel) road_network_closed = cv2.erode(road_network_dilated, kernel) # Remove Disconnected Components components, objects, stats, _ = cv2.connectedComponentsWithStats(road_network_closed, connectivity=4) sizes = stats[1:, -1] # Remove the background as a component max_component = np.where(sizes == max(sizes))[0] + 1 road_network_closed[objects != max_component] = 0 # Resize to the required size using Interpolation and convert to Binary processed_road_network = np.array(Image.fromarray(road_network_closed).resize((min_size, max_size), Image.LANCZOS)) return cv2.threshold(processed_road_network, int(np.mean(processed_road_network)), 255, cv2.THRESH_BINARY)[1] # This method build the road if not in water # @param level The level provided by MCEdit # @param floor_points, usable_floor The whole floor map and the array containing the roads # @param road The road generated image as an array # @param box The bounding box provided by MCEdit # @param blocks A list of block types def build_road(self, level, floor_points, road, box, usable_floor, blocks): for pos in sorted(floor_points): x, y, z = floor_points[pos] # Remove Lava self.remove_lava(level, x, y, z, box) if pos in tuple(zip(*np.where(road == 255))) and level.blockAt(x, y, z) not in [0, 8, 9]: # Remove trees if on road self.remove_tree(level, x, y, z) # Build the road uf.setBlock(level, blocks[0], x, y, z) # Build tunnel self.build_tunnel(level, x, y, z, blocks[0]) try: usable_floor[pos[0]][pos[1]] = 255 except: print("Error: Index is out of range for usable_floor!\nNo Roads will be connected!\nProbably the floor is invalid!") # Assign floor array and map self.usable_floor = usable_floor self.floor = floor_points self.blocks = blocks # Get Components components, usable_floor = self.get_components(level, usable_floor, floor_points) floor = np.zeros(usable_floor.shape) if usable_floor is not None else None # Check if there are separated components if components is not None: self.connect_components(level, components, floor, floor_points, np.array(usable_floor), blocks) # This method builds a tunnel if there are block above the path # @param level The level provided by MCEdit # @param x, y, z The coordinates of the path # @param block The type of block def build_tunnel(self, level, x, y, z, block): for i in range(1, 3): # Make the tunnel 2 blocks high if level.blockAt(x, y+i, z) in [1, 2, 3, 12, 13, 78, 80]: uf.setBlock(level, (0, 0), x, y+i, z) block_points = [(x+1, z), (x+1, z+1), (x+1, z-1), (x-1, z), (x-1, z+1), (x-1, z-1), (x, z+1), (x, z-1)] is_tunnel_roof = False for p in block_points: if level.blockAt(p[0], y+3, p[1]) != 0: is_tunnel_roof = True; break # Build tunnel ceiling if necessary if is_tunnel_roof and level.blockAt(x, y+3, z) in [0, 17, 81, 162, 18, 161]: uf.setBlock(level, block, x, y+3, z) # This method tries to find a path between every disconnected road # @param level The level provided by MCEdit # @param components The map of disconnected roads # @param free_floor The floor without any obstructions # @param floor_points, usable_floor The whole floor map and the array containing the roads # @param blocks A list of block types def connect_components(self, level, components, free_floor, floor_points, usable_floor, blocks): start_end_points = list(combinations(components.keys(), 2)) print("There are " + str(len(components)) + " disconnected roads!") visited = set() # For every disconnected road point for points in start_end_points: if points[0] in visited: continue visited.add(points[0]) path = star.search(free_floor, 1, components[points[0]], components[points[1]]) ar_path = np.array(path) if path is not None: # Build connecting road rows, cols = np.where(ar_path != -1) for i in range(len(rows)-1): usable_floor[rows[i]][cols[i]] == 255 # Add the new path self.connect_roads(rows, cols, level, floor_points, usable_floor, blocks) # Update floor array self.usable_floor = usable_floor # This method uses the A* path to connect the disconnected roads # @param rows, cols The rows and columns of the path array # @param level The level provided by MCEdit # @param floor_points, usable_floor The whole floor map and the array containing the roads # @param blocks A list of block types # @param package=None The package of lvl, start point and blocks for when connecting houses def connect_roads(self, rows, cols, level, floor_points, usable_floor, blocks, package=None): is_start, is_end = False, False block, slab, _ = blocks # Go through every path point for i in range(len(rows)): r, c = rows[i], cols[i] x, y, z = floor_points[(r, c)] # Check if connecting houses to roads if package is not None: lvl, start, floor_blocks = package if [r, c] == start or i in [1, 2, 3]: # If the first several blocks if lvl == 0: y = y - 2 elif lvl == 1: y = y - 1 else: y = y if level.blockAt(x, y, z) in floor_blocks or level.blockAt(x, y-1, z) in floor_blocks: continue if level.blockAt(x, y, z) in [0, 8, 9]: # Build Bridge uf.setBlock(level, block, x, y+1, z) if not is_start: self.build_bridge_walls(level, block, x, y, z) else: is_start = False is_end = True else: # Build Road if is_end: uf.setBlock(level, slab, x, y+1, z) is_end = False uf.setBlock(level, block, x, y, z) try: # Put a step in front of the bridge if usable_floor[r+1][c+1] != len(usable_floor)-1 and usable_floor[r+1][c+1] == 1: uf.setBlock(level, slab, x, y+1, z) is_start = True except: print("Out of bounds for slab - maybe the floor is invalid!") # This method builds the walls of any bridge # @param level The level provided by MCEdit # @param block The block type for the walls # @param x, y, z The coordinates def build_bridge_walls(self, level, block, x, y, z): wall_points = [(x+1, y+1, z+1), (x-1, y+1, z-1), (x+1, y+1, z-1), (x-1, y+1, z+1), (x, y+1, z+1), (x, y+1, z-1), (x+1, y+1, z), (x-1, y+1, z)] for p in wall_points: # Build the block for each wall point if level.blockAt(p[0], p[1], p[2]) not in [block[0], 8, 9] and level.blockAt(p[0], p[1]-1, p[2]) in [0, 8, 9]: uf.setBlock(level, block, p[0], y+2, p[2]) if level.blockAt(x, y+2, z) in [block[0]]: uf.setBlock(level, (0, 0), x, y+2, z) # Remove wall if on path # This method gets if there are any disconnected roads # @param level The level provided by MCEdit # @param floor_points, usable_floor The whole floor map and the array containing the roads def get_components(self, level, usable_floor, floor_points): try: # Check if the selected bottom has no air gaps ar_floor = np.array(usable_floor, dtype=np.uint8) except: print("Invalid floor has been selected!\nNo components will be found!") return None, None # Get any disconnected components from the road map array/image components, objects, _, _ = cv2.connectedComponentsWithStats(ar_floor, connectivity=8) if components < 3: return None, None # The background + 2 separated roads = 3 components comp = np.arange(1, components) # All components except the background components_map = {} for x in range(0, ar_floor.shape[0]): for y in range(0, ar_floor.shape[1]): posx, posy, posz = floor_points[(x, y)] if level.blockAt(posx, posy, posz) in [8, 9]: ar_floor[x][y] = 1 # put water in path array if objects[x][y] in comp: # Record the positions of each component components_map[objects[x][y]] = [x, y] comp = np.delete(comp, np.argwhere(comp == objects[x][y])) return components_map, ar_floor # This method removes any detected lava # @param level The level provided by MCEdit # @param box The selected Minecraft region # @param x, y, z The coordinates of the block def remove_lava(self, level, x, y, z, box): block = level.blockAt(x, y, z) c_x, c_y = 0, 0 # Get the closest non-obstacle block while block in [8, 9, 10, 11]: if x+c_x != box.maxx: block = level.blockAt(x+c_x, y, z) c_x += 1 else: block = level.blockAt(x, y+c_y, z) c_y += 1 if y+c_y == box.maxy: block = 0 # If there is lava if level.blockAt(x, y, z) in [10, 11]: uf.setBlock(level, (block, 0), x, y, z) elif level.blockAt(x, y+1, z) in [10, 11]: uf.setBlock(level, (block, 0), x, y+1, z) # This method sets the bounding box of each tree on path # @param level The level provided by MCEdit # @param x, y, z The coordinates of the road def remove_tree(self, level, x, y, z): points_x, points_y, points_z = [], [y], [] is_start = True posy = y+1 y += 1 while True: # For each y (height) level, get the bounding box if a tree if level.blockAt(x, y, z) in [17, 81, 162] and is_start: # Remove tree iff the tree base is on the road points_y.append(y) points_x = self.get_x_bound(level, x, y, z, points_x) points_z = self.get_z_bound(level, x, y, z, points_z) if level.blockAt(x, y+1, z) in [18, 161]: is_start = False elif level.blockAt(x, y, z) in [18, 161] and not is_start: # Remove the leaves of the tree points_y.append(y) points_x = self.get_x_bound(level, x, y, z, points_x) points_z = self.get_z_bound(level, x, y, z, points_z) else: break y += 1 self.remove_tree_from_bound(level, points_x, points_y, points_z, [x, posy, z]) # This method goes through every point in the found # x, z, y boundary box and removes any trees found # @param level The level given from MCEdit # @param points_x, points_y, points_z The list of x, y, z points # @param road The coordinates of the current road def remove_tree_from_bound(self, level, points_x, points_y, points_z, road): if points_x and points_y and points_z: # Get the min and max of each direction of the box minx, maxx = min(points_x), max(points_x) miny, maxy = min(points_y), max(points_y) minz, maxz = min(points_z), max(points_z) first_tree, leaf = False, None last_tree, trees = [], {} # Remove Trees on Path using the found x, z, y boundary box for x in range(minx-2, maxx+2): for z in range(minz-2, maxz+2): for y in range(miny-1, 350): if level.blockAt(x, y, z) in [17, 18, 81, 161, 162]: if level.blockAt(x, y, z) in [17, 81, 162] and not first_tree and [x, y, z] != road: trees[(x, z)] = y if level.blockAt(x, y, z) in [17, 81, 162] and not first_tree and [x, y, z] == road: first_tree = True uf.setBlock(level, (0, 0), x, y, z) last_tree.append((x, z)) elif level.blockAt(x, y, z) in [17, 81, 162] and first_tree: if (x, z) in last_tree: uf.setBlock(level, (0, 0), x, y, z) else: break elif level.blockAt(x, y, z) in [18, 161]: leaf = level.blockAt(x, y, z) uf.setBlock(level, (0, 0), x, y, z) first_tree = False # Grow back leaves on cut trees that are not on road for tree in trees.iterkeys(): y = trees[tree] points = [(tree[0]+1, tree[1]+1), (tree[0]-1, tree[1]-1), (tree[0]+1, tree[1]-1), (tree[0]-1, tree[1]+1), (tree[0], tree[1]+1), (tree[0]+1, tree[1]), (tree[0]-1, tree[1]), (tree[0], tree[1]-1)] leaf = leaf if leaf is not None else 18 # Set default leaf for p in points: uf.setBlock(level, (leaf, 0), p[0], y, p[1]) uf.setBlock(level, (leaf, 0), tree[0], y+1, tree[1]) # Get the leaves of the tree for the X axis # @param level The level provided by MCEdit # @param x, y, z The coordinates to search from # @param points_x The list of found points on the X axis def get_x_bound(self, level, x, y, z, points_x): posx = x+1 reverse = False while True: if reverse is False: # Search one direction if level.blockAt(posx, y, z) in [18, 161]: points_x.append(posx) posx += 1 else: posx = x-1 reverse = True else: # Search the other direction if level.blockAt(posx, y, z) in [18, 161]: points_x.append(posx) posx -= 1 else: break return points_x # Get the leaves of the tree for the Z axis # @param level The level provided by MCEdit # @param x, y, z The coordinates to search from # @param points_z The list of found points on the Z axis def get_z_bound(self, level, x, y, z, points_z): posz = z+1 reverse = False while True: if reverse is False: # Search one direction if level.blockAt(x, y, posz) in [18, 161]: # Removes all trees TODO: Move it so you remove only if on path way points_z.append(posz) posz += 1 else: posz = z-1 reverse = True else: # Search the other direction if level.blockAt(x, y, posz) in [18, 161]: # Removes all trees TODO: Move it so you remove only if on path way points_z.append(posz) posz -= 1 else: break return points_z """ This is the main function that gets called after executing the filter in MCEdit """ def perform(level, box, options, block=None, need_return=False): road = Roads() road_network = road.process_road_network(box) # Get the road as a Numpy array Image biom, road_blocks = get_biom(level, box) # Get the biom and types of blocks floor, usable_floor = get_floor(level, box) # Get the usable floor box region if block is not None: road_blocks[0] = block # Select Block types road.build_road(level, floor, road_network, box, usable_floor, road_blocks) # Build and connect roads if need_return: return road # This method connects a House (from the door position) # To the closest road, by extending the road system. # It should be called from another filter, and roads should # already be present. # @param level The level provided by MCEdit # @param door_loc The location point of the door # @param road The road class # @param blocks A list of block types def connect_houses_to_roads(level, door_loc, road, blocks): if road.floor is None or road.usable_floor is None or road.blocks is None: print("Road Floor is None!") return floor = dict((value, key) for key, value in road.floor.iteritems()) # Revert the point map usable_floor = np.array(road.usable_floor) if len(usable_floor.shape) != 2: return x, z, y = door_loc # Get the point in space of the door (Depending on the door position) if floor.get((x, y-2, z)) is not None: # Beginning of door start = floor.get((x, y-2, z)) lvl = abs((x, y, z)[1]) - abs((x, y-2, z)[1]) # 2 elif floor.get((x, y-1, z)) is not None: # Middle of door start = floor.get((x, y-1, z)) lvl = abs((x, y, z)[1]) - abs((x, y-1, z)[1]) # 1 elif floor.get((x, y, z)) is not None: # Top of door start = floor.get((x, y, z)) lvl = 0 else: print("Path cannot be found!"); return start = [start[0], start[1]] # Get end point (First run => get closest) end, run = None, 1 ending = [usable_floor.shape[0], usable_floor.shape[1]] beginning = [start[0], start[1]] if start[1] < ending[1] else [0, 0] while run < 3: for r in range(beginning[0], ending[0]): for c in range(beginning[1], ending[1]): if usable_floor[r][c] == 255: end = [r, c] if end is None: beginning = [0, 0]; run += 1 else: break if end is None: return # Get the A* path path = star.search(np.zeros(usable_floor.shape), 1, start, end) if path is None: return rows, cols = np.where(np.array(path) != -1) # Get the actual path positions package = [lvl, start, [block[0] for block in blocks]] road.connect_roads(rows, cols, level, road.floor, usable_floor, road.blocks, package) # Get the floor points array and the floor map of coordinates # @param level The level provided by MCEdit # @param box The region selected in Minecraft def get_floor(level, box): mapped_points = {} usable_floor = [] pos_x, pos_y = 0, 0 for x in range(box.minx, box.maxx): # depth col = [] for z in range(box.minz, box.maxz): # width for y in range(box.maxy, box.miny-1, -1): # height (col) but count the selected level if level.blockAt(x, y, z) in [1, 2, 3, 8, 9, 10, 11, 12, 13, 78, 80] and (pos_x, pos_y) not in mapped_points.keys(): mapped_points[(pos_x, pos_y)] = (x, y, z) col.append(0) break elif level.blockAt(x, y-1, z) in [1, 2, 3, 8, 9, 10, 11, 12, 13, 78, 80] and (pos_x, pos_y) not in mapped_points.keys(): mapped_points[(pos_x, pos_y)] = (x, y-1, z) col.append(0) break pos_y += 1 usable_floor.append(col) pos_y = 0 pos_x += 1 return mapped_points, usable_floor # This method gets the biom and # selects road block types given that information. # It is based on probabilities # @param level The level provided by MCEdit # @param box The region selected in Minecraft # @return road_biom, road_blocks The biom and road block types selected on majority voting def get_biom(level, box): road_choices = [] # Choice per slice for (chunk, slices, point) in level.getChunkSlices(box): bins = np.bincount(chunk.root_tag["Level"]["Biomes"].value) count = bins/float(len(chunk.root_tag["Level"]["Biomes"].value)) bioms = np.flatnonzero(count) probs = {i:count[i] for i in bioms} road_choices.append(np.random.choice(probs.keys(), p=probs.values())) road_biom = max(road_choices, key=road_choices.count) road_blocks = get_road_blocks(road_biom) return road_biom, road_blocks # All Minecraft blocks can be found here - https://minecraft-ids.grahamedgecombe.com/ # All Minecraft biomes can be found here - https://minecraft.fandom.com/wiki/Biome/ID # From official Minecraft Wiki (Biomes and Blocks ID) # This method is to be used if the filter is used alone def get_road_blocks(road_biom): # Block, Slab, Stairs if road_biom in [2, 7, 16, 17, 27, 28, 36, 37, 38, 39, 130, 165, 166, 167]: return [(43, 0), (44, 0), (109, 0)] else: return [(1, 0), (44, 5), (67, 0)]
[ "preslavkisyov98@gmail.com" ]
preslavkisyov98@gmail.com
e9438a6805885c511dd1e083ebf82a4d655f36f7
bdb97c54781664620e18077c14c1b879c987ddcd
/src/ned.py
b6af0698b28a071bfafaaacfc734edf022c3c253
[]
no_license
b07902067/Usage-and-some-experiment-of-Omnet-Nesting-
551d3389551d9c8ccf118b40fb3e9cd03dae6bb1
f5d54e76a5cd4739fd4fc3cd8975c8494c830acb
refs/heads/main
2023-08-15T14:35:13.742073
2021-10-02T05:27:10
2021-10-02T05:27:10
407,749,467
0
0
null
null
null
null
UTF-8
Python
false
false
2,727
py
from topology import * from util import * import sys ned_head = "package nesting.simulations;\nimport ned.DatarateChannel;\nimport nesting.node.ethernet.VlanEtherHostQ;\nimport nesting.node.ethernet.VlanEtherHostSched;\nimport nesting.node.ethernet.VlanEtherSwitchPreemptable;" def make_ned(T, network_name, out_f): with open(out_f, 'w') as of: print(ned_head, file=of) print('network {}'.format(str(network_name)), file=of) print('{\n\t@display(\"bgb=831,521\")\;\n', file=of) '''types''' print("\ttypes:\n", file=of) print("\t\tchannel C extends DatarateChannel\n\t\t{\n\t\t\tdelay = 0.1us;\n\t\t\tdatarate = 1Gbps;\n\t\t}", file=of) # for i in range(T.node_n): # for j in range(T.node_n): # if i == j: # continue # if T.links_list[i][j].cap == -1: # continue # print("\tchannel C{}{} extends DatarateChannel".format(i , j), file=of) # print("\t{", file=of) # print("\t\tdatarate = {}Gbps;".format(T.links_list[i][j].cap), file=of) # print("\t}", file=of) # print("", file=of) '''submodules''' print("\tsubmodules:\n", file=of) # host for i in range(T.node_n): print("\t\thost{}: VlanEtherHostSched ".format(i), file=of) print("\t\t{", file=of) print("\t\t\t@display(\"p=66,207\");", file=of) print("\t\t}", file=of) print("\t\tswitch{}: VlanEtherSwitchPreemptable".format(i), file=of) print("\t\t{", file=of) print("\t\t\tparameters:", file=of) print("\t\t\t\t@display(\"p=307.65,94.5\");", file=of) print("\t\t\tgates:", file=of) print("\t\t\t\tethg[{}];".format(T.switch_list[i].free_port), file=of) print("\t\t}", file=of) print("", file=of) # switch '''connections''' print("\tconnections:\n", file=of) # host <---> switch for i in range(T.node_n): print("\t\thost{}.ethg <--> C <--> switch{}.ethg[0];".format(i, i), file=of) # switch <--> switch for i in range(T.node_n): for j in range(T.node_n): if i == j: continue if T.links_list[i][j].cap == -1: continue print("\t\tswitch{}.ethg[{}] <--> C <--> switch{}.ethg[{}];".format(i, T.links_list[i][j].src_port, j, T.links_list[i][j].dst_port), file=of) print("}", file=of) if __name__ == "__main__": T, _ = parse_topology_file("./5.in") make_ned(T, "./test.ned")
[ "b07902067@ntu.edu.tw" ]
b07902067@ntu.edu.tw
efb302e6899348b8a39d8588818d325e6a0f9ada
1d1a21b37e1591c5b825299de338d18917715fec
/Mathematics/Data science/Mathmatics/02/Exercise_2_4_5.py
4c1094e1a0624eace4209363bf4bc2727406716d
[]
no_license
brunoleej/study_git
46279c3521f090ebf63ee0e1852aa0b6bed11b01
0c5c9e490140144caf1149e2e1d9fe5f68cf6294
refs/heads/main
2023-08-19T01:07:42.236110
2021-08-29T16:20:59
2021-08-29T16:20:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,206
py
# 보스턴 집값 문제는 미국 보스턴내 각 지역(town)의 주택 가격을 그 지역의 범죄율이나 공기 오염도 등의 특징 # 을 사용하여 예측하는 문제다. Scikit-Learn 패키지에서 임포트할 수 있다. 보스턴 집값 문제를 선형 예측모형 # Ax = b_hat로 풀었을 때의 가중치 벡터 를 구하라. 행렬과 벡터 데이터는 다음과 같이 얻을 수 있다. 여기에서는 # 문제를 간단하게 하기 위해 입력 데이터를 범죄율(CRIM), 공기 오염도(NOX), 방의 개수(RM), 오래된 정도 # (AGE)의 4종류로 제한했고 데이터도 4개만 사용했다 import numpy as np from sklearn.datasets import load_boston boston = load_boston() X = boston.data y = boston.target A = X[:4, [0, 4, 5, 6]] # 'CRIM', 'NOX', 'RM', 'AGE' b = y[:4] x, resid, rank, s = np.linalg.lstsq(A,b) print(A) ''' [[6.320e-03 5.380e-01 6.575e+00 6.520e+01] [2.731e-02 4.690e-01 6.421e+00 7.890e+01] [2.729e-02 4.690e-01 7.185e+00 6.110e+01] [3.237e-02 4.580e-01 6.998e+00 4.580e+01]] ''' print(x) # [-3.12710043e+02 -1.15193942e+02 1.44996465e+01 -1.13259317e-01] print(b) # [24. 21.6 34.7 33.4]
[ "jk04059@naver.com" ]
jk04059@naver.com
94a9e541b2fa2135a91a001dba9d02732f78755a
63ef5054927443d020cfff3db0a86211b4ebe7f7
/copy_paster/board.py
ca5861b66c9cf74b3628ecf766dc805b1a5092e8
[]
no_license
JemitDave/Automation_scripts
d34b5e207a2142475a8beb82455917bcc9d9f672
b5ee9dd4755ba6ca8c76d1bfb8f7aab249c31973
refs/heads/master
2022-10-09T23:41:56.637300
2020-06-09T10:31:05
2020-06-09T10:31:05
269,611,351
0
0
null
null
null
null
UTF-8
Python
false
false
625
py
from pynput.keyboard import Key, Listener '''<qwwsxfdxdcs < ī ''' def on_press(key): if key==Key.ctrl_l: print('ctrl is pressed') #enter screenchot Code elif key==Key.tab: print('tab is pressed') #copy paste code else:pass # print('{0} pressed'.format( # key)) def on_release(key): # print('{0} release'.format( # key)) if key == Key.esc: # Stop listener return False # Collect events until released with Listener( on_press=on_press, on_release=on_release) as listener: listener.join()
[ "jemitdave@gmail.com" ]
jemitdave@gmail.com
3c47e45da6cd34f39675fdab3e6faf464b0c474b
10800834f081b59bb35f0205788c6a9a794ce3f9
/zhihuuser/zhihuuser/pipelines.py
0447149ee141cda07337dd49a1ec5f3ec0185e1c
[]
no_license
snackdeng/python-crawler
58574fe98cf36f8a2697d32bd8bfda06e6068be8
81337d8b42ab5b37e992f20a41cbd541171dcf83
refs/heads/master
2022-12-09T14:26:33.566593
2020-09-18T08:11:40
2020-09-18T08:11:40
284,236,477
2
1
null
null
null
null
UTF-8
Python
false
false
302
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html class ZhihuuserPipeline(object): def process_item(self, item, spider): return item
[ "noreply@github.com" ]
noreply@github.com
93dab5e033bf2be71722860d57e80346b770aa7b
3b1daac7c1f72b985da899770d98e5f0e8fb835c
/Configurations/VBS/2017CR_v7/variables.py
695bd91e5fdd8c45254bfdcdab37fb9d9235b46a
[]
no_license
freejiebao/PlotsConfigurations
7e10aa45aa3bf742f30d1e21dc565d59d2a025d8
cdfd3aff38d1ece9599a699997753bc8ba01b9b1
refs/heads/master
2020-06-18T19:22:00.561542
2019-09-02T12:52:28
2019-09-02T12:52:28
186,931,874
0
0
null
2019-05-16T01:58:07
2019-05-16T01:58:07
null
UTF-8
Python
false
false
5,363
py
# variables #variables = {} #'fold' : # 0 = not fold (default), 1 = fold underflowbin, 2 = fold overflow bin, 3 = fold underflow and overflow # variables['events'] = { 'name': '1', # 'range' : (1,0,2), # 'xaxis' : 'events', # 'fold' : 3 # } variables['nJet'] = { 'name': 'nJet', 'range' : (6,0,6), 'xaxis' : 'njets', 'fold' : 3 } variables['nJet_v2'] = { 'name': 'Sum$(CleanJet_pt>30)', 'range' : (4,0,4), 'xaxis' : 'njets', 'fold' : 3 } variables['nLepton'] = { 'name': '1*(Alt$(Lepton_pt[0],0.)>20) + 1*(Alt$(Lepton_pt[1],0.)>20) + 1*(Alt$(Lepton_pt[2],0.)>20)+ 1*(Alt$(Lepton_pt[3],0.)>20) + 1*(Alt$(Lepton_pt[4],0.)>20)', 'range': (5,0,5), 'xaxis': '# leptons', 'fold': 3 } variables['mll'] = { 'name': 'mll', # variable name 'range' : (4, 0. ,500), # variable range 'xaxis' : 'mll [GeV]', # x axis name 'fold' : 3 } variables['mll_v3'] = { 'name': 'mll', # variable name 'range' : (12, 20. ,320), # variable range 'xaxis' : 'mll [GeV]', # x axis name 'fold' : 3 } variables['mll_v2'] = { 'name': 'mll', # variable name 'range' : (80, 0. ,800), # variable range 'xaxis' : 'mll [GeV]', # x axis name 'fold' : 3 } variables['mjj'] = { 'name': 'mjj', 'range': ([500,800,1200,1600,2000],), #for 500 < mjj < 1000 'xaxis': 'mjj [GeV]', 'fold': 3 } variables['mjj_v2'] = { 'name': 'mjj', 'range': ([500,800,1200,1800,2000],), #for 500 < mjj < 1000 'xaxis': 'mjj [GeV]', 'fold': 3 } variables['mjj_v3'] = { 'name': 'mjj', 'range': (15, 500. ,2000), #for 500 < mjj < 1000 'xaxis': 'mjj [GeV]', 'fold': 3 } variables['mjj_v4'] = { 'name': 'mjj', 'range': (10,0 ,500), #for 500 < mjj < 1000 'xaxis': 'mjj [GeV]', 'fold': 3 } variables['pt1'] = { 'name': 'Alt$(Lepton_pt[0],-9999.)', 'range' : (10,0.,100), 'xaxis' : 'p_{T} 1st lep', 'fold' : 3 } variables['pt2'] = { 'name': 'Alt$(Lepton_pt[0],-9999.)', 'range' : (10,0.,150), 'xaxis' : 'p_{T} 2nd lep', 'fold' : 3 } variables['jetpt1'] = { 'name': 'Alt$(Jet_pt[0],-9999.)', 'range' : (15,0.,200), 'xaxis' : 'p_{T} 1st jet', 'fold' : 3 } variables['jetpt2'] = { 'name': 'Alt$(Jet_pt[1],-9999.)', 'range' : (15,0.,150), 'xaxis' : 'p_{T} 2nd jet', 'fold' : 3 } variables['met'] = { 'name': 'MET_pt', # variable name 'range' : (10,0,200), # variable range 'xaxis' : 'pfmet [GeV]', # x axis name 'fold' : 3 } variables['etaj1'] = { 'name': 'Alt$(Jet_eta[0],-9999.)', 'range': (10,-5,5), 'xaxis': 'etaj1', 'fold': 3 } variables['etaj2'] = { 'name': 'Alt$(Jet_eta[1],-9999.)', 'range': (10,-5,5), 'xaxis': 'etaj2', 'fold': 3 } variables['detajj'] = { 'name': 'detajj', 'range': (7,0.0,7.0), 'xaxis': 'detajj', 'fold': 3 } variables['Zlep1'] = { 'name': '(Alt$(Lepton_eta[0],-9999.) - (Alt$(Jet_eta[0],-9999.)+Alt$(Jet_eta[1],-9999.))/2)/detajj', 'range': (10,-1.5,1.5), 'xaxis': 'Z^{lep}_{1}', 'fold': 3 } variables['Zlep2'] = { 'name': '(Alt$(Lepton_eta[1],-9999.) - (Alt$(Jet_eta[0],-9999.)+Alt$(Jet_eta[1],-9999.))/2)/detajj', 'range': (10,-1.5,1.5), 'xaxis': 'Z^{lep}_{2}', 'fold': 3 } variables['csvv2ivf_1'] = { 'name': 'Alt$(Jet_btagCSVV2[0],0.)', 'range' : (10,0,1), 'xaxis' : 'csvv2ivf 1st jet ', 'fold' : 3 } variables['csvv2ivf_2'] = { 'name': 'Alt$(Jet_btagCSVV2[1],0.)', 'range' : (10,0,1), 'xaxis' : 'csvv2ivf 2nd jet ', 'fold' : 3 }
[ "jiexiao@pku.edu.cn" ]
jiexiao@pku.edu.cn
29972e6e177514dbea16cb61205578ba3cf7944b
aa9044b8cdcd1659e185b3351fa277b4ac32caf7
/api/migrations/0003_auto_20161211_1835.py
605a1be9fefd653a49aa68411ea37feb4625ce5a
[ "MIT" ]
permissive
ericpinet/MarkupEasy
4b289501b1070e23c3e29b90af6234b164ec7a48
09d17404e69587373436afbf60bbf0d1013b992b
refs/heads/master
2021-01-12T12:15:47.766376
2018-05-25T13:03:23
2018-05-25T13:03:23
72,394,785
1
0
MIT
2018-05-25T13:03:24
2016-10-31T03:14:15
JavaScript
UTF-8
Python
false
false
456
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-12-11 18:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20161120_2042'), ] operations = [ migrations.RemoveField( model_name='file', name='project', ), migrations.DeleteModel( name='File', ), ]
[ "pineri01@gmail.com" ]
pineri01@gmail.com
9c33c8ae778388e7fc2f54a5ecae6a2b4374b342
2892731203f7b59faa8f5182b756c0b3575e796f
/cma/droneinfo.py
d6b9218e794c97fb383e45b94cab59d6b0ad28a1
[]
no_license
assimilation/assimilation-official
1024b92badcbaf6b7c42f01f52e71c926a4b65f8
9ac993317c6501cb1e1cf09025f43dbe1d015035
refs/heads/rel_2_dev
2023-05-10T20:12:33.935123
2022-12-08T16:21:22
2022-12-08T16:21:22
42,373,046
52
17
null
2023-08-16T12:43:49
2015-09-12T21:04:36
Python
UTF-8
Python
false
false
23,416
py
#!/usr/bin/env python # vim: smartindent tabstop=4 shiftwidth=4 expandtab number colorcolumn=100 # # This file is part of the Assimilation Project. # # Copyright (C) 2011, 2012 - Alan Robertson <alanr@unix.sh> # # The Assimilation software is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # The Assimilation software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with the Assimilation Project software. If not, see http://www.gnu.org/licenses/ # # """ We implement the Drone class - which implements all the properties of drones as a Python class. """ from __future__ import print_function import time, sys # import os, traceback from cmadb import CMAdb from consts import CMAconsts from graphnodes import registergraphclass from systemnode import SystemNode from frameinfo import FrameSetTypes, FrameTypes from AssimCclasses import pyNetAddr, DEFAULT_FSP_QID, pyCryptFrame from assimevent import AssimEvent from cmaconfig import ConfigFile # droneinfo.py:39: [R0904:Drone] Too many public methods (21/20) # droneinfo.py:39: [R0902:Drone] Too many instance attributes (11/10) # pylint: disable=R0904,R0902 @registergraphclass class Drone(SystemNode): """Everything about Drones - endpoints that run our nanoprobes. There are two Cypher queries that get initialized later: Drone.IPownerquery_1: Given an IP address, return th SystemNode (probably Drone) 'owning' it. Drone.OwnedIPsQuery: Given a Drone object, return all the IPaddrNodes that it 'owns' """ IPownerquery_1 = None OwnedIPsQuery = None IPownerquery_1_txt = """MATCH (n:Class_IPaddrNode)<-[:%s]-()<-[:%s]-(drone) WHERE n.ipaddr = $ipaddr AND n.domain = $domain RETURN drone LIMIT 1""" OwnedIPsQuery_txt = """MATCH (d:Class_Drone)-[:%s]->()-[:%s]->(ip:Class_IPaddrNode) WHERE ID(d) = $droneid return ip""" # R0913: Too many arguments to __init__() # pylint: disable=R0913 def __init__( self, designation, port=None, startaddr=None, primary_ip_addr=None, domain=CMAconsts.globaldomain, status="(unknown)", reason="(initialization)", roles=None, key_id="", ): """Initialization function for the Drone class. We mainly initialize a few attributes from parameters as noted above... The first time around we also initialize a couple of class-wide query strings for a few queries we know we'll need later. We also behave as though we're a dict from the perspective of JSON attributes. These discovery strings are converted into pyConfigContext objects and are then searchable like dicts themselves - however updating these dicts has no direct impact on the underlying JSON strings stored in the database. The reason for treating these as a dict is so we can easily change the implementation to put JSON strings in separate nodes, or perhaps eventually in a separate data store. This is necessary because the performance of putting lots of really large strings in Neo4j is absolutely horrible. Putting large strings in is dumb and what Neo4j does with them is even dumber... The result is at least DUMB^2 -not 2*DUMB ;-) """ SystemNode.__init__(self, domain=domain, designation=designation) if roles is None: roles = ["host", "drone"] self.addrole(roles) self._io = CMAdb.io self.lastjoin = "None" self._active_nic_count = None self.status = status self.reason = reason self.key_id = key_id self.startaddr = str(startaddr) self.primary_ip_addr = str(primary_ip_addr) self.time_status_ms = int(round(time.time() * 1000)) self.time_status_iso8601 = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) if port is not None: self.port = int(port) else: self.port = None if Drone.IPownerquery_1 is None: Drone.IPownerquery_1 = Drone.IPownerquery_1_txt % ( CMAconsts.REL_ipowner, CMAconsts.REL_nicowner, ) Drone.OwnedIPsQuery_subtxt = Drone.OwnedIPsQuery_txt % ( CMAconsts.REL_nicowner, CMAconsts.REL_ipowner, ) Drone.OwnedIPsQuery = Drone.OwnedIPsQuery_subtxt self.set_crypto_identity() if self.association.is_abstract and not CMAdb.store.readonly: # print 'Creating BP rules for', self.designation from bestpractices import BestPractices bprules = CMAdb.config["bprulesbydomain"] rulesetname = bprules[domain] if domain in bprules else bprules[CMAconsts.globaldomain] for rule in BestPractices.gen_bp_rules_by_ruleset(CMAdb.store, rulesetname): # print ('ADDING RELATED RULE SET for', # self.designation, rule.bp_class, rule, file=sys.stderr) CMAdb.store.relate( self, CMAconsts.REL_bprulefor, rule, properties={"bp_class": rule.bp_class} ) print(f"PRIMARY IP for {self}: {repr(self.primary_ip_addr)})") def gen_current_bp_rules(self): """Return a generator producing all the best practice rules that apply to this Drone. """ return CMAdb.store.load_related(self, CMAconsts.REL_bprulefor) def get_bp_head_rule_for(self, trigger_discovery_type): """ Return the head of the ruleset chain for the particular set of rules that go with this particular node """ rules = CMAdb.store.load_related(self, CMAconsts.REL_bprulefor) for rule in rules: if rule.bp_class == trigger_discovery_type: return rule return None def get_merged_bp_rules(self, trigger_discovery_type): """Return a merged version of the best practices rules for this particular discovery type. This involves creating a hash table of rules, where the contents are merged together such that we return a single consolidated view of the rules to our viewer. We start out with the head of the ruleset chain and then merge in the ones its based on. We return a dict-like object reflecting this merger suitable for evaluating the rules. You just walk the set of rules and evaluate them. """ # Although we ought to hit the database once and get the PATH of the # rules in one fell swoop, we don't yet support PATHs, so we're going # at it the somewhat slower way -- incrementally. start = self.get_bp_head_rule_for(trigger_discovery_type) if start is None: return {} ret = start.jsonobj() this = start while True: nextrule = None for nextrule in CMAdb.store.load_related(this, CMAconsts.REL_basis): break if nextrule is None: break nextobj = nextrule.jsonobj() for elem in nextobj: if elem not in ret: ret[elem] = nextobj[elem] this = nextrule return ret @staticmethod def bp_category_score_attrname(category): "Compute the attribute name of a best practice score category" return "bp_category_%s_score" % category def bp_category_list(self): "Provide the list best practice score categories that we have stored" result = [] for attr in dir(self): if attr.startswith("bp_category_") and attr.endswith("_score"): result.append(attr[12:-6]) return result def bp_discoverytypes_list(self): "List the discovery types that we have recorded" result = [] for attr in dir(self): if attr.startswith("BP_") and attr.endswith("_rulestatus"): result.append(attr[3:-11]) return result @staticmethod def bp_discoverytype_result_attrname(discoverytype): "Compute the attribute name of a best practice score category" return "BP_%s_rulestatus" % discoverytype def get_owned_ips(self): """Return a list of all the IP addresses that this Drone owns""" params = {"droneid": self.association.node_id} if CMAdb.debug: print( "IP owner query:\n%s\nparams %s" % (Drone.OwnedIPsQuery_subtxt, str(params)), file=sys.stderr, ) ip_list = [ node for node in CMAdb.store.load_cypher_nodes(Drone.OwnedIPsQuery, params=params) ] # print ("Query returned: %s" # % str([str(ip) for ip in ip_list]), file=sys.stderr) return ip_list def get_owned_nics(self): """Return an iterator returning all the NICs that this Drone owns""" return CMAdb.store.load_related(self, CMAconsts.REL_nicowner) def get_active_nic_count(self): """Return the number of "active" NICs this Drone has""" if self._active_nic_count is not None: return self._active_nic_count count = 0 for nic in self.get_owned_nics(): if nic.operstate == "up" and nic.carrier and nic.macaddr != "00-00-00-00-00-00": count += 1 self._active_nic_count = count return count def crypto_identity(self): """Return the Crypto Identity that should be associated with this Drone Note that this current algorithm isn't ideal for a multi-tenant environment. """ return self.designation def destaddr(self, ring=None): """Return the "primary" IP for this host as a pyNetAddr with port""" return pyNetAddr(self.select_ip(ring=ring), port=self.port) def select_ip(self, ring=None): """Select an appropriate IP address for talking to a partner on this ring or our primary IP if ring is None""" # Current code is not really good enough for the long term, # but is good enough for now... # In particular, when talking on a particular switch ring, or # subnet ring, we want to choose an IP that's on that subnet, # and preferably on that particular switch for a switch-level ring. # For TheOneRing, we want their primary IP address. ring = ring return self.primary_ip_addr def send_frames(self, framesettype, frames): "Send messages to our real concrete Drone system..." # This doesn't work if the client has bound to a VIP ourip = pyNetAddr(self.select_ip()) # meaning select our primary IP if ourip.port() == 0: ourip.setport(self.port) # print('ADDING PACKET TO TRANSACTION: %s', str(frames), file=sys.stderr) if CMAdb.debug: CMAdb.log.debug("Sending request to %s Frames: %s" % (str(ourip), str(frames))) CMAdb.net_transaction.add_packet(ourip, framesettype, frames) # print('Sent Discovery request to %s Frames: %s' # % (str(ourip), str(frames)), file=sys.stderr) # Current implementation does not use 'self' # pylint: disable=R0201 def send_hbmsg(self, dest, fstype, addrlist): """Send a message with an attached pyNetAddr list - each including port numbers' This is intended primarily for start or stop heartbeating messages.""" # Now we create a collection of frames that looks like this: # # One FrameTypes.RSCJSON frame containing JSON Heartbeat parameters # one frame per dest, type FrameTypes.IPPORT # params = ConfigFile.agent_params(CMAdb.config, "heartbeats", None, self.designation) framelist = [{"frametype": FrameTypes.RSCJSON, "framevalue": str(params)}] for addr in addrlist: if addr is None: continue framelist.append({"frametype": FrameTypes.IPPORT, "framevalue": addr}) CMAdb.net_transaction.add_packet(dest, fstype, framelist) def death_report(self, status, reason, fromaddr, frameset): "Process a death/shutdown report for us. RIP us." from hbring import HbRing # print ('DEAD REPORT: %s' % self, file=sys.stderr) frameset = frameset # We don't use the frameset at this point in time if reason != "HBSHUTDOWN": if self.status != status or self.reason != reason: CMAdb.log.info( "Node %s has been reported as %s by address %s. Reason: %s" % (self.designation, status, str(fromaddr), reason) ) oldstatus = self.status self.status = status self.reason = reason self.monitors_activated = False self.time_status_ms = int(round(time.time() * 1000)) self.time_status_iso8601 = time.strftime("%Y-%m-%d %H:%M:%S") if status == oldstatus: # He was already dead, Jim. return # There is a need for us to be a little more sophisticated # in terms of the number of peers this particular drone had # It's here in this place that we will eventually add the ability # to distinguish death of a switch or subnet or site from death of a single drone for ring in self.find_associated_rings(): # print ('Calling Ring(%s).leave(%s).' % (ring_name, self), file=sys.stderr) ring.leave(self) deadip = pyNetAddr(self.select_ip(), port=self.port) if CMAdb.debug: CMAdb.log.debug("Closing connection to %s/%d" % (deadip, DEFAULT_FSP_QID)) # # So, if this is a death report from another system we could shut down ungracefully # and it would be OK. # # But if it's a graceful shutdown, we need to not screw up the comm shutdown in progress # If it's broken, our tests and the real world will eventually show that up :-D. # if reason != "HBSHUTDOWN": self._io.closeconn(DEFAULT_FSP_QID, deadip) AssimEvent(self, AssimEvent.OBJDOWN) def find_associated_rings(self): """ Return a generator yielding the ring objects which this Drone is a member of This could be more efficient, albeit without some error checking we're doing now... :return: generator(HbRing) """ for label in self.association.store.labels(self): if label.startswith("Ring_"): ring_name = label[5:] query = "MATCH(r:Class_HbRing) WHERE r.name=$name RETURN r" ring = self.association.store.load_cypher_node(query, {"name": ring_name}) if ring is None: raise RuntimeError("Cannot locate ring [%s] for %s" % (ring_name, self)) else: yield ring def start_heartbeat(self, ring, partner1, partner2=None): """Start heartbeating to the given partners. We insert ourselves between partner1 and partner2. We only use forward links - because we can follow them in both directions in Neo4J. So, we need to create a forward link from partner1 to us and from us to partner2 (if any) """ ouraddr = pyNetAddr(self.select_ip(), port=self.port) print(f"OURADDR: {ouraddr}", file=sys.stderr) print(f"PARTNER1: {partner1}", file=sys.stderr) print(f"PARTNER2: {partner2}", file=sys.stderr) print(f"PARTNER1.select_ip: {partner1.select_ip(ring)}", file=sys.stderr) partner1addr = pyNetAddr(partner1.select_ip(ring), port=partner1.port) if partner2 is not None: partner2addr = pyNetAddr(partner2.select_ip(ring), port=partner2.port) else: partner2addr = None if CMAdb.debug: CMAdb.log.debug( "STARTING heartbeat(s) from %s [%s] to %s [%s] and %s [%s]" % (self, ouraddr, partner1, partner1addr, partner2, partner2addr) ) self.send_hbmsg(ouraddr, FrameSetTypes.SENDEXPECTHB, (partner1addr, partner2addr)) def stop_heartbeat(self, ring, partner1, partner2=None): """Stop heartbeating to the given partners.' We don't know which node is our forward link and which our back link, but we need to remove them either way ;-). """ ouraddr = pyNetAddr(self.select_ip(), port=self.port) partner1addr = pyNetAddr(partner1.select_ip(ring), port=partner1.port) if partner2 is not None: partner2addr = pyNetAddr(partner2.select_ip(ring), port=partner2.port) else: partner2addr = None # Stop sending the heartbeat messages between these (former) peers if CMAdb.debug: CMAdb.log.debug( "STOPPING heartbeat(s) from %s [%s] to %s [%s] and %s [%s]" % (self, ouraddr, partner1, partner1addr, partner2, partner2addr) ) self.send_hbmsg(ouraddr, FrameSetTypes.STOPSENDEXPECTHB, (partner1addr, partner2addr)) def set_crypto_identity(self, keyid=None): "Associate our IP addresses with our key id" if CMAdb.store.readonly or not CMAdb.use_network: return if keyid is not None and keyid != "": if self.key_id != "" and keyid != self.key_id: raise ValueError( "Cannot change key ids for % from %s to %s." % (str(self), self.key_id, keyid) ) self.key_id = keyid # Encryption is required elsewhere - we ignore this here... if self.key_id != "": pyCryptFrame.dest_set_key_id(self.destaddr(), self.key_id) pyCryptFrame.associate_identity(self.crypto_identity(), self.key_id) def __str__(self): "Give out our designation" return "Drone(%s)" % self.designation def find_child_system_from_json(self, jsonobj): """Locate the child drone that goes with this JSON - or maybe it's us""" if "proxy" in jsonobj: path = jsonobj["proxy"] if path == "local/local": return self else: return self # This works - could be a bit slow if you have lots of child nodes... q = """MATCH (drone)<-[:parentsys*]-(child) WHERE ID(drone) = {id} AND child.childpath = {path} RETURN child""" store = self.association.store child = store.load_cypher_node(q, {"id": self.association.node_id, "path": path}) if child is None: raise ( ValueError( "Child system %s from %s [%s] was not found." % (path, str(self), str(self.association.node_id)) ) ) return child @staticmethod def find(designation, port=None, domain=None): """Find a drone with the given designation or IP address, or Neo4J node.""" desigstr = str(designation) if isinstance(designation, Drone): designation.set_crypto_identity() return designation elif isinstance(designation, str): if domain is None: domain = CMAconsts.globaldomain designation = designation.lower() drone = CMAdb.store.load_or_create( Drone, port=port, domain=domain, designation=designation ) assert drone.designation == designation assert drone.association.node_id is not None drone.set_crypto_identity() return drone elif isinstance(designation, pyNetAddr): desig = designation.toIPv6() desig.setport(0) desigstr = str(desig) # We do everything by IPv6 addresses... drone = CMAdb.store.load_cypher_node( Drone.IPownerquery_1, {"ipaddr": desigstr, "domain": str(domain)} ) if drone is not None: assert drone.association.node_id is not None drone.set_crypto_identity() return drone if CMAdb.debug: CMAdb.log.warn( "Could not find IP NetAddr address in Drone.find... %s [%s] [%s]" % (designation, desigstr, type(designation)) ) if CMAdb.debug: CMAdb.log.debug("DESIGNATION2 (%s) = %s" % (designation, desigstr)) CMAdb.log.debug("QUERY (%s) = %s" % (designation, Drone.IPownerquery_1)) print("DESIGNATION2 (%s) = %s" % (designation, desigstr), file=sys.stderr) print("QUERY (%s) = %s" % (designation, Drone.IPownerquery_1), file=sys.stderr) if CMAdb.debug: print(f"drone.find({designation}) ({desigstr}) ({type(designation)}) => returning None", file=sys.stderr) # tblist = traceback.extract_stack() # tblist = traceback.extract_tb(trace, 20) # CMAdb.log.info('======== Begin missing IP Traceback ========') # for tbelem in tblist: # (filename, line, funcname, text) = tbelem # filename = os.path.basename(filename) # CMAdb.log.info('%s.%s:%s: %s'% (filename, line, funcname, text)) # CMAdb.log.info('======== End missing IP Traceback ========') # CMAdb.log.warn('drone.find(%s) (%s) (%s) => returning None' % ( return None @staticmethod def add( designation, reason, primary_ip_addr, status="up", port=None, domain=CMAconsts.globaldomain, ): """Add a drone to our set unless it is already there.""" assert primary_ip_addr is not None drone = CMAdb.store.load_or_create( Drone, domain=domain, designation=designation, primary_ip_addr=primary_ip_addr, port=port, status=status, reason=reason, ) assert drone.association.node_id is not None drone.reason = reason drone.status = status drone.statustime = int(round(time.time() * 1000)) drone.iso8601 = time.strftime("%Y-%m-%d %H:%M:%S") if port is not None: drone.port = port if primary_ip_addr is not None and drone.primary_ip_addr != primary_ip_addr: # This means they've changed their IP address and/or port since we last saw them... CMAdb.log.info( "DRONE %s changed IP address from %s to %s" % (str(drone), drone.primary_ip_addr, primary_ip_addr) ) drone.primary_ip_addr = str(primary_ip_addr) if port is None: drone.port = int(primary_ip_addr.port()) return drone
[ "alanr@unix.sh" ]
alanr@unix.sh
52fdef2d1b401d6fbf97cf036746c5cdbac652d8
7a8663a0d5a75baba2174dccb0045b51e1ed2056
/run.py
c1f0fa13ae82ed7c8df3dd2c5294c911bce184e5
[]
no_license
davebland/ci-flask-website
5ae7e08f12e6674024d35e29d27a3537427adec8
72d58706b4fbbf28c7cdc48799a1fbc4892018cc
refs/heads/master
2021-06-16T03:30:50.654798
2019-07-17T17:57:21
2019-07-17T17:57:21
197,021,511
0
0
null
2021-06-10T21:42:10
2019-07-15T15:07:00
JavaScript
UTF-8
Python
false
false
1,273
py
import os import json from flask import Flask, render_template, request, flash app = Flask(__name__) app.secret_key = "my_test_key" @app.route("/") def index(): return render_template("index.html", page_title="Home") @app.route("/about") def about(): data = [] with open("data/company.json","r") as json_data: data = json.load(json_data) return render_template("about.html", page_title="About", company = data) @app.route("/contact", methods=["GET", "POST"]) def contact(): if request.method == "POST": flash("Thanks {}, the dwarf will be in contact".format(request.form["name"])) return render_template("contact.html", page_title="Contact") @app.route("/careers") def careers(): return render_template("careers.html", page_title="Careers") @app.route("/about/<dwarf_name>") def about_member(dwarf_name): dwarf = {} with open("data/company.json","r") as json_data: data = json.load(json_data) for obj in data: if obj["url"] == dwarf_name: dwarf = obj return render_template("member.html", page_title="BIO", dwarf = dwarf) if __name__ == "__main__": app.run(host=os.environ.get("IP"), port=int(os.environ.get("PORT")), debug=True)
[ "ubuntu@ip-172-31-23-141.eu-west-1.compute.internal" ]
ubuntu@ip-172-31-23-141.eu-west-1.compute.internal
d5cf9442ea2191db9198f0cef63ea002f7fa5b79
b3513e040a2687a59ae18c3db0db3127c307c04b
/overlap_matching_v3.py
3c5f5cb5a2b68a83530a8a8b1f3ea6fd24576190
[]
no_license
jbartz/KELT_catalog_repo
ec1cb29a29ee5eeb5eac4f95a785a3848203f1f4
510e16d861f024e5668119c82e198de1d1e28594
refs/heads/master
2021-01-18T14:05:38.607109
2014-07-23T16:46:19
2014-07-23T16:46:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
22,961
py
#!/usr/bin/python import os,sys import numpy as np import time import matplotlib.pyplot as plt from math import * from os import listdir from os.path import isfile, join from subprocess import call #treat id labels as strings, but specify their size as the largest id #in northern fields, only expect adjacent fields to overlap #create script/subroutine that takes two fields and determines the maximum and min RA and Dec, and then #checks whether there is overlap between those coordinates between the two fields (both RA and dec overlap) #will I need to hardcode the field size to do this? #2 fields, arbitrarly placed on sky... can we determine overlap without knowing size of fields? #just use 26 deg. as the field size- easier #if one field has RA positions within > 334 degrees, watch out for RA -> 0 #output should be 1+2_overlap, 2+3_overlap, etc... #for output coordinates for field 1, east west match, use the mean of (ra_1 and ra_2), and (dec_1, and dec_2) as RA, Dec #precision to a tenth of an arcsecond #once all overlap files are output, then compare those to eachother... #for canonical output file: # key point is a single line for every object (things with a match) # for cases where 1 and 2 match: East_1, West_1, East_2, West_2, East_3, West_3, etc..., also: # in the long term, build this with the option where this file will not necessarily be rectangular start_time = time.clock() #used to time the code #Kelt columns are: x, y, ID, mag, mag_err, RA, Dec ###-----This section from Josh Pepper's code-----### def rAngSep(ra1r, dec1r, ra2r, dec2r): """ Compute angular separation(s) with a dot product. All input/output is in radians. Inputs are converted to Cartesian coordinates and their dot product is computed. The arccosine of the dot product is the angular separation (since A dot B = |A||B| * cos(angular_separation). """ x1 = np.cos(dec1r) * np.cos(ra1r) y1 = np.cos(dec1r) * np.sin(ra1r) z1 = np.sin(dec1r) x2 = np.cos(dec2r) * np.cos(ra2r) y2 = np.cos(dec2r) * np.sin(ra2r) z2 = np.sin(dec2r) dot = x1*x2 + y1*y2 + z1*z2 #print dot return np.arccos(dot) ## Angular separation in degrees (a wrapper for the above): def dAngSep(ra1d, dec1d, ra2d, dec2d): """ Compute angular separation(s) using a dot product. This is a wrapper for the rAngSep() function. See its docstring for more info. """ ra1r, dec1r = np.radians([ra1d, dec1d]) ra2r, dec2r = np.radians([ra2d, dec2d]) return np.degrees(rAngSep(ra1r, dec1r, ra2r, dec2r)) ###-----End copied section for computing angular seperation-----### kelt_cat_files = [ f for f in listdir('/media/sf_Astro/k_cat/single_canon/') if isfile(join('/media/sf_Astro/k_cat/single_canon/',f))] overlap_sets = [ ('N01','N02'),('N02','N03'),('N03','N04'),('N04','N05'),('N05','N06'),('N06','N07'),('N07','N08'),('N08','N09'),\ ('N09','N10'),('N10','N11'),('N11','N12'),('N12','N13'),('N01','N13'),('S19','S20'),('S20','S22'),\ ('S22','S23'),('S23','S24'),('S24','S25'),('S25','S26'),('S26','S27'),('S27','S28') ] def Overlap_search(field_1, field_2): #for file_no in range(0,len(kelt_cat_files)-1): #each tuple in overlap_sets contains fields that overlap, with the lower-numbered field first #use this syntax to compare just two overlappingfields #for file_no in range(1,2,1): #file2 = 'S12_all.dat' #file1 = 'S26_all.dat' ### Use this block when looking at overlap between 1 -> 2 # file1 = kelt_cat_files[file_no] # file2 = kelt_cat_files[file_no+1] ### Use this block when looking at overlap between 1 -> 2 ### Use this block when looking at overlap between 2 -> 1 #file2 = kelt_cat_files[file_no] #file1 = kelt_cat_files[file_no+1] ### Use this block when looking at overlap between 2 -> 1 field1 = field_1[:3] field2 = field_2[:3] #######Use this to get data for most adjacent files (like N01 and N02, N02 and N03,...) ####### The single_canon folder contains files for each field with unique entries, as opposed to ####### files in single_all, which have duplicate lines data1 = np.genfromtxt('/media/sf_Astro/k_cat/single_canon/{0}'.format(field_1), dtype='|S44') data2 = np.genfromtxt('/media/sf_Astro/k_cat/single_canon/{0}'.format(field_2), dtype='|S44') #######Use this to get data for overlapping, but non-adjacent files (like N01 and N13) ### be careful with the order. for 1 -> 2 matching, data1=N01, data2=N02. reverse for 2 -> 1 #data1 = np.genfromtxt('/media/sf_Astro/k_cat/single_canon/N01_all.dat', dtype='|S44') #data2 = np.genfromtxt('/media/sf_Astro/k_cat/single_canon/N13_all.dat', dtype='|S44') #tacks on east or west, and field number: lc_xxxxx.dat -> e_02_lc_xxxxx.dat. Takes very little time to run this part. #for some reason sorting like this seems to fuck up the east_1 RA... # data1_sort = data1[data1[:,3].argsort()] #sorts by RA # data2_sort = data2[data2[:,3].argsort()] #sorts by RA data1_sort = data1 data2_sort = data2 #When this runs, we only see 2:2 matches (1_e, 1_w):(2_e, 2_w) and 1:1 matches (1_e, null):(2_e,null) eid2 = np.array([ row[0] for row in data2_sort ]) eid1 = np.array([ row[0] for row in data1_sort ]) wid2 = np.array([ row[1] for row in data2_sort ]) wid1 = np.array([ row[1] for row in data1_sort ]) dec2 = np.array([ row[3] for row in data2_sort ]).astype(np.float) dec1 = np.array([ row[3] for row in data1_sort ]).astype(np.float) ra2 = np.array([ row[2] for row in data2_sort ]).astype(np.float) ra1 = np.array([ row[2] for row in data1_sort ]).astype(np.float) mag2e = np.array([ row[4] for row in data2_sort ]) mag1e = np.array([ row[4] for row in data1_sort ]) mag2w = np.array([ row[5] for row in data2_sort ]) mag1w = np.array([ row[5] for row in data1_sort ]) e_x1 = np.array([ row[6] for row in data1_sort ]) e_y1 = np.array([ row[7] for row in data1_sort ]) w_x1 = np.array([ row[8] for row in data1_sort ]) w_y1 = np.array([ row[9] for row in data1_sort ]) e_x2 = np.array([ row[6] for row in data2_sort ]) e_y2 = np.array([ row[7] for row in data2_sort ]) w_x2 = np.array([ row[8] for row in data2_sort ]) w_y2 = np.array([ row[9] for row in data2_sort ]) if ra2.max() > ra1.max(): ra_min = ra2.min() ra_max = ra1.max() else: ra_min = ra1.min() ra_max = ra2.max() #if dec2.max() > dec1.max(): # dec_min = dec2.min() # dec_max = dec1.max() #else: # dec_min = dec1.min() # dec_max = dec2.max() #gets the coordinate range that we want to search through #limits our search to objects only within the overlap region between two fields coord1_cond = (ra1 >= ra_min) & (ra1 <= ra_max) # & (dec1 >= dec_min) & (dec1 <= dec_max) coord2_cond = (ra2 >= ra_min) & (ra2 <= ra_max) # & (dec2 >= dec_min) & (dec2 <= dec_max) eid2 = eid2[coord2_cond] eid1 = eid1[coord1_cond] wid2 = wid2[coord2_cond] wid1 = wid1[coord1_cond] dec2 = dec2[coord2_cond] dec1 = dec1[coord1_cond] ra2 = ra2[coord2_cond] ra1 = ra1[coord1_cond] mag2e = mag2e[coord2_cond] mag1e = mag1e[coord1_cond] mag2w = mag2w[coord2_cond] mag1w = mag1w[coord1_cond] e_x1 = e_x1[coord1_cond] e_y1 = e_y1[coord1_cond] w_x1 = w_x1[coord1_cond] w_y1 = w_y1[coord1_cond] e_x2 = e_x2[coord2_cond] e_y2 = e_y2[coord2_cond] w_x2 = w_x2[coord2_cond] w_y2 = w_y2[coord2_cond] match_0_list = [] match_1_list = [] match_2_list = [] match_3_list = [] match_4_list = [] rad = 0.0147 #matching radius in degrees. 0.0147 deg = 52.9" = 2.3 kelt pixels for (i,cand) in enumerate(eid1): lowdec = dec1[i] - rad highdec = dec1[i] + rad cond = (dec2 >= lowdec) & (dec2 <= highdec) if (np.sum(cond)>=1): wid2_ = wid2[cond] eid2_ = eid2[cond] ra2_ = ra2[cond] dec2_ = dec2[cond] file2_line_ = data2_sort[cond] mag2e_ = mag2e[cond] mag2w_ = mag2w[cond] e_x2_ = e_x2[cond] e_y2_ = e_y2[cond] w_x2_ = w_x2[cond] w_y2_ = w_y2[cond] angsep = dAngSep(ra1[i], dec1[i],ra2_, dec2_) rcond = (angsep<rad) #Do we note objects with 0 cross matches? if (np.sum(rcond)==0): # match_0_list.append(' '.join(data1_sort[i])) if (np.sum(rcond)==1): wid2_m = wid2_[rcond] eid2_m = eid2_[rcond] asep = angsep[rcond] ra2_m = ra2_[rcond] dec2_m = dec2_[rcond] e_x2_m = e_x2_[rcond] e_y2_m = e_y2_[rcond] w_x2_m = w_x2_[rcond] w_y2_m = w_y2_[rcond] # file2_line_m = file2_line_[rcond] #is this used? order = np.argsort(asep) asep_sort = asep[order] wid2_m_sort = wid2_m[order] eid2_m_sort = eid2_m[order] ra2_m_sort = ra2_m[order] dec2_m_sort = dec2_m[order] mag2e_m = mag2e_[rcond] mag2e_m_sort = mag2e_m[order] mag2w_m = mag2w_[rcond] mag2w_m_sort = mag2w_m[order] dec2_m_sort = dec2_m[order] e_x2_m_sort = e_x2_m[order] e_y2_m_sort = e_y2_m[order] w_x2_m_sort = w_x2_m[order] w_y2_m_sort = w_y2_m[order] # if (abs(mag1e[i] - mag2e_m_sort[0]) <= 2.0) : mean_ra = 0.5 * (ra1[i] + ra2_m_sort[0]) mean_dec = 0.5 * (dec1[i] + dec2_m_sort[0]) # match_1_list.append( "%19s %19s %19s %19s %i %9.5f %9.5f %6s %6s %6s %6s %8s %8s %8s %8s %8s %8s %8s %8s " %(eid1[i],wid1[i],eid2_m_sort[0],wid2_m_sort[0],np.sum(rcond), mean_ra, mean_dec,mag1e[i],mag1w[i],mag2e_m_sort[0],mag2w_m_sort[0], e_x1[i],e_y1[i],w_x1[i], w_y1[i],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0]) ) if int(field1[1:]) < int(field2[1:]): #if iterating through the lower numbered field DO i NEED TO DO THIS...? CANOT TELL IF THIS WILL HELP OR ADD USELESS COMPLEXITY i THINK IT'S A GOOD IDEA THOUHG match_1_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i],eid2_m_sort[0],wid2_m_sort[0],ra2_m_sort[0],dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0]) ) if int(field2[1:]) < int(field1[1:]): #if iterating through the higher numbered field match_1_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid2_m_sort[0],wid2_m_sort[0], ra2_m_sort[0], dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0], e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0],eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i] ) ) #np.savetxt('./kelt_overlap_match/N01_N13_ew_cat.dat',match_1_list,fmt='%s') #put in some code to change the last entry in this line from '0' -> '1', to show that this object has overlap matches. This needs to make it #to the final canonical file, so we can see if an object has other id's #data1 # np.savetxt('./kelt_overlap_match/{0}_ew_cat.dat'.format(field1 + '_' + field2),match_1_list,fmt='%s') if (np.sum(rcond)==2): wid2_m = wid2_[rcond] eid2_m = eid2_[rcond] asep = angsep[rcond] ra2_m = ra2_[rcond] dec2_m = dec2_[rcond] e_x2_m = e_x2_[rcond] e_y2_m = e_y2_[rcond] w_x2_m = w_x2_[rcond] w_y2_m = w_y2_[rcond] # file2_line_m = file2_line_[rcond] #is this used? order = np.argsort(asep) asep_sort = asep[order] wid2_m_sort = wid2_m[order] eid2_m_sort = eid2_m[order] ra2_m_sort = ra2_m[order] dec2_m_sort = dec2_m[order] mag2e_m = mag2e_[rcond] mag2e_m_sort = mag2e_m[order] mag2w_m = mag2w_[rcond] mag2w_m_sort = mag2w_m[order] dec2_m_sort = dec2_m[order] e_x2_m_sort = e_x2_m[order] e_y2_m_sort = e_y2_m[order] w_x2_m_sort = w_x2_m[order] w_y2_m_sort = w_y2_m[order] # if (abs(mag1e[i] - mag2e_m_sort[0]) <= 2.0) : mean_ra = 0.5 * (ra1[i] + ra2_m_sort[0]) mean_dec = 0.5 * (dec1[i] + dec2_m_sort[0]) if int(field1[1:]) < int(field2[1:]): #if iterating through the lower numbered field match_2_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i],eid2_m_sort[0],wid2_m_sort[0],ra2_m_sort[0],dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0],eid2_m_sort[1],wid2_m_sort[1],ra2_m_sort[1],dec2_m_sort[1],mag2e_m_sort[1],mag2w_m_sort[1],e_x2_m_sort[1],e_y2_m_sort[1],w_x2_m_sort[1],w_y2_m_sort[1]) ) if int(field2[1:]) < int(field1[1:]): #if iterating through the higher numbered field match_2_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid2_m_sort[0],wid2_m_sort[0],ra2_m_sort[0],dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0],eid2_m_sort[1],wid2_m_sort[1],ra2_m_sort[1],dec2_m_sort[1],mag2e_m_sort[1],mag2w_m_sort[1],e_x2_m_sort[1],e_y2_m_sort[1],w_x2_m_sort[1],w_y2_m_sort[1],eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i]) ) if (np.sum(rcond)==3): wid2_m = wid2_[rcond] eid2_m = eid2_[rcond] asep = angsep[rcond] ra2_m = ra2_[rcond] dec2_m = dec2_[rcond] e_x2_m = e_x2_[rcond] e_y2_m = e_y2_[rcond] w_x2_m = w_x2_[rcond] w_y2_m = w_y2_[rcond] # file2_line_m = file2_line_[rcond] #is this used? order = np.argsort(asep) asep_sort = asep[order] wid2_m_sort = wid2_m[order] eid2_m_sort = eid2_m[order] ra2_m_sort = ra2_m[order] dec2_m_sort = dec2_m[order] mag2e_m = mag2e_[rcond] mag2e_m_sort = mag2e_m[order] mag2w_m = mag2w_[rcond] mag2w_m_sort = mag2w_m[order] dec2_m_sort = dec2_m[order] e_x2_m_sort = e_x2_m[order] e_y2_m_sort = e_y2_m[order] w_x2_m_sort = w_x2_m[order] w_y2_m_sort = w_y2_m[order] # if (abs(mag1e[i] - mag2e_m_sort[0]) <= 2.0) : mean_ra = 0.5 * (ra1[i] + ra2_m_sort[0]) mean_dec = 0.5 * (dec1[i] + dec2_m_sort[0]) if int(field1[1:]) < int(field2[1:]): #if iterating through the lower numbered field match_3_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i],eid2_m_sort[0],wid2_m_sort[0],ra2_m_sort[0],dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0],eid2_m_sort[1],wid2_m_sort[1],ra2_m_sort[1],dec2_m_sort[1],mag2e_m_sort[1],mag2w_m_sort[1],e_x2_m_sort[1],e_y2_m_sort[1],w_x2_m_sort[1],w_y2_m_sort[1], eid2_m_sort[2],wid2_m_sort[2],ra2_m_sort[2],dec2_m_sort[2],mag2e_m_sort[2],mag2w_m_sort[2],e_x2_m_sort[2],e_y2_m_sort[2],w_x2_m_sort[2],w_y2_m_sort[2]) ) if int(field2[1:]) < int(field1[1:]): #if iterating through the higher numbered field match_3_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid2_m_sort[0],wid2_m_sort[0],ra2_m_sort[0],dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0],eid2_m_sort[1],wid2_m_sort[1],ra2_m_sort[1],dec2_m_sort[1],mag2e_m_sort[1],mag2w_m_sort[1],e_x2_m_sort[1],e_y2_m_sort[1],w_x2_m_sort[1],w_y2_m_sort[1], eid2_m_sort[2],wid2_m_sort[2],ra2_m_sort[2],dec2_m_sort[2],mag2e_m_sort[2],mag2w_m_sort[2],e_x2_m_sort[2],e_y2_m_sort[2],w_x2_m_sort[2],w_y2_m_sort[2],eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i]) ) if (np.sum(rcond)==4): wid2_m = wid2_[rcond] eid2_m = eid2_[rcond] asep = angsep[rcond] ra2_m = ra2_[rcond] dec2_m = dec2_[rcond] e_x2_m = e_x2_[rcond] e_y2_m = e_y2_[rcond] w_x2_m = w_x2_[rcond] w_y2_m = w_y2_[rcond] # file2_line_m = file2_line_[rcond] #is this used? order = np.argsort(asep) asep_sort = asep[order] wid2_m_sort = wid2_m[order] eid2_m_sort = eid2_m[order] ra2_m_sort = ra2_m[order] dec2_m_sort = dec2_m[order] mag2e_m = mag2e_[rcond] mag2e_m_sort = mag2e_m[order] mag2w_m = mag2w_[rcond] mag2w_m_sort = mag2w_m[order] dec2_m_sort = dec2_m[order] e_x2_m_sort = e_x2_m[order] e_y2_m_sort = e_y2_m[order] w_x2_m_sort = w_x2_m[order] w_y2_m_sort = w_y2_m[order] # if (abs(mag1e[i] - mag2e_m_sort[0]) <= 2.0) : mean_ra = 0.5 * (ra1[i] + ra2_m_sort[0]) mean_dec = 0.5 * (dec1[i] + dec2_m_sort[0]) print 'Damn! ' + str(field1) + ' ' + str(field2) if int(field1[1:]) < int(field2[1:]): #if iterating through the lower numbered field match_4_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i],eid2_m_sort[0],wid2_m_sort[0],ra2_m_sort[0],dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0],eid2_m_sort[1],wid2_m_sort[1],ra2_m_sort[1],dec2_m_sort[1],mag2e_m_sort[1],mag2w_m_sort[1],e_x2_m_sort[1],e_y2_m_sort[1],w_x2_m_sort[1],w_y2_m_sort[1], eid2_m_sort[2],wid2_m_sort[2],ra2_m_sort[2],dec2_m_sort[2],mag2e_m_sort[2],mag2w_m_sort[2],e_x2_m_sort[2],e_y2_m_sort[2],w_x2_m_sort[2],w_y2_m_sort[3],eid2_m_sort[3],wid2_m_sort[3],ra2_m_sort[3],dec2_m_sort[3],mag2e_m_sort[3],mag2w_m_sort[3],e_x2_m_sort[3],e_y2_m_sort[3],w_x2_m_sort[3],w_y2_m_sort[3]) ) if int(field2[1:]) < int(field1[1:]): #if iterating through the higher numbered field match_4_list.append( "%i %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s %19s %19s %9.5f %9.5f %6s %6s %8s %8s %8s %8s" %(np.sum(rcond),eid2_m_sort[0],wid2_m_sort[0],ra2_m_sort[0],dec2_m_sort[0],mag2e_m_sort[0],mag2w_m_sort[0],e_x2_m_sort[0],e_y2_m_sort[0],w_x2_m_sort[0],w_y2_m_sort[0],eid2_m_sort[1],wid2_m_sort[1],ra2_m_sort[1],dec2_m_sort[1],mag2e_m_sort[1],mag2w_m_sort[1],e_x2_m_sort[1],e_y2_m_sort[1],w_x2_m_sort[1],w_y2_m_sort[1], eid2_m_sort[2],wid2_m_sort[2],ra2_m_sort[2],dec2_m_sort[2],mag2e_m_sort[2],mag2w_m_sort[2],e_x2_m_sort[2],e_y2_m_sort[2],w_x2_m_sort[2],w_y2_m_sort[3],eid2_m_sort[3],wid2_m_sort[3],ra2_m_sort[3],dec2_m_sort[3],mag2e_m_sort[3],mag2w_m_sort[3],e_x2_m_sort[3],e_y2_m_sort[3],w_x2_m_sort[3],w_y2_m_sort[3],eid1[i],wid1[i], ra1[i], dec1[i], mag1e[i],mag1w[i], e_x1[i],e_y1[i],w_x1[i], w_y1[i]) ) #use this line when doing 1 -> 2 overlap matching if int(field1[1:]) < int(field2[1:]): print("field1 : {0} field2 : {1}\nwrite to overlap_1_2".format(field1,field2)) np.savetxt('/media/sf_Astro/k_cat/overlap_1_2/{0}_overlap.dat'.format(field1 + '_' + field2),(match_1_list + match_2_list + match_3_list + match_4_list),fmt='%s') #np.savetxt('/media/sf_Astro/k_cat/temp1/{0}_overlap.dat'.format(field1 + '_' + field2),(match_1_list + match_2_list + match_3_list + match_4_list),fmt='%s') else:# int(field2[1:]) < int(field1[1:]): print("field1 : {0} field2 : {1}\nwrite to overlap_2_1".format(field1,field2)) np.savetxt('/media/sf_Astro/k_cat/overlap_2_1/{0}_overlap.dat'.format(field2 + '_' + field1),(match_1_list + match_2_list + match_3_list + match_4_list),fmt='%s') #np.savetxt('/media/sf_Astro/k_cat/temp2/{0}_overlap.dat'.format(field2 + '_' + field1),(match_1_list + match_2_list + match_3_list + match_4_list),fmt='%s') # np.savetxt('./new/kelt_overlap_match_all/{0}_ew_cat.dat'.format('N01_N13'),(match_1_list + match_2_list + match_3_list + match_4_list),fmt='%s') #use this line when doing N01 -> N13 overlap # np.savetxt('/media/sf_Astro/k_cat/overlap_1_2/{0}_overlap.dat'.format('N01_N13'),(match_1_list + match_2_list + match_3_list + match_4_list),fmt='%s') #use this line when doing N13 -> N01 overlap # np.savetxt('/media/sf_Astro/k_cat/overlap_2_1/{0}_overlap.dat'.format('N13_N01'),(match_1_list + match_2_list + match_3_list + match_4_list),fmt='%s') # np.savetxt('./new/kelt_overlap_multi_reverse/{0}_overlap.dat'.format(field1 + '_' + field2),(match_2_list + match_3_list + match_4_list),fmt='%s') #np.savetxt('./kelt_e_w_multi_match/{0}_ew_cat.dat'.format(field),(match_2_list + match_3_list + match_4_list),fmt='%s') #np.savetxt('./kelt_e_w_no_matches/{0}_e_cat.dat'.format(field),match_0_list,fmt='%s') print field1 + ' ' + field2 + ' : ' + '%.1f' %((time.clock() - start_time)/60.) + " minutes" #for field_pair in [('N05','N06'),('N06','N07')]: for field_pair in overlap_sets: #loops through all pairs of overlapping fields file1 = field_pair[0] + '_all.dat' file2 = field_pair[1] + '_all.dat' #first iterates through each object in file1 comparing to all objs in file2, then does the reverse Overlap_search(file1,file2) Overlap_search(file2,file1) dir_cat = "/media/sf_Astro/k_cat/" cat_command = "cat {0}overlap_1_2/{1}_overlap.dat {0}overlap_2_1/{1}_overlap.dat | sort | uniq > {0}overlap_all/{1}_overlap.dat".format(dir_cat,field_pair[0]+'_'+field_pair[1]) call(cat_command, shell=True) print("{1}_overlap.dat has been written to directory {0}overlap_all/".format(dir_cat,field_pair[0]+'_'+field_pair[1])) cat_cmd_all = "cat {0}overlap_all/* > {0}overlap_all.dat".format(dir_cat) call(cat_cmd_all, shell=True) print("{0}overlap_all.dat has been written to disk".format(dir_cat))
[ "jml612@gmail.com" ]
jml612@gmail.com
f4915b84fd21a6254b6431e90f134ce840d92905
d2dfd6cdbb935b64f77b32496533b019c0fde9af
/training.py
8e420b01934843e47a7992eb891fda72b9eeccf4
[]
no_license
Ricardicus/qlearn
5d051a11c77de4a92e09b24454a7d0b2db8dc71e
a9c999c1d9a8dba9f31581f1c511edbd4cdf10de
refs/heads/master
2021-01-12T05:37:42.892111
2016-12-23T12:09:11
2016-12-23T12:09:11
77,151,371
0
1
null
null
null
null
UTF-8
Python
false
false
5,707
py
from util import * from random import uniform, randint dimension = 10 update_time = 5 rewards = {'apple': 1.0, 'death': -100.0, 'default': -0.01} Q_vals = {} ### parameters ### # bellman coefficient gamma = 0.9 # learning rate alpha = 0.80 # greedyness epsilon = 0.001 episode_count = 1 episode_score = 0 store_every = 100 store_info_every = 1 avg_score_hundred = [] explored = [] new_states = 0 root = "" def timerFired(data): global episode_count, episode_score, avg_score_hundred, explored, Q_vals, root # The game loop event trigger! if (data["isGameOver"] == False): # Will only process if the game is not over redrawAll(data) direct = data["direction"] snakeBoard = data["snakeBoard"] # testing all direction best_action = "forward" qval_best = -9999 for action in ["forward", "left", "right"]: # Updating the Q-values for each action # Action is based upon arg_{max} Q(state, arg) # or random, based on greedyness parameter eplison results = next_state(data, action) reward = results["reward"] new_direction = results["newDirection"] if ( reward == rewards["death"]): key = get_key(snakeBoard, action) Q_vals[key] = reward if ( Q_vals[key] > qval_best ): qval_best = Q_vals[key] best_action = action else: # looking one step ahead to find the highest Q-value! # Q(s,a) = R(s,a) + gamma * [max_{a'} Q(s',a')] key = get_key(snakeBoard, action) new_snakeBoard = results["newSnakeBoard"] scoreTemp = data["score"] if ( reward == rewards["apple"] ): scoreTemp += 1 place_food(new_snakeBoard) qval_highest = -9999 for sample_action in ["forward", "left", "right"]: sample_data = {} sample_data["snakeBoard"] = new_snakeBoard sample_data["direction"] = new_direction sample_data["rewards"] = rewards sample_result = next_state(sample_data, sample_action) sample_scoreTemp = scoreTemp sample_snakeBoard = deepcopy(new_snakeBoard) if ( sample_result["reward"] == rewards["apple"] ): sample_scoreTemp += 1 place_food(sample_snakeBoard) sample_key = get_key(sample_snakeBoard, sample_action) try: Q_vals[sample_key] except: Q_vals[sample_key] = 0 if ( Q_vals[sample_key] > qval_highest ): qval_highest = Q_vals[sample_key] try: Q_vals[key] except: Q_vals[key] = 0 # the highest q-value found.. Q_vals[key] = ( 1 - alpha ) * Q_vals[key] + alpha * ( reward + gamma * qval_highest ) if ( Q_vals[key] > qval_best ): qval_best = Q_vals[key] best_action = action next_action = best_action # act randomly, to increase state space # and prevent getting stuck greed = uniform(0,1) if ( greed < epsilon ): moves = ["forward", "left", "right"] moves.remove(best_action) next_action = moves[randint(0,1)] #print "random move!" results = next_state(data, next_action) reward = results["reward"] if ( reward == rewards["default"] ): new_snakeBoard = results["newSnakeBoard"] new_direction = results["newDirection"] data["snakeBoard"] = new_snakeBoard data["direction"] = new_direction elif ( reward == rewards["death"] ): #print "died!!" data["isGameOver"] = True elif (reward == rewards["apple"]): #print "ate an apple!" data["score"] += 1 new_snakeBoard = results["newSnakeBoard"] new_direction = results["newDirection"] place_food(new_snakeBoard) data["snakeBoard"] = new_snakeBoard data["direction"] = new_direction #print "states: ", len(Q_vals) # Call if the game is not over! data["canvas"].after(update_time, timerFired, data) # The main game-loop! else: if ( len(avg_score_hundred) >= 10000 ): avg_score_hundred = avg_score_hundred[1:] avg_score_hundred.append(data["score"]) print "episode: ", episode_count, " score: ", data["score"], " avg score over 100: ", sum(avg_score_hundred) / (1.0*len(avg_score_hundred)), " states: ", len(Q_vals) if ( episode_count % store_info_every == 0): f = open('info.txt', "w") f.write("episode: " + str(episode_count) + " score: " + str(data["score"]) + " avg score over 100: " + str(sum(avg_score_hundred) / (1.0*len(avg_score_hundred))) + " states: " + str(len(Q_vals))) f.close() episode_count += 1 start_new_episode(data) if (episode_count % store_every == 0): store_Q_vals(Q_vals) root.quit() else: data["canvas"].after(update_time, timerFired, data) def game_on(): global root, Q_vals root = Tk() margin = 3 cellSize = 15 canvasWidth = 2*margin + dimension*cellSize canvasHeight = 2*margin + dimension*cellSize canvas = Canvas(root, width=canvasWidth, height=canvasHeight) canvas.pack() root.resizable(width=0, height=0) # Stores canvas in root and in itself for callbacks. (Not original idea.. found help online) root.canvas = canvas.canvas = canvas # Setting up the canvas and the dictionary containg data of the game in canvas. data = {} data["canvas"] = canvas data["margin"] = margin data["cellSize"] = cellSize data["canvasWidth"] = canvasWidth data["canvasHeight"] = canvasHeight data["points"] = 0 data["rewards"] = rewards data["isGameOver"] = False data["training"] = False data["dimension"] = dimension snakeBoard = [] for r in range(0,dimension): snakeBoard.append([]) for c in range(0, dimension): snakeBoard[r].append(0) data["snakeBoard"] = snakeBoard # set up events # root.bind("<Button-1>", mousePressed) # root.bind("<Key>", keyPressed) start_new_episode(data) Q_vals = load_Q_vals() print len(Q_vals), " states loaded." timerFired(data) # and launch the app root.mainloop() if __name__ == "__main__": game_on()
[ "rickard_hallerback@hotmail.com" ]
rickard_hallerback@hotmail.com
d654571b75c42601d497f2010175e9d03db70f79
a9f38bb28ff9bd04b151d86c653cde9f46768c7c
/easy/guessNumberHigherLower.py
3d9a440d88b43dfb848527e6505af7060a690b0d
[]
no_license
Xynoclafe/leetcode
02388516b10b8ee6bec6ee1b91ab5681c3254d33
4a80f02683e7fc14cb49c07170651ea3eeb280ac
refs/heads/master
2020-12-01T21:05:44.656581
2020-02-02T09:05:32
2020-02-02T09:05:32
230,770,600
0
0
null
null
null
null
UTF-8
Python
false
false
699
py
# The guess API is already defined for you. # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num: int) -> int: class Solution: def guessNumber(self, n: int) -> int: def binSearch(start, end): if start == end: start pivot = (start + end) // 2 return pivot start = 0 end = n while True: num = binSearch(start, end) result = guess(num) if result == 0: return num elif result == 1: start = num + 1 else: end = num - 1
[ "gokulprem.94@gmail.com" ]
gokulprem.94@gmail.com
d247dd62af5574d3992537c6c76a62e2c664d13e
e4609b577b402c92a943215ff29bca30157264d0
/widgets/charset_display.py
b6cbbf039628c251c6242822ce04725d3b5c3c26
[]
no_license
mlambir/c64editor
6472bc20d440593dad0740fbe55e997dba2a60a0
cde82538d451d8a2610a3a1d4944b4c11942ef22
refs/heads/master
2020-03-19T02:50:02.780945
2018-06-02T02:31:07
2018-06-02T02:31:07
135,665,885
0
0
null
null
null
null
UTF-8
Python
false
false
1,218
py
import numpy from kivy.properties import StringProperty, NumericProperty from kivy.uix.gridlayout import GridLayout from widgets.char_display import CharDisplay class CharsetDisplay(GridLayout): charset = StringProperty('') fg_color = NumericProperty(0) bg_color = NumericProperty(0) def __init__(self, **kwargs): super(CharsetDisplay, self).__init__(**kwargs) self.chars = [] for i in range(256): cd = CharDisplay() self.chars.append(cd) cd.fg_color = self.fg_color cd.bg_color = self.bg_color self.add_widget(cd) def on_bg_color(self, *args): for char in self.chars: char.bg_color = self.bg_color def on_fg_color(self, *args): for char in self.chars: char.fg_color = self.fg_color def on_charset(self, *args): barr = numpy.fromfile(self.charset, dtype=numpy.ubyte) barr = barr[1:] char_arrs = numpy.split(barr, len(barr) / 8) for i, char in enumerate(self.chars): if i < len(char_arrs): char.binary_char_data = reversed(char_arrs[i]) else: char.binary_char_data = b''
[ "mlambir@fiqus.com" ]
mlambir@fiqus.com
d8577e261b7ebe5587cb76a006b27c70d766bb1a
62aa1701c9300c39ae55fde80857cfc0ed435ef4
/homework3/models/__init__.py
432f5a9236f186ef0e26a1d32793290df095e7f7
[]
no_license
shaj/otus.python.base
a0c2d9a81a1be1ddebc9af976e96b35028e21f4d
95a27bd4d27048736a117319719194339ec2f395
refs/heads/main
2023-04-10T07:10:21.419777
2021-03-30T14:55:05
2021-03-30T14:55:05
318,856,583
0
0
null
null
null
null
UTF-8
Python
false
false
335
py
from .base import Base, Session, DB_DSN, db from .user import User from .post import Post from .comment import Comment from .todo import Todo from .photo import Photo from .album import Album __all__ = [ "Base", "DB_DSN", "db", "Session", "User", "Todo", "Post", "Comment", "Album", "Photo", ]
[ "kolobrod2002@yandex.ru" ]
kolobrod2002@yandex.ru
29bc8f763d05f89cac084a1f5a9875a7726536f1
654730516142b43e7b19f2fc1116559398090367
/main.py
0a0d59325336b59b1e36f0ccf072be03b01d5efa
[]
no_license
ibykovsky/findMin
c28d62681ff5c00fb251cad517b8388991e9f6ac
3f53601f2a5f8eff573b4bd9a284b907ce45f049
refs/heads/master
2023-07-13T22:55:21.464220
2021-08-24T14:41:30
2021-08-24T14:41:30
399,018,566
0
0
null
null
null
null
UTF-8
Python
false
false
1,225
py
from math import sin from time import sleep # This is a sample Python script. # Press Ctrl+F5 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press F9 to toggle the breakpoint. def func(x): # return (x-1.5)**2 return (x) ** 3 + x**2 def findMin(a, b, eps, f): def printout(x, fx, fn, dx): print(f"{x:18}\t\t{dx:18}\t\t{fx:18}\t\t{fn:18}") x = (a + b) / 2 dx = abs((a - b) / 4) while 1: fx = f(x) xn = x + dx if xn < a or xn > b: return (x, fx) fn = f(xn) df = fn - fx printout(x, fx, fn, dx) if abs(df) > eps: if (df > 0): dx = -dx / 3 x = xn else: return (x, fx) if fx < fn else (xn, fn) # sleep(1) # Press the green button in the gutter to run the script. if __name__ == '__main__': print_hi('PyCharm') print(f"result = {findMin(-10, 10, 1e-9, func)}") # See PyCharm help at https://www.jetbrains.com/help/pycharm/
[ "ibykovsky@yandex.ru" ]
ibykovsky@yandex.ru
263593084810f01979ec9fe7bc488df7d06878cc
4b6cadbd775604b0f9080cd5569355352fdc5b26
/epifpm/zfm20.py
0b87275df883fcdde165f7aae634874cc49a4617
[ "MIT" ]
permissive
Epi10/epifpm
3a45a868c861ee090cb51fa34dce4beeee534f43
3714f9c0ac2a16378d36b70104131d2d6347a454
refs/heads/master
2020-05-18T15:54:54.477804
2015-12-18T14:26:21
2015-12-18T14:26:21
40,840,260
1
0
null
null
null
null
UTF-8
Python
false
false
8,279
py
__author__ = 'aleivag' import logging import serial from cStringIO import StringIO HEADER = [0xEF, 0x01] PACKAGE_HANDSHAKE = 0x17 #: To greet (and posible ping) the fingerprint PACKAGE_EMPTY = 0x0d PACKAGE_GETIMAGE = 0x01 PACKAGE_IMAGE2TZ = 0x02 PACKAGE_REGMODEL = 0x05 PACKAGE_RANDOM = 0x14 PACKAGE_STORE = 0x06 PACKAGE_MATCH = 0x03 PACKAGE_SEARCH = 0x04 PACKAGE_TEMPLATE_NUM = 0x1d PACKAGE_UP_IMAGE = 0x0A PACKAGE_UP_CHAR = 0x08 PACKAGE_GET_SYS_PARS = 0x0f PACKAGE_DOWN_IMAGE = 0x0B PACKAGE_COMMAND = 0x01 PACKAGE_DATA = 0x02 PACKAGE_ACK = 0x07 PACKAGE_END_OF_DATA = 0x08 FINGERPRINT_OK = 0x00 FINGERPRINT_NOFINGER = 0x02 FINGERPRINT_ENROLLMISMATCH = 0x0A #logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class Fingerprint(object): def __init__(self, port='/dev/ttyAMA0', baudrate=57600, timeout=2): self.password = 0 self.address = [0xFF, 0xFF, 0xFF, 0xFF] self.serial = None self.port = port self.baudrate=baudrate self.timeout=timeout def connect(self): self.serial = serial.Serial(self.port, self.baudrate, timeout=self.timeout) def close(self): self.serial.close() def __enter__(self): self.connect() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def write(self, instruction_code, data, identifier=PACKAGE_COMMAND): size = len(data) + 3 packet_size = list(divmod(size, 256)) checksum = identifier + sum(packet_size) + (instruction_code or 0) + sum(data) checksum = list(divmod(checksum, 256)) buffer = map( lambda x: chr(x), HEADER + self.address + [identifier] + packet_size + filter(None, [instruction_code]) + data + checksum ) self.last_write_package = buffer logger.debug('write package: %s' % repr(buffer)) self.serial.write(''.join(buffer)) def read(self): header = self.serial.read(2) addr = self.serial.read(4) pi = ord(self.serial.read(1)) length = self.serial.read(2) ilen = sum([ord(i) for i in length]) edata=self.serial.read(ilen-2) resp = {'identifier': pi} if pi == 0x07: resp['confirmation_code'] = ord(edata[0]) edata = edata[1:] resp['extra_data'] = edata csum = self.serial.read(2) self.last_read_package = [header, addr, pi, length, resp.get('confirmation_code'), edata, csum] logger.debug('read package: %s' % self.last_read_package) logger.debug('return read dict: %s' % resp) return resp def handshake(self): self.write(instruction_code=PACKAGE_HANDSHAKE, data=[0]) return self.read() def get_system_parameters(self): self.write(instruction_code=PACKAGE_GET_SYS_PARS, data=[]) ret = self.read() ret['Status register'] = ret['extra_data'][0:0+1] ret['System identifier code'] = ret['extra_data'][1:1+1] ret['Finger library size'] = ret['extra_data'][2:2+1] ret['Security level'] = ret['extra_data'][3:3+1] ret['Device address'] = ret['extra_data'][4:4+2] ret['Data packet size'] = [32, 64, 128, 256][ord(ret['extra_data'][6:6+1])] ret['Baud settings'] = ret['extra_data'][7:7+1] return ret def empty(self): self.write(instruction_code=PACKAGE_EMPTY, data=[]) print self.read() def get_image(self): """Get a single read from the sensor looking for a fingerprint and load it into a "ImageBuffer" if successful""" self.write(instruction_code=PACKAGE_GETIMAGE, data=[]) return self.read() def get_image_until(self, condition=FINGERPRINT_OK): """ Will continuously lookup for a fingerprint from the sensor until a condition """ r = self.get_image() while r.get('confirmation_code') != condition: r = self.get_image() return r def up_image(self, fo=None): """ Get Image src from ImageBuffer """ logger.info('UPLOAD IMAGE') self.write(instruction_code=PACKAGE_UP_IMAGE, data=[]) resp = self.read() r = {'identifier': 0x00} datas = [] while r['identifier'] != 0x08: r = self.read() datas.append(r['extra_data']) #resp['image'].write(r['extra_data']) logger.debug("get %s bytes" % len(r['extra_data'])) if fo: fo.write(''.join(datas)) resp['image'] = StringIO(''.join(datas)) resp['image-data'] = datas return resp def down_image(self, fo): """ Not finish """ logger.info('DOWNLOAD IMAGE') chunks = self.get_system_parameters()['Data packet size'] self.write(instruction_code=PACKAGE_DOWN_IMAGE, data=[]) self.read() rdata = [] data = fo.read(chunks) while data: rdata.append(map(ord, data)) data = fo.read(chunks) for idata in rdata[:-1]: self.write(instruction_code=None, data=idata, identifier=PACKAGE_DATA) self.write(instruction_code=None, data=rdata[-1], identifier=PACKAGE_END_OF_DATA) #def up_char(self, fo, buffer, chunks=128): # logger.info('uploading char') # self.write(instruction_code=PACKAGE_UP_CHAR, data=[buffer]) # # add read sequence def image_2_tz(self, buffer): self.write(instruction_code=PACKAGE_IMAGE2TZ, data=[buffer]) return self.read() def up_char(self, buffer, fo=None): self.write(instruction_code=PACKAGE_UP_CHAR, data=[buffer]) resp = self.read() resp['char'] = StringIO() r = {'identifier': 0x00} while r['identifier'] != 0x08: r = self.read() resp['char'].write(r['extra_data']) if fo: fo.write(r['extra_data']) resp['char'].seek(0) return resp def match(self): self.write(instruction_code=PACKAGE_MATCH, data=[]) resp = self.read() resp['score'] = sum(map(ord, resp['extra_data'])) return resp def register_model(self): self.write(instruction_code=PACKAGE_REGMODEL, data=[]) return self.read() def store_model(self, id, buffer=0x01): self.write(instruction_code=PACKAGE_STORE, data=[buffer] + list(divmod(id, 255))) return self.read() def template_number(self): self.write(instruction_code=PACKAGE_TEMPLATE_NUM, data=[]) resp = self.read() resp['number'] = sum(map(ord, resp['extra_data'])) return resp def get_random_code(self): self.write(instruction_code=PACKAGE_RANDOM, data=[]) resp = self.read() resp['random'] = sum(map(ord, resp['extra_data'])) return resp def search(self, buffer, start_page=0, page_num=0x00a3): self.write(instruction_code=PACKAGE_SEARCH, data=[buffer] + list(divmod(start_page, 255)) + list(divmod(page_num, 255))) resp = self.read() resp['page_id'] = sum(map(ord, resp['extra_data'][:2])) resp['score'] = sum(map(ord, resp['extra_data'][2:])) if resp['confirmation_code'] == 0: resp['confirmation_desc'] = 'OK' elif resp['confirmation_code'] == 9: resp['desc'] = "No matching in the library (both the PageID and matching score are 0)" return resp def register_finger(id): with Fingerprint() as f: print "place finger" f.get_image_until() f.image_2_tz(buffer=1) print "remove your finger" f.get_image_until(condition=FINGERPRINT_NOFINGER) print "place finger again" f.get_image_until() f.image_2_tz(buffer=2) model = f.register_model() if model['confirmation_code'] != FINGERPRINT_OK: raise Exception("No Match") print f.store_model(id=id, buffer=1) def validate_finger(): with Fingerprint() as f: print "place finger" f.get_image_until() print f.image_2_tz(0x01) print f.search(buffer=0x01) if __name__ == '__main__': with Fingerprint() as f: f.handshake() f.empty() image = f.get_image_until() print image
[ "aleivag@gmail.com" ]
aleivag@gmail.com
39d733a4728b22b3c24809699489e960b1cd04f0
46cbedd79e09cbc813b858f855dd4712e63d6cae
/app/apiviews.py
08cb05e926c3cdd9470877ae29ec73999e545619
[ "MIT" ]
permissive
ZandTree/bloggy
d8844a743f82a0854df042e3387cb8fb8c79320b
532efecb66ffdcaa61efa2aa19cf25e2bd534f59
refs/heads/master
2020-08-02T18:48:03.881998
2019-05-23T12:57:46
2019-05-23T12:57:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,249
py
from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from django.shortcuts import get_object_or_404 from django.utils import timezone from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.exceptions import ValidationError from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .models import Entry, Notification, PrivateMessage, Tag, User from .permissions import (DeletedReadOnly, DisallowVoteChanges, IsOwnerOrReadOnly, IsTarget, PrivateMessageGetOnlyRelatedMessages, PrivateMessagePostAndGetOnly, TagGetOnly, NotificationGetOnly) from .serializers import (EntrySerializer, NotificationSerializer, PrivateMessageSerializer, TagSerializer) class TagViewSet(viewsets.ModelViewSet): serializer_class = TagSerializer permission_classes = [IsAuthenticated, TagGetOnly] @action(detail=True, methods=["post"]) def blacklist(self, request, pk=None): tag = self.get_object() if tag.blacklisters.filter(username=self.request.user.username): tag.blacklisters.remove(self.request.user) else: # If user is observing a tag and blacklists it # then delete user from observers if tag.observers.filter(username=self.request.user.username): tag.observers.remove(self.request.user) tag.blacklisters.add(self.request.user) serializer = self.serializer_class(tag, context={"request": request}) return Response(serializer.data) @action(detail=True, methods=["post"]) def observe(self, request, pk=None): tag = self.get_object() if tag.observers.filter(username=self.request.user.username): tag.observers.remove(self.request.user) else: # If user blacklisted a tag and starts observing it # then delete user from blacklisters if tag.blacklisters.filter(username=self.request.user.username): tag.blacklisters.remove(self.request.user) tag.observers.add(self.request.user) serializer = self.serializer_class(tag, context={"request": request}) return Response(serializer.data) def get_queryset(self): return Tag.objects.all() class NotificationViewSet(viewsets.ModelViewSet): serializer_class = NotificationSerializer permission_classes = [IsTarget, IsAuthenticated, NotificationGetOnly] @action(detail=False, methods=["post"]) def read_all(self, request): user_notifications = Notification.objects.filter(target=self.request.user) user_notifications.update(read=True) page = self.paginate_queryset(user_notifications) if page: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(user_notifications, many=True) return Response(serializer.data) @action(detail=True, methods=["post"]) def read(self, request, pk=None): notification = self.get_object() if self.request.user == notification.target: notification.read = True notification.save() serializer = self.get_serializer(notification) return Response(serializer.data) @action(detail=False, methods=["get"]) def unread(self, request): unread_notifications = Notification.objects.filter( target=self.request.user ).filter(read=False) page = self.paginate_queryset(unread_notifications) if page: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(unread_notifications, many=True) return Response(serializer.data) def get_queryset(self): return Notification.objects.filter(target=self.request.user) class PrivateMessageViewSet(viewsets.ModelViewSet): serializer_class = PrivateMessageSerializer permission_classes = ( IsAuthenticated, PrivateMessageGetOnlyRelatedMessages, PrivateMessagePostAndGetOnly, ) @action(detail=False, methods=["get"]) def unread(self, request): unread_pms = PrivateMessage.objects.filter(target=self.request.user).filter(read=False) author = request.GET.get('from', None) if author: try: author = User.objects.get(username=author) except ObjectDoesNotExist: return Response({"status": "user with such nickname doesn't exist"}) unread_pms = unread_pms.filter(author=author) serializer = self.get_serializer(unread_pms, many=True) return Response(serializer.data) @action(detail=False, methods=["post"]) def read_all(self, request): user_pms = PrivateMessage.objects.filter(target=self.request.user).filter(read=False) n = user_pms.update(read=True, read_date=timezone.now()) return Response({"status": f"succesfully read {n} messages"}) @action(detail=True, methods=["post"]) def read(self, request, pk=None): private_message = self.get_object() if not private_message.read and private_message.target == self.request.user: private_message.read = True private_message.read_date = timezone.now() private_message.save() serializer = self.get_serializer(private_message) return Response(serializer.data) def perform_create(self, serializer): try: target = serializer.validated_data["target"].lower() target = User.objects.get(username=target) except User.DoesNotExist: raise ValidationError("User with that username doesn't exist!") if target == self.request.user: raise ValidationError("You cannot message yourself!") serializer.save(author=self.request.user, target=target) def get_queryset(self): """ API accepts two parameters: ::read - if false, will return messages to user that are not read ::from - if set to valid user will return messages from that user """ private_messages = PrivateMessage.objects.filter(Q(author=self.request.user) | Q(target=self.request.user)) q_read = self.request.query_params.get('read', None) if q_read: q_read = q_read.lower() if q_read == "false": private_messages = private_messages.filter(target=self.request.user).filter(read=False) elif q_read == "true": private_messages = private_messages.filter(target=self.request.user).filter(read=True) q_from = self.request.query_params.get('from', None) if q_from: try: author = User.objects.get(username=q_from.lower()) private_messages = private_messages.filter(author=author) except ObjectDoesNotExist: pass return private_messages.order_by('-created_date') class EntryViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer permission_classes = [ IsOwnerOrReadOnly, IsAuthenticated, DisallowVoteChanges, DeletedReadOnly, ] def perform_create(self, serializer): serializer.save(user=self.request.user) @action(detail=True, methods=['post']) def upvote(self, request, pk=None): entry = self.get_object() if request.user in entry.downvotes.all(): entry.downvotes.remove(request.user) if request.user in entry.upvotes.all(): entry.upvotes.remove(request.user) else: entry.upvotes.add(request.user) serializer = self.get_serializer(entry) return Response(serializer.data) @action(detail=True, methods=['post']) def downvote(self, request, pk=None): entry = self.get_object() if request.user in entry.upvotes.all(): entry.upvotes.remove(request.user) if request.user in entry.downvotes.all(): entry.downvotes.remove(request.user) else: entry.downvotes.add(request.user) serializer = self.get_serializer(entry) return Response(serializer.data) def list(self, request): queryset = self.get_queryset() page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer( page, many=True, context={"request": request} ) return self.get_paginated_response(serializer.data) serializer = self.serializer_class( queryset, many=True, context={"request": request} ) return Response(serializer.data) def retrieve(self, request, pk=None): entry = get_object_or_404(Entry, pk=pk) context = {"request": request} serializer = self.serializer_class(entry, many=False, context=context) return Response(serializer.data)
[ "MakuZo90@gmail.com" ]
MakuZo90@gmail.com
f711a1201562b3798dc9f064116fff6d11313bc0
0295f421e6e8fa20431b58254c6c442d481909af
/main_app/migrations/0002_auto_20200103_1932.py
b043ea9417357e8abecf1bdd7c79b843bbcba128
[]
no_license
luish1012/Project-3-Assessment
b459d7ad21cbf9e169948e13cc7993800be53a1e
02f893cb3dbbe4e5fc26efed94cb4afc7c44c6e9
refs/heads/master
2020-12-04T17:13:12.603996
2020-01-04T18:24:14
2020-01-04T18:24:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
# Generated by Django 3.0.1 on 2020-01-03 19:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='item', name='description', field=models.CharField(max_length=100, unique=True), ), ]
[ "marcoarteaga26@gmail.com" ]
marcoarteaga26@gmail.com
abc6033c2e6d934210b40a79a22887cc8eabc140
9e447f76058f3c4470f822388c3210f6292db44c
/gentNiews.py
c50c42d126172cf5ead1bd985d4fd90f6a824f4d
[]
no_license
ArneDeV/PythonScripts
8920d57c55306768a3890ddb941fae13f7d20940
d47d03ffb711e1bb53da7255f03631798feb4bac
refs/heads/master
2023-01-21T12:18:09.334716
2023-01-12T19:30:43
2023-01-12T19:30:43
281,193,063
0
0
null
null
null
null
UTF-8
Python
false
false
1,178
py
import bs4 as bs import urllib.request import schedule import time from datetime import datetime URL = 'https://www.voetbalkrant.com' source = urllib.request.urlopen('https://www.voetbalkrant.com/').read() soup = bs.BeautifulSoup(source, 'lxml') artikels = soup.find('div', id="more_news") gent_artikels = {} def artikel_toevoegen(artikel_dict, artikel_titel, artikel_link): if artikel_titel not in artikel_dict: artikel_dict[artikel_titel] = artikel_link print(f'[{datetime.now():%d-%m-%Y %H:%M}]{artikel_titel}') print(f'{artikel_link}\n') else: pass def ophalen(): for artikel in artikels.find_all('div', class_="item-content"): for logo in artikel.find_all('a', class_='rel_team_logo'): if logo.img['alt'] == 'KAA Gent': # if logo.img['alt'] == 'Borussia Dortmund': # ! Test case, indien geen Gent Artikels beschikbaar titel = str(artikel.h3.text).strip() link = (URL+artikel.h3.find('a')['href']).strip() artikel_toevoegen(gent_artikels, titel, link) schedule.every().hour.do(ophalen) while True: schedule.run_pending() time.sleep(1)
[ "arne.de.veyder@telenet.be" ]
arne.de.veyder@telenet.be
d8e584e0ecf6bb9ddcb5ee69f56b8a8b8d4d7b67
367ecb02d7300d9c704620accc9ce0bcec679e0c
/Valute/Valute/urls.py
ebdfb6a88f4dd16c7958f36b09a09de5bba0bae1
[]
no_license
Dmitriy-11/---
103d942224e1d256a3192c4458d8e1620f98283c
4c4993f25bccaf4aeb54eed36af5f2806f2fc78f
refs/heads/master
2023-03-21T12:18:49.210007
2021-03-09T17:45:37
2021-03-09T17:45:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
934
py
"""Valute URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
[ "pestrov.dmitrij@yandex.ru" ]
pestrov.dmitrij@yandex.ru
48e041f6ec0490dda24a909975088a5c3df5fbe9
cab3bea646fc60d4226b161568c8e7bf66edcd61
/bidirectional_list.py
750c031a2b623c12da9b9f6ea1f5b2862f100622
[]
no_license
frolkin28/linked_lists
6f615378becfd3ddd452cb93527d4454f7df51ba
742a81c71782665aae264c9befe4a3a19f51d8e1
refs/heads/master
2021-01-07T22:02:50.906859
2020-02-25T19:56:28
2020-02-25T19:56:28
241,832,692
0
0
null
null
null
null
UTF-8
Python
false
false
3,193
py
from linked_list import List class Node: def __init__(self, value, next=None, prev=None): self.value = value self.next = next self.prev = prev def __eq__(self, other): return self.value == other.value def __ne__(self, other): return not self.value == other.value class BidirectionalList(List): def __init__(self): self.head = None def insert_to_begin(self, node): if self.head: node.next = self.head self.head.prev = node self.head = node else: self.head = node def insert_to_end(self, node): current = self.head while current.next: current = current.next current.next = node node.prev = current def insert_to_middle(self, node, index): previous = self.head current = previous.next for i in range(1, index): previous = previous.next current = current.next previous.next = node node.prev = previous node.next = current def delete_from_begin(self): current = self.head current = current.next current.prev = None self.head = current def delete_from_middle(self, index): previous = self.head current = previous.next for i in range(1, index): previous = previous.next current = current.next current = current.next previous.next = current current.prev = previous def delete_from_end(self): current = self.head while current.next.next: current = current.next current.next = None def sub_from_begin(self, node): if self.head: current = self.head node.next = current.next self.head = node def sub_from_middle(self, node, index): previous = self.head current = previous.next for i in range(1, index): previous = previous.next current = current.next current = current.next previous.next = node node.prev = previous node.next = current current.prev = node def sub_from_end(self, node): current = self.head while current.next.next: current = current.next current.next = node node.prev = current def sum(self): sum = 0 if not self.head: return None current = self.head while current: sum += current.value current = current.next return sum def find(self, value): index = 0 current = self.head while current: if current.value == value: return index index += 1 current = current.next return None def display(self): if self.head: current = self.head print(current.value, ' <-> ', end='') else: print('List is empty') return None while current.next: current = current.next print(current.value, ' <-> ', end='') print('none')
[ "frolkin2801@gmail.com" ]
frolkin2801@gmail.com
f66deabdce6d3147a46d26b87dda3dc397346f83
f8ba335ff73e0a79257f0e018e24f0bd6676e611
/02/solution.py
5c9c2effc67a6e124abc8e947a92329e6b88d71e
[ "MIT" ]
permissive
sjking/aoc2020
4ce4412d0cb70a5478b13010b39759fba90befb6
c8b802291ed7865c632f22ff52748b1502e5c136
refs/heads/main
2023-02-14T04:53:14.229083
2020-12-30T07:42:32
2020-12-30T07:42:32
317,753,673
0
0
null
null
null
null
UTF-8
Python
false
false
508
py
valid = 0 def is_valid(lo, hi, ch, pwd): cnt = 0 for c in pwd: if c == ch: cnt += 1 return lo <= cnt <= hi def is_valid_2(lo, hi, ch, pwd): return (pwd[lo-1] == ch and pwd[hi-1] != ch) or (pwd[lo-1] != ch and pwd[hi-1] == ch) with open('input', 'r') as f: for line in f: a, b, pswd = line.split() lo, hi = a.split("-") lo, hi = int(lo), int(hi) ch = b[0] if is_valid_2(lo, hi, ch, pswd): valid += 1 print(valid)
[ "noReply@steveking.site" ]
noReply@steveking.site
1ae3b4e990d7f32a6c6565f8bd27caab86566e6b
8b9b09aa738c9a68ddf69eae64af28fc463bdb39
/tutorial/tutorial/items.py
42d6bf8c853f36e2ecaef14834fe8066daa9e329
[]
no_license
duoduo369/spiders
337ceb67e822eaed2cc7de91d9c7c4042fa5dc24
1f06333ea34993a2c7d65a8d04f0ec01c2d42875
refs/heads/master
2021-01-19T10:02:51.941631
2014-03-18T12:09:14
2014-03-18T12:09:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
401
py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy.item import Item, Field from scrapy.contrib.djangoitem import DjangoItem from douban.models import Book class DmozItem(Item): title = Field() link = Field() desc = Field() class BookItem(DjangoItem): django_model = Book
[ "yangyang@admaster.com.cn" ]
yangyang@admaster.com.cn
164b25b05085c828e869ca41bbabfa5671265b28
4cf3f8845d64ed31737bd7795581753c6e682922
/.history/main_20200118153116.py
17842057b52a9388e5ecd34d985ca161511000dd
[]
no_license
rtshkmr/hack-roll
9bc75175eb9746b79ff0dfa9307b32cfd1417029
3ea480a8bf6d0067155b279740b4edc1673f406d
refs/heads/master
2021-12-23T12:26:56.642705
2020-01-19T04:26:39
2020-01-19T04:26:39
234,702,684
1
0
null
2021-12-13T20:30:54
2020-01-18T08:12:52
Python
UTF-8
Python
false
false
301,331
py
from telegram.ext import Updater, CommandHandler import requests import re # API call to source, get json (url is obtained): contents = requests.get('https://random.dog/woof.json').json() image_url = contents['url'] def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main() def get_url(): contents = requests.get('https://random.dog/woof.json').json() url = contents['url'] return url def get_tasks(): response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json() def extract_list(obj): return obj.map(lambda item: item.title) tasks = extract_list(response) return tasks # sending the image: # we require: # - the image URL # - the recipient's ID: group/user id def bop(bot, update): # image url: url = get_url() # recipient's ID: chat_id = update.message.chat_id bot.send_photo(chat_id=chat_id, photo=url) def getTaskList(bot, update): taskList = get_tasks() chat_id = update.message.chat_id for task in taskList: bot.sendMessage(chat_id, task, Markdown); def main(): updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ') dp = updater.dispatcher dp.add_handler(CommandHandler('bop',bop)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
[ "ritesh@emerald.pink" ]
ritesh@emerald.pink
4655a05a2e59738d661f9702526dbfdea1f20f57
ce083128fa87ca86c65059893aa8882d088461f5
/python/flask-webservices-labs/graphene/graphene/types/mutation.py
fe15f6a2daa5be2a7b09b6fd4419a7e2f2e88fd1
[ "MIT" ]
permissive
marcosptf/fedora
581a446e7f81d8ae9a260eafb92814bc486ee077
359db63ff1fa79696b7bc803bcfa0042bff8ab44
refs/heads/master
2023-04-06T14:53:40.378260
2023-03-26T00:47:52
2023-03-26T00:47:52
26,059,824
6
5
null
2022-12-08T00:43:21
2014-11-01T18:48:56
null
UTF-8
Python
false
false
2,892
py
from collections import OrderedDict from ..utils.get_unbound_function import get_unbound_function from ..utils.props import props from .field import Field from .objecttype import ObjectType, ObjectTypeOptions from .utils import yank_fields_from_attrs from ..utils.deprecated import warn_deprecation # For static type checking with Mypy MYPY = False if MYPY: from .argument import Argument # NOQA from typing import Dict, Type, Callable # NOQA class MutationOptions(ObjectTypeOptions): arguments = None # type: Dict[str, Argument] output = None # type: Type[ObjectType] resolver = None # type: Callable class Mutation(ObjectType): ''' Mutation Type Definition ''' @classmethod def __init_subclass_with_meta__(cls, resolver=None, output=None, arguments=None, _meta=None, **options): if not _meta: _meta = MutationOptions(cls) output = output or getattr(cls, 'Output', None) fields = {} if not output: # If output is defined, we don't need to get the fields fields = OrderedDict() for base in reversed(cls.__mro__): fields.update( yank_fields_from_attrs(base.__dict__, _as=Field) ) output = cls if not arguments: input_class = getattr(cls, 'Arguments', None) if not input_class: input_class = getattr(cls, 'Input', None) if input_class: warn_deprecation(( "Please use {name}.Arguments instead of {name}.Input." "Input is now only used in ClientMutationID.\n" "Read more:" " https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#mutation-input" ).format(name=cls.__name__)) if input_class: arguments = props(input_class) else: arguments = {} if not resolver: mutate = getattr(cls, 'mutate', None) assert mutate, 'All mutations must define a mutate method in it' resolver = get_unbound_function(mutate) if _meta.fields: _meta.fields.update(fields) else: _meta.fields = fields _meta.output = output _meta.resolver = resolver _meta.arguments = arguments super(Mutation, cls).__init_subclass_with_meta__(_meta=_meta, **options) @classmethod def Field(cls, name=None, description=None, deprecation_reason=None): return Field( cls._meta.output, args=cls._meta.arguments, resolver=cls._meta.resolver, name=name, description=description, deprecation_reason=deprecation_reason, )
[ "marcosptf@yahoo.com.br" ]
marcosptf@yahoo.com.br
b0547da90c0b97d968d6b770cf775f8e1fda9969
c20b571c7a5bc0dfbab1db3d42539c327b6bc335
/python3源码/Test25.py
8f5ec1b6154e63ac484e9d6b81969d58c93cfb01
[]
no_license
TaoistZhang/aimed-at-offer
55d7a9eb09573ccc7ef6b8d751a1d9bf9279c357
3038c8eaeb521892ea9d04f72f05b31d125b8186
refs/heads/master
2021-10-26T03:20:22.904376
2019-04-10T07:56:29
2019-04-10T07:56:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,564
py
# -*- coding:utf-8 -*- # 剑指offer-题25:二叉树中和为某一值的路径 # 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定 # 义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): self.path_list = [] self.stack = [] self.cur_sum = 0 return self.get_path(root, expectNumber) def get_path(self, root, expectNumber): if root is None: return self.path_list self.cur_sum += root.val self.stack.append(root.val) is_leaf = root.right is None and root.left is None if self.cur_sum == expectNumber and is_leaf: temp_path = self.stack[:] self.path_list.append(temp_path) # self.path_list.append(self.stack.copy()) if root.left: self.get_path(root.left, expectNumber) if root.right: self.get_path(root.right, expectNumber) self.stack.pop() self.cur_sum -= root.val return self.path_list solution = Solution() root = TreeNode(10) a = TreeNode(5) b = TreeNode(4) c = TreeNode(7) d = TreeNode(12) root.left = a a.left = b a.right = c root.right = d print(solution.FindPath(root, 22)) print(solution.FindPath(root, 15))
[ "454592297@qq.com" ]
454592297@qq.com
064ea35b9500dd3698d390637eb2185728749c11
c492b6f6dd52ad17867713a6a35298916c8dcfe6
/Lab_6/graph_AL.py
762bb988c5c4040b53f8607bcd5b1a4ffb932ce5
[]
no_license
iarivas/CS2302
544e7a332c00d8dc8d2a2180270e0a82a5a5300a
9f1c511b57edeef021888a96431cf5897ce1e2d9
refs/heads/master
2020-07-22T02:09:33.795729
2019-12-14T03:48:35
2019-12-14T03:48:35
207,042,593
0
0
null
null
null
null
UTF-8
Python
false
false
5,421
py
import numpy as np import matplotlib.pyplot as plt import math from scipy.interpolate import interp1d import graph_AM as gAM import graph_EL as gEL class Edge: def __init__(self, dest, weight=1): self.dest = dest self.weight = weight class Graph: # Constructor def __init__(self, vertices, weighted=False, directed = False): self.al = [[] for i in range(vertices)] self.weighted = weighted self.directed = directed self.representation = 'AL' def insert_edge(self,source,dest,weight=1): if source >= len(self.al) or dest>=len(self.al) or source <0 or dest<0: print('Error, vertex number out of range') elif weight!=1 and not self.weighted: print('Error, inserting weighted edge to unweighted graph') else: self.al[source].append(Edge(dest,weight)) if not self.directed: self.al[dest].append(Edge(source,weight)) def delete_edge_(self,source,dest): i = 0 for edge in self.al[source]: if edge.dest == dest: self.al[source].pop(i) return True i+=1 return False def delete_edge(self,source,dest): if source >= len(self.al) or dest>=len(self.al) or source <0 or dest<0: print('Error, vertex number out of range') else: deleted = self.delete_edge_(source,dest) if not self.directed: deleted = self.delete_edge_(dest,source) if not deleted: print('Error, edge to delete not found') def display(self): print('[',end='') for i in range(len(self.al)): print('[',end='') for edge in self.al[i]: print('('+str(edge.dest)+','+str(edge.weight)+')',end='') print(']',end=' ') print(']') def draw(self): scale = 30 fig, ax = plt.subplots() for i in range(len(self.al)): for edge in self.al[i]: d,w = edge.dest, edge.weight if self.directed or d>i: x = np.linspace(i*scale,d*scale) x0 = np.linspace(i*scale,d*scale,num=5) diff = np.abs(d-i) if diff == 1: y0 = [0,0,0,0,0] else: y0 = [0,-6*diff,-8*diff,-6*diff,0] f = interp1d(x0, y0, kind='cubic') y = f(x) s = np.sign(i-d) ax.plot(x,s*y,linewidth=1,color='k') if self.directed: xd = [x0[2]+2*s,x0[2],x0[2]+2*s] yd = [y0[2]-1,y0[2],y0[2]+1] yd = [y*s for y in yd] ax.plot(xd,yd,linewidth=1,color='k') if self.weighted: xd = [x0[2]+2*s,x0[2],x0[2]+2*s] yd = [y0[2]-1,y0[2],y0[2]+1] yd = [y*s for y in yd] ax.text(xd[2]-s*2,yd[2]+3*s, str(w), size=12,ha="center", va="center") ax.plot([i*scale,i*scale],[0,0],linewidth=1,color='k') ax.text(i*scale,0, str(i), size=20,ha="center", va="center", bbox=dict(facecolor='w',boxstyle="circle")) ax.axis('off') ax.set_aspect(1.0) def as_EL(self): temp = gEL.Graph(16,directed = False) for x in range(len(self.al)): for y in range(len(self.al[x])): temp.insert_edge(x, self.al[x][y].dest) return temp def as_AM(self): temp = gAM.Graph(len(self.al),directed = False) for x in range(len(self.al)): for y in range(len(self.al[x])): temp.insert_edge(x, self.al[x][y].dest) return temp def as_AL(self): return self def BFS(self): frontierQueue = [] discoveredSet = [] frontierQueue.append(0) discoveredSet.append(0) path = [[] for i in range(len(self.al))] while(len(frontierQueue) > 0): currentV = frontierQueue.pop(0) for x in range(len(self.al[currentV])): if(self.al[currentV][x].dest not in discoveredSet): frontierQueue.append(self.al[currentV][x].dest) discoveredSet.append(self.al[currentV][x].dest) path[currentV].append(self.al[currentV][x].dest) return path def DFS(self): Stack = [] discoveredSet = [] Stack.append(0) discoveredSet.append(0) path = [[] for i in range(len(self.al))] while(len(Stack) > 0): currentV = Stack.pop() for x in range(len(self.al[currentV])): if(self.al[currentV][x].dest not in discoveredSet): Stack.append(self.al[currentV][x].dest) discoveredSet.append(self.al[currentV][x].dest) path[currentV].append(self.al[currentV][x].dest) return path
[ "noreply@github.com" ]
noreply@github.com
e1c2bc490c75b452877f8a4120dffebbb6fdc933
b5b6cbb6d515b1247a095e29375ec0fdc60fd581
/prep_images.py
0459645a6aec86507e10a1bc5acecda049064ed5
[]
no_license
acisneros-intern/DECO-Scripts
f82134616e29eadfad068b128c642f2a90a4227e
4c47c5c2e1e265c08af0d1846ec8bc3c698522ed
refs/heads/master
2021-01-20T20:14:24.028489
2016-08-01T17:11:23
2016-08-01T17:11:23
63,608,866
0
0
null
null
null
null
UTF-8
Python
false
false
4,954
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import math import os try: from PIL import Image import numpy as np import sys except ImportError,e: print "plotID.py requires PIL for image processing; You can install PIL with 'pip install PIL --user'" print e quit() ONE_EIGHTY_OVER_PI = 180.0 / math.pi PI_OVER_ONE_EIGHTY = math.pi / 180.0 class ImageManipulator(object): """ pull events from processed images, takes an Image() picture, the string name of the image, and a boolean 'replaces' that determines whether or not the new replaces the old (if the directory is the same) """ image = None pixelObj = None def __init__(self,image,name,replaces=False): self.name = name self.replaces = replaces self.image = image.convert('RGB') self.pixelObj = self.image.load() #the pixelObj allows for faster access to pixels in the image def find_illumination(self,samples=300): """find an average illumination in the image by sampling samples^2 number of pixels""" intensities = [] for y in range(0,self.image.height-1,int(float(self.image.height)/float(samples)+1)): for x in range(0,self.image.width-1,int(float(self.image.width)/float(samples)+1)): r,g,b = self.pixelObj[x,y] if (r,g,b) != (255,255,255): intensities.append((r+g+b)/3) avg = 0 for x in intensities: avg += x avg = avg / len(intensities) return avg def draw_above_threshold(self,threshold): """put all pixels above the 'threshold' into an array and save it. Crop the image so only these pixels are displayed.""" print "threshold luminance: {}".format(threshold) size = self.image.width * self.image.height px = [] py = [] #store a 2d array of pixels array_2 = [] #append pixels that are likely part of an event to array_2 first_px = [self.image.width-1,self.image.height-1] last_px = [0,0] for y in range(0,self.image.height-1): row = [] for x in range(0,self.image.width-1): r,g,b = self.pixelObj[x,y] brightness = (r + g + b)/3 if brightness >= threshold: if x < first_px[0]: first_px[0] = x if y < first_px[1]: first_px[1] = y if x > last_px[0]: last_px[0] = x if y > last_px[1]: last_px[1] = y self.pixelObj[x,y] = (100,100,100) row.append([brightness,brightness,brightness]) px.append(x) py.append(y) else: row.append([0,0,0]) array_2.append(row) #crop the image so only the selected pixels are visible np_array = np.array(array_2) crop = (first_px[0],first_px[1],last_px[0],last_px[1]) width, height = (abs(last_px[0]-first_px[0]),abs(last_px[1]-first_px[1])) if width <= 3 or height <= 3: print "Insufficient area: {} px ({}x{})".format(width * height,width,height) return straight = Image.new('RGB', (len(array_2[0]), len(array_2))) straight.putdata([tuple(p) for row in array_2 for p in row]) straight = straight.crop(crop) #save image and replace if specified straight.save('{}_edited.png'.format(self.name)) if self.replaces: os.system('rm -f {}'.format(self.name)) new_arr = np.array(straight) def start(self): """find average illumination and use that in the threshold value to find the event""" avg = self.find_illumination(100) self.draw_above_threshold(avg * 5.0) #ensure user input if len(sys.argv) == 2: name = sys.argv[1] #determine if being called on image or directory #TODO://fix this if name[-4:] == ".png": #apply to one image i = ImageManipulator(Image.open(name),name) i.start() else: #apply to many images in a directory count = 0 for (dirname,dnames,fnames) in os.walk(name): size = len(fnames) print "Editing {} files in {}...".format(size,dirname) for f in fnames: if f[-4:] != '.png': size -= 1 continue i = ImageManipulator(Image.open(os.path.join(dirname,f)),name=f,replaces=True) i.start() count += 1 print "Finished {}, {} of {} complete".format(f,count,size)
[ "cisnerosa2000@gmail.com" ]
cisnerosa2000@gmail.com
fc768d86e67ffc89d1d24ffed58e0444d7d7b40f
01fc3bd7098dd265a78dcf23c08f427a59581dd3
/src/prosestats/stats.py
4988679a238bb6f0a0baadab6ab16ec4a26ccb0c
[]
no_license
rosspeckomplekt/textual-analogy-parsing
68ba0a6e259d26059552eb8a5082c38890a43a32
d60bdfd1d7c69bb28a16ee69c99a4f9c53044c1e
refs/heads/master
2020-12-09T10:21:30.208376
2018-12-06T16:57:45
2018-12-06T16:57:45
233,275,236
1
0
null
2020-01-11T18:06:47
2020-01-11T18:06:46
null
UTF-8
Python
false
false
12,237
py
from collections import defaultdict, Counter import numpy as np import scipy.stats as scstats def invert_dict(data): ret = defaultdict(dict) for m, dct in data.items(): for n, v in dct.items(): ret[n][m] = v return ret def flatten_dict(data): ret = {} for k, vs in data.items(): for k_, v in vs.items(): ret[k,k_] = v return ret def nominal_agreement(a,b): return int(a==b) def ordinal_agreement(a,b, V): return 1 - abs(a - b)/(V-1) def nominal_metric(a, b): return a != b def interval_metric(a, b): return (a-b)**2 def ratio_metric(a, b): return ((a-b)/(a+b))**2 def ordinal_metric(N_v, a, b): a, b = min(a,b), max(a,b) return (sum(N_v[a:b+1]) - (N_v[a] + N_v[b])/2)**2 def compute_alpha(data, metric="ordinal", V=None): """ Computes Krippendorff's alpha for a coding matrix V. V implicitly represents a M x N matrix where M is the number of coders and N is the number of instances. In reality, to represent missing values, it is a dictionary of M dictionaries, with each dictionary having some of N keys. @V is the number of elements. """ data_ = invert_dict(data) if V is None: V = max({v for worker in data.values() for v in worker.values()})+1 O = np.zeros((V, V)) E = np.zeros((V, V)) for _, dct in data_.items(): if len(dct) <= 1: continue o = np.zeros((V,V)) for m, v in dct.items(): v = int(v) for m_, v_ in dct.items(): v_ = int(v_) if m != m_: o[v, v_] += 1 M_n = len(dct) O += o/(M_n - 1) N_v = O.sum(0) E = (np.outer(N_v, N_v) - N_v * np.eye(V))/(sum(N_v)-1) if metric == "nominal": metric = nominal_metric elif metric == "interval": metric = lambda a, b: interval_metric(a/V, b/V) elif metric == "ratio": metric = ratio_metric elif metric == "ordinal": metric = lambda v, v_: ordinal_metric(N_v, v, v_) else: raise ValueError("Invalid metric " + metric) delta = np.array([[metric(v, v_) for v in range(V)] for v_ in range(V)]) D_o = (O * delta).sum() D_e = (E * delta).sum() return 1 - D_o/D_e def test_compute_alpha(): # Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha data = { 'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,}, 'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,}, 'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,}, } assert np.allclose(compute_alpha(data, "nominal", 4), 0.691, 5e-3) assert np.allclose(compute_alpha(data, "interval", 4), 0.811, 5e-3) assert np.allclose(compute_alpha(data, "ordinal", 4), 0.807, 5e-3) def outliers_modified_z_score(ys, threshold = 3.5): median_y = np.median(ys) median_absolute_deviation_y = np.median([np.abs(y - median_y) for y in ys]) modified_z_scores = [0.6745 * (y - median_y) / median_absolute_deviation_y for y in ys] return np.where(np.abs(modified_z_scores) > threshold) def outliers_modified_z_score_one_sided(ys, threshold = 3.5): median_y = np.median(ys) median_absolute_deviation_y = np.median([np.abs(y - median_y) for y in ys]) modified_z_scores = [0.6745 * (y - median_y) / median_absolute_deviation_y for y in ys] return np.where(np.abs(modified_z_scores) > threshold) def compute_pearson_rho(data): """ Given matrix of (task, worker_responses), computes pairs of (worker_response - avg) for every task and averages over all workers. """ data_ = invert_dict(data) # get task means. pearson_data = defaultdict(list) for _, worker_responses in data_.items(): # compute pairs, if len(worker_responses) < 2: continue avg = np.mean(list(worker_responses.values())) for worker, response in worker_responses.items(): pearson_data[worker].append([response, avg]) micro_data = np.array(sum(pearson_data.values(), [])) micro, _ = scstats.pearsonr(micro_data.T[0], micro_data.T[1]) macros = [] for _, vs in pearson_data.items(): if len(vs) < 3: continue vs = np.array(vs) rho, _ = scstats.pearsonr(vs.T[0], vs.T[1]) if not np.isnan(rho): # uh, not sure how to handle this... macros.append(rho) return micro #, np.mean(macros) def test_pearson_rho(): # Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha data = { 'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,}, 'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,}, 'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,}, } micro, macro = compute_pearson_rho(data) assert np.allclose(micro, 0.947, 5e-3) assert np.allclose(macro, 0.948, 5e-3) def compute_tmean(data, mode="function", frac=0.1): if mode == "worker": ret = [] for vs in data.values(): vs = list(vs.values()) ret.append(scstats.trim_mean(vs, frac)) return np.mean(ret) else: data = invert_dict(data) ret = [] for vs in data.values(): vs = list(vs.values()) ret.extend(vs) return scstats.trim_mean(ret, frac) def compute_mean(data, mode="function"): if mode == "worker": ret = [] for vs in data.values(): vs = list(vs.values()) ret.extend(vs) return np.mean(ret) else: data = invert_dict(data) ret = [] for vs in data.values(): vs = list(vs.values()) ret.append(np.mean(vs)) return np.mean(ret) def compute_median(data): ret = [] for vs in data.values(): vs = list(vs.values()) ret.extend(vs) return np.median(ret) def compute_std(data, mode="worker"): data = invert_dict(data) if mode == "worker": ret = [] for vs in data.values(): vs = list(vs.values()) ret.extend((vs - np.mean(vs)).tolist()) return np.std(ret) else: ret = [] for vs in data.values(): vs = list(vs.values()) ret.append(np.mean(vs)) return np.std(ret) def compute_nu(data): return compute_std(data, "worker")/compute_std(data, "function") def compute_mad(data, mode="worker"): data = invert_dict(data) if mode == "worker": ret = [] for vs in data.values(): vs = list(vs.values()) ret.extend((vs - np.median(vs)).tolist()) return np.mean(np.abs(ret)) else: ret = [] for vs in data.values(): vs = list(vs.values()) ret.append(np.mean(vs)) return np.mean(np.abs(ret - np.median(ret))) def compute_agreement(data, mode="nominal", V=None): """ Computes simple agreement by taking pairs of data and simply computing probabilty that they agree. @V is range of values """ if V is None: V = len({v for worker in data.values() for v in worker}) if mode == "nominal": f = nominal_agreement elif mode == "ordinal": f = lambda a,b: ordinal_agreement(a, b, V) else: raise ValueError("Invalid mode {}".format(mode)) data_ = invert_dict(data) ret, i = 0., 0 for _, worker_responses in data_.items(): # compute pairs, if len(worker_responses) < 2: continue responses = sorted(worker_responses.values()) # get pairs for j, r in enumerate(responses): for _, r_ in enumerate(responses[j+1:]): # compute probability ret += (f(r,r_) - ret)/(i+1) i += 1 return ret def test_compute_agreement_nominal(): # Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha data = { 'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,}, 'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,}, 'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,}, } agreement = compute_agreement(data, "nominal") assert np.allclose(agreement, 0.75, 5e-3) def test_compute_agreement_ordinal(): # Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha data = { 'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,}, 'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,}, 'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,}, } agreement = compute_agreement(data, "ordinal") assert np.allclose(agreement, 0.75, 5e-3) def _factorize(data): """ Try to learn turker and task scores as a linear model. """ workers = sorted(data.keys()) tasks = sorted({hit for hits in data.values() for hit in hits}) n_entries = sum(len(hits) for hits in data.values()) X = np.zeros((n_entries, len(workers)+len(tasks))) Y = np.zeros(n_entries) i = 0 for worker, hits in data.items(): for task, value in hits.items(): X[i, workers.index(worker)] = 1 X[i, len(workers) + tasks.index(task)] = 1 Y[i] = value i += 1 return X, Y def compute_mean_agreement(data, mode="nominal", V=None): if V is None: V = len({v for worker in data.values() for v in worker}) if mode == "nominal": f = nominal_agreement elif mode == "ordinal": f = lambda a,b: ordinal_agreement(a, b, V) else: raise ValueError("Invalid mode {}".format(mode)) data_ = invert_dict(data) ret, i = 0., 0 for _, worker_responses in data_.items(): # compute pairs, if len(worker_responses) < 2: continue responses = sorted(worker_responses.values()) if mode == "nominal": m = scstats.mode(responses)[0] elif mode == "ordinal": m = np.mean(responses) # get pairs for r in responses: # compute probability ret += (f(m,r) - ret)/(i+1) i += 1 return ret def compute_worker(data, mode="std"): data_ = invert_dict(data) if mode == "std": Ms = {hit_id: np.mean(list(ws.values())) for hit_id, ws in data_.items()} elif mode == "mad": Ms = {hit_id: np.median(list(ws.values())) for hit_id, ws in data_.items()} elif mode == "iaa": Ms = {hit_id: np.median(list(ws.values())) for hit_id, ws in data_.items()} else: raise ValueError() ret = {} for worker, responses in data.items(): vs = [Ms[hit_id] - response for hit_id, response in responses.items()] if mode == "std": ret[worker] = np.std(vs) elif mode == "mad": ret[worker] = np.mean(np.abs(vs)) elif mode == "iaa": ret[worker] = np.mean([1 if v == 0 else 0 for v in vs]) return ret def compute_task_worker_interactions(data, alpha=0.1): """ Using a mixed-effects model: y = Wx + Za jk """ data = flatten_dict(data) keys = sorted(data.keys()) workers, hits = zip(*keys) workers, hits = sorted(set(workers)), sorted(set(hits)) Y = np.zeros(len(keys) + 2) X = np.zeros((len(keys) + 2, len(workers) + len(hits))) # + len(keys)-1)) wf = [0 for _ in workers] hf = [0 for _ in hits] for i, (worker, hit) in enumerate(keys): Y[i] = data[worker,hit] wi, hi = workers.index(worker), hits.index(hit) X[i, wi] = 1 X[i, len(workers) + hi] = 1 wf[wi] += 1 hf[hi] += 1 # constraint: proportional sum of workers = 0 Y[len(keys)], X[len(keys), :len(workers)] = 0, wf # constraint: proportional sum of tasks = 0 Y[len(keys)+1], X[len(keys)+1, len(workers):] = 0, hf model = Ridge(alpha=alpha)#, fit_intercept=False) model.fit(X, Y)# - Y.mean()) mean = model.intercept_ worker_coefs = model.coef_[:len(workers)] hit_coefs = model.coef_[len(workers):] residuals = Y - model.predict(X) ret = { "mean": mean, "worker-std": np.std(worker_coefs), "task-std": np.std(hit_coefs), "residual-std": np.std(residuals), } return ret
[ "arunchaganty@gmail.com" ]
arunchaganty@gmail.com
b8496eb601d1410da36c19c8c2d3e91c50929aa0
0e10ddf7a6addf11602013c9919b064de91d74ff
/braitenberg_love.py
e16448df60c98ca0cae21209467f297d2d859411
[]
no_license
JulienAndres/L3_3I025_Projet2
a450df4d88662c28ffb36b8e84fb2a2b9171aa93
3e08789bb407cf67abb1d233ad830aa7ac7b6fe3
refs/heads/master
2021-01-22T08:39:24.198858
2017-05-27T23:57:16
2017-05-27T23:57:16
92,628,343
0
1
null
null
null
null
UTF-8
Python
false
false
9,099
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # multirobot.py # Contact (ce fichier uniquement): nicolas.bredeche(at)upmc.fr # # Description: # Template pour simulation mono- et multi-robots type khepera/e-puck/thymio # Ce code utilise pySpriteWorld, développé par Yann Chevaleyre (U. Paris 13) # # Dépendances: # Python 2.x # Matplotlib # Pygame # # Historique: # 2016-03-28__23:23 - template pour 3i025 (IA&RO, UPMC, licence info) # # Aide: code utile # - Partie "variables globales" # - La méthode "step" de la classe Agent # - La fonction setupAgents (permet de placer les robots au début de la simulation) # - La fonction setupArena (permet de placer des obstacles au début de la simulation) # - il n'est pas conseillé de modifier les autres parties du code. # from robosim import * from random import random, shuffle import time import sys import atexit from itertools import count ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ''' Aide ''' ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' #game.setMaxTranslationSpeed(3) # entre -3 et 3 # size of arena: # screenw,screenh = taille_terrain() # OU: screen_width,screen_height ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ''' variables globales ''' ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' game = Game() agents = [] screen_width=512 #512,768,... -- multiples de 32 screen_height=512 #512,768,... -- multiples de 32 nbAgents = 10 maxSensorDistance = 30 # utilisé localement. maxRotationSpeed = 5 SensorBelt = [-170,-80,-40,-20,+20,40,80,+170] # angles en degres des senseurs maxIterations = -1 # infinite: -1 showSensors = True frameskip = 0 # 0: no-skip. >1: skip n-1 frames verbose = True ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ''' Classe Agent/Robot ''' ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' class Agent(object): agentIdCounter = 0 # use as static id = -1 robot = -1 name = "Equipe Alpha" # A modifier avec le nom de votre équipe def __init__(self,robot): self.id = Agent.agentIdCounter Agent.agentIdCounter = Agent.agentIdCounter + 1 #print "robot #", self.id, " -- init" self.robot = robot def getRobot(self): return self.robot def step(self): #print "robot #", self.id, " -- step" p = self.robot # actions #p.rotate( -1 ) # normalisé -1,+1 -- valeur effective calculé avec maxRotationSpeed et maxTranslationSpeed p.forward(1) # normalisé -1,+1 tabdist=[(maxSensorDistance+1) for i in range(len(SensorBelt))] tab_dist=dict() for i,impact in enumerate(sensors[p]): if impact.dist_from_border > maxSensorDistance: #print "- sensor #" + str(i) + " touches nothing" tabdist[i]=maxSensorDistance+1 tab_dist[i]=(maxSensorDistance+1,impact.layer) else: #print "- sensor #" + str(i) + " touches something at distance " + str(impact.dist_from_border) tabdist[i]=impact.dist_from_border tab_dist[i]=(impact.dist_from_border,impact.layer) #print str(tab_dist)+"\n" print str(tab_dist)+"\n" dist_min=min(tabdist) ind_min=tabdist.index(dist_min) if (dist_min != maxSensorDistance+1): impact=tab_dist[ind_min][1] print impact print ind_min print dist_min if (impact==None): print "NONNNNNNE"+"\n" if (SensorBelt[ind_min]<0): p.rotate(1) else: p.rotate(-1) if (impact=='obstacle'): print "obstacle"+"\n" if (SensorBelt[ind_min]<0): p.rotate(-1) else: p.rotate(1) if (impact=='joueur'): if (SensorBelt[ind_min]<0): p.rotate(1) else: p.rotate(-1) #Exemple: comment récuperer le senseur #2 #dist = sensor_infos[2].dist_from_border #if dist > maxSensorDistance: # dist = maxSensorDistance # borne # monitoring - affiche diverses informations sur l'agent et ce qu'il voit. # pour ne pas surcharger l'affichage, je ne fais ca que pour le player 1 # if verbose == True and self.id == 0: # # efface() # j'efface le cercle bleu de l'image d'avant # color( (0,0,255) ) # circle( *game.player.get_centroid() , r = 22) # je dessine un rond bleu autour de ce robot # # print "\n# Current robot at " + str(p.get_centroid()) + " with orientation " + str(p.orientation()) # # sensor_infos = sensors[p] # sensor_infos est une liste de namedtuple (un par capteur). # for i,impact in enumerate(sensors[p]): # impact est donc un namedtuple avec plein d'infos sur l'impact: namedtuple('RayImpactTuple', ['sprite','layer','x', 'y','dist_from_border','dist_from_center','rel_angle_degree','abs_angle_degree']) # if impact.dist_from_border > maxSensorDistance: # print "- sensor #" + str(i) + " touches nothing" # else: # print "- sensor #" + str(i) + " touches something at distance " + str(impact.dist_from_border) # if impact.layer == 'joueur': # playerTMP = impact.sprite # print " - type: robot no." + str(playerTMP.numero) # print " - x,y = " + str( playerTMP.get_centroid() ) + ")" # renvoi un tuple # print " - orientation = " + str( playerTMP.orientation() ) + ")" # p/r au "nord" # elif impact.layer == 'obstacle': # print " - type obstacle" # else: # print " - type boundary of window" return ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ''' Fonctions init/step ''' ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' def setupAgents(): global screen_width, screen_height, nbAgents, agents, game # Make agents nbAgentsCreated = 0 for i in range(nbAgents): while True: p = -1 while p == -1: # p renvoi -1 s'il n'est pas possible de placer le robot ici (obstacle) p = game.add_players( (random()*screen_width , random()*screen_height) , None , tiled=False) if p: p.oriente( random()*360 ) p.numero = nbAgentsCreated nbAgentsCreated = nbAgentsCreated + 1 agents.append(Agent(p)) break game.mainiteration() def setupArena(): for i in range(6,13): addObstacle(row=3,col=i) for i in range(3,10): addObstacle(row=12,col=i) addObstacle(row=4,col=12) addObstacle(row=5,col=12) addObstacle(row=6,col=12) addObstacle(row=11,col=3) addObstacle(row=10,col=3) addObstacle(row=9,col=3) def stepWorld(): # chaque agent se met à jour. L'ordre de mise à jour change à chaque fois (permet d'éviter des effets d'ordre). shuffledIndexes = [i for i in range(len(agents))] shuffle(shuffledIndexes) ### TODO: erreur sur macosx for i in range(len(agents)): agents[shuffledIndexes[i]].step() return ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ''' Fonctions internes ''' ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' def addObstacle(row,col): # le sprite situe colone 13, ligne 0 sur le spritesheet game.add_new_sprite('obstacle',tileid=(0,13),xy=(col,row),tiled=True) class MyTurtle(Turtle): # also: limit robot speed through this derived class maxRotationSpeed = maxRotationSpeed # 10, 10000, etc. def rotate(self,a): mx = MyTurtle.maxRotationSpeed Turtle.rotate(self, max(-mx,min(a,mx))) def onExit(): print "\n[Terminated]" ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' ''' Main loop ''' ''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''' init('vide3',MyTurtle,screen_width,screen_height) # display is re-dimensioned, turtle acts as a template to create new players/robots game.auto_refresh = False # display will be updated only if game.mainiteration() is called game.frameskip = frameskip atexit.register(onExit) setupArena() setupAgents() game.mainiteration() iteration = 0 while iteration != maxIterations: # c'est plus rapide d'appeler cette fonction une fois pour toute car elle doit recalculer le masque de collision, # ce qui est lourd.... sensors = throw_rays_for_many_players(game,game.layers['joueur'],SensorBelt,max_radius = maxSensorDistance+game.player.diametre_robot() , show_rays=showSensors) stepWorld() game.mainiteration() iteration = iteration + 1
[ "julienandres06@gmail.com" ]
julienandres06@gmail.com
8e48cdc36af358ce63b9cee3a6d9027cf929722e
a838d4bed14d5df5314000b41f8318c4ebe0974e
/sdk/deviceupdate/azure-iot-deviceupdate/setup.py
3b4d52e9e304da8944d2b8b5c37ac85830a070fd
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
scbedd/azure-sdk-for-python
ee7cbd6a8725ddd4a6edfde5f40a2a589808daea
cc8bdfceb23e5ae9f78323edc2a4e66e348bb17a
refs/heads/master
2023-09-01T08:38:56.188954
2021-06-17T22:52:28
2021-06-17T22:52:28
159,568,218
2
0
MIT
2019-08-11T21:16:01
2018-11-28T21:34:49
Python
UTF-8
Python
false
false
2,815
py
#!/usr/bin/env python #------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import re import os.path from io import open from setuptools import find_packages, setup PACKAGE_NAME = "azure-iot-deviceupdate" PACKAGE_PPRINT_NAME = "Device Update" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace('-', '/') # a-b-c => a.b.c namespace_name = PACKAGE_NAME.replace('-', '.') # azure v0.x is not compatible with this package # azure v0.x used to have a __version__ attribute (newer versions don't) try: import azure try: ver = azure.__version__ raise Exception( 'This package is incompatible with azure=={}. '.format(ver) + 'Uninstall it with "pip uninstall azure".' ) except AttributeError: pass except ImportError: pass # Version extraction inspired from 'requests' with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.md', encoding='utf-8') as f: readme = f.read() with open('CHANGELOG.md', encoding='utf-8') as f: changelog = f.read() setup( name=PACKAGE_NAME, version=version, description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), long_description=readme + "\n\n" + changelog, long_description_content_type='text/markdown', url='https://github.com/Azure/azure-sdk-for-python', author='Microsoft Corporation', author_email='adupmdevteam@microsoft.com', license='MIT License', zip_safe=False, classifiers=[ "Development Status :: 4 - Beta", 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'License :: OSI Approved :: MIT License', ], packages=find_packages(exclude=[ 'tests', # Exclude packages that will be covered by PEP420 or nspkg 'azure', 'azure.iot', ]), install_requires=[ 'msrest>=0.5.0', 'azure-common~=1.1', 'azure-core>=1.6.0,<2.0.0', ], extras_require={ ":python_version<'3.0'": ['azure-iot-nspkg'], } )
[ "noreply@github.com" ]
noreply@github.com
71005eb5e40000b0a87144dcba860b1dc4522d1d
232c017298cf5687c802fe6d57c6b53cbc507b0b
/Ranker/run_multiple_choice_custom.py
c635a15ffa9d2348fce8e4b6f79e2ae9ddfdd47a
[]
no_license
dongfang91/Generate-and-Rank-ConNorm
55954ad9fe17f4d1d3fd5cd9788835d5cf40f454
2c26211125454439389e98aeb5c344a88c79d2ff
refs/heads/master
2023-03-08T22:20:00.110971
2021-02-22T17:07:51
2021-02-22T17:07:51
257,353,866
27
4
null
null
null
null
UTF-8
Python
false
false
10,423
py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Finetuning the library models for multiple choice (Bert, Roberta, XLNet).""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, TrainingArguments, set_seed, ) from utils_multiple_choice_custom import MultipleChoiceDataset, Split, processors from modeling_auto_custom import AutoModelForMultipleChoice from trainer_custom import Trainer logger = logging.getLogger(__name__) def simple_accuracy(preds, labels): return (preds == labels).mean() @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) tokenizer_name: Optional[str] = field( default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. """ task_name: str = field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys())}) data_dir: str = field(metadata={"help": "Should contain the data files for the task."}) n_labels: int = field(default=128,metadata={"help": "# of candidates"}) lambda_1: float = field(default=0.0, metadata={"help": "weight for lambda_1"}) lambda_2: float = field(default=0.0, metadata={"help": "weight for lambda_2"}) margin1: float = field(default=0.0, metadata={"help": "margin1 for positive candidates"}) margin2: float = field(default=0.0, metadata={"help": "margin2 for negative candidates"}) max_seq_length: int = field( default=128, metadata={ "help": "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", training_args.local_rank, training_args.device, training_args.n_gpu, bool(training_args.local_rank != -1), training_args.fp16, ) logger.info("Training/evaluation parameters %s", training_args) # Set seed set_seed(training_args.seed) try: processor = processors[data_args.task_name]() label_list = processor.get_labels(int(data_args.n_labels)) # label_list = processor.get_labels() num_labels = len(label_list) except KeyError: raise ValueError("Task not found: %s" % (data_args.task_name)) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, ) model = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, ) # Get datasets train_dataset = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=tokenizer, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.train, n_labels=data_args.n_labels ) if training_args.do_train else None ) eval_dataset = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=tokenizer, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, n_labels=data_args.n_labels ) if training_args.do_eval else None ) test_dataset = ( MultipleChoiceDataset( data_dir=data_args.data_dir, tokenizer=tokenizer, task=data_args.task_name, max_seq_length=data_args.max_seq_length, overwrite_cache=data_args.overwrite_cache, mode=Split.dev, n_labels=data_args.n_labels ) if training_args.do_predict else None ) def compute_metrics(p: EvalPrediction) -> Dict: preds = np.argmax(p.predictions, axis=1) return {"acc": simple_accuracy(preds, p.label_ids)} custom_parameters = [data_args.lambda_1, data_args.lambda_2, data_args.margin1, data_args.margin2] # Initialize our Trainer trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, compute_metrics=compute_metrics, custom_hyperparameters=custom_parameters ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir) # Evaluation results = {} if training_args.do_eval: logger.info("*** Evaluate ***") result = trainer.evaluate() output_eval_file = os.path.join(training_args.output_dir, "eval_results.txt") if trainer.is_world_master(): with open(output_eval_file, "w") as writer: logger.info("***** Eval results *****") for key, value in result.items(): logger.info(" %s = %s", key, value) writer.write("%s = %s\n" % (key, value)) results.update(result) return results if training_args.do_predict: logging.info("*** Evaluate ***") predictions = trainer.predict(test_dataset=eval_dataset) metrics, results = predictions.metrics, predictions.predictions output_eval_file = os.path.join(training_args.output_dir, "eval_results_checkpoint.txt") if trainer.is_world_master(): with open(output_eval_file, "w") as writer: logger.info("***** Eval results *****") for key, value in metrics.items(): logger.info(" %s = %s", key, value) writer.write("%s = %s\n" % (key, value)) output_test_predictions_file = os.path.join(training_args.output_dir, "eval_predictions_checkpoint.txt") np.savetxt(output_test_predictions_file, predictions) logging.info("*** Test ***") predictions = trainer.predict(test_dataset=test_dataset) metrics, results = predictions.metrics, predictions.predictions output_eval_file = os.path.join(training_args.output_dir, "test_results_checkpoint.txt") if trainer.is_world_master(): with open(output_eval_file, "w") as writer: logger.info("***** Test results *****") for key, value in metrics.items(): logger.info(" %s = %s", key, value) writer.write("%s = %s\n" % (key, value)) output_test_predictions_file = os.path.join(training_args.output_dir, "test_predictions_checkpoint.txt") np.savetxt(output_test_predictions_file, predictions) def _mp_fn(index): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
[ "xudffaint@gmail.com" ]
xudffaint@gmail.com
a8972a430ffb07204980882f80982295def04f91
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02690/s260373583.py
683e4c44817819625608097b879fb92b1bb0fe95
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
181
py
def get(n): for i in range(-1000,1001): for j in range(-1000,1001): if(i**5-j**5==n): print(i,j) return n=int(input()) get(n)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
1b1bd7d6aa1f441bdeaafa9620bf191652f717af
55d2c05f1eff505485b90a6d327ef0a12b9644a0
/lab5/.venv/bin/pip3.5
cf84dd4f7e4bda790e7d35be9d9f889527b33d9b
[]
no_license
TonyYuhuiJiang/ECE361
d35ccb643277a06148bb60c185d225a2528ca200
7290d68fbbadc229c4db5a5b8719137101a417d6
refs/heads/master
2022-04-23T09:16:36.734265
2020-04-27T03:32:20
2020-04-27T03:32:20
259,188,998
0
0
null
null
null
null
UTF-8
Python
false
false
243
5
#!/home/ubuntu/lab5/.venv/bin/python3 # -*- coding: utf-8 -*- import re import sys from pip._internal.cli.main import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "yuhui.jiang@mail.utoronto.ca" ]
yuhui.jiang@mail.utoronto.ca
bf903b573e0cfb74678bfe23f802357bcf78522b
2b963beeffb8c826c13d9e757f01b36b7aa8625f
/data/manuscripts/greek_WH_UBS4_parsed.py
4de63dd4fde924a8294210ac4a9ee5e9fe386901
[]
no_license
bydesign/openscriptures
68e01f20fa5a127e11a4cc8f57f7cbdf37057a05
a6decbc19425a42338a6c5706750a00fd363f590
refs/heads/master
2021-01-18T07:44:25.069480
2009-12-21T02:28:44
2009-12-21T02:28:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
17,833
py
#!/usr/bin/env python # encoding: utf-8 msID = 2 varMsID = 3 import sys, os, re, unicodedata, difflib, zipfile, StringIO from datetime import date from django.core.management import setup_environ from django.utils.encoding import smart_str, smart_unicode sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../')) #There's probably a better way of doing this from openscriptures import settings setup_environ(settings) from openscriptures.data.unbound_bible import UNBOUND_CODE_TO_OSIS_CODE # Why does this have to be explicit? from openscriptures.data import import_helpers from openscriptures.core.models import * # Abort if MS has already been added (or --force not supplied) import_helpers.abort_if_imported(msID) # Download the source file source_url = "http://www.unboundbible.org/downloads/bibles/greek_WH_UBS4_parsed.zip" import_helpers.download_resource(source_url) # Delete existing works and their contents import_helpers.delete_work(msID, varMsID) msWork = Work( id = msID, title = "Westcott/Hort", abbreviation = "W/H", language = Language('grc'), type = 'Bible', osis_slug = 'WH', publish_date = date(1881, 1, 1), originality = 'manuscript-edition', creator = "By <a href='http://en.wikipedia.org/wiki/Brooke_Foss_Westcott' title='Brooke Foss Westcott @ Wikipedia'>Brooke Foss Westcott</a> and <a href='http://en.wikipedia.org/wiki/Fenton_John_Anthony_Hort' title='Fenton John Anthony Hort @ Wikipedia'>Fenton John Anthony Hort</a>.", url = source_url, variant_number = 1, license = License.objects.filter(url="http://creativecommons.org/licenses/publicdomain/")[0] ) msWork.save() # Now we need to create additional works for each set of variants that this work contains # Diff/variant works will have tokens that have positions that are the same as those in the base work? The base work's tokens will have positions that have gaps? # When processing a line with enclosed variants, it will be important to construct the verse for VAR1, VAR2, etc... and then merge these together. variantWork = Work( id = varMsID, title = "UBS4 Variants", abbreviation = "UBS4-var", language = Language('grc'), type = 'Bible', osis_slug = 'UBS4-var', publish_date = date(1993, 1, 1), originality = 'manuscript-edition', creator = "By <a href='http://en.wikipedia.org/wiki/Eberhard_Nestle' title='Eberhard Nestle @ Wikipedia'>Eberhard Nestle</a>, <a href='http://en.wikipedia.org/wiki/Erwin_Nestle' title='Erwin Nestle @ Wikipedia'>Erwin Nestle</a>, <a href='http://en.wikipedia.org/wiki/Kurt_Aland' title='Kurt Aland @ Wikipedia'>Kurt Aland</a>, <a href='http://www.biblesociety.org/'>United Bible Societies</a> et al", url = "http://www.unboundbible.org/downloads/bibles/greek_textus_receptus_parsed.zip", base = msWork, variant_number = 2, license = License.objects.get(url="http://en.wikipedia.org/wiki/Fair_use") ) variantWork.save() # The followig regular epression identifies the parts of the following line: # 40N 1 1 10 Βίβλος G976 N-NSF γενέσεως G1078 N-GSF Ἰησοῦ G2424 N-GSM χριστοῦ G5547 N-GSM , υἱοῦ G5207 N-GSM Δαυίδ G1138 N-PRI , υἱοῦ G5207 N-GSM Ἀβραάμ G11 N-PRI . lineParser = re.compile(ur"""^ (?P<book>\d+\w+)\t+ # Unbound Bible Code (?P<chapter>\d+)\t+ # Chapter (?P<verse>\d+)\t+ # Verse \d+\t+ # Ignore orderby column (?P<data>.*?) \s*$""", re.VERBOSE ) # Regular expression to parse each individual word on a line (the data group from above) tokenParser = re.compile(ur""" \[*(?P<word>ινα\s+τι|\S+?)\]*\s+ (?P<rawParsing> G?\d+ (?: \s+G?\d+ | \s+[A-Z0-9\-:]+ | \] )+ ) #(?P<strongs1>G?\d+)\]*\s+ #(?: # G?(?P<strongs2>\d+\]*)\s+ #)? #(?P<parsing>[A-Z0-9\-]+)\]* #(?P<extra> # (?: \s+G?\d+ | \s+[A-Z0-9\-:]+ | \] )+ #)? (?:\s+|$) """, re.VERBOSE | re.UNICODE) # We need to deal with single variant brackets and double variant brackets; actually, what we need to do is pre-process the entire file and fix the variant brackets #reMatchVariantString = re.compile(ur"\[\s*([^\]]+\s[^\]]+?)\s*\]") #re.compile(ur"(\[(?!\s)\b\p{Greek}+.+?\p{Greek}\b(?<!\s)\])") # Compile the regular expressions that are used to isolate the variants for each work reFilterVar1 = re.compile(ur"\s* ( {VAR[^1]:.+?} | {VAR1: | } )""", re.VERBOSE) reFilterVar2 = re.compile(ur"\s* ( {VAR[^2]:.+?} | {VAR2: | } )""", re.VERBOSE) reHasVariant = re.compile(ur'{VAR') reHasBracket = re.compile(ur'\[|\]') bookRefs = [] chapterRefs = [] verseRefs = [] tokens = [] previousTokens = [] class TokenContainer: "Contains a regular expression match for a work; used for collating two works' variants and merging them together before insertion into model" def __init__(self, match, variant_number = None, position = None, open_brackets = 0): self.match = match self.variant_number = variant_number self.position = position self.normalized_word = import_helpers.normalize_token(match['word']) self.open_brackets = open_brackets def __hash__(self): return hash(self.normalized_word) def __eq__(self, other): return self.normalized_word == other.normalized_word var1OpenBrackets = 0 var2OpenBrackets = 0 tokenPosition = 0 zip = zipfile.ZipFile(os.path.basename(source_url)) for verseLine in StringIO.StringIO(zip.read("greek_WH_UBS4_parsed_utf8.txt")): if(verseLine.startswith('#')): continue verseLine = unicodedata.normalize("NFC", smart_unicode(verseLine)) verseInfo = lineParser.match(verseLine) if(not verseInfo): raise Exception("Parse error on line: " + verseLine) if(not verseInfo.group('data') or UNBOUND_CODE_TO_OSIS_CODE[verseInfo.group('book')] not in OSIS_BIBLE_BOOK_CODES): continue meta = verseInfo.groupdict() # Not only do we need to handle {VARX: } but also [variant blocks] # Here we need to fix bracketed words (find the span and then add them around each individual word contained in the span) tokenContainers = [] verseTokens = [] # Parse words for both variants, or if there are open brackets or if this verse has brackets, then we need to do some special processing # Regarding two editions having identical variants but differing degrees of assurance: we will have to not insert them as Token(variant_number=None) but rather # as two tokens at the same position with different variant_numbers and different certainties: # Token(variant_number=1, position=X, certainty=0) # Token(variant_number=2, position=X, certainty=1) if((var1OpenBrackets or var2OpenBrackets) or reHasVariant.search(meta['data']) or reHasBracket.search(meta['data'])): # Get the tokens from the first variant verseVar1 = reFilterVar1.sub('', meta['data']).strip() verseTokensVar1 = [] pos = 0 while(pos < len(verseVar1)): tokenMatch = tokenParser.match(verseVar1, pos) if(not tokenMatch): print "at " + str(pos) + ": " + verseVar1 raise Exception("Parse error") token = TokenContainer(tokenMatch.groupdict(), 1) # Determine if this token is within brackets if(re.search(r'\[\[', verseVar1[tokenMatch.start() : tokenMatch.end()])): var1OpenBrackets = 2 elif(re.search(r'\[', verseVar1[tokenMatch.start() : tokenMatch.end()])): var1OpenBrackets = 1 token.open_brackets = var1OpenBrackets # Determine if this token is the last one in brackets if(re.search(r'\]', verseVar1[tokenMatch.start() : tokenMatch.end()])): var1OpenBrackets = 0 verseTokensVar1.append(token) pos = tokenMatch.end() # Get the tokens from the second variant verseVar2 = reFilterVar2.sub('', meta['data']).strip() verseTokensVar2 = [] pos = 0 while(pos < len(verseVar2)): tokenMatch = tokenParser.match(verseVar2, pos) if(not tokenMatch): print "at " + str(pos) + ": " + verseVar2 raise Exception("Parse error") token = TokenContainer(tokenMatch.groupdict(), 2) # Determine if this token is within brackets if(re.search(r'\[\[', verseVar2[tokenMatch.start() : tokenMatch.end()])): var2OpenBrackets = 2 elif(re.search(r'\[', verseVar2[tokenMatch.start() : tokenMatch.end()])): var2OpenBrackets = 1 token.open_brackets = var2OpenBrackets # Determine if this token is the last one in brackets if(re.search(r'\]', verseVar2[tokenMatch.start() : tokenMatch.end()])): var2OpenBrackets = 0 verseTokensVar2.append(token) pos = tokenMatch.end() # Now merge verseTokensVar1 and verseTokensVar2 into verseTokens, and then set each token's position according to where it was inserted # 'replace' a[i1:i2] should be replaced by b[j1:j2]. # 'delete' a[i1:i2] should be deleted. Note that j1 == j2 in this case. # 'insert' b[j1:j2] should be inserted at a[i1:i1]. Note that i1 == i2 in this case. # 'equal' a[i1:i2] == b[j1:j2] (the sub-sequences are equal). # However, we need to not set variant_number to None if the certainty is not the same!!! diffedTokenMatches = difflib.SequenceMatcher(None, verseTokensVar1, verseTokensVar2) for opcode in diffedTokenMatches.get_opcodes(): if(opcode[0] == 'equal'): var1indicies = range(opcode[1], opcode[2]) var2indicies = range(opcode[3], opcode[4]) while(len(var1indicies)): i = var1indicies.pop(0) j = var2indicies.pop(0) # Set the position in both var1 and var2 to be the same verseTokensVar1[i].position = tokenPosition verseTokensVar2[j].position = tokenPosition #print verseTokensVar1[i].match['word'] + " == " + verseTokensVar2[j].match['word'] # If the two variants are identical even in the open bracket count, then only insert one and set # variant_number to None because there is absolutely no variance if(verseTokensVar1[i].open_brackets == verseTokensVar2[j].open_brackets): verseTokensVar1[i].variant_number = None tokenContainers.append(verseTokensVar1[i]) # The open_bracket count in the two tokens is different, so insert both but at the exact same position else: tokenContainers.append(verseTokensVar1[i]) tokenContainers.append(verseTokensVar2[j]) tokenPosition = tokenPosition + 1 elif(opcode[0] == 'delete'): for i in range(opcode[1], opcode[2]): #print "1: " + verseTokensVar1[i].match['word'] + " (delete)" verseTokensVar1[i].position = tokenPosition tokenPosition = tokenPosition + 1 tokenContainers.append(verseTokensVar1[i]) elif(opcode[0] == 'insert'): for i in range(opcode[3], opcode[4]): #print "2: " + verseTokensVar2[i].match['word'] + " (insert)" verseTokensVar2[i].position = tokenPosition tokenPosition = tokenPosition + 1 tokenContainers.append(verseTokensVar2[i]) elif(opcode[0] == 'replace'): #print str(verseTokensVar1[opcode[1]] == verseTokensVar2[opcode[3]]) + " THATIS " + (verseTokensVar1[opcode[1]].normalized_word) + " == " + (verseTokensVar2[opcode[3]].normalized_word) for i in range(opcode[1], opcode[2]): #print "1: " + verseTokensVar1[i].match['word'] + " (replace)" verseTokensVar1[i].position = tokenPosition tokenPosition = tokenPosition + 1 tokenContainers.append(verseTokensVar1[i]) for i in range(opcode[3], opcode[4]): #print "2: " + verseTokensVar2[i].match['word'] + " (replace)" verseTokensVar2[i].position = tokenPosition tokenPosition = tokenPosition + 1 tokenContainers.append(verseTokensVar2[i]) # No variants and there weren't any variant brackets, so just parse them out of one verse else: pos = 0 while(pos < len(meta['data'])): tokenMatch = tokenParser.match(meta['data'], pos) if(not tokenMatch): print "%s %02d %02d" % (verseInfo.group('book'), int(verseInfo.group('chapter')), int(verseInfo.group('verse'))) print "Unable to parse at position " + str(pos) + ": " + verseInfo.group('data') raise Exception("Unable to parse at position " + str(pos) + ": " + verseInfo.group('data')) tokenContainers.append(TokenContainer(tokenMatch.groupdict(), None, tokenPosition)) tokenPosition = tokenPosition + 1 pos = tokenMatch.end() # Create book ref if it doesn't exist if(not len(bookRefs) or bookRefs[-1].osis_id != UNBOUND_CODE_TO_OSIS_CODE[meta['book']]): print UNBOUND_CODE_TO_OSIS_CODE[meta['book']] # Reset tokens previousTokens = tokens tokens = [] # Close book and chapter refs if(len(previousTokens)): bookRefs[-1].end_token = previousTokens[-1] bookRefs[-1].save() chapterRefs[-1].end_token = previousTokens[-1] chapterRefs[-1].save() chapterRefs = [] verseRefs = [] # Set up the book ref bookRef = Ref( work = msWork, type = Ref.BOOK, osis_id = UNBOUND_CODE_TO_OSIS_CODE[meta['book']], position = len(bookRefs), title = OSIS_BOOK_NAMES[UNBOUND_CODE_TO_OSIS_CODE[meta['book']]] ) #bookRef.save() #bookRefs.append(bookRef) # Now process the tokens like normal verseTokens = [] for tokenContainer in tokenContainers: # Insert token token = Token( data = tokenContainer.match['word'], type = Token.WORD, work = msWork, position = tokenContainer.position, variant_number = tokenContainer.variant_number, certainty = tokenContainer.open_brackets ) token.save() tokens.append(token) verseTokens.append(token) # Token Parsing #strongs = [tokenContainer.match['strongs1']] #if(tokenContainer.match['strongs2']): # strongs.append(tokenContainer.match['strongs2']) parsing = TokenParsing( token = token, raw = tokenContainer.match['rawParsing'], #parse = tokenContainer.match['parsing'], #strongs = ";".join(strongs), language = Language('grc'), work = msWork ) parsing.save() # Make this token the first in the book ref, and set the first token in the book if len(tokens) == 1: bookRef.start_token = tokens[0] bookRef.save() bookRefs.append(bookRef) # Set up the Chapter ref if(not len(chapterRefs) or chapterRefs[-1].numerical_start != meta['chapter']): if(len(chapterRefs)): chapterRefs[-1].end_token = tokens[-2] chapterRefs[-1].save() chapterRef = Ref( work = msWork, type = Ref.CHAPTER, osis_id = ("%s.%s" % (bookRefs[-1].osis_id, meta['chapter'])), position = len(chapterRefs), parent = bookRefs[-1], numerical_start = meta['chapter'], start_token = tokens[-1] ) chapterRef.save() chapterRefs.append(chapterRef) # Create verse ref verseRef = Ref( work = msWork, type = Ref.VERSE, osis_id = ("%s.%s.%s" % (bookRefs[-1].osis_id, meta['chapter'], meta['verse'])), position = len(verseRefs), parent = chapterRefs[-1], numerical_start = meta['verse'], start_token = verseTokens[0], end_token = verseTokens[-1] ) verseRef.save() verseRefs.append(verseRef) #Close out the last book and save the chapters bookRefs[-1].end_token = tokens[-1] bookRefs[-1].save() chapterRefs[-1].end_token = tokens[-1] chapterRefs[-1].save() #for chapterRef in chapterRefs: # chapterRef.save()
[ "jleineweber@gmail.com" ]
jleineweber@gmail.com
3218938f4ff24c3363c12fa9d7ea10d14f347fda
afc8d5a9b1c2dd476ea59a7211b455732806fdfd
/Configurations/VBSjjlnu/Full2018v6s5/conf_tests_HEM/nuisances.py
974c0373478496cf6e80d8576ac4c314386b397e
[]
no_license
latinos/PlotsConfigurations
6d88a5ad828dde4a7f45c68765081ed182fcda21
02417839021e2112e740607b0fb78e09b58c930f
refs/heads/master
2023-08-18T20:39:31.954943
2023-08-18T09:23:34
2023-08-18T09:23:34
39,819,875
10
63
null
2023-08-10T14:08:04
2015-07-28T07:36:50
Python
UTF-8
Python
false
false
15,703
py
# # nuisances # #FIXME: TO BE UPDATED FOR 2018! # # name of samples here must match keys in samples.py mc =["DY", "top", "VV", "VVV", "VBF-V", "top", "VBS", "Wjets_LO", "Wjets_njetsLO"] # phase_spaces_boost = [] # phase_spaces_res = [] # for d in ["all","high","low", "all_lowvtx", "all_loweta", "all_higheta"]: # for cat in ["sig", "wjetcr", "topcr"]: # phase_spaces_boost.append("boost_{}_dnn{}".format(cat, d)) # phase_spaces_res.append("res_{}_dnn{}".format(cat, d)) # phase_spaces_res_ele = [ ph+"_ele" for ph in phase_spaces_res] # phase_spaces_res_mu = [ ph+"_mu" for ph in phase_spaces_res] # phase_spaces_boost_ele = [ ph+"_ele" for ph in phase_spaces_boost] # phase_spaces_boost_mu = [ ph+"_mu" for ph in phase_spaces_boost] # phase_spaces_tot_ele = phase_spaces_res_ele + phase_spaces_boost_ele # phase_spaces_tot_mu = phase_spaces_res_mu + phase_spaces_boost_mu # phase_spaces_tot_res = phase_spaces_res_ele + phase_spaces_res_mu # phase_spaces_tot_boost = phase_spaces_boost_ele + phase_spaces_boost_mu # phase_spaces_dict = {"boost": phase_spaces_boost, "res": phase_spaces_res} # phase_spaces_tot = phase_spaces_tot_ele + phase_spaces_tot_mu # ################################ EXPERIMENTAL UNCERTAINTIES ################################# # #### Luminosity nuisances['lumi_Uncorrelated'] = { 'name': 'lumi_13TeV_2018', 'type': 'lnN', 'samples': dict((skey, '1.015') for skey in mc if skey not in ['top', "Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"]) } nuisances['lumi_XYFact'] = { 'name': 'lumi_13TeV_XYFact', 'type': 'lnN', 'samples': dict((skey, '1.02') for skey in mc if skey not in ['top',"Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"]) } nuisances['lumi_LScale'] = { 'name': 'lumi_13TeV_LSCale', 'type': 'lnN', 'samples': dict((skey, '1.002') for skey in mc if skey not in ['top',"Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"]) } nuisances['lumi_CurrCalib'] = { 'name': 'lumi_13TeV_CurrCalib', 'type': 'lnN', 'samples': dict((skey, '1.002') for skey in mc if skey not in ['top',"Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"]) } # #### FAKES # if Nlep == '2' : # # already divided by central values in formulas ! # fakeW_EleUp = fakeW+'_EleUp' # fakeW_EleDown = fakeW+'_EleDown' # fakeW_MuUp = fakeW+'_MuUp' # fakeW_MuDown = fakeW+'_MuDown' # fakeW_statEleUp = fakeW+'_statEleUp' # fakeW_statEleDown = fakeW+'_statEleDown' # fakeW_statMuUp = fakeW+'_statMuUp' # fakeW_statMuDown = fakeW+'_statMuDown' # else: # fakeW_EleUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lElUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' # fakeW_EleDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lElDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' # fakeW_MuUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lMuUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' # fakeW_MuDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lMuDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' # fakeW_statEleUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatElUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' # fakeW_statEleDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatElDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' # fakeW_statMuUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatMuUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' # fakeW_statMuDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatMuDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )' nuisances['fake_syst'] = { 'name' : 'CMS_fake_syst', 'type' : 'lnN', 'samples' : { 'Fake' : '1.30', }, } # nuisances['fake_ele'] = { # 'name' : 'hww_fake_ele_2018', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # 'Fake' : [ fakeW_EleUp , fakeW_EleDown ], # }, # } # nuisances['fake_ele_stat'] = { # 'name' : 'hww_fake_ele_stat_2018', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # 'Fake' : [ fakeW_statEleUp , fakeW_statEleDown ], # }, # } # nuisances['fake_mu'] = { # 'name' : 'hww_fake_mu_2018', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # 'Fake' : [ fakeW_MuUp , fakeW_MuDown ], # }, # } # nuisances['fake_mu_stat'] = { # 'name' : 'hww_fake_mu_stat_2018', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # 'Fake' : [ fakeW_statMuUp , fakeW_statMuDown ], # }, # } ##### Btag nuisances for shift in ['jes', 'lf', 'hf', 'hfstats1', 'hfstats2', 'lfstats1', 'lfstats2', 'cferr1', 'cferr2']: btag_syst = ['(btagSF%sup)/(btagSF)' % shift, '(btagSF%sdown)/(btagSF)' % shift] btag_syst_new = ['(btagSF_new%sup)/(btagSF_new)' % shift, '(btagSF_new%sdown)/(btagSF_new)' % shift] name = 'CMS_btag_%s' % shift if 'stats' in shift: name += '_2018' nuisances['btag_shape_%s' % shift] = { 'name': name, 'kind': 'weight', 'type': 'shape', 'samples': dict((skey, btag_syst) for skey in mc if skey not in ["Wjets_njetsLO"]), } nuisances['btag_shape_new_%s' % shift] = { 'name': name, 'kind': 'weight', 'type': 'shape', 'samples': { "Wjets_njetsLO": btag_syst_new} } ####### Fatjet uncertainties fatjet_eff = ['Wtagging_SF_up/Wtagging_SF_nominal', 'Wtagging_SF_down/Wtagging_SF_nominal'] nuisances['Wtagging_eff'] = { 'name': 'CMS_eff_fatjet_2018', 'kind' : 'weight', 'type' : 'shape', 'samples': dict( (skey, fatjet_eff) for skey in mc) } # ##### Trigger Efficiency trig_syst = ['((TriggerEffWeight_'+Nlep+'l_u)/(TriggerEffWeight_'+Nlep+'l))*(TriggerEffWeight_'+Nlep+'l>0.02) + (TriggerEffWeight_'+Nlep+'l<=0.02)', '(TriggerEffWeight_'+Nlep+'l_d)/(TriggerEffWeight_'+Nlep+'l)'] nuisances['trigg'] = { 'name' : 'CMS_eff_trigger_2018', 'kind' : 'weight', 'type' : 'shape', 'samples' : dict((skey, trig_syst) for skey in mc) } # ##### Electron Efficiency and energy scale ele_id_syst_up = '(abs(Lepton_pdgId[0]) == 11)*(Lepton_tightElectron_'+eleWP+'_TotSF'+'_Up[0])/\ (Lepton_tightElectron_'+eleWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 13)' ele_id_syst_do = '(abs(Lepton_pdgId[0]) == 11)*(Lepton_tightElectron_'+eleWP+'_TotSF'+'_Down[0])/\ (Lepton_tightElectron_'+eleWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 13)' mu_id_syst_up = '(abs(Lepton_pdgId[0]) == 13)*(Lepton_tightMuon_'+muWP+'_TotSF'+'_Up[0])/\ (Lepton_tightMuon_'+muWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 11)' mu_id_syst_do = '(abs(Lepton_pdgId[0]) == 13)*(Lepton_tightMuon_'+muWP+'_TotSF'+'_Down[0])/\ (Lepton_tightMuon_'+muWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 11)' id_syst_ele = [ ele_id_syst_up, ele_id_syst_do ] id_syst_mu = [ mu_id_syst_up, mu_id_syst_do ] nuisances['eff_e'] = { 'name' : 'CMS_eff_e_2018', 'kind' : 'weight', 'type' : 'shape', 'samples' : dict((skey, id_syst_ele) for skey in mc), } nuisances['electronpt'] = { 'name' : 'CMS_scale_e_2018', 'kind' : 'tree', 'type' : 'shape', 'samples' : dict((skey, ['1', '1']) for skey in mc), 'folderUp' : directory_bkg +"_ElepTup", 'folderDown' : directory_bkg +"_ElepTdo" } # ##### Muon Efficiency and energy scale # nuisances['eff_m'] = { # 'name' : 'CMS_eff_m_2018', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : dict((skey, id_syst_mu) for skey in mc) # nuisances['muonpt'] = { # 'name' : 'CMS_scale_m_2018', # 'kind' : 'tree', # 'type' : 'shape', # 'samples' : dict((skey, ['1', '1']) for skey in mc), # 'folderUp' : directory_bkg +"_MupTup", # 'folderDown' : directory_bkg +"_MupTdo" # } ##### Jet energy scale nuisances['jes'] = { 'name' : 'CMS_scale_j_2018', 'kind' : 'tree', 'type' : 'shape', 'samples' : dict((skey, ['1', '1']) for skey in mc ), 'folderUp' : directory_bkg +"_JESup", 'folderDown' : directory_bkg +"_JESdo", } # nuisances['fatjet_jes'] = { # 'name' : 'CMS_scale_fatj_2018', # 'kind' : 'tree', # 'type' : 'shape', # 'samples' : dict((skey, ['1', '1']) for skey in mc), # 'folderUp' : directory_bkg +"_fatjet_JESup", # 'folderDown' : directory_bkg +"_fatjet_JESdo", # } # nuisances['fatjet_jms'] = { # 'name' : 'CMS_mass_fatj_2018', # 'kind' : 'tree', # 'type' : 'shape', # 'samples' : dict((skey, ['1', '1']) for skey in mc), # 'folderUp' : directory_bkg +"_fatjet_JMSup", # 'folderDown' : directory_bkg +"_fatjet_JMSdo", # } # ##### MET energy scale nuisances['met'] = { 'name' : 'CMS_scale_met_2018', 'kind' : 'tree', 'type' : 'shape', 'samples' : dict((skey, ['1', '1']) for skey in mc), 'folderUp' : directory_bkg +"_METup", 'folderDown' : directory_bkg +"_METdo", } ###################### # Theory nuisance nuisances['QCD_scale_wjets'] = { 'name' : 'QCDscale_wjets', 'kind' : 'weight', 'type' : 'shape', 'samples' : { "Wjets" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], "Wjets_HT" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], "Wjets_njetsLO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], "Wjets_NLO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], "Wjets_LO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], } } nuisances['QCD_scale_top'] = { 'name' : 'QCDscale_top', 'kind' : 'weight', 'type' : 'shape', 'samples' : { "top" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], } } nuisances['QCD_scale_DY'] = { 'name' : 'QCDscale_DY', 'kind' : 'weight', 'type' : 'shape', 'samples' : { "DY_NLO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], "DY" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], } } # nuisances['QCD_scale_VV'] = { # 'name' : 'QCDscale_VV', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # "VV" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], # } # } nuisances['QCD_scale_VBF-V'] = { 'name' : 'QCDscale_VBF-V', 'kind' : 'weight', 'type' : 'shape', 'samples' : { "VBF-V" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], } } # nuisances['QCD_scale_VBS'] = { # 'name' : 'QCDscale_VBS', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # "VBS" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"], # } # } ################################## #### Custom nuisances # if useEmbeddedDY: del nuisances['prefire']['samples']['DY'] # # # # PS and UE # # # nuisances['PS'] = { # 'name' : 'PS', # 'skipCMS' : 1, # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # 'WW' : ['PSWeight[0]', 'PSWeight[3]'], # }, # } # nuisances['UE'] = { # 'name' : 'UE', # 'skipCMS' : 1, # 'kind' : 'tree', # 'type' : 'shape', # 'samples' : { # # 'WW' : ['1.12720771849', '1.13963144574'], # 'ggH_hww' : ['1.00211385568', '0.994966378288'], # 'qqH_hww' : ['1.00367895901', '0.994831373195'] # }, # 'folderUp' : treeBaseDir+'Fall2018_nAOD_v1_Full2018v2/MCl1loose2018v2__MCCorr2018__btagPerEvent__l2loose__l2tightOR2018__UEup', # 'folderDown' : treeBaseDir+'Fall2018_nAOD_v1_Full2018v2/MCl1loose2018v2__MCCorr2018__btagPerEvent__l2loose__l2tightOR2018__UEdo', # 'AsLnN' : '1', # } # nuisances['PU'] = { # 'name' : 'CMS_PU_2018', # 'kind' : 'weight', # 'type' : 'shape', # 'samples' : { # 'DY': ['0.993259983266*(puWeightUp/puWeight)', '0.997656381501*(puWeightDown/puWeight)'], # 'top': ['1.00331969187*(puWeightUp/puWeight)', '0.999199609528*(puWeightDown/puWeight)'], # 'WW': ['1.0033022059*(puWeightUp/puWeight)', '0.997085330608*(puWeightDown/puWeight)'], # 'ggH_hww': ['1.0036768006*(puWeightUp/puWeight)', '0.995996570285*(puWeightDown/puWeight)'], # 'qqH_hww': ['1.00374694528*(puWeightUp/puWeight)', '0.995878596852*(puWeightDown/puWeight)'], # }, # 'AsLnN' : '1', # } ## Top pT reweighting uncertainty # nuisances['singleTopToTTbar'] = { # 'name': 'singleTopToTTbar', # 'skipCMS': 1, # 'kind': 'weight', # 'type': 'shape', # 'samples': { # 'top': [ # 'isSingleTop * 1.0816 + isTTbar', # 'isSingleTop * 0.9184 + isTTbar'] # } # } ## Top pT reweighting uncertainty # nuisances['TopPtRew'] = { # 'name': 'CMS_topPtRew', # Theory uncertainty # 'kind': 'weight', # 'type': 'shape', # 'samples': {'top': ["1.", "1./Top_pTrw"]}, # 'symmetrize': True # } ################# ## Samples normalizations # nuisances['Top_norm'] = { # 'name' : 'CMS_Top_norm_2018', # 'samples' : { # 'top' : '1.00', # }, # 'type' : 'rateParam', # 'cuts' : phase_spaces_tot # } # for wjbin in Wjets_lptbins: # for fl in ["ele", "mu"]: # for phs in ["res", "boost"]: # nuisances["{}_norm_{}_{}_2018".format(wjbin, fl, phs )] = { # 'name' : 'CMS{}_norm_{}_{}_2018'.format(wjbin, fl, phs), # 'samples' : { wjbin: '1.00' }, # 'type' : 'rateParam', # 'cuts' : [f+"_"+fl for f in phase_spaces_dict[phs]] # } ## Use the following if you want to apply the automatic combine MC stat nuisances. nuisances['stat'] = { 'type' : 'auto', 'maxPoiss' : '10', 'includeSignal' : '1', # nuisance ['maxPoiss'] = Number of threshold events for Poisson modelling # nuisance ['includeSignal'] = Include MC stat nuisances on signal processes (1=True, 0=False) 'samples' : {} } for n in nuisances.values(): n['skipCMS'] = 1 #print ' '.join(nuis['name'] for nname, nuis in nuisances.iteritems() if nname not in ('lumi', 'stat'))
[ "davide.valsecchi@cern.ch" ]
davide.valsecchi@cern.ch
ee3ab7b304dcfd2627a23109f9e5a4af1e9cf3b9
02b6f852787c0f169c298090e412de84d9fffdfa
/src/dsrlib/ui/configuration.py
1f6bd8871dcf3223bf9723382947e5adbfa4f922
[ "MIT" ]
permissive
ca4ti/dsremap
f5ffa0d5f15e37af23ec5bd2c326a0dfa5e6f99c
ad0929adfe5fa8499515b3a6a80e94dfd8c1c0bc
refs/heads/master
2023-04-02T10:02:02.147173
2021-04-11T11:16:59
2021-04-11T11:16:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,439
py
#!/usr/bin/env python3 import os import shutil from PyQt5 import QtCore, QtGui, QtWidgets from dsrlib.domain import ConfigurationMixin, commands from dsrlib.meta import Meta from .actions import ActionWidgetBuilder from .mixins import MainWindowMixin from .utils import LayoutBuilder from .uicommands import AddActionButton, DeleteActionsButton, ConvertToCustomActionButton class ThumbnailView(MainWindowMixin, ConfigurationMixin, QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setFixedWidth(170) self.setFixedHeight(300) self._pixmap = None self.reload() self.setAcceptDrops(True) def reload(self): filename = self.configuration().thumbnail() if filename is None: self._pixmap = QtGui.QIcon(':icons/image.svg').pixmap(150, 150) else: pixmap = QtGui.QPixmap(filename) self._pixmap = pixmap.scaled(QtCore.QSize(150, 300), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) self.update() def paintEvent(self, event): # pylint: disable=W0613 painter = QtGui.QPainter(self) painter.setRenderHint(painter.Antialiasing, True) rect = QtCore.QRect(QtCore.QPoint(0, 0), self._pixmap.size()) rect.moveCenter(self.rect().center()) painter.drawPixmap(rect.topLeft(), self._pixmap) if self.configuration().thumbnail() is None: text = _('Drop an image here') bbox = painter.fontMetrics().boundingRect(text) bbox.moveCenter(rect.center()) bbox.moveTop(rect.bottom()) painter.drawText(bbox, 0, text) def dragEnterEvent(self, event): data = event.mimeData() if data.hasFormat('text/uri-list'): if len(data.urls()) != 1: return url = data.urls()[0] if not url.isLocalFile(): return filename = url.toLocalFile() if not os.path.isfile(filename): return pixmap = QtGui.QPixmap(filename) if pixmap.isNull(): return event.setDropAction(QtCore.Qt.CopyAction) event.accept() def dropEvent(self, event): src = event.mimeData().urls()[0].toLocalFile() dst = Meta.newThumbnail(src) shutil.copyfile(src, dst) cmd = commands.ChangeConfigurationThumbnailCommand(configuration=self.configuration(), filename=dst) self.history().run(cmd) # From https://gist.github.com/hahastudio/4345418 with minor changes class TextEdit(QtWidgets.QTextEdit): """ A TextEdit editor that sends editingFinished events when the text was changed and focus is lost. """ editingFinished = QtCore.pyqtSignal() receivedFocus = QtCore.pyqtSignal() def __init__(self, parent): super().__init__(parent) self._changed = False self.setTabChangesFocus(True) self.textChanged.connect(self._handle_text_changed) def focusInEvent(self, event): super().focusInEvent(event) self.receivedFocus.emit() def focusOutEvent(self, event): if self._changed: self.editingFinished.emit() super().focusOutEvent(event) def _handle_text_changed(self): # pylint: disable=C0103 self._changed = True def setTextChanged(self, state=True): self._changed = state def setHtml(self, html): super().setHtml(html) self._changed = False def setPlainText(self, text): super().setPlainText(text) self._changed = False class ConfigurationView(MainWindowMixin, ConfigurationMixin, QtWidgets.QWidget): selectionChanged = QtCore.pyqtSignal() def __init__(self, parent, **kwargs): super().__init__(parent, **kwargs) self.actions().rowsInserted.connect(self._addRows) self.actions().rowsRemoved.connect(self._removeRows) self._name = QtWidgets.QLineEdit(self.configuration().name(), self) self._name.editingFinished.connect(self._changeName) self._thumbnail = ThumbnailView(self, configuration=self.configuration(), mainWindow=self.mainWindow()) self._description = TextEdit(self) self._description.setAcceptRichText(False) self._description.setPlainText(self.configuration().description()) self._description.editingFinished.connect(self._changeDescription) # We don't actually use a QTreeView because setItemWidget is # convenient. Not in the mood to write a custom delegate. self._tree = QtWidgets.QTreeWidget(self) self._tree.setHeaderHidden(True) self._tree.itemSelectionChanged.connect(self.selectionChanged) self._tree.setAlternatingRowColors(True) btnAdd = AddActionButton(self, configuration=self.configuration(), mainWindow=self.mainWindow()) btnDel = DeleteActionsButton(self, configuration=self.configuration(), container=self, mainWindow=self.mainWindow()) btnConv = ConvertToCustomActionButton(self, configuration=self.configuration(), container=self, mainWindow=self.mainWindow()) bld = LayoutBuilder(self) with bld.vbox(): with bld.hbox() as header: header.addWidget(self._name) header.addWidget(btnConv) header.addWidget(btnDel) header.addWidget(btnAdd) with bld.hbox() as content: content.addWidget(self._thumbnail) with bld.vbox() as vbox: vbox.addWidget(self._tree) vbox.addWidget(self._description) self.configuration().changed.connect(self._updateValues) # In case of redo, the model may not be empty count = len(self.actions()) if count: self._addRows(None, 0, count - 1) def selection(self): return [item.data(0, QtCore.Qt.UserRole) for item in self._tree.selectedItems()] def _addRows(self, parent, first, last): # pylint: disable=W0613 for index, action in enumerate(self.actions().items()[first:last+1]): item = QtWidgets.QTreeWidgetItem() item.setData(0, QtCore.Qt.UserRole, action) self._tree.insertTopLevelItem(first + index, item) widget = ActionWidgetBuilder(self, self.mainWindow()).visit(action) self._tree.setItemWidget(item, 0, widget) widget.geometryChanged.connect(item.emitDataChanged) def _removeRows(self, parent, first, last): # pylint: disable=W0613 for _ in range(last - first + 1): self._tree.takeTopLevelItem(first) def _changeName(self): name = self._name.text() if name != self.configuration().name(): cmd = commands.ChangeConfigurationNameCommand(configuration=self.configuration(), name=name) self.history().run(cmd) def _changeDescription(self): text = self._description.toPlainText() if text != self.configuration().description(): cmd = commands.ChangeConfigurationDescriptionCommand(configuration=self.configuration(), description=text) self.history().run(cmd) def _updateValues(self): self._name.setText(self.configuration().name()) self._description.setPlainText(self.configuration().description()) self._thumbnail.reload()
[ "jerome@jeromelaheurte.net" ]
jerome@jeromelaheurte.net
b39d9af6975ebd68c2462a2f7225507c19658b53
908990c2121a9b14e4358cb5c5f98b980bc7b743
/binreconfiguration/item/__init__.py
44fc9b3d50d01aeeec69af8d1d2fd0316f5512b1
[ "MIT" ]
permissive
vialette/binreconfiguration
78ac21e9e37175b6947666169a91a6af0158e474
57cc024fdcf9b083a830270176ade185b65a85d0
refs/heads/master
2020-12-19T19:00:50.342707
2016-07-29T20:59:11
2016-07-29T20:59:11
31,128,571
0
0
null
null
null
null
UTF-8
Python
false
false
48
py
from .item import Item from .items import Items
[ "vialette@gmail.com" ]
vialette@gmail.com
2091be8a347d0729d9fad89614085cf924e9e4dc
922d1a3cf985ce1dd1fa6134a7a2c6a47f65a3d5
/src/sqlite_class.py
aa3d016ac656f3d5006ddf599be71bb67fb508ef
[]
no_license
marzig76/bitspread
b2e599c116a0225355d9727d3d386fb6b9eb0f20
f6fa7501d46b6410d1395d8f3f8da33354be12ff
refs/heads/master
2020-12-24T13:17:30.920793
2015-10-06T01:24:49
2015-10-06T01:24:49
40,491,580
1
0
null
null
null
null
UTF-8
Python
false
false
1,895
py
import sqlite3 import collections class ratedata: conn = "" c = "" # initialize the database connection def __init__(self): self.conn = sqlite3.connect('../db/rates.db') self.c = self.conn.cursor() # inserts a rate with the current timestamp def rateinsert(self, pair, rate): self.c.execute("INSERT INTO rate VALUES (?,?,datetime('now', 'localtime'))", (pair,rate)) self.conn.commit() # inserts a trade with the current timestamp def tradeinsert(self, pair, rate, amount, src_addr, dst_addr): self.c.execute("INSERT INTO trade VALUES (?, ?, ?, ?, ?, datetime('now', 'localtime'))", (pair, rate, amount, src_addr, dst_addr)) self.conn.commit() # returns the latest rate # if it's older than 2 minutes, return False # this ensures the rate that's returned is very recent def getlatestrate(self): query = "SELECT rate FROM rate WHERE dtg > datetime('now', '-2 minute', 'localtime') AND rate > 0 ORDER BY dtg DESC LIMIT 1" result = self.c.execute(query).fetchone() if result is not None: return result[0] else: return False # gets the latest trade details # returns an associative collection of the trade details def getlatesttrade(self): query = "SELECT pair, rate, amount, src_addr, dst_addr FROM trade ORDER BY dtg DESC LIMIT 1" result = self.c.execute(query).fetchone() if result is not None: trade = collections.defaultdict(dict) trade['pair'] = result[0] trade['rate'] = result[1] trade['amount'] = result[2] trade['src_addr'] = result[3] trade['dst_addr'] = result[4] return trade else: return False # closes the datastore connection def dataclose(self): self.conn.close()
[ "marzig76@gmail.com" ]
marzig76@gmail.com
b6e18fb848dd511799b8a86d1bf3eb79f3e9b704
ab72baa32f46806f7eaa5139e11c1fefb75e504c
/S7-1200pi/S71200.py
730a575b204a43fdc20107f61310ba501f7f9d35
[]
no_license
Tambralinga/raspberrypi
34308df22d76bf433e8bae7002581e0b065387b6
50f02834761064e89e3131993e5d2762dd4c4f97
refs/heads/master
2020-12-30T19:11:40.653863
2015-04-26T02:16:24
2015-04-26T02:16:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,739
py
from time import sleep import snap7 from snap7.util import * import struct class output(object): bool=1 int=2 real=3 word=4 dword=5 class S71200(): def __init__(self,ip,debug=False): self.debug = debug self.plc = snap7.client.Client() self.plc.connect(ip,0,1) self.ip = ip def getMem(self,mem,returnByte=False): area=0x83 length=1 type=0 out=None bit=0 start=0 if(mem[0].lower()=='m'): area=0x83 if(mem[0].lower()=='q'): area=0x82 if(mem[0].lower()=='i'): area=0x81 if(mem[1].lower()=='x'): #bit length=1 out=output().bool start = int(mem.split('.')[0][2:]) if(mem[1].lower()=='b'): #byte length=1 out=output().int start = int(mem[2:]) if(mem[1].lower()=='w'): #word length=2 out=output().int start = int(mem[2:]) if(mem[1].lower()=='d'): out=output().dword length=4 start = int(mem.split('.')[0][2:]) if('freal' in mem.lower()): #double word (real numbers) length=4 start=int(mem.lower().replace('freal','')) out=output().real #print start,hex(area) if(output().bool==out): bit = int(mem.split('.')[1]) if(self.debug): print mem[0].lower(),bit self.plc.read_area(area,0,start,length) mbyte=self.plc.read_area(area,0,start,length) #print str(mbyte),start,length if(returnByte): return mbyte elif(output().bool==out): return get_bool(mbyte,0,bit) elif(output().int==out): return get_int(mbyte,start) elif(output().real==out): return get_real(mbyte,0) elif(output().dword==out): return get_dword(mbyte,0) elif(output().word==out): return get_int(mbyte,start) def writeMem(self,mem,value): data=self.getMem(mem,True) area=0x83 length=1 type=0 out=None bit=0 start=0 if(mem[0].lower()=='m'): area=0x83 if(mem[0].lower()=='q'): area=0x82 if(mem[0].lower()=='i'): area=0x81 if(mem[1].lower()=='x'): #bit length=1 out=output().bool start = int(mem.split('.')[0][2:]) bit = int(mem.split('.')[1]) set_bool(data,0,bit,int(value)) if(mem[1].lower()=='b'): #byte length=1 out=output().int start = int(mem[2:]) set_int(data,0,value) if(mem[1].lower()=='d'): out=output().dword length=4 start = int(mem.split('.')[0][2:]) set_dword(data,0,value) if('freal' in mem.lower()): #double word (real numbers) length=4 start=int(mem.lower().replace('freal','')) out=output().real print data set_real(data,0,value) return self.plc.write_area(area,0,start,data) plc = S71200('10.10.55.131') #,debug=True) #turn on outputs cascading for x in range(0,7): plc.writeMem('qx0.'+str(x),True) sleep(.5) sleep(1) #turn off outputs for x in range(0,7): plc.writeMem('qx0.'+str(x),False) sleep(.5) plc.plc.disconnect()
[ "nextabyte@gmail.com" ]
nextabyte@gmail.com
92e70f3375c49b5f0f371ed4cc14858df4e12007
2c4763aa544344a3a615f9a65d1ded7d0f59ae50
/waflib/Node.py
3024f5f7b3370c9e79f3ce9efc8e4d02de3fe9ca
[]
no_license
afeldman/waf
572bf95d6b11571bbb2941ba0fe463402b1e39f3
4c489b38fe1520ec1bc0fa7e1521f7129c20f8b6
refs/heads/master
2021-05-09T18:18:16.598191
2019-03-05T06:33:42
2019-03-05T06:33:42
58,713,085
0
0
null
2016-05-13T07:34:33
2016-05-13T07:34:33
null
UTF-8
Python
false
false
26,479
py
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005-2018 (ita) """ Node: filesystem structure #. Each file/folder is represented by exactly one node. #. Some potential class properties are stored on :py:class:`waflib.Build.BuildContext` : nodes to depend on, etc. Unused class members can increase the `.wafpickle` file size sensibly. #. Node objects should never be created directly, use the methods :py:func:`Node.make_node` or :py:func:`Node.find_node` for the low-level operations #. The methods :py:func:`Node.find_resource`, :py:func:`Node.find_dir` :py:func:`Node.find_or_declare` must be used when a build context is present #. Each instance of :py:class:`waflib.Context.Context` has a unique :py:class:`Node` subclass required for serialization. (:py:class:`waflib.Node.Nod3`, see the :py:class:`waflib.Context.Context` initializer). A reference to the context owning a node is held as *self.ctx* """ import os, re, sys, shutil from waflib import Utils, Errors exclude_regs = ''' **/*~ **/#*# **/.#* **/%*% **/._* **/*.swp **/CVS **/CVS/** **/.cvsignore **/SCCS **/SCCS/** **/vssver.scc **/.svn **/.svn/** **/BitKeeper **/.git **/.git/** **/.gitignore **/.bzr **/.bzrignore **/.bzr/** **/.hg **/.hg/** **/_MTN **/_MTN/** **/.arch-ids **/{arch} **/_darcs **/_darcs/** **/.intlcache **/.DS_Store''' """ Ant patterns for files and folders to exclude while doing the recursive traversal in :py:meth:`waflib.Node.Node.ant_glob` """ def ant_matcher(s, ignorecase): reflags = re.I if ignorecase else 0 ret = [] for x in Utils.to_list(s): x = x.replace('\\', '/').replace('//', '/') if x.endswith('/'): x += '**' accu = [] for k in x.split('/'): if k == '**': accu.append(k) else: k = k.replace('.', '[.]').replace('*','.*').replace('?', '.').replace('+', '\\+') k = '^%s$' % k try: exp = re.compile(k, flags=reflags) except Exception as e: raise Errors.WafError('Invalid pattern: %s' % k, e) else: accu.append(exp) ret.append(accu) return ret def ant_sub_filter(name, nn): ret = [] for lst in nn: if not lst: pass elif lst[0] == '**': ret.append(lst) if len(lst) > 1: if lst[1].match(name): ret.append(lst[2:]) else: ret.append([]) elif lst[0].match(name): ret.append(lst[1:]) return ret def ant_sub_matcher(name, pats): nacc = ant_sub_filter(name, pats[0]) nrej = ant_sub_filter(name, pats[1]) if [] in nrej: nacc = [] return [nacc, nrej] class Node(object): """ This class is organized in two parts: * The basic methods meant for filesystem access (compute paths, create folders, etc) * The methods bound to a :py:class:`waflib.Build.BuildContext` (require ``bld.srcnode`` and ``bld.bldnode``) """ dict_class = dict """ Subclasses can provide a dict class to enable case insensitivity for example. """ __slots__ = ('name', 'parent', 'children', 'cache_abspath', 'cache_isdir') def __init__(self, name, parent): """ .. note:: Use :py:func:`Node.make_node` or :py:func:`Node.find_node` instead of calling this constructor """ self.name = name self.parent = parent if parent: if name in parent.children: raise Errors.WafError('node %s exists in the parent files %r already' % (name, parent)) parent.children[name] = self def __setstate__(self, data): "Deserializes node information, used for persistence" self.name = data[0] self.parent = data[1] if data[2] is not None: # Issue 1480 self.children = self.dict_class(data[2]) def __getstate__(self): "Serializes node information, used for persistence" return (self.name, self.parent, getattr(self, 'children', None)) def __str__(self): """ String representation (abspath), for debugging purposes :rtype: string """ return self.abspath() def __repr__(self): """ String representation (abspath), for debugging purposes :rtype: string """ return self.abspath() def __copy__(self): """ Provided to prevent nodes from being copied :raises: :py:class:`waflib.Errors.WafError` """ raise Errors.WafError('nodes are not supposed to be copied') def read(self, flags='r', encoding='latin-1'): """ Reads and returns the contents of the file represented by this node, see :py:func:`waflib.Utils.readf`:: def build(bld): bld.path.find_node('wscript').read() :param flags: Open mode :type flags: string :param encoding: encoding value for Python3 :type encoding: string :rtype: string or bytes :return: File contents """ return Utils.readf(self.abspath(), flags, encoding) def write(self, data, flags='w', encoding='latin-1'): """ Writes data to the file represented by this node, see :py:func:`waflib.Utils.writef`:: def build(bld): bld.path.make_node('foo.txt').write('Hello, world!') :param data: data to write :type data: string :param flags: Write mode :type flags: string :param encoding: encoding value for Python3 :type encoding: string """ Utils.writef(self.abspath(), data, flags, encoding) def read_json(self, convert=True, encoding='utf-8'): """ Reads and parses the contents of this node as JSON (Python ≥ 2.6):: def build(bld): bld.path.find_node('abc.json').read_json() Note that this by default automatically decodes unicode strings on Python2, unlike what the Python JSON module does. :type convert: boolean :param convert: Prevents decoding of unicode strings on Python2 :type encoding: string :param encoding: The encoding of the file to read. This default to UTF8 as per the JSON standard :rtype: object :return: Parsed file contents """ import json # Python 2.6 and up object_pairs_hook = None if convert and sys.hexversion < 0x3000000: try: _type = unicode except NameError: _type = str def convert(value): if isinstance(value, list): return [convert(element) for element in value] elif isinstance(value, _type): return str(value) else: return value def object_pairs(pairs): return dict((str(pair[0]), convert(pair[1])) for pair in pairs) object_pairs_hook = object_pairs return json.loads(self.read(encoding=encoding), object_pairs_hook=object_pairs_hook) def write_json(self, data, pretty=True): """ Writes a python object as JSON to disk (Python ≥ 2.6) as UTF-8 data (JSON standard):: def build(bld): bld.path.find_node('xyz.json').write_json(199) :type data: object :param data: The data to write to disk :type pretty: boolean :param pretty: Determines if the JSON will be nicely space separated """ import json # Python 2.6 and up indent = 2 separators = (',', ': ') sort_keys = pretty newline = os.linesep if not pretty: indent = None separators = (',', ':') newline = '' output = json.dumps(data, indent=indent, separators=separators, sort_keys=sort_keys) + newline self.write(output, encoding='utf-8') def exists(self): """ Returns whether the Node is present on the filesystem :rtype: bool """ return os.path.exists(self.abspath()) def isdir(self): """ Returns whether the Node represents a folder :rtype: bool """ return os.path.isdir(self.abspath()) def chmod(self, val): """ Changes the file/dir permissions:: def build(bld): bld.path.chmod(493) # 0755 """ os.chmod(self.abspath(), val) def delete(self, evict=True): """ Removes the file/folder from the filesystem (equivalent to `rm -rf`), and remove this object from the Node tree. Do not use this object after calling this method. """ try: try: if os.path.isdir(self.abspath()): shutil.rmtree(self.abspath()) else: os.remove(self.abspath()) except OSError: if os.path.exists(self.abspath()): raise finally: if evict: self.evict() def evict(self): """ Removes this node from the Node tree """ del self.parent.children[self.name] def suffix(self): """ Returns the file rightmost extension, for example `a.b.c.d → .d` :rtype: string """ k = max(0, self.name.rfind('.')) return self.name[k:] def height(self): """ Returns the depth in the folder hierarchy from the filesystem root or from all the file drives :returns: filesystem depth :rtype: integer """ d = self val = -1 while d: d = d.parent val += 1 return val def listdir(self): """ Lists the folder contents :returns: list of file/folder names ordered alphabetically :rtype: list of string """ lst = Utils.listdir(self.abspath()) lst.sort() return lst def mkdir(self): """ Creates a folder represented by this node. Intermediate folders are created as needed. :raises: :py:class:`waflib.Errors.WafError` when the folder is missing """ if self.isdir(): return try: self.parent.mkdir() except OSError: pass if self.name: try: os.makedirs(self.abspath()) except OSError: pass if not self.isdir(): raise Errors.WafError('Could not create the directory %r' % self) try: self.children except AttributeError: self.children = self.dict_class() def find_node(self, lst): """ Finds a node on the file system (files or folders), and creates the corresponding Node objects if it exists :param lst: relative path :type lst: string or list of string :returns: The corresponding Node object or None if no entry was found on the filesystem :rtype: :py:class:´waflib.Node.Node´ """ if isinstance(lst, str): lst = [x for x in Utils.split_path(lst) if x and x != '.'] if lst and lst[0].startswith('\\\\') and not self.parent: node = self.ctx.root.make_node(lst[0]) node.cache_isdir = True return node.find_node(lst[1:]) cur = self for x in lst: if x == '..': cur = cur.parent or cur continue try: ch = cur.children except AttributeError: cur.children = self.dict_class() else: try: cur = ch[x] continue except KeyError: pass # optimistic: create the node first then look if it was correct to do so cur = self.__class__(x, cur) if not cur.exists(): cur.evict() return None if not cur.exists(): cur.evict() return None return cur def make_node(self, lst): """ Returns or creates a Node object corresponding to the input path without considering the filesystem. :param lst: relative path :type lst: string or list of string :rtype: :py:class:´waflib.Node.Node´ """ if isinstance(lst, str): lst = [x for x in Utils.split_path(lst) if x and x != '.'] cur = self for x in lst: if x == '..': cur = cur.parent or cur continue try: cur = cur.children[x] except AttributeError: cur.children = self.dict_class() except KeyError: pass else: continue cur = self.__class__(x, cur) return cur def search_node(self, lst): """ Returns a Node previously defined in the data structure. The filesystem is not considered. :param lst: relative path :type lst: string or list of string :rtype: :py:class:´waflib.Node.Node´ or None if there is no entry in the Node datastructure """ if isinstance(lst, str): lst = [x for x in Utils.split_path(lst) if x and x != '.'] cur = self for x in lst: if x == '..': cur = cur.parent or cur else: try: cur = cur.children[x] except (AttributeError, KeyError): return None return cur def path_from(self, node): """ Path of this node seen from the other:: def build(bld): n1 = bld.path.find_node('foo/bar/xyz.txt') n2 = bld.path.find_node('foo/stuff/') n1.path_from(n2) # '../bar/xyz.txt' :param node: path to use as a reference :type node: :py:class:`waflib.Node.Node` :returns: a relative path or an absolute one if that is better :rtype: string """ c1 = self c2 = node c1h = c1.height() c2h = c2.height() lst = [] up = 0 while c1h > c2h: lst.append(c1.name) c1 = c1.parent c1h -= 1 while c2h > c1h: up += 1 c2 = c2.parent c2h -= 1 while not c1 is c2: lst.append(c1.name) up += 1 c1 = c1.parent c2 = c2.parent if c1.parent: lst.extend(['..'] * up) lst.reverse() return os.sep.join(lst) or '.' else: return self.abspath() def abspath(self): """ Returns the absolute path. A cache is kept in the context as ``cache_node_abspath`` :rtype: string """ try: return self.cache_abspath except AttributeError: pass # think twice before touching this (performance + complexity + correctness) if not self.parent: val = os.sep elif not self.parent.name: val = os.sep + self.name else: val = self.parent.abspath() + os.sep + self.name self.cache_abspath = val return val if Utils.is_win32: def abspath(self): try: return self.cache_abspath except AttributeError: pass if not self.parent: val = '' elif not self.parent.name: val = self.name + os.sep else: val = self.parent.abspath().rstrip(os.sep) + os.sep + self.name self.cache_abspath = val return val def is_child_of(self, node): """ Returns whether the object belongs to a subtree of the input node:: def build(bld): node = bld.path.find_node('wscript') node.is_child_of(bld.path) # True :param node: path to use as a reference :type node: :py:class:`waflib.Node.Node` :rtype: bool """ p = self diff = self.height() - node.height() while diff > 0: diff -= 1 p = p.parent return p is node def ant_iter(self, accept=None, maxdepth=25, pats=[], dir=False, src=True, remove=True, quiet=False): """ Recursive method used by :py:meth:`waflib.Node.ant_glob`. :param accept: function used for accepting/rejecting a node, returns the patterns that can be still accepted in recursion :type accept: function :param maxdepth: maximum depth in the filesystem (25) :type maxdepth: int :param pats: list of patterns to accept and list of patterns to exclude :type pats: tuple :param dir: return folders too (False by default) :type dir: bool :param src: return files (True by default) :type src: bool :param remove: remove files/folders that do not exist (True by default) :type remove: bool :param quiet: disable build directory traversal warnings (verbose mode) :type quiet: bool :returns: A generator object to iterate from :rtype: iterator """ dircont = self.listdir() dircont.sort() try: lst = set(self.children.keys()) except AttributeError: self.children = self.dict_class() else: if remove: for x in lst - set(dircont): self.children[x].evict() for name in dircont: npats = accept(name, pats) if npats and npats[0]: accepted = [] in npats[0] node = self.make_node([name]) isdir = node.isdir() if accepted: if isdir: if dir: yield node elif src: yield node if isdir: node.cache_isdir = True if maxdepth: for k in node.ant_iter(accept=accept, maxdepth=maxdepth - 1, pats=npats, dir=dir, src=src, remove=remove, quiet=quiet): yield k def ant_glob(self, *k, **kw): """ Finds files across folders and returns Node objects: * ``**/*`` find all files recursively * ``**/*.class`` find all files ending by .class * ``..`` find files having two dot characters For example:: def configure(cfg): # find all .cpp files cfg.path.ant_glob('**/*.cpp') # find particular files from the root filesystem (can be slow) cfg.root.ant_glob('etc/*.txt') # simple exclusion rule example cfg.path.ant_glob('*.c*', excl=['*.c'], src=True, dir=False) For more information about the patterns, consult http://ant.apache.org/manual/dirtasks.html Please remember that the '..' sequence does not represent the parent directory:: def configure(cfg): cfg.path.ant_glob('../*.h') # incorrect cfg.path.parent.ant_glob('*.h') # correct The Node structure is itself a filesystem cache, so certain precautions must be taken while matching files in the build or installation phases. Nodes objects that do have a corresponding file or folder are garbage-collected by default. This garbage collection is usually required to prevent returning files that do not exist anymore. Yet, this may also remove Node objects of files that are yet-to-be built. This typically happens when trying to match files in the build directory, but there are also cases when files are created in the source directory. Run ``waf -v`` to display any warnings, and try consider passing ``remove=False`` when matching files in the build directory. Since ant_glob can traverse both source and build folders, it is a best practice to call this method only from the most specific build node:: def build(bld): # traverses the build directory, may need ``remove=False``: bld.path.ant_glob('project/dir/**/*.h') # better, no accidental build directory traversal: bld.path.find_node('project/dir').ant_glob('**/*.h') # best In addition, files and folders are listed immediately. When matching files in the build folders, consider passing ``generator=True`` so that the generator object returned can defer computation to a later stage. For example:: def build(bld): bld(rule='tar xvf ${SRC}', source='arch.tar') bld.add_group() gen = bld.bldnode.ant_glob("*.h", generator=True, remove=True) # files will be listed only after the arch.tar is unpacked bld(rule='ls ${SRC}', source=gen, name='XYZ') :param incl: ant patterns or list of patterns to include :type incl: string or list of strings :param excl: ant patterns or list of patterns to exclude :type excl: string or list of strings :param dir: return folders too (False by default) :type dir: bool :param src: return files (True by default) :type src: bool :param maxdepth: maximum depth of recursion :type maxdepth: int :param ignorecase: ignore case while matching (False by default) :type ignorecase: bool :param generator: Whether to evaluate the Nodes lazily :type generator: bool :param remove: remove files/folders that do not exist (True by default) :type remove: bool :param quiet: disable build directory traversal warnings (verbose mode) :type quiet: bool :returns: The corresponding Node objects as a list or as a generator object (generator=True) :rtype: by default, list of :py:class:`waflib.Node.Node` instances """ src = kw.get('src', True) dir = kw.get('dir') excl = kw.get('excl', exclude_regs) incl = k and k[0] or kw.get('incl', '**') remove = kw.get('remove', True) maxdepth = kw.get('maxdepth', 25) ignorecase = kw.get('ignorecase', False) quiet = kw.get('quiet', False) pats = (ant_matcher(incl, ignorecase), ant_matcher(excl, ignorecase)) if kw.get('generator'): return Utils.lazy_generator(self.ant_iter, (ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet)) it = self.ant_iter(ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet) if kw.get('flat'): # returns relative paths as a space-delimited string # prefer Node objects whenever possible return ' '.join(x.path_from(self) for x in it) return list(it) # ---------------------------------------------------------------------------- # the methods below require the source/build folders (bld.srcnode/bld.bldnode) def is_src(self): """ Returns True if the node is below the source directory. Note that ``!is_src() ≠ is_bld()`` :rtype: bool """ cur = self x = self.ctx.srcnode y = self.ctx.bldnode while cur.parent: if cur is y: return False if cur is x: return True cur = cur.parent return False def is_bld(self): """ Returns True if the node is below the build directory. Note that ``!is_bld() ≠ is_src()`` :rtype: bool """ cur = self y = self.ctx.bldnode while cur.parent: if cur is y: return True cur = cur.parent return False def get_src(self): """ Returns the corresponding Node object in the source directory (or self if already under the source directory). Use this method only if the purpose is to create a Node object (this is common with folders but not with files, see ticket 1937) :rtype: :py:class:`waflib.Node.Node` """ cur = self x = self.ctx.srcnode y = self.ctx.bldnode lst = [] while cur.parent: if cur is y: lst.reverse() return x.make_node(lst) if cur is x: return self lst.append(cur.name) cur = cur.parent return self def get_bld(self): """ Return the corresponding Node object in the build directory (or self if already under the build directory). Use this method only if the purpose is to create a Node object (this is common with folders but not with files, see ticket 1937) :rtype: :py:class:`waflib.Node.Node` """ cur = self x = self.ctx.srcnode y = self.ctx.bldnode lst = [] while cur.parent: if cur is y: return self if cur is x: lst.reverse() return self.ctx.bldnode.make_node(lst) lst.append(cur.name) cur = cur.parent # the file is external to the current project, make a fake root in the current build directory lst.reverse() if lst and Utils.is_win32 and len(lst[0]) == 2 and lst[0].endswith(':'): lst[0] = lst[0][0] return self.ctx.bldnode.make_node(['__root__'] + lst) def find_resource(self, lst): """ Use this method in the build phase to find source files corresponding to the relative path given. First it looks up the Node data structure to find any declared Node object in the build directory. If None is found, it then considers the filesystem in the source directory. :param lst: relative path :type lst: string or list of string :returns: the corresponding Node object or None :rtype: :py:class:`waflib.Node.Node` """ if isinstance(lst, str): lst = [x for x in Utils.split_path(lst) if x and x != '.'] node = self.get_bld().search_node(lst) if not node: node = self.get_src().find_node(lst) if node and node.isdir(): return None return node def find_or_declare(self, lst): """ Use this method in the build phase to declare output files which are meant to be written in the build directory. This method creates the Node object and its parent folder as needed. :param lst: relative path :type lst: string or list of string """ if isinstance(lst, str) and os.path.isabs(lst): node = self.ctx.root.make_node(lst) else: node = self.get_bld().make_node(lst) node.parent.mkdir() return node def find_dir(self, lst): """ Searches for a folder on the filesystem (see :py:meth:`waflib.Node.Node.find_node`) :param lst: relative path :type lst: string or list of string :returns: The corresponding Node object or None if there is no such folder :rtype: :py:class:`waflib.Node.Node` """ if isinstance(lst, str): lst = [x for x in Utils.split_path(lst) if x and x != '.'] node = self.find_node(lst) if node and not node.isdir(): return None return node # helpers for building things def change_ext(self, ext, ext_in=None): """ Declares a build node with a distinct extension; this is uses :py:meth:`waflib.Node.Node.find_or_declare` :return: A build node of the same path, but with a different extension :rtype: :py:class:`waflib.Node.Node` """ name = self.name if ext_in is None: k = name.rfind('.') if k >= 0: name = name[:k] + ext else: name = name + ext else: name = name[:- len(ext_in)] + ext return self.parent.find_or_declare([name]) def bldpath(self): """ Returns the relative path seen from the build directory ``src/foo.cpp`` :rtype: string """ return self.path_from(self.ctx.bldnode) def srcpath(self): """ Returns the relative path seen from the source directory ``../src/foo.cpp`` :rtype: string """ return self.path_from(self.ctx.srcnode) def relpath(self): """ If a file in the build directory, returns :py:meth:`waflib.Node.Node.bldpath`, else returns :py:meth:`waflib.Node.Node.srcpath` :rtype: string """ cur = self x = self.ctx.bldnode while cur.parent: if cur is x: return self.bldpath() cur = cur.parent return self.srcpath() def bld_dir(self): """ Equivalent to self.parent.bldpath() :rtype: string """ return self.parent.bldpath() def h_file(self): """ See :py:func:`waflib.Utils.h_file` :return: a hash representing the file contents :rtype: string or bytes """ return Utils.h_file(self.abspath()) def get_bld_sig(self): """ Returns a signature (see :py:meth:`waflib.Node.Node.h_file`) for the purpose of build dependency calculation. This method uses a per-context cache. :return: a hash representing the object contents :rtype: string or bytes """ # previous behaviour can be set by returning self.ctx.node_sigs[self] when a build node try: cache = self.ctx.cache_sig except AttributeError: cache = self.ctx.cache_sig = {} try: ret = cache[self] except KeyError: p = self.abspath() try: ret = cache[self] = self.h_file() except EnvironmentError: if self.isdir(): # allow folders as build nodes, do not use the creation time st = os.stat(p) ret = cache[self] = Utils.h_list([p, st.st_ino, st.st_mode]) return ret raise return ret pickle_lock = Utils.threading.Lock() """Lock mandatory for thread-safe node serialization""" class Nod3(Node): """Mandatory subclass for thread-safe node serialization""" pass # do not remove
[ "anton.feldmann@outlook.de" ]
anton.feldmann@outlook.de
6d9657f418a5c867591bbfaa573fbadb4ca75a42
f28224ebcca66c4e8e0e31ae6135863e9d2e7f00
/15.3-sum.py
f2a6ecbff6f5e2bce949f47e3351e8de04e26b87
[]
no_license
fkljboy/my-leetcode
8df5df625be2c3559ad4376d731ea0e6b25cb3c8
f5d05b437b9938f82e85d19a08b16779bd790c4f
refs/heads/master
2021-04-02T11:09:25.022762
2020-03-18T15:31:18
2020-03-18T15:31:18
248,268,439
0
0
null
null
null
null
UTF-8
Python
false
false
1,121
py
# # @lc app=leetcode id=15 lang=python3 # # [15] 3Sum # # @lc code=start class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() res, k = [], 0 for k in range(len(nums) - 2): if nums[k] > 0: break # 1. because of j > i > k. if k > 0 and nums[k] == nums[k - 1]: continue # 2. skip the same `nums[k]`. i, j = k + 1, len(nums) - 1 while i < j and (nums[k]*nums[j]<=0) : # 3. double pointer s = nums[k] + nums[i] + nums[j] if s < 0: i += 1 while i < j and nums[i] == nums[i - 1]: i += 1 elif s > 0: j -= 1 while i < j and nums[j] == nums[j + 1]: j -= 1 else: res.append([nums[k], nums[i], nums[j]]) i += 1 j -= 1 while i < j and nums[i] == nums[i - 1]: i += 1 while i < j and nums[j] == nums[j + 1]: j -= 1 return res '''实现原理和c++解法类似 # @lc code=end
[ "851923289@qq.com" ]
851923289@qq.com
eebd17850d9af74e3791099693378022287e89b0
027a3e90eed1da5df95bc3472fb42c5c3ac5edd7
/fall/portal.py
6292dca534f687e791d45945fd9d9fe12e65e638
[]
no_license
TeamAwesomeTOJam/fall
c3d979af736998406fc28cd1758d8aabf9ac3ec9
1516787e2c5f9c67d870b4f74ba0ae7b3289b253
refs/heads/master
2023-01-23T17:56:32.908399
2022-12-25T03:37:02
2022-12-25T03:37:02
34,182,357
0
0
null
null
null
null
UTF-8
Python
false
false
839
py
import pygame from pygame.locals import * import pymunk from .settings import * class Portal(object): def __init__(self, position): self.position = position self._init_pymunk() def _init_pymunk(self): self.body = pymunk.Body(body_type=pymunk.Body.STATIC) self.body.position = self.position self.shape = pymunk.Circle(self.body, 30) self.shape.collision_type = COLLTYPE_GOAL def __getstate__(self): return {'position' : (self.position[0], self.position[1])} def __setstate__(self, state): self.position = state['position'] self._init_pymunk() def draw(self, screen, game): x, y = game.world2screen(self.body.position) pygame.draw.ellipse(screen, (2,107,251), pygame.Rect(x - 30, y - 60, 60, 120), 4)
[ "jonathan@jdoda.ca" ]
jonathan@jdoda.ca
8e52e5124bb4d7475be9e1aba419b63c10e1da71
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/105/usersdata/188/50874/submittedfiles/av1_3.py
0328c1b58fec2bb6085db012bf78c1af432e4c52
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
311
py
# -*- coding: utf-8 -*- import math N1=int(input('Digite o valor do número 1:')) N2=int(input('Digite o valor do número 2:')) N3=int(input('Digite o valor do número 3:')) n=1 b=0 while n>0: if(n%a)==0 and (n%b)==0 and (n%c)==0: b=b+n break else: n=n+1 print ('b')
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
85310ee2436c773f327232a271c59d1b109e970d
be0d6486b466fb552d4f448d9d3f9d9f14c94c90
/apps/organization/migrations/0006_teacher_age.py
62db67a0c0f696e14701f2cdb3099fbe169f2bd5
[]
no_license
crawlerwolf/mxonline
1331f446702fcb2cb4da41d7a62bee484b2f7fa5
4ae4318b46e34604354789d9c4b269e94bd16f00
refs/heads/master
2022-03-12T07:19:44.262623
2022-03-04T07:35:48
2022-03-04T07:35:48
196,338,773
0
0
null
null
null
null
UTF-8
Python
false
false
432
py
# Generated by Django 2.0 on 2019-06-24 17:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organization', '0005_teacher_image'), ] operations = [ migrations.AddField( model_name='teacher', name='age', field=models.CharField(blank=True, max_length=10, null=True, verbose_name='教师年龄'), ), ]
[ "154080724@qq.com" ]
154080724@qq.com
7ac2dd42e28125077ec9c6e7c210f9a7f1c139f9
fda8a4bdc4f69bdfc064ebeb6ca3b18209dd6240
/floworld/data/tool/latestgen
5cd443d9648df2f234ca93221fb5d121caef8162
[]
no_license
gzlixiaochao/world
0703c25dca53767731a2326965ad3d65f93b46d8
e6146c288068917aecc6f4935afda902f1b2a5ee
refs/heads/master
2021-01-15T08:59:44.493453
2012-11-18T08:49:37
2012-11-18T08:49:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
877
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re import urllib2 results = [] weibo = urllib2.urlopen("http://t.qq.com/huajie_mobile/mine") html = weibo.read() weibo.close() titles = re.findall('<div class="msgCnt">(.*?)<\/div>',html,re.I) for title in titles: results.append("{\"title\":\"" + title + "\",\"category\":\"" + title + "\",") images = re.findall("(http://t[\d].qpic.cn/mblogpic/.*?/)460",html,re.I) index = 0; for image in images: results[index] = results[index] + "\"origin\":\"" + image + "2000\"" + ",\"thumbnail\":\"" + image + "160\",\"tag\":\"\"}," index = index + 1 file = open('result.txt','a+') for result in results: file.write(result + "\n") file.close() print len(results) #imageRex = "http://t2\.qpic\.cn/mblogpic/*/460" #result = re.findall(imageRex,html,re.S) #print result
[ "jayfeng@jayfeng-ubuntu.(none)" ]
jayfeng@jayfeng-ubuntu.(none)
583f6ed0d8c5e3fb6fa51c092b5ad40be07ad49d
ec67c26c8411926afcfe7785a8b1b01a2696a4c3
/src/server.py
2f1257f92913e9a66bc57a840accd4206252518b
[ "MIT" ]
permissive
ianphil/BasicPyDevEnv
bc448935269ad66d63fe1b47603172dfe1e9b2f9
a7a4e5566f3a89a184a24a4a6346352b7b1c4e83
refs/heads/master
2020-09-02T13:17:06.979068
2019-11-05T20:43:45
2019-11-05T20:43:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
57
py
#!/usr/bin/env python name='Ian' print(f'Hello {name}')
[ "ian.philpot@microsoft.com" ]
ian.philpot@microsoft.com
9c70f2977027209074ec9416df02fa63c9d58dfd
8f16d76421c6ad3816da983de5dab79c81d55eb4
/DataAnalysis/ARIMA.py
db9df7158e44b415bd81998cf6a794e0a6145335
[]
no_license
IcamStrasbourgEurope/ProjetIoT
87066e4703faa72edbc9854bfad4ab29d4a4dc4b
1a4edff6d962a5bca10dd8f0c295faca7fe96643
refs/heads/main
2023-08-29T15:48:46.630280
2021-10-18T08:25:14
2021-10-18T08:25:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,063
py
# -*- coding: utf-8 -*- # line plot of time series from pandas import Series from matplotlib import pyplot from statsmodels.tsa.arima_model import ARIMA import numpy # Shows data on a chart def showDatas(dataset): # load dataset series = Series.from_csv(dataset, header=0) # display first few rows print(series.head(20)) # line plot of dataset series.plot() pyplot.show() # Splits data to get a learn dataset and a test dataset def splitData(dataset2): series = Series.from_csv(dataset2, header=0) split_point = len(series) - 7 dataset, validation = series[0:split_point], series[split_point:] print('Dataset %d, Validation %d' % (len(dataset), len(validation))) dataset.to_csv('./Sample/dataset.csv') validation.to_csv('./Sample/validation.csv') # create a differenced series def difference(dataset, interval=1): diff = list() for i in range(interval, len(dataset)): value = float(dataset[i]) - float(dataset[i - interval]) diff.append(value) return numpy.array(diff) # invert differenced value def inverse_difference(history, yhat, interval=1): return yhat + history[-interval] # Forecast the temperature of next day def execute(dataset): # load dataset splitData(dataset) series = Series.from_csv('./Sample/dataset.csv', header=None) series_validation = Series.from_csv('./Sample/validation.csv', header=None) # Set X with the value in the CSV X = series.values Y = series_validation.values # Set the value of the cycle days_in_year = 365 # Create a list with temperature difference differenced = difference(X, days_in_year) # fit model model = ARIMA(differenced, order=(7,0,1)) model_fit = model.fit(disp=0) # one-step out-of sample forecast forecast = model_fit.forecast()[0] # invert the differenced forecast to something usable forecast = inverse_difference(X, forecast, days_in_year) print('Forecast: %f' % forecast) print('Real: %f' % Y[0]) execute('./Sample/daily-minimum-temperatures.csv')
[ "noreply@github.com" ]
noreply@github.com
8e381188c01196c1bf3dfa781be56dd54f903631
79a72e268139e3a858acaf43357c631c1e657e3b
/tests/conftest.py
51194732b143a6175d61f9f83a752cf97f40fb82
[]
no_license
sakharovmaksim/performance-sla-metrics-tests-engine
e1958acba0737f22a83f9320672f5ad0ac21b916
be785a480648698b7114fe042b4d4da157e3a2a8
refs/heads/master
2023-02-01T03:37:40.431294
2020-12-14T11:19:58
2020-12-14T11:19:58
290,176,755
0
0
null
null
null
null
UTF-8
Python
false
false
1,461
py
import pytest from _pytest.fixtures import FixtureRequest from core import env from core.helpers.test_result_data import TestResultData @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = yield rep = outcome.get_result() # Hack https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures setattr(item, "rep_" + rep.when, rep) # Create attribute request.node.exception for request.node if test failed if rep.when == "call" and rep.failed: setattr(item, "exception", call.excinfo.value) @pytest.fixture(autouse=True) def run_test(request): # Test running here yield test_result_data = TestResultData() if __is_test_failed(request): if env.is_need_send_metrics(): send_test_metrics(request, test_result_data) test_result_data.log_overload_url() test_result_data.delete_test_logs_dir() close_clients() def send_test_metrics(request: FixtureRequest, test_result_data: TestResultData): # TODO Go to Sentry Client and configurate it pass def close_clients(): # TODO Go to Sentry Client and configurate it # SentryClient.close_instance() pass def __is_test_failed(request: FixtureRequest) -> bool: # For good test exit by CTRL+C check attr 'rep_call' exists in request.node return hasattr(request.node, 'rep_call') and request.node.rep_call.failed
[ "msakharov@zoon.ru" ]
msakharov@zoon.ru
b1c04562cbcc6a038d058a44d1b883787dd62d0d
06068a92983d0b4a79b6cfb604fd5fc225d18a33
/scripts/colors.py
edecbcd5f25f0472baf1175157e5f5e6c1e438ee
[]
no_license
krfl/dotfiles
1dc42fc987a256a5fe7b804194248f8bebfcd5c3
0ee932cc3eed22b0cb7d3be576ca13020a9c193e
refs/heads/master
2023-08-17T22:12:31.631201
2023-08-15T09:00:28
2023-08-15T09:00:28
163,996,021
2
0
null
null
null
null
UTF-8
Python
false
false
188
py
import sys for i in range(0, 16): for j in range(0, 16): code = str(i * 16 + j) sys.stdout.write(u"\u001b[48;5;" + code + "m " + code.ljust(4)) print(u"\u001b[0m")
[ "kr.fl@outlook.com" ]
kr.fl@outlook.com
0c5b75952bd055ee2807574adfbafd0a1718e38e
ab670d6e59ebd4a0c23fa867fb77866d223163da
/Python/Problem243.py
4e68455830c3935144068fae503f0d467fa66e99
[]
no_license
JeromeLefebvre/ProjectEuler
18799e85947e378e18839704c349ba770af4a128
3f16e5f231e341a471ffde8b0529407090920b56
refs/heads/master
2020-07-05T02:42:44.844607
2014-07-26T01:04:38
2014-07-26T01:04:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,847
py
''' Problem 243 A positive fraction whose numerator is less than its denominator is called a proper fraction. For any denominator, d, there will be d−1 proper fractions; for example, with d = 12: 1/12 , 2/12 , 3/12 , 4/12 , 5/12 , 6/12 , 7/12 , 8/12 , 9/12 , 10/12 , 11/12 . We shall call a fraction that cannot be cancelled down a resilient fraction. Furthermore we shall define the resilience of a denominator, R(d), to be the ratio of its proper fractions that are resilient; for example, R(12) = 4/11 . In fact, d = 12 is the smallest denominator having a resilience R(d) < 4/10 . Find the smallest denominator d, having a resilience R(d) < 15499/94744 . ''' from projectEuler import primes,phiFromFactors, generateFactors,product from itertools import combinations import random from math import log def maxExponent(p,maximum): if maximum <= 1: return 0 return int(log(maximum)/log(p)) def phiFromFactors(factors): if factors == []: return 0 ph = 1 for p in set(factors): ph *= p**factors.count(p) - p**(factors.count(p) - 1) return ph def genFactors(l = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29], maximum=10**10): exp = {} n = maximum # 1 until q = random.choice(l) one = 1 for p in l: try: exp[p] = random.randint(one,maxExponent(p,n)) except: exp[p] = 0 n //= p**exp[p] if p == q: one = 0 phi = product([p**exp[p] - p**(exp[p] - 1) for p in l if exp[p] > 0]) return phi, product([p**exp[p] for p in l]) genFactors(maximum=1000) #892371480 #200560490130 #70274254050 # 10000 -> 36427776000 def problem243(): record = 2*3*5*7*11*13*17*19*23*29*31 record = 70274254050 for i in range(1,10000): phi, n = genFactors(maximum=record) r = phi/(n-1) if r < 15499/94744 and n < record: record = n return record if __name__ == "__main__": print(problem243()) 68916891abcABC
[ "jerome.p.lefebvre@gmail.com" ]
jerome.p.lefebvre@gmail.com
1195b634fdacf15f93931254dfdc60eb03d3e39e
dba919fcbcec45ddd79d56fbf8c4daa244527559
/2020/Genders/nisha_scripts/test/setvariables.py
088f7fe4a9859afdbc1c779378db57a70130b904
[ "MIT" ]
permissive
LLNL/HPCCEA
3dc9d8b95c35721cfc8c28ff6a8db48b75c5db04
938da4f3e2d60ea8ad5cc515308bfd1e7225112c
refs/heads/master
2023-08-28T19:05:45.193502
2022-08-19T21:17:05
2022-08-19T21:17:05
184,619,652
16
30
MIT
2022-08-19T21:17:06
2019-05-02T17:03:26
Python
UTF-8
Python
false
false
489
py
# Test setting environment variables in python # UPDATE ----------- # ERROR: doesn't work the same as exporting the variables in bash - create a driver script instead + debug import os os.environ['PYTHONPATH'] = '/usr/local/lib64/python3.6/site-packages' os.environ['LD_LIBRARY_PATH'] = '/usr/local/lib' print(os.environ.get('PYTHONPATH')) print(os.environ.get('LD_LIBRARY_PATH')) import genders genders_object = genders.Genders(filename="/etc/genders") print(genders_object.getattr())
[ "nishap1225@gmail.com" ]
nishap1225@gmail.com
e8e1925708c0164676bbd31c49e957d88755a8d4
35e9662055b20a811f8d0177ee285faa6ec87cf8
/python/grpc_protos/textmining/textminingservice_pb2_grpc.py
04ec019a49e3947659dad93f6d76c1ab854c777f
[]
no_license
blakenerdway/textmining
35088fd84d2100cbf588692348eb45d3b891a7ca
2fd16db9c805742b98add919a9932af7e13fe38d
refs/heads/master
2020-04-02T18:12:31.886687
2018-12-13T18:33:15
2018-12-13T18:33:15
154,690,799
0
0
null
null
null
null
UTF-8
Python
false
false
2,295
py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from . import request_pb2 as request__pb2 from . import textsummary_pb2 as textsummary__pb2 from . import topicmining_pb2 as topicmining__pb2 class TextMiningStub(object): """The service definition """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GenerateTopics = channel.stream_stream( '/grpc_protos.textmining.TextMining/GenerateTopics', request_serializer=request__pb2.Request.SerializeToString, response_deserializer=topicmining__pb2.Topics.FromString, ) self.GenerateTextSummary = channel.stream_stream( '/grpc_protos.textmining.TextMining/GenerateTextSummary', request_serializer=request__pb2.Request.SerializeToString, response_deserializer=textsummary__pb2.Summary.FromString, ) class TextMiningServicer(object): """The service definition """ def GenerateTopics(self, request_iterator, context): """Sends a request to get topics from a file """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GenerateTextSummary(self, request_iterator, context): """Requests a summary of the text from a file """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_TextMiningServicer_to_server(servicer, server): rpc_method_handlers = { 'GenerateTopics': grpc.stream_stream_rpc_method_handler( servicer.GenerateTopics, request_deserializer=request__pb2.Request.FromString, response_serializer=topicmining__pb2.Topics.SerializeToString, ), 'GenerateTextSummary': grpc.stream_stream_rpc_method_handler( servicer.GenerateTextSummary, request_deserializer=request__pb2.Request.FromString, response_serializer=textsummary__pb2.Summary.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'grpc_protos.textmining.TextMining', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
[ "bordway@ihmc.us" ]
bordway@ihmc.us
a518b587bddb375c937acbbeac0c899400d706d2
34e1e4d955e7a4689309ce8dcd503181ae1bd2c8
/src/DNN_3layer_train_model.py
c4d43d2f7ede47041f9a1beb16130b673d7d8836
[]
no_license
Vibek/Anomanly_detection_packages
817540e8b347cae615a3545a3d1c77b2be7d8cc8
a9df3a8d33377f0082e2df5f34fa1d10c9d40992
refs/heads/master
2020-12-06T22:57:08.038025
2020-07-04T07:47:43
2020-07-04T07:47:43
232,574,348
1
0
null
null
null
null
UTF-8
Python
false
false
6,843
py
from __future__ import print_function from datetime import datetime import pandas as pd import numpy as np import io import itertools import pickle import shutil import time import matplotlib.pyplot as plt from IPython.display import clear_output from sklearn.model_selection import train_test_split from sklearn.metrics import (precision_score, recall_score,f1_score, accuracy_score,mean_squared_error,mean_absolute_error) from sklearn import metrics from sklearn.ensemble import ExtraTreesClassifier import h5py from livelossplot.keras import PlotLossesCallback from keras.models import Model from keras.utils import plot_model from keras.optimizers import Adam from keras.layers import Dense, Reshape, Dropout, Input, LSTM, Bidirectional from keras.layers.normalization import BatchNormalization from keras.optimizers import Adam from keras.layers import Dense, Reshape, Dropout, Input, LSTM, Bidirectional from keras.preprocessing.sequence import TimeseriesGenerator from tensorflow.keras.preprocessing import sequence from tensorflow.keras.datasets import imdb from tensorflow.keras import callbacks from keras.callbacks import EarlyStopping, ReduceLROnPlateau, CSVLogger, TensorBoard, LearningRateScheduler, ModelCheckpoint, Callback from tensorflow.keras import backend as k #custome libaries from data_preprocessing_CICDS import cicids_data from data_preprocessing_CICDS import balance_data from data_preprocessing_unsw import unsw_data from Autoencoder_unsw_model import build_AE from Autoencoder_model import build_AE import tensorflow.compat.v1 as tf tf.disable_v2_behavior() logdir = "/home/vibek/Anomanly_detection_packages/DNN_Package/logs_directory/" + datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard_callback = TensorBoard(log_dir=logdir, histogram_freq=0, write_graph=True, write_images=True) params = {'dataset': 'unsw_NB'} #loading the data from data preprocessing print("Loading dataset unsw 2015.....\n") train_data, train_labels, test_data, test_labels = unsw_data(params) #print("train shape: ", train_data.shape) #print("test shape: ", test_data.shape) #print("train_label shape: ", train_labels.shape) #print("test_label shape: ", test_labels.shape) print("Loading AutoEncoder model....\n") autoencoder_1, encoder_1, autoencoder_2, encoder_2, autoencoder_3, encoder_3, sSAE, SAE_encoder = build_AE() print("value of SAE_encoder:\n", SAE_encoder.output) print("value of SAE_encoder:\n", SAE_encoder.input) #TimesereisGenerator time_steps = 1 batch_size = 1024 epochs = 1000 # updatable plot class Plot_loss_accuracy(Callback): def on_train_begin(self, logs={}): self.i = 0 self.x = [] self.losses = [] self.val_losses = [] self.acc = [] self.val_acc = [] self.fig = plt.figure() self.logs = [] def on_epoch_end(self, epoch, logs={}): self.logs.append(logs) self.x.append(self.i) self.losses.append(logs.get('loss')) self.val_losses.append(logs.get('val_loss')) self.acc.append(logs.get('accuracy')) self.val_acc.append(logs.get('val_accuracy')) self.i += 1 f, (ax1, ax2) = plt.subplots(1, 2, sharex=True) clear_output(wait=True) ax1.set_yscale('log') ax1.plot(self.x, self.losses, label="loss") ax1.plot(self.x, self.val_losses, label="val_loss") ax1.legend() ax2.plot(self.x, self.acc, label="accuracy") ax2.plot(self.x, self.val_acc, label="validation accuracy") ax2.legend() plt.show(); plot = Plot_loss_accuracy() print('Finding feature importances.....\n') def find_importances(X_train, Y_train): model = ExtraTreesClassifier() model = model.fit(X_train, Y_train) importances = model.feature_importances_ std = np.std([tree.feature_importances_ for tree in model.estimators_], axis=0) indices = np.argsort(importances)[::-1] # Top ranking features' indices return importances, indices, std # Plot the feature importances of the forest def plot_feature_importances(X_train, importances, indices, std, title): #tagy # for f in range(X_train.shape[1]): # print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) plt.figure(num=None, figsize=(18, 12), dpi=80, facecolor='w', edgecolor='k') plt.title(title) width=5 plt.bar(range(X_train.shape[1]), importances[indices], width=5, color="r", yerr=std[indices], align="center") #tagy 1.5 > .8 plt.xticks(range(X_train.shape[1]), indices) #plt.axis('tight') plt.xlim([-1, X_train.shape[1]]) # -1 tagy plt.show() # Neural network is classified with correct 'attack or not' labels X_nn_train = np.concatenate((train_labels, train_data), axis=1) nn_importances, nn_indices, nn_std = find_importances(X_nn_train, train_labels) plot_feature_importances(X_nn_train, nn_importances, nn_indices, nn_std, title='Feature importances (unsw_NB15)') def build_model_DNN(): # 1. define the network mlp0 = Dense(units=32, activation='relu')(SAE_encoder.output) mlp0_drop = Dropout(0.3)(mlp0) mlp1 = Dense(units=16, activation='relu')(mlp0_drop) mlp_drop1 = Dropout(0.3)(mlp1) mlp2 = Dense(units=10, activation='relu')(mlp_drop1) mlp_drop2 = Dropout(0.3)(mlp2) mlp3 = Dense(units=6, activation='relu')(mlp_drop2) mlp_drop3 = Dropout(0.3)(mlp3) mlp4 = Dense(units=2, activation='sigmoid')(mlp_drop3) model = Model(SAE_encoder.input, mlp4) model.summary() plot_model(model,to_file='/home/vibek/Anomanly_detection_packages/DNN_Package/model_details_unsw.png',show_shapes=True) return model """ # try using different optimizers and different optimizer configs start = time.time() model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) print ("Compilation Time:", time.time() - start) plot_losses = PlotLossesCallback() #save model and the values save_model = ModelCheckpoint(filepath="/home/vibek/Anomanly_detection_packages/DNN_Package/checkpoint-{epoch:02d}.hdf5", verbose=1, monitor='val_acc', save_best_only=True) csv_logger = CSVLogger('/home/vibek/Anomanly_detection_packages/DNN_Package/training_set_dnnanalysis_unsw.csv', separator=',', append=False) early_stopping_monitor = EarlyStopping(monitor='val_loss', patience=100) callbacks = [save_model, csv_logger, tensorboard_callback, early_stopping_monitor] global_start_time = time.time() print("Start Training...") model.fit(train_data, train_labels, batch_size=batch_size, epochs=epochs, validation_data=(test_data, test_labels), callbacks=callbacks) model.save("/home/vibek/Anomanly_detection_packages/DNN_Package/best_model_unsw.hdf5") print("Done Training...") """
[ "vibek4989@gmail.com" ]
vibek4989@gmail.com
6be766d1b4041955df7bb8efb22ff6e7e6d54821
6a9f1ef2aeeafa46a771dc942822a74149afd6e8
/Array/two-sum-ii-input-array-is-sorted.py
b2690c3426a01d5564d63c4f2234b94047848e37
[]
no_license
kuz0/LeetCode
1ba22c1d2a3dff34f694dea6bb5fa891d5459d59
43a017e00cb0846b0493e083406014dae087f518
refs/heads/master
2021-01-24T12:14:52.536597
2018-04-16T08:30:22
2018-04-16T08:30:22
123,125,584
0
0
null
null
null
null
UTF-8
Python
false
false
466
py
class Solution: def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ left, right = 1, len(numbers) while left < right: two_sum = numbers[left - 1] + numbers[right - 1] if two_sum == target: return left, right elif two_sum < target: left += 1 else: right -= 1
[ "kuz0@outlook.com" ]
kuz0@outlook.com
3c0702ec4a5003244e3b954e3d649b8f4dc6bbb3
c569134861900551d036bc469fb8463e20dc54ac
/main.py
ff4abe108cf18596747a845ed39b8efa8a454073
[]
no_license
Wizard-Fingers/try2
1d77839e8df6f05ef2fd1140d78295a33399675b
3daa773bef26fd799f9157399206c9d047978662
refs/heads/master
2023-08-19T03:49:46.463217
2021-09-23T16:09:05
2021-09-23T16:09:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
359
py
# This is a sample Python script. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print("Hello", name) # Press to toggle the breakpoint. # Press the green button in the gutter to run the script. if __name__ == '__main__': print_hi('PyCharm') # See PyCharm help at https://www.jetbrains.com/help/pycharm/
[ "joyofcoding4all@gmail.com" ]
joyofcoding4all@gmail.com
aa224609e56626ea877f8b8b5b446b09c04ba066
08d6f25c664669b36d6e03250f1e96ad6872f589
/services/api/src/documents/serializers.py
5e0d00c17a38cf80d991e14e2dac8d4809dd876f
[]
no_license
JeffreyMFarley/malta
4692446852ac373d4c15ec4b4300d9b6e31ee930
52c033c0c17bc2f714f263d9a207d4fd0447e60e
refs/heads/main
2023-06-21T04:27:55.222652
2021-07-16T13:46:20
2021-07-16T13:46:20
386,630,302
0
0
null
null
null
null
UTF-8
Python
false
false
311
py
from rest_framework import serializers from .models import Document class DocumentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Document fields = ['id', 'title', 'raw', 'url'] extra_kwargs = { 'url': {'view_name': 'document-detail'}, }
[ "jeffrey.m.farley@gmail.com" ]
jeffrey.m.farley@gmail.com
92fcdeca91eaee9bd82dc56ca775883e1a752c96
6cf9dc76a91237e1cb284cc63d0bef0e2f9d75a8
/src/custom.py
a9ddae74252e8a36eb6b9fe3b4661daaac71d5b0
[]
no_license
lepisma/audi
e3cc11dbea9a31a4bc776d3cd456a7f74b554f4b
a9b8be06f2f183d2f592db399a824ac8ae7890a0
refs/heads/master
2016-09-05T21:24:41.626558
2014-12-16T21:02:24
2014-12-16T21:02:24
27,975,943
0
1
null
2014-12-16T19:45:06
2014-12-13T22:34:16
Python
UTF-8
Python
false
false
2,769
py
""" Custom cnversion of data to music """ import numpy as np import pyaudio def modulate(data): """ Modulates the data given to be transferred via audi. Modulation works as described below - Change each uint8 element (byte) in the given array to binary representation - Form a wave byte by binning the 256 levels in 4 (higher might cause errors at receiving end) - So, each byte in wave is representing 2 bits of data. This gives (4 wave bytes) = (1 data byte) Neglecting the start and stop pattern, this should get to a speed of : sample_rate / (1024 * 4) KBps For (say) 18000Hz, speed = 4.39 KBps Parameters ---------- data : numpy.ndarray Data array in numpy.uint8 format Returns ------- wave : str The output in form of pulsating waves represented in a form to work with pyaudio """ wave = '' levels = ('\x00', '\x55', '\xaa', '\xff') for frame in data: next_num = frame for grp in range(4): wave += levels[next_num % 4] next_num /= 4 return wave def demodulate(wave): """ Demodulates the data received from the microphone. Demodulation works as described below - Find the range of values - Scale the values (or don't, since the relative values are important) - Construct 2 bits per wave byte using the 4 levels Doing this on chunks rather than whole will allow the program to stop the stream after getting the stop pattern. Parameters ---------- wave : str Wave from microphone Returns ------- levels : numpy.ndarray Levels output from the wave """ levels = np.frombuffer(wave, np.uint8) levels = np.array(levels, dtype = np.float16) max_data = np.max(levels) # Assuming it contains real '\xff' # Leveling data bins = np.linspace(0, max_data, 5) levels= np.digitize(levels, bins) - 1 levels[levels == 4] = 3 # Resolving edge issue return levels def levels_to_data(levels): """ Converts the levels from demodulation to data array Parameters ---------- levels : numpy.ndarray Contains converted form of wave in 4 levels Returns ------- data : numpy.ndarray The data array in uint8 form """ b4_conv_fact = [1, 4, 16, 64] levels = levels.reshape(levels.size / 4, 4) data = np.array(np.dot(levels, b4_conv_fact), dtype = np.uint8) return data def add_trails(wave): """ Adds start and stop pattern to the given wave Adding 'audi' on both sides """ text = 'audi' as_int = map(ord, text) as_wave = modulate(as_int) return as_wave + wave + as_wave
[ "abhinav.tushar.vs@gmail.com" ]
abhinav.tushar.vs@gmail.com
376d81f18957b729df1c5d3158ad6a37aa802021
a183a600e666b11331d9bd18bcfe1193ea328f23
/pdt/core/migrations/0032_case_revision.py
ff8909b6297a1b81d520bff33753bd05266aae58
[ "MIT" ]
permissive
AbdulRahmanAlHamali/pdt
abebc9cae04f4afa1fc31b87cbf4b981affdca62
5c32aab78e48b5249fd458d9c837596a75698968
refs/heads/master
2020-05-15T07:51:09.877614
2015-12-01T18:22:56
2015-12-01T18:22:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
410
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('core', '0031_auto_20150618_1116'), ] operations = [ migrations.AddField( model_name='case', name='revision', field=models.CharField(blank=True, max_length=255), ), ]
[ "bubenkoff@gmail.com" ]
bubenkoff@gmail.com
06711799efc8419d428058ea3f7582f7a48c0a3e
284713c5e6ad6681d2c6c379efc96e5c42833321
/DB_SQLITE/04_sql_injection.py
ba90ecf3dcc02dcf9e5f32d856ff698089f5add3
[]
no_license
alexeysorok/Udemy_Python_2019_YouRa
ddfa1f620dcac44cc53958bb88169845072db38e
8ebd8483f7927892b346af209b4325c9ae0c7dab
refs/heads/master
2020-09-27T03:24:08.997040
2019-12-07T19:04:17
2019-12-07T19:04:17
226,417,119
0
0
null
null
null
null
UTF-8
Python
false
false
1,097
py
import sqlite3 conn = sqlite3.connect('users.db') # cursor.execute('CREATE TABLE users (user_name TEXT,' # 'user_password TEXT)') users = [ ('jack123', 'asdasdasd'), ('kasdsa', 'asdsadasd'), ('Bio', 'asdasda') ] # insert_query = "INSERT INTO users VALUES (?, ?);" user_name = input('Input user name: ') user_password = input('Input you password: ') # select_query = f"SELECT * FROM users WHERE user_name = '{user_name}' AND " \ # f"user_password = '{user_password}'" # правильная запись запроса select_query = f"SELECT * FROM users WHERE user_name = ? AND user_password = ?" cursor = conn.cursor() cursor.execute(select_query, (user_name, user_password)) data = cursor.fetchone() if data: print('You are logged in!') else: print("Please try again") conn.commit() conn.close() # Итоговая строка выполнения запроса # SELECT * FROM users WHERE user_name = '{user_name}' AND user_password = '' OR 1=1 # инъекция по парол # ' or 1=1--' # -- означает коментарий
[ "alexe@W10SSD" ]
alexe@W10SSD
522047d834980f56f0fe77576f61a6b45afc28e9
4aa7bf21bc6793393e63735d805e56ab53d2e89d
/Fashion.py~
284eb1312b9874af3abeeac533ae662897dd6fde
[]
no_license
chy/SPOJ-Problem-Solutions
493250112101f175c7265cd4d1e64e097be5ca50
196f6435e5ef97d062d0b837cc3769b554b448ae
refs/heads/master
2021-01-23T14:52:08.234172
2012-10-02T04:04:48
2012-10-02T04:04:48
6,039,923
1
0
null
null
null
null
UTF-8
Python
false
false
654
#SPOJ FASHION : http://www.spoj.pl/problems/FASHION/. Christa Wimberley def MMDS(men, women): men.sort() men = men[::-1] women.sort() women = women[::-1] s = 0 #sum m = len(men) #length of shorter list so it'll still work with uneven lists if len(women) < len(men): m = len(women) for i in range(0, m): s += men[i] * women[i] return s a = [] cases = int(raw_input()) for i in range(0, cases): n = raw_input() men = [int(x) for x in raw_input().split()] #men needs to be a list of integers, raw input gives a string women = [int(y) for y in raw_input().split()] a.append(MMDS(men, women)) print "\n".join([str(i) for i in a])
[ "sylvantier@gmail.com" ]
sylvantier@gmail.com
2af42a2b6608396255e292e61e930cbde59accca
32c56293475f49c6dd1b0f1334756b5ad8763da9
/google-cloud-sdk/lib/third_party/kubernetes/client/apis/autoscaling_v2beta1_api.py
dded44c74978be142fca5084827f341ddb1b8418
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
bopopescu/socialliteapp
b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494
85bb264e273568b5a0408f733b403c56373e2508
refs/heads/master
2022-11-20T03:01:47.654498
2020-02-01T20:29:43
2020-02-01T20:29:43
282,403,750
0
0
MIT
2020-07-25T08:31:59
2020-07-25T08:31:59
null
UTF-8
Python
false
false
95,742
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.14.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..api_client import ApiClient class AutoscalingV2beta1Api(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_namespaced_horizontal_pod_autoscaler(self, namespace, body, **kwargs): """ create a HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_horizontal_pod_autoscaler(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.create_namespaced_horizontal_pod_autoscaler_with_http_info( namespace, body, **kwargs) else: (data) = self.create_namespaced_horizontal_pod_autoscaler_with_http_info( namespace, body, **kwargs) return data def create_namespaced_horizontal_pod_autoscaler_with_http_info( self, namespace, body, **kwargs): """ create a HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_horizontal_pod_autoscaler_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ all_params = ['namespace', 'body', 'pretty', 'dry_run', 'field_manager'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method create_namespaced_horizontal_pod_autoscaler' % key) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `create_namespaced_horizontal_pod_autoscaler`' ) # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError( 'Missing the required parameter `body` when calling `create_namespaced_horizontal_pod_autoscaler`' ) collection_formats = {} path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) if 'field_manager' in params: query_params.append(('fieldManager', params['field_manager'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscaler', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_horizontal_pod_autoscaler( self, namespace, **kwargs): """ delete collection of HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_horizontal_pod_autoscaler(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info( namespace, **kwargs) else: (data ) = self.delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info( namespace, **kwargs) return data def delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info( self, namespace, **kwargs): """ delete collection of HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread. """ all_params = [ 'namespace', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method delete_collection_namespaced_horizontal_pod_autoscaler' % key) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `delete_collection_namespaced_horizontal_pod_autoscaler`' ) collection_formats = {} path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if '_continue' in params: query_params.append(('continue', params['_continue'])) if 'field_selector' in params: query_params.append(('fieldSelector', params['field_selector'])) if 'label_selector' in params: query_params.append(('labelSelector', params['label_selector'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'resource_version' in params: query_params.append(('resourceVersion', params['resource_version'])) if 'timeout_seconds' in params: query_params.append(('timeoutSeconds', params['timeout_seconds'])) if 'watch' in params: query_params.append(('watch', params['watch'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_horizontal_pod_autoscaler(self, name, namespace, **kwargs): """ delete a HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_horizontal_pod_autoscaler(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param V1DeleteOptions body: :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, **kwargs) else: (data) = self.delete_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, **kwargs) return data def delete_namespaced_horizontal_pod_autoscaler_with_http_info( self, name, namespace, **kwargs): """ delete a HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param V1DeleteOptions body: :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :return: V1Status If the method is called asynchronously, returns the request thread. """ all_params = [ 'name', 'namespace', 'pretty', 'body', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method delete_namespaced_horizontal_pod_autoscaler' % key) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError( 'Missing the required parameter `name` when calling `delete_namespaced_horizontal_pod_autoscaler`' ) # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `delete_namespaced_horizontal_pod_autoscaler`' ) collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) if 'grace_period_seconds' in params: query_params.append( ('gracePeriodSeconds', params['grace_period_seconds'])) if 'orphan_dependents' in params: query_params.append(('orphanDependents', params['orphan_dependents'])) if 'propagation_policy' in params: query_params.append(('propagationPolicy', params['propagation_policy'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_api_resources(self, **kwargs): """ get available resources This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources(async_req=True) >>> result = thread.get() :param async_req bool :return: V1APIResourceList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_api_resources_with_http_info(**kwargs) else: (data) = self.get_api_resources_with_http_info(**kwargs) return data def get_api_resources_with_http_info(self, **kwargs): """ get available resources This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: V1APIResourceList If the method is called asynchronously, returns the request thread. """ all_params = [] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError("Got an unexpected keyword argument '%s'" ' to method get_api_resources' % key) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIResourceList', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def list_horizontal_pod_autoscaler_for_all_namespaces(self, **kwargs): """ list or watch objects of kind HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_horizontal_pod_autoscaler_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V2beta1HorizontalPodAutoscalerList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info( **kwargs) else: (data ) = self.list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info( **kwargs) return data def list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info( self, **kwargs): """ list or watch objects of kind HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V2beta1HorizontalPodAutoscalerList If the method is called asynchronously, returns the request thread. """ all_params = [ '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'timeout_seconds', 'watch' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method list_horizontal_pod_autoscaler_for_all_namespaces' % key) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if '_continue' in params: query_params.append(('continue', params['_continue'])) if 'field_selector' in params: query_params.append(('fieldSelector', params['field_selector'])) if 'label_selector' in params: query_params.append(('labelSelector', params['label_selector'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'resource_version' in params: query_params.append(('resourceVersion', params['resource_version'])) if 'timeout_seconds' in params: query_params.append(('timeoutSeconds', params['timeout_seconds'])) if 'watch' in params: query_params.append(('watch', params['watch'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/horizontalpodautoscalers', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscalerList', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_horizontal_pod_autoscaler(self, namespace, **kwargs): """ list or watch objects of kind HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_horizontal_pod_autoscaler(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V2beta1HorizontalPodAutoscalerList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.list_namespaced_horizontal_pod_autoscaler_with_http_info( namespace, **kwargs) else: (data) = self.list_namespaced_horizontal_pod_autoscaler_with_http_info( namespace, **kwargs) return data def list_namespaced_horizontal_pod_autoscaler_with_http_info( self, namespace, **kwargs): """ list or watch objects of kind HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_horizontal_pod_autoscaler_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V2beta1HorizontalPodAutoscalerList If the method is called asynchronously, returns the request thread. """ all_params = [ 'namespace', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError("Got an unexpected keyword argument '%s'" ' to method list_namespaced_horizontal_pod_autoscaler' % key) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `list_namespaced_horizontal_pod_autoscaler`' ) collection_formats = {} path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if '_continue' in params: query_params.append(('continue', params['_continue'])) if 'field_selector' in params: query_params.append(('fieldSelector', params['field_selector'])) if 'label_selector' in params: query_params.append(('labelSelector', params['label_selector'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'resource_version' in params: query_params.append(('resourceVersion', params['resource_version'])) if 'timeout_seconds' in params: query_params.append(('timeoutSeconds', params['timeout_seconds'])) if 'watch' in params: query_params.append(('watch', params['watch'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscalerList', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_horizontal_pod_autoscaler(self, name, namespace, body, **kwargs): """ partially update the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.patch_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, body, **kwargs) else: (data) = self.patch_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, body, **kwargs) return data def patch_namespaced_horizontal_pod_autoscaler_with_http_info( self, name, namespace, body, **kwargs): """ partially update the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'force' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method patch_namespaced_horizontal_pod_autoscaler' % key) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError( 'Missing the required parameter `name` when calling `patch_namespaced_horizontal_pod_autoscaler`' ) # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `patch_namespaced_horizontal_pod_autoscaler`' ) # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError( 'Missing the required parameter `body` when calling `patch_namespaced_horizontal_pod_autoscaler`' ) collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) if 'field_manager' in params: query_params.append(('fieldManager', params['field_manager'])) if 'force' in params: query_params.append(('force', params['force'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscaler', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, body, **kwargs): """ partially update status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.patch_namespaced_horizontal_pod_autoscaler_status_with_http_info( name, namespace, body, **kwargs) else: (data ) = self.patch_namespaced_horizontal_pod_autoscaler_status_with_http_info( name, namespace, body, **kwargs) return data def patch_namespaced_horizontal_pod_autoscaler_status_with_http_info( self, name, namespace, body, **kwargs): """ partially update status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'force' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method patch_namespaced_horizontal_pod_autoscaler_status' % key) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError( 'Missing the required parameter `name` when calling `patch_namespaced_horizontal_pod_autoscaler_status`' ) # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `patch_namespaced_horizontal_pod_autoscaler_status`' ) # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError( 'Missing the required parameter `body` when calling `patch_namespaced_horizontal_pod_autoscaler_status`' ) collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) if 'field_manager' in params: query_params.append(('fieldManager', params['field_manager'])) if 'force' in params: query_params.append(('force', params['force'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}/status', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscaler', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_horizontal_pod_autoscaler(self, name, namespace, **kwargs): """ read the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_horizontal_pod_autoscaler(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.read_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, **kwargs) else: (data) = self.read_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, **kwargs) return data def read_namespaced_horizontal_pod_autoscaler_with_http_info( self, name, namespace, **kwargs): """ read the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. :param bool export: Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'namespace', 'pretty', 'exact', 'export'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError("Got an unexpected keyword argument '%s'" ' to method read_namespaced_horizontal_pod_autoscaler' % key) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError( 'Missing the required parameter `name` when calling `read_namespaced_horizontal_pod_autoscaler`' ) # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `read_namespaced_horizontal_pod_autoscaler`' ) collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'exact' in params: query_params.append(('exact', params['exact'])) if 'export' in params: query_params.append(('export', params['export'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscaler', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, **kwargs): """ read status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_horizontal_pod_autoscaler_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.read_namespaced_horizontal_pod_autoscaler_status_with_http_info( name, namespace, **kwargs) else: (data ) = self.read_namespaced_horizontal_pod_autoscaler_status_with_http_info( name, namespace, **kwargs) return data def read_namespaced_horizontal_pod_autoscaler_status_with_http_info( self, name, namespace, **kwargs): """ read status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'namespace', 'pretty'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method read_namespaced_horizontal_pod_autoscaler_status' % key) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError( 'Missing the required parameter `name` when calling `read_namespaced_horizontal_pod_autoscaler_status`' ) # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `read_namespaced_horizontal_pod_autoscaler_status`' ) collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}/status', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscaler', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_horizontal_pod_autoscaler(self, name, namespace, body, **kwargs): """ replace the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.replace_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, body, **kwargs) else: (data) = self.replace_namespaced_horizontal_pod_autoscaler_with_http_info( name, namespace, body, **kwargs) return data def replace_namespaced_horizontal_pod_autoscaler_with_http_info( self, name, namespace, body, **kwargs): """ replace the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method replace_namespaced_horizontal_pod_autoscaler' % key) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError( 'Missing the required parameter `name` when calling `replace_namespaced_horizontal_pod_autoscaler`' ) # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `replace_namespaced_horizontal_pod_autoscaler`' ) # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError( 'Missing the required parameter `body` when calling `replace_namespaced_horizontal_pod_autoscaler`' ) collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) if 'field_manager' in params: query_params.append(('fieldManager', params['field_manager'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscaler', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_horizontal_pod_autoscaler_status( self, name, namespace, body, **kwargs): """ replace status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info( name, namespace, body, **kwargs) else: (data ) = self.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info( name, namespace, body, **kwargs) return data def replace_namespaced_horizontal_pod_autoscaler_status_with_http_info( self, name, namespace, body, **kwargs): """ replace status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager' ] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" ' to method replace_namespaced_horizontal_pod_autoscaler_status' % key) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError( 'Missing the required parameter `name` when calling `replace_namespaced_horizontal_pod_autoscaler_status`' ) # verify the required parameter 'namespace' is set if ('namespace' not in params) or (params['namespace'] is None): raise ValueError( 'Missing the required parameter `namespace` when calling `replace_namespaced_horizontal_pod_autoscaler_status`' ) # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError( 'Missing the required parameter `body` when calling `replace_namespaced_horizontal_pod_autoscaler_status`' ) collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] if 'namespace' in params: path_params['namespace'] = params['namespace'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) if 'field_manager' in params: query_params.append(('fieldManager', params['field_manager'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api( '/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}/status', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V2beta1HorizontalPodAutoscaler', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "jonathang132298@gmail.com" ]
jonathang132298@gmail.com
7b3a712859fc7662ee93e36826fd4fc434b815dc
aad0b20eb2d9e7b5d76e7cdebd9c17232db290aa
/setup.py
c55165d7248459b5478fe52f50919af6a2f57dee
[ "MIT" ]
permissive
antianna/test
5e025ff2b00eefc510d511f0d3b7e9079cfd28bf
1eb137d68a706275179b2c42a9900163d70480f9
refs/heads/master
2021-06-17T06:39:01.468968
2021-03-06T13:24:28
2021-03-06T13:24:28
174,735,848
0
0
null
null
null
null
UTF-8
Python
false
false
204
py
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='I am testing the template', author='anna', license='MIT', )
[ "anna.antoniou@gmail.com" ]
anna.antoniou@gmail.com
e5315f8b7c310518d01996764c66eafb2677554c
ba13167f5610fbe108663f0029531401c49714c6
/.ycm_extra_conf.py
1f96b2fb314a3bdaec298dfc4fff4538e751419a
[]
no_license
captainsmiley/esp_com
f2727fc00dc59c863be63b5a2890507f9911ec5f
2dd0fb16075a13ca44083e7164651ca986b455a2
refs/heads/master
2020-06-30T01:51:11.710770
2017-05-25T18:34:41
2017-05-25T18:34:41
74,398,672
0
0
null
null
null
null
UTF-8
Python
false
false
6,157
py
""" YouCompleteMe extra configuration for Platformio based projects. Based on the `.ycm_extra_conf.py` by @ladislas in his Bare-Arduino-Project. Anthony Ford <github.com/ajford> """ import os import ycm_core import logging # Logger for additional logging. # To enable debug logging, add `let g:ycm_server_log_level = 'debug'` to # your .vimrc file. logger = logging.getLogger('ycm-extra-conf') # Platformio Autogen libs. ## Platformio automatically copies over the libs you use after your first run. ## Be warned that you will not receive autocompletion on libraries until after ## your first `platformio run`. PlatformioAutogen = ".pioenvs/" # All Platformio Arduin Libs ## This will link directly to the Platformio Libs for Arduino. ## Be warned that this can polute your namespace (in #include) ## and slightly increase startup time (while crawling the lib ## dir for header files). This will however allow you to ## complete for header files you haven't included yet. PlatformioArduinoLibs = "~/.platformio/packages/framework-arduinoavr/libraries/" # Platformio Arduino Core ## This links to the Platformio Arduino Cores. This provides ## the core libs, such as Arduino.h and HardwareSerial.h PlatformioArduinoCore = "~/.platformio/packages/framework-arduinoavr/cores/arduino/" # Platformio Arduino Std Libs ## Arduino Std libs from .platformio packages. Provides stdlib.h and such. PlatformioArduinoSTD = '~/.platformio/packages/toolchain-atmelavr/avr/include' # This is the list of all directories to search for header files. # Dirs in this list can be paths relative to this file, absolute # paths, or paths relative to the user (using ~/path/to/file). libDirs = [ "lib" ,PlatformioAutogen ,PlatformioArduinoCore ,PlatformioArduinoLibs ,PlatformioArduinoSTD ] flags = [ # General flags '-std=c++11', '-Wall', '-x' ,'c++' #,'-ansi' # Customize microcontroler and Arduino version ,'-mmcu=atmega328p' ,'-DF_CPU=16000000L' ,'-DARDUINO_ARCH_AVR' ,'-DARDUINO_AVR_DUEMILANOVE' ,'-DARDUINO=106000' # ,'-MMD -DUSB_VID=null' # ,'-DUSB_PID=null' ] compilation_database_folder = '' if os.path.exists( compilation_database_folder ): database = ycm_core.CompilationDatabase( compilation_database_folder ) else: database = None SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.ino', '.m', '.mm' ] def DirectoryOfThisScript(): return os.path.dirname( os.path.abspath( __file__ ) ) def MakeRelativePathsInFlagsAbsolute( flags, working_directory ): if not working_directory: return list( flags ) new_flags = [] make_next_absolute = False path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ] for libDir in libDirs: # dir is relative to $HOME if libDir.startswith('~'): libDir = os.path.expanduser(libDir) # dir is relative to `working_directory` if not libDir.startswith('/'): libDir = os.path.join(working_directory,libDir) # Else, assume dir is absolute for path, dirs, files in os.walk(libDir): # Add to flags if dir contains a header file and is not # one of the metadata dirs (examples and extras). if any(IsHeaderFile(x) for x in files) and\ path.find("examples") is -1 and path.find("extras") is -1: logger.debug("Directory contains header files - %s"%path) flags.append('-I'+path) for flag in flags: new_flag = flag if make_next_absolute: make_next_absolute = False if not flag.startswith( '/' ): new_flag = os.path.join( working_directory, flag ) for path_flag in path_flags: if flag == path_flag: make_next_absolute = True break if flag.startswith( path_flag ): path = flag[ len( path_flag ): ] new_flag = path_flag + os.path.join( working_directory, path ) break if new_flag: new_flags.append( new_flag ) return new_flags def IsHeaderFile( filename ): extension = os.path.splitext( filename )[ 1 ] return extension in [ '.h', '.hxx', '.hpp', '.hh' ] def GetCompilationInfoForFile( filename ): # The compilation_commands.json file generated by CMake does not have entries # for header files. So we do our best by asking the db for flags for a # corresponding source file, if any. If one exists, the flags for that file # should be good enough. if IsHeaderFile( filename ): basename = os.path.splitext( filename )[ 0 ] for extension in SOURCE_EXTENSIONS: replacement_file = basename + extension if os.path.exists( replacement_file ): compilation_info = database.GetCompilationInfoForFile( replacement_file ) if compilation_info.compiler_flags_: return compilation_info return None return database.GetCompilationInfoForFile( filename ) def FlagsForFile( filename, **kwargs ): if database: # Bear in mind that compilation_info.compiler_flags_ does NOT return a # python list, but a "list-like" StringVec object compilation_info = GetCompilationInfoForFile( filename ) if not compilation_info: return None final_flags = MakeRelativePathsInFlagsAbsolute( compilation_info.compiler_flags_, compilation_info.compiler_working_dir_ ) # NOTE: This is just for YouCompleteMe. it's highly likely that your project # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT. #try: # final_flags.remove( '-stdlib=libc++' ) #except ValueError: # pass else: relative_to = DirectoryOfThisScript() final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to ) return { 'flags': final_flags, 'do_cache': True }
[ "tg.tobias@gmail.com" ]
tg.tobias@gmail.com
ff2e3f190b0dfc55dacf523353dd603176cd4917
01b3c5fccd0a49fc0ae104b5eb0e948f0a9281c3
/env/lib/python3.6/abc.py
0f8531aaa7cc6af1ab6756aa76a10816ebe010cf
[]
no_license
YaraA/dlc-task
f14c87e73a52ed2b6ba22fcf203daeda993148f8
456956179fde621f9f4d09dc8449424673cc6100
refs/heads/master
2020-03-23T23:25:09.372466
2018-07-25T01:54:29
2018-07-25T01:54:29
142,233,065
0
0
null
null
null
null
UTF-8
Python
false
false
47
py
/Users/Yarayehia/anaconda3/lib/python3.6/abc.py
[ "yaraasy@gmail.com" ]
yaraasy@gmail.com
75e7b42363cb042feea0f589acb029e4fe18e94b
520230d05bd159fcc47bc173c8fbec607a6476db
/myPython/习题课练习/logging/logging01.py
d75b3926d553e3d9bf3dc4ddd0e73942f7bee0b6
[]
no_license
duanzhijianpanxia/myPython
c9a2f01c9861b16925cf5e86d713e35f4334cad3
b5fb32e7660a813a3f34ed870e9e8ab5df7e33f4
refs/heads/master
2020-05-13T21:19:47.325682
2019-06-27T09:28:08
2019-06-27T09:28:08
181,662,204
0
0
null
null
null
null
UTF-8
Python
false
false
188
py
import logging logging.debug("This is a debug") logging.info("This is a info") logging.warning("This is a warning") logging.error("This is a error") logging.critical("This is a critical")
[ "45039007+duanzhijianpanxia@users.noreply.github.com" ]
45039007+duanzhijianpanxia@users.noreply.github.com
c7ef589bf879fb64a6c1ba7225ee9fec2cfe12bb
ccd30f827fb3bd4231c59d05e6d61c5963019291
/Practice/LeetCode/EverydayPrac/3.py
603f49bc17eca59b1792306e56056465b5c878af
[]
no_license
anthony20102101/Python_practice
d6709e7768baebaa248612e0795dd3e3fa0ae6ba
56bb1335c86feafe2d3d82efe68b207c6aa32129
refs/heads/master
2023-06-10T18:49:11.619624
2021-06-27T15:36:10
2021-06-27T15:36:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
628
py
# 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 # # 在杨辉三角中,每个数是它左上方和右上方的数的和。 # # 示例: # 输入: 3 # 输出: [1,3,3,1] # 进阶: # 你可以优化你的算法到 O(k) 空间复杂度吗? # 优化: # 注意到对第 i+1 行的计算仅用到了第 i 行的数据,因此可以使用滚动数组的思想优化空间复杂度。 # 利用上述公式我们可以在线性时间计算出第 n 行的所有组合数。 # # 复杂度分析 # # 时间复杂度:O(rowIndex)。 # # 空间复杂度:O(1)。不考虑返回值的空间占用。
[ "492193947@qq.com" ]
492193947@qq.com
04003011021ed9b70a92bbdc33e87c7af6f9ad9e
6fa0c051f742c3f9c99ee2800cd132db5ffb28c7
/src/account/migrations/0008_auto_20200806_2318.py
03591749cf0b1a71c7d4f20b7e81927a0e349322
[]
no_license
MCN10/NXTLVL
9c37bf5782bfd8f24d0fb0431cb5885c585369b0
76d8818b7961e4f0362e0d5f41f48f53ce1bfdc5
refs/heads/main
2023-06-02T13:51:34.432668
2021-06-02T14:19:21
2021-06-02T14:19:21
328,625,042
1
0
null
2021-06-16T10:16:17
2021-01-11T10:19:44
Python
UTF-8
Python
false
false
611
py
# Generated by Django 3.0.8 on 2020-08-06 23:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0007_account_is_axisstaff'), ] operations = [ migrations.AlterField( model_name='account', name='phone', field=models.CharField(max_length=200, null=True, verbose_name='Phone Number'), ), migrations.AlterField( model_name='account', name='username', field=models.CharField(max_length=30, verbose_name='Full Name'), ), ]
[ "mcn10.foxx@gmail.com" ]
mcn10.foxx@gmail.com
f2d9eaf8a235500ef2b96da940bfa065479d2e95
e4f81fda493e48b5a65912fa1ac28d0c505eeb11
/backend/views/customerdetail.py
b62307d0d8aba8216ca217a9688085c881e8ec77
[]
no_license
shtsai/xigua_shopping
b60417b8a1c31eea56fe12537c35c53f7274b01b
bd60d862234497d675de0dfb17aad71a2d81a2c8
refs/heads/master
2021-09-07T10:49:50.344561
2018-02-21T20:48:06
2018-02-21T20:48:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,069
py
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.views import generic from django.db import connection from django.contrib.auth.decorators import login_required from backend.models import Customer, Order, Product, Inventory from .util import * def customerdetail(request, customer_id): customer = get_object_or_404(Customer, pk=customer_id) template_name = 'backend/customer_detail.html' # orders = Order.objects.filter(cid_id=customer.cid); orders = get_customer_orders(customer_id) return render(request, template_name, { 'customer': customer, 'message': "hello cash", 'orders': orders, }) def get_customer_orders(customer_id): with connection.cursor() as cursor: cursor.execute(''' SELECT * FROM backend_customer AS C JOIN backend_order AS O ON C.cid = O.cid_id WHERE C.cid = %s ''', [customer_id]) res = dictfetchall(cursor) return res
[ "st3127@nyu.edu" ]
st3127@nyu.edu
038ce77a7609a8d5994d211f43224d6dc39aa18e
7ba57aa7922e6e91ff5e271ca76fde9a9774e5e1
/min_max_division.py
b10d27e26ca76fa4766fb564ea91eac2a141382f
[]
no_license
yama2908/Codility
a6083428ea4ca02507946c21a28efb8df4b07901
21df43d177992795201fd1de8b0472909a7391e0
refs/heads/master
2021-05-21T10:14:47.319880
2020-04-03T15:43:05
2020-04-03T15:43:05
252,650,623
0
0
null
null
null
null
UTF-8
Python
false
false
806
py
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(K, M, A): # write your code in Python 3.6 blocksNeeded = 0 lower, upper = max(A), sum(A) ans = 0 if K == 1: return upper if K >= len(A): return lower while lower <= upper: mid = (lower + upper) // 2 blocksNeeded = blocksNo(A, mid) if blocksNeeded <= K: upper = mid - 1 ans = mid else: lower = mid + 1 return ans def blocksNo(A, maxBlock): blocksNumber = 1 blockSum = A[0] for element in A[1:]: if blockSum + element > maxBlock: blockSum = element blocksNumber += 1 else: blockSum += element return blocksNumber
[ "noreply@github.com" ]
noreply@github.com
3adfa4770faeaadd94adabd51231577e49815129
c54a4cc4d084e4778907f61fa22e320b53d4983a
/deep_head_pose/test_on_video_retina.py
a140a75845b76ca3d23fd00b2ebafd26ddb24a78
[]
no_license
ToeiKanta/head-pose-module
755525076a945d778c9f37de7e3d6fad1ad8fe17
e6b31a316fdae33d19b9ceb9d433241c8ffce8e6
refs/heads/master
2023-03-20T09:35:30.963397
2021-03-11T10:02:32
2021-03-11T10:02:32
312,546,067
0
0
null
null
null
null
UTF-8
Python
false
false
7,093
py
import sys, os, argparse import numpy as np import cv2 import matplotlib.pyplot as plt import torch import torch.nn as nn from torch.autograd import Variable from torch.utils.data import DataLoader from torchvision import transforms import torch.backends.cudnn as cudnn import torchvision import torch.nn.functional as F from PIL import Image from face_detection import RetinaFace import hopenet, utils from skimage import io import dlib def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Head pose estimation using the Hopenet network.') parser.add_argument('--scale', metavar='FLOAT', dest='video_scale', type=float, default=1.0, help='Video scale.') parser.add_argument('-sf', metavar='N', dest='start_frame', type=int, default=0, help='Start frame number.') parser.add_argument('--rotate', dest='rotate',action='store_true',help='Rotate frame right 90 degree.') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--snapshot', dest='snapshot', help='Path of model snapshot.', default='', type=str) parser.add_argument('--face_model', dest='face_model', help='Path of DLIB face detection model.', default='', type=str) parser.add_argument('--video', dest='video_path', help='Path of video') parser.add_argument('--output_string', dest='output_string', help='String appended to output file') parser.add_argument('--n_frames', dest='n_frames', help='Number of frames', type=int) parser.add_argument('--fps', dest='fps', help='Frames per second of source video', type=float, default=30.) args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() cudnn.enabled = True scale = args.video_scale batch_size = 1 gpu = args.gpu_id snapshot_path = args.snapshot out_dir = 'output/video' video_path = args.video_path detector = RetinaFace(gpu_id=0) if not os.path.exists(out_dir): os.makedirs(out_dir) if not os.path.exists(args.video_path): sys.exit('Video does not exist') # ResNet50 structure model = hopenet.Hopenet(torchvision.models.resnet.Bottleneck, [3, 4, 6, 3], 66) # Dlib face detection model cnn_face_detector = dlib.cnn_face_detection_model_v1(args.face_model) print('Loading snapshot.') # Load snapshot saved_state_dict = torch.load(snapshot_path) #, map_location='cpu') model.load_state_dict(saved_state_dict) print('Loading data.') transformations = transforms.Compose([transforms.Scale(224), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) model.cuda(gpu) print('Ready to test network.') # Test the Model model.eval() # Change model to 'eval' mode (BN uses moving mean/var). total = 0 idx_tensor = [idx for idx in range(66)] idx_tensor = torch.FloatTensor(idx_tensor).cuda(gpu) video = cv2.VideoCapture(video_path) video.set(cv2.CAP_PROP_POS_FRAMES, args.start_frame) # New cv2 width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) # float height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) # float widthScale = int(width * scale) heightScale = int(height * scale) # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'MJPG') if args.rotate: out = cv2.VideoWriter('output/video/output-%s.avi' % args.output_string, fourcc, args.fps, (heightScale, widthScale)) else: out = cv2.VideoWriter('output/video/output-%s.avi' % args.output_string, fourcc, args.fps, (widthScale, heightScale)) # # Old cv2 # width = int(video.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)) # float # height = int(video.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) # float # # # Define the codec and create VideoWriter object # fourcc = cv2.cv.CV_FOURCC(*'MJPG') # out = cv2.VideoWriter('output/video/output-%s.avi' % args.output_string, fourcc, 30.0, (width, height)) txt_out = open('output/video/output-%s.txt' % args.output_string, 'w') frame_num = 1 while frame_num <= args.n_frames: print(frame_num) ret,frame = video.read() if ret == False: break frame = cv2.resize(frame, (int(widthScale), int(heightScale))) if args.rotate: frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE) cv2_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) # Retina detect # dets = cnn_face_detector(cv2_frame, 1) faces = detector(cv2_frame) for box, landmarks, score in faces: # box = x,y,w,h โดย frame[y:h, x:w] # Get x_min, y_min, x_max, y_max, conf x_min = box[0]#-(box[2]-box[0])/5 y_min = box[1]#-(box[3]-box[1])/2 x_max = box[2]#+(box[2]-box[0])/5 y_max = box[3]#+(box[3]-box[1])/2 conf = score if conf > 0.3: bbox_width = abs(x_max - x_min) bbox_height = abs(y_max - y_min) x_min -= 2 * bbox_width / 4 x_max += 2 * bbox_width / 4 y_min -= 3 * bbox_height / 4 y_max += bbox_height / 4 x_min = max(x_min, 0); y_min = max(y_min, 0) x_max = min(frame.shape[1], x_max); y_max = min(frame.shape[0], y_max) # Crop image img = cv2_frame[int(y_min):int(y_max),int(x_min):int(x_max)] img = Image.fromarray(img) # Transform img = transformations(img) img_shape = img.size() img = img.view(1, img_shape[0], img_shape[1], img_shape[2]) img = Variable(img).cuda(gpu) yaw, pitch, roll = model(img) yaw_predicted = F.softmax(yaw) pitch_predicted = F.softmax(pitch) roll_predicted = F.softmax(roll) # Get continuous predictions in degrees. yaw_predicted = torch.sum(yaw_predicted.data[0] * idx_tensor) * 3 - 99 pitch_predicted = torch.sum(pitch_predicted.data[0] * idx_tensor) * 3 - 99 roll_predicted = torch.sum(roll_predicted.data[0] * idx_tensor) * 3 - 99 # Print new frame with cube and axis txt_out.write(str(frame_num) + ' %f %f %f\n' % (yaw_predicted, pitch_predicted, roll_predicted)) # utils.plot_pose_cube(frame, yaw_predicted, pitch_predicted, roll_predicted, (x_min + x_max) / 2, (y_min + y_max) / 2, size = bbox_width) utils.draw_axis(frame, yaw_predicted, pitch_predicted, roll_predicted, tdx = (x_min + x_max) / 2, tdy= (y_min + y_max) / 2, size = bbox_height/2) # Plot expanded bounding box cv2.rectangle(frame, (int(x_min), int(y_min)), (int(x_max), int(y_max)), (0,255,0), 1) out.write(frame) frame_num += 1 out.release() video.release()
[ "41673034+ToeiKanta@users.noreply.github.com" ]
41673034+ToeiKanta@users.noreply.github.com
cbb0002323e43dc7093ab60b67d77db7c93c8b17
41ff6e7b7261db5e277c4bbcc7af9e7f18d15331
/cnn_model.py
7fb85f3b9818eaa98d175ba1e6adf22e2d181121
[]
no_license
jakeywu/tf_classification
d4a1b9da5d444fe904639477c91b1d80f866b3d7
d9076971dca4085593d80f97aa5aca06be8236df
refs/heads/master
2020-03-25T17:50:26.197284
2018-08-28T05:52:30
2018-08-28T05:52:30
143,998,652
8
1
null
null
null
null
UTF-8
Python
false
false
5,777
py
import tensorflow as tf from data_utils import PrepareClassifyData class CnnModel(object): def __init__(self, conf): self._config = conf self._init_placeholder() self._embedding_layers() self._inference() self._build_train_op() self.sess = tf.Session() self.checkpointDir = "model/cnn/" def _init_placeholder(self): self.inputs = tf.placeholder(tf.int32, [None, self._config.sequence_length], name="input_x") self.targets = tf.placeholder(tf.int32, [None], name="input_y") self.keep_prob = tf.placeholder(tf.float32, name="keep_prob") def _embedding_layers(self): with tf.variable_scope(name_or_scope="embedding_layers"): embedding_matrix = tf.get_variable( name="embedding_matrix", shape=[self._config.vocab_size, self._config.embedding_size], dtype=tf.float32, initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1) ) self.embedded_inputs = tf.nn.embedding_lookup(params=embedding_matrix, ids=self.inputs) self.embedded_chars_expanded = tf.expand_dims(self.embedded_inputs, 1) def _inference(self): self.total_features = len(self._config.filter_sizes) * self._config.num_filters self._cnn_layers() with tf.variable_scope("score"): w = tf.get_variable(name="w", shape=[self.total_features, self._config.num_classes], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.1)) b = tf.get_variable(name="b", shape=[self._config.num_classes], dtype=tf.float32) self.logits = tf.matmul(self._dropout_pool_flat, w, name="logits") + b self.predictions = tf.argmax(self.logits, 1, name="predictions") def _build_train_op(self): with tf.variable_scope("loss"): losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits, labels=self.targets) self.loss = tf.reduce_mean(losses) with tf.variable_scope("accuracy"): correct_predictions = tf.equal(tf.cast(self.predictions, tf.int32), self.targets) self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name="accuracy") global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(self._config.learning_rate) grads_and_vars = optimizer.compute_gradients(self.loss) self.train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) def _cnn_layers(self): pooled_outputs = [] for filter_size in self._config.filter_sizes: with tf.variable_scope("cnn-%s" % str(filter_size)): conv1 = self._cnn_2d( self.embedded_chars_expanded, "1", self._config.embedding_size, self._config.num_filters, 1, filter_size) relu1 = tf.nn.relu(conv1) pool1 = self._max_pool(relu1, self._config.sequence_length - filter_size + 1) pooled_outputs.append(pool1) pool_flat = tf.reshape(tf.concat(pooled_outputs, 3), [-1, self.total_features]) with tf.variable_scope("dropout"): self._dropout_pool_flat = tf.nn.dropout(pool_flat, self.keep_prob) @staticmethod def _cnn_2d(neural, scope_name, in_channels, out_channels, filter_height, filter_width): """二维图像卷积""" with tf.variable_scope(name_or_scope=scope_name): kernel = tf.get_variable( name="W", shape=[filter_height, filter_width, in_channels, out_channels], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.01) ) bias = tf.get_variable(name="a", shape=[out_channels], dtype=tf.float32, initializer=tf.constant_initializer()) con2d_op = tf.nn.conv2d(input=neural, filter=kernel, strides=[1, 1, 1, 1], padding="VALID") return tf.nn.bias_add(con2d_op, bias=bias) @staticmethod def _max_pool(neural, width_ksize): return tf.nn.max_pool( neural, ksize=(1, 1, width_ksize, 1), strides=[1, 1, 1, 1], padding="VALID", name="max_pool" ) def _save(self): if not tf.gfile.Exists(self.checkpointDir): tf.gfile.MakeDirs(self.checkpointDir) saver = tf.train.Saver() saver.save(sess=self.sess, save_path=self.checkpointDir + "model") def train(self, flag): self.sess.run(tf.global_variables_initializer()) print("\nbegin train ....\n") step = 0 _iter = 0 for i in range(flag.epoch): trainset = PrepareClassifyData(flag, "train", False) for input_x, input_y in trainset: _iter += 1 step += len(input_y) _, loss, acc = self.sess.run( fetches=[self.train_op, self.loss, self.accuracy], feed_dict={self.inputs: input_x, self.targets: input_y, self.keep_prob: 0.5}) print("<Train>\t Epoch: [%d] Iter: [%d] Step: [%d] Loss: [%.3F]\t Acc: [%.3f]" % (i+1, _iter, step, loss, acc)) self._save() def test(self, flag): print("\nbegin test ....\n") _iter = 0 testset = PrepareClassifyData(flag, "test", False) for input_x, input_y in testset: _iter += 1 acc, loss = self.sess.run( fetches=[self.accuracy, self.loss], feed_dict={self.inputs: input_x, self.targets: input_y, self.keep_prob: 1.}) print("<Test>\t Iter: [%d] Loss: [%.3F]\t Acc: [%.3f]" % (_iter, loss, acc))
[ "wanjie.wu@socialcredits.cn" ]
wanjie.wu@socialcredits.cn
6c8ded239c4ef4b19711c36be8c3a7ac710c6069
dc19f6df97aea3d11f07c60d2263ee768ed5bf92
/Algorithmic Toolbox/Algorithmic Toolbox Week 3/dot_product.py
5ad26b88044cfe6e6b774022677d75e8363deb20
[]
no_license
Minjaben/Algorithmic_Toolbox
2b702d8db73a1e7275a1e2eaf7efaacea21b76ff
9a9d2011769bed92c35d04a795dddedb1f981b66
refs/heads/master
2020-04-12T15:00:14.801940
2019-01-07T04:07:55
2019-01-07T04:07:55
162,567,972
0
0
null
null
null
null
UTF-8
Python
false
false
785
py
#Uses python3 import sys def max_dot_product(a, b): #write your code here res = 0 for i in range(len(a)): res += a[i] * b[i] return res def sortdata(a,b): # In this function we need to sort the revenue per click (a[i]) in descending order, # then sort the amount paid per click (b[i]), and return both lists to reassign the original lists as their ordered permutations. asorted = sorted(a, reverse=True) #print(asorted) bsorted = sorted(b, reverse=True) #print(bsorted) return (asorted, bsorted) if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] a = data[1:(n + 1)] b = data[(n + 1):] a, b = sortdata(a,b) print(max_dot_product(a, b))
[ "minjaben@gmail.com" ]
minjaben@gmail.com
ed5253e35e270b6375dce2c71f542db9f45bf3b7
930f7f2b96104606884cea146f1b0579edb17b21
/testTF.py
80cfa6066327273ea4d18fc90f950388c6213539
[]
no_license
reinisirmejs/LVGMC
c6fac1b3493c1f936301ddad0484902a5f182012
a81ed7ae7e76f538bdcdcbdadba088467e5880f3
refs/heads/master
2020-07-24T21:50:27.976238
2019-09-17T10:48:16
2019-09-17T10:48:16
208,058,660
0
0
null
null
null
null
UTF-8
Python
false
false
1,231
py
import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() #print(x_train[0]) #print(y_train[0]) x_train = tf.keras.utils.normalize(x_train, axis=1) x_test = tf.keras.utils.normalize(x_test, axis=1) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten(input_shape=x_train[0].shape)) #act = tf.keras.activations.relu(alpha = 0, max_value = 0.98, threshold = 0.01) model.add(tf.keras.layers.Dense(512, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(256, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax)) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=4) model.save('mnist_trained.h5') model.summary() new_model = tf.keras.models.load_model('mnist_trained.h5') val_loss, val_acc = new_model.evaluate(x_test, y_test) print(val_loss) print(val_acc) predictions = new_model.predict([x_test[0:10]]) #print(predictions) import numpy as np cleaned = np.zeros(10) for i in range(10): cleaned[i] = np.argmax(predictions[i]) print(cleaned)
[ "reinisirmejs@gmail.com" ]
reinisirmejs@gmail.com
387590d8abe835d5a0a36446f5760f666e277312
7bf2b8ddc0281a3b72e6d265fc29a3f410cd5b99
/Verification/__init__.py
de0afee8ee0cc2ad0a04c8778053485c233cf7dc
[]
no_license
Asuri-Team/CtfToolKit
9f4a5700a9748feed341db223bf26cab67089298
c6cf3d9afd249eba03b3654a53ae9d05b0108739
refs/heads/master
2020-05-20T06:26:40.768980
2015-06-11T01:51:41
2015-06-11T01:51:41
37,233,366
1
0
null
null
null
null
UTF-8
Python
false
false
894
py
import Image import ImageEnhance import ImageFilter import sys from pytesser import * # 二值化 threshold = 140 table = [] for i in range(256): if i < threshold: table.append(0) else: table.append(1) #由于都是数字 #对于识别成字母的 采用该表进行修正 rep={'O':'0', 'I':'1','L':'1', 'Z':'2', 'S':'8' }; def getverify1(name): #打开图片 im = Image.open(name) #转化到亮度 imgry = im.convert('L') imgry.save('g'+name) #二值化 out = imgry.point(table,'1') out.save('b'+name) #识别 text = image_to_string(out) #识别对吗 text = text.strip() text = text.upper(); for r in rep: text = text.replace(r,rep[r]) #out.save(text+'.jpg') print text return text getverify1('v1.jpg') getverify1('v2.jpg') getverify1('v3.jpg') getverify1('v4.jpg')
[ "cuihao5135@gmail.com" ]
cuihao5135@gmail.com
5629d477d8fa2067198e65ffdfb9c0886d901cde
4ef12058ec6bd844002607f4d5d313d10ef0d885
/bot/language/BotLocalizer.py
5dc27eb3bcc2261b03d4eb6f46cfc84c30193134
[ "BSD-3-Clause" ]
permissive
TheLegendofPiratesOnline/discord-bot
a6949510bd9573d5511d762ad261b8e3be7d2cb2
e8582e84ff9f745b05c2e257a21e5cc9f78087ad
refs/heads/stable
2022-12-05T01:34:53.809933
2022-11-25T11:33:31
2022-11-25T11:33:31
116,735,857
7
9
BSD-3-Clause
2022-11-25T11:33:33
2018-01-08T22:30:32
Python
UTF-8
Python
false
false
1,122
py
# Filename: BotLocalizer.py # Author: mfwass # Date: January 8th, 2017 # # The Legend of Pirates Online Software # Copyright (c) The Legend of Pirates Online. All rights reserved. # # All use of this software is subject to the terms of the revised BSD # license. You should have received a copy of this license along # with this source code in a file named "LICENSE." """ The class BotLocalizer will select which language to use when providing responses in Discord channels. There are corresponding files to this class which will contain the actual strings in their respective language. Those files will have the same name as this class + the language they are in. For example, BotLocalizerEnglish. """ def importLanguageModule(module): """ Imports other language modules and places them into the globals. """ try: x = __import__(module, {}, {}, ['bot.language']) except ImportError: x = __import__('bot.language.BotLocalizerEnglish', {}, {}, ['bot.language']) globals().update(x.__dict__) ## TODO: Process other languages from settings. importLanguageModule('English')
[ "michael@mfwass.com" ]
michael@mfwass.com
0f5d730440ef71b975b089ab342a71ad7cea9813
7a8f6f7a032e026007228b6223763ff046fc457a
/NeoBoot/files/tools.py
899a7da5b76023ee09619d9bc1c7b2c53d51c798
[]
no_license
VARAVAN1/neoboot
189fb8c5fa6bca1d52dd07e5143fb86d1cc2bced
b316149f7ade85491d3f719cdd3fec8eae4a07aa
refs/heads/master
2021-08-08T22:37:01.083721
2017-11-11T13:44:35
2017-11-11T13:44:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
46,196
py
#!/usr/bin/python # -*- coding: utf-8 -*- from __init__ import _ import codecs from enigma import getDesktop from Components.ActionMap import ActionMap from Components.Label import Label from Components.ScrollLabel import ScrollLabel from Components.Pixmap import Pixmap from Components.Sources.List import List from Components.ConfigList import ConfigListScreen from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest from Components.config import getConfigListEntry, config, ConfigYesNo, ConfigText, ConfigSelection, NoSave from Plugins.Extensions.NeoBoot.plugin import Plugins from Plugins.Plugin import PluginDescriptor from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox from Screens.Console import Console from Screens.Screen import Screen from Tools.LoadPixmap import LoadPixmap from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE, SCOPE_CURRENT_SKIN, fileExists, pathExists, createDir from os import system, listdir, mkdir, chdir, getcwd, rename as os_rename, remove as os_remove, popen from os.path import dirname, isdir, isdir as os_isdir from enigma import eTimer from Plugins.Extensions.NeoBoot.files.stbbranding import getKernelVersionString import os PLUGINVERSION = '6.00' if os.path.exists('/etc/hostname'): with open('/etc/hostname', 'r') as f: myboxname = f.readline().strip() f.close() if os.path.exists('/proc/stb/info/vumodel'): with open('/proc/stb/info/vumodel', 'r') as f: vumodel = f.readline().strip() f.close() if os.path.exists('/proc/stb/info/boxtype'): with open('/proc/stb/info/boxtype', 'r') as f: boxtype = f.readline().strip() f.close() class BoundFunction: __module__ = __name__ def __init__(self, fnc, *args): self.fnc = fnc self.args = args def __call__(self): self.fnc(*self.args) class MBTools(Screen): screenwidth = getDesktop(0).size().width() if screenwidth and screenwidth == 1920: skin = '\n <screen name="NeoBoot" position="center,center" size="1159,750" title="Narzedzia NeoBoota">\n\t\t<widget source="list" render="Listbox" position="15,27" size="1131,720" scrollbarMode="showOnDemand">\n\t\t\t<convert type="TemplatedMultiContent">\n \t\t{"template": [\n \t\t\tMultiContentEntryText(pos = (50, 1), size = (820, 46), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0),\n \t\t\tMultiContentEntryPixmapAlphaTest(pos = (4, 2), size = (66, 66), png = 1),\n \t\t\t],\n \t\t\t"fonts": [gFont("Regular", 35)],\n \t\t\t"itemHeight": 50\n \t\t}\n \t\t</convert>\n\t\t</widget>\n </screen>' else: skin = '\n <screen position="center,center" size="590,330" title="Narzedzia NeoBoota">\n\t\t<widget source="list" render="Listbox" position="10,16" size="570,300" scrollbarMode="showOnDemand" >\n\t\t\t<convert type="TemplatedMultiContent">\n \t\t{"template": [\n \t\t\tMultiContentEntryText(pos = (50, 1), size = (520, 36), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0),\n \t\t\tMultiContentEntryPixmapAlphaTest(pos = (4, 2), size = (36, 36), png = 1),\n \t\t\t],\n \t\t\t"fonts": [gFont("Regular", 22)],\n \t\t\t"itemHeight": 36\n \t\t}\n \t\t</convert>\n\t\t</widget>\n </screen>' __module__ = __name__ def __init__(self, session): Screen.__init__(self, session) self.list = [] self['list'] = List(self.list) self.updateList() self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.KeyOk, 'back': self.close}) def updateList(self): self.list = [] mypath = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot' if not fileExists(mypath + 'icons'): mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/ok.png' png = LoadPixmap(mypixmap) res = (_('Przywr\xc3\xb3\xc4\x87 kopi\xc4\x99 obrazu do NeoBoota'), png, 0) self.list.append(res) self['list'].list = self.list res = (_('Menad\xc5\xbcer urz\xc4\x85dze\xc5\x84'), png, 1) self.list.append(res) self['list'].list = self.list res = (_('Usu\xc5\x84 image ZIP z katalogu ImagesUpload '), png, 2) self.list.append(res) self['list'].list = self.list res = (_('Odinstalowanie NeoBoota'), png, 3) self.list.append(res) self['list'].list = self.list res = (_('Reinstalacja NeoBoota'), png, 4) self.list.append(res) self['list'].list = self.list res = (_('Zaktualizuj NeoBoota na wszystkich obrazach.'), png, 5) self.list.append(res) self['list'].list = self.list res = (_('Kopia Zapasowa NeoBoota'), png, 6) self.list.append(res) self['list'].list = self.list res = (_('Aktualizacja listy TV na zainstalowanych image.'), png, 7) self.list.append(res) self['list'].list = self.list res = (_('Aktualizacja IPTVPlayer na zainstalowanych image.'), png, 8) self.list.append(res) self['list'].list = self.list res = (_('Usuniecie hasla do root.'), png, 9) self.list.append(res) self['list'].list = self.list res = (_('Informacje NeoBoota'), png, 10) self.list.append(res) self['list'].list = self.list def KeyOk(self): self.sel = self['list'].getCurrent() if self.sel: self.sel = self.sel[2] if self.sel == 0 and self.session.open(MBRestore): pass if self.sel == 1 and self.session.open(MenagerDevices): pass if self.sel == 2 and self.session.open(MBDeleUpload): pass if self.sel == 3 and self.session.open(UnistallMultiboot): pass if self.sel == 4 and self.session.open(ReinstllNeoBoot): pass if self.sel == 5 and self.session.open(UpdateNeoBoot): pass if self.sel == 6 and self.session.open(BackupMultiboot): pass if self.sel == 7 and self.session.open(ListTv): pass if self.sel == 8 and self.session.open(IPTVPlayer): pass if self.sel == 9 and self.session.open(SetPasswd): pass if self.sel == 10 and self.session.open(MultiBootMyHelp): pass class MBBackup(Screen): screenwidth = getDesktop(0).size().width() if screenwidth and screenwidth == 1920: skin = ' <screen position="center,center" size="850,750" title="Wykonaj kopie zapasowa obrazu z NeoBoota">\n\t\t\n <widget name="lab1" position="24, 5" size="819, 62" font="Regular;35" halign="center" valign="center" transparent="1" foregroundColor="blue" />\n\n <widget name="lab2" position="22, 82" size="819, 61" font="Regular;35" halign="center" valign="center" transparent="1" foregroundColor="blue" />\n\n <widget name="lab3" position="21, 150" size="819, 62" font="Regular;35" halign="center" valign="center" transparent="1" foregroundColor="blue" />\n \n <widget source="list" render="Listbox" itemHeight="40" selectionPixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/selektor.png" font="Regular;25" position="20, 218" zPosition="1" size="820, 376" scrollbarMode="showOnDemand" transparent="1">\n\t\t\t\n <convert type="StringList" font="Regular;35" />\n\n </widget>\n\n <ePixmap position="336, 596" size="181, 29" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" />\n\n <widget name="key_red" position="307, 629" zPosition="2" size="251, 77" font="Regular;35" halign="center" valign="center" backgroundColor="red" transparent="1" foregroundColor="red" />\n\n </screen>' else: skin = ' <screen position="center,center" size="700,550" title="Wykonaj kopie zapasowa obrazu z NeoBoota">\n\t\t\n <widget name="lab1" position="20,20" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\n <widget name="lab2" position="20,50" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\n <widget name="lab3" position="20,100" size="660,30" font="Regular;22" halign="center" valign="center" transparent="1"/>\n \n <widget source="list" render="Listbox" position="40,130" zPosition="1" size="620,360" scrollbarMode="showOnDemand" transparent="1" >\n\t\t\t\n <convert type="StringList" />\n</widget>\n<ePixmap position="280,500" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" />\n\n <widget name="key_red" position="280,500" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" />\n\n </screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('') self['lab2'] = Label('') self['lab3'] = Label(_('Wybierz obraz z kt\xc3\xb3rego chcesz zrobi\xc4\x87 kopie')) self['key_red'] = Label(_('Kopia Zapasowa')) self['list'] = List([]) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'ok': self.backupImage, 'red': self.backupImage}) self.backupdir = '/media/neoboot/NeoBootImageBackup' self.availablespace = '0' self.onShow.append(self.updateInfo) def updateInfo(self): device = '/media/neoboot' usfree = '0' devicelist = ['cf', 'hdd', 'card', 'usb', 'usb2'] for d in devicelist: test = '/media/' + d + '/ImageBoot/.neonextboot' if fileExists(test): device = '/media/' + d rc = system('df > /tmp/ninfo.tmp') f = open('/proc/mounts', 'r') for line in f.readlines(): if line.find('/hdd') != -1: self.backupdir = '/media/neoboot/NeoBootImageBackup' device = '/media/neoboot' f.close() if pathExists(self.backupdir) == 0 and createDir(self.backupdir): pass if fileExists('/tmp/ninfo.tmp'): f = open('/tmp/ninfo.tmp', 'r') for line in f.readlines(): line = line.replace('part1', ' ') parts = line.strip().split() totsp = len(parts) - 1 if parts[totsp] == device: if totsp == 5: usfree = parts[3] else: usfree = parts[2] break f.close() os_remove('/tmp/ninfo.tmp') self.availablespace = usfree[0:-3] strview = _('Masz zainstalowane nas\xc5\xa7\xc4\x99puj\xc4\x85ce obrazy') self['lab1'].setText(strview) strview = _('Masz jeszcze wolne: ') + self.availablespace + ' MB' self['lab2'].setText(strview) imageslist = ['Flash'] for fn in listdir('/media/neoboot/ImageBoot'): dirfile = '/media/neoboot/ImageBoot/' + fn if os_isdir(dirfile) and imageslist.append(fn): pass self['list'].list = imageslist def backupImage(self): image = self['list'].getCurrent() if image: self.backimage = image.strip() myerror = '' if self.backimage == 'Flash': myerror = _('Niestety nie mo\xc5\xbcna wykona\xc4\x87 kopii zapasowej z flesza t\xc4\x85 wtyczk\xc4\x85\nZainstaluj backupsuite do kopii obrazu z pamieci flesza') if int(self.availablespace) < 150: myerror = _('Brak miejca do zrobienia kopii obrazu. Potrzebne jest 150 Mb wolnego miejsca na kopie obrazu.') if myerror == '': message = _('Wykona\xc4\x87 kopi\xc4\x99 obrazu:') + image + ' teraz ?' ybox = self.session.openWithCallback(self.dobackupImage, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_('Potwierdzenie kopii zapasowej')) else: self.session.open(MessageBox, myerror, MessageBox.TYPE_INFO) def dobackupImage(self, answer): if answer is True: cmd = "echo -e '\n\n%s '" % _('Prosz\xc4\x99 czeka\xc4\x87, NeoBoot dzia\xc5\x82a, wykonywanie kopii zapasowej moze zajac kilka chwil, proces w toku...') cmd1 = '/bin/tar -cf ' + self.backupdir + '/' + self.backimage + '.tar /media/neoboot/ImageBoot/' + self.backimage + ' > /dev/null 2>&1' cmd2 = 'mv -f ' + self.backupdir + '/' + self.backimage + '.tar ' + self.backupdir + '/' + self.backimage + '.mb' cmd3 = "echo -e '\n\n%s '" % _('NeoBoot: Kopia Zapasowa KOMPLETNA !') self.session.open(Console, _('NeoBoot: Kopia Zapasowa Obrazu'), [cmd, cmd1, cmd2, cmd3]) self.close() class MBRestore(Screen): __module__ = __name__ skin = ' \n\t<screen position="center,center" size="700,550" title="NeoBoot Przywracanie Obrazu">\n <widget name="lab1" position="20,20" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n <widget name="lab2" position="20,50" size="660,30" font="Regular;24" halign="center" valign="center" transparent="1"/>\n <widget name="lab3" position="20,100" size="660,30" font="Regular;22" halign="center" valign="center" transparent="1"/>\n <widget source="list" render="Listbox" position="40,130" zPosition="1" size="620,380" scrollbarMode="showOnDemand" transparent="1" >\n\t\t\t<convert type="StringList" />\n </widget>\n <ePixmap position="140,500" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" />\n <ePixmap position="420,500" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/greencor.png" alphatest="on" zPosition="1" />\n <widget name="key_red" position="140,500" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" />\n <widget name="key_green" position="420,500" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="green" transparent="1" />\n </screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('') self['lab2'] = Label('') self['lab3'] = Label(_('Wybierz kopi\xc4\x99 kt\xc3\xb3r\xc4\x85 chcesz przywr\xc3\xb3ci\xc4\x87')) self['key_red'] = Label(_('Restore')) self['key_green'] = Label(_('Delete')) self['list'] = List([]) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'ok': self.restoreImage, 'red': self.restoreImage, 'green': self.deleteback}) self.backupdir = '/media/neoboot/NeoBootImageBackup' self.availablespace = '0' self.onShow.append(self.updateInfo) def updateInfo(self): device = '/media/neoboot' usfree = '0' devicelist = ['cf', 'CF', 'hdd', 'card', 'sd', 'SD', 'usb', 'USB', 'usb2'] for d in devicelist: test = '/media/' + d + '/ImageBoot/.neonextboot' if fileExists(test): device = '/media/' + d rc = system('df > /tmp/ninfo.tmp') f = open('/proc/mounts', 'r') for line in f.readlines(): if line.find('/neoboot') != -1: self.backupdir = '/media/neoboot/NeoBootImageBackup' f.close() if pathExists(self.backupdir) == 0 and createDir(self.backupdir): pass if fileExists('/tmp/ninfo.tmp'): f = open('/tmp/ninfo.tmp', 'r') for line in f.readlines(): line = line.replace('part1', ' ') parts = line.strip().split() totsp = len(parts) - 1 if parts[totsp] == device: if totsp == 5: usfree = parts[3] else: usfree = parts[2] break f.close() os_remove('/tmp/ninfo.tmp') self.availablespace = usfree[0:-3] strview = _('Kopie Zapasowe znajduj\xc4\x85 si\xc4\x99 w katalogu /media/neoboot/NeoBootImageBackup') self['lab1'].setText(strview) strview = _('Ilo\xc5\x9b\xc4\x87 wolnego miejsca w Superbocie: ') + self.availablespace + ' MB' self['lab2'].setText(strview) imageslist = [] for fn in listdir(self.backupdir): imageslist.append(fn) self['list'].list = imageslist def deleteback(self): image = self['list'].getCurrent() if image: self.delimage = image.strip() message = _('Wybierz obraz do przywr\xc3\xb3cenia lub usuni\xc4\x99cia:\n ') + image + '?' ybox = self.session.openWithCallback(self.dodeleteback, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_('Potwierdzenie Usuni\xc4\x99cia')) def dodeleteback(self, answer): if answer is True: cmd = "echo -e '\n\n%s '" % _('SuperBoot usuwanie plik\xc3\xb3w kopi zapasowej.....') cmd1 = 'rm ' + self.backupdir + '/' + self.delimage self.session.open(Console, _('SuperBoot: Pliki kopii zapasowej usuni\xc4\x99te'), [cmd, cmd1]) self.updateInfo() def restoreImage(self): image = self['list'].getCurrent() if image: curimage = 'Flash' if fileExists('/.neonextboot'): f = open('/.neonextboot', 'r') curimage = f.readline().strip() f.close() self.backimage = image.strip() imagename = self.backimage[0:-3] myerror = '' if curimage == imagename: myerror = _('Sorry you cannot overwrite the image currently booted from. Please, boot from Flash to restore this backup.') if myerror == '': message = _('Przed przywracaniem sprawdz czy masz wolne miejsce na swoim urz\xc4\x85dzeniu - 300Mb \nCzy chcesz przywr\xc3\xb3ci\xc4\x87 ten obraz:\n ') + image + '?' ybox = self.session.openWithCallback(self.dorestoreImage, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_('Potwierdzenie Przywracania')) else: self.session.open(MessageBox, myerror, MessageBox.TYPE_INFO) def dorestoreImage(self, answer): if answer is True: imagename = self.backimage[0:-3] cmd = "echo -e '\n\n%s '" % _('Wait please, NeoBoot is working: ....Restore in progress....') cmd1 = 'mv -f ' + self.backupdir + '/' + self.backimage + ' ' + self.backupdir + '/' + imagename + '.tar' cmd2 = '/bin/tar -xf ' + self.backupdir + '/' + imagename + '.tar -C /' cmd3 = 'mv -f ' + self.backupdir + '/' + imagename + '.tar ' + self.backupdir + '/' + imagename + '.mb' cmd4 = 'sync' cmd5 = "echo -e '\n\n%s '" % _('Superboot: Restore COMPLETE !') self.session.open(Console, _('NeoBoot: Restore Image'), [cmd, cmd1, cmd2, cmd3, cmd4, cmd5]) self.close() def myclose(self): self.close() def myclose2(self, message): self.session.open(MessageBox, message, MessageBox.TYPE_INFO) self.close() class MenagerDevices(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="Menad\xc5\xbcer urz\xc4\x85dze\xc5\x84">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Uruchomic Menad\xc5\xbcer urz\xc4\x85dze\xc5\x84 ?') self['key_red'] = Label(_('Uruchom')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.MD}) def MD(self): try: if fileExists('/usr/lib/enigma2/python/Plugins/SystemPlugins/DeviceManager/devicemanager.cfg'): system('rm -f /usr/lib/enigma2/python/Plugins/SystemPlugins/DeviceManager/devicemanager.cfg') if fileExists('/etc/devicemanager.cfg'): system(' rm -f /etc/devicemanager.cfg') else: from Plugins.Extensions.NeoBoot.files.devices import ManagerDevice self.session.open(ManagerDevice) except: False class UnistallMultiboot(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="Odinstaluj NeoBoota">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Czy odinstalowa\xc4\x87 NeoBoota ?') self['key_red'] = Label(_('Odinstaluj')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.usun}) def usun(self): message = _('Je\xc5\x9bli wybierzesz Tak, zostan\xc4\x85 przywr\xc3\xb3cone ustawienia obrazu pli \nMultibot zostanie tylko odinstalowany. \nBedziesz m\xc3\xb3g\xc5\x82 go zainstalowa\xc4\x87 ponownie') ybox = self.session.openWithCallback(self.reinstallneoboot, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_('Delete Confirmation')) def reinstallneoboot(self, answer): if answer is True: cmd0 = "echo -e '\n\nPrzywracanie ustawie\xc5\x84.....'" cmd = "echo -e '\n%s '" % _('Czekaj usuwam...') cmd1 = 'rm /sbin/multinit; sleep 2' cmd1a = "echo -e '\nNeoBoot usuwanie mened\xc5\xbcera rozruchu....'" cmd2 = 'rm /sbin/init; sleep 2' cmd3 = 'ln -sfn /sbin/init.sysvinit /sbin/init' cmd4 = 'chmod 777 /sbin/init; sleep 2' cmd4a = "echo -e '\nNeoBoot restoring media mounts....'" cmd5 = 'mv /etc/init.d/volatile-media.sh.org /etc/init.d/volatile-media.sh; sleep 2' cmd6 = 'rm /media/neoboot/ImageBoot/.neonextboot;rm /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/.location; sleep 2' cmd7 = 'rm /media/neoboot/ImageBoot/.Flash; rm /media/neoboot/ImageBoot/.version' cmd7a = "echo -e '\n\nOdinstalowywanie neoboota...'" cmd8 = 'mv /etc/init.d/volatile-media.sh.org /etc/init.d/volatile-media.sh; sleep 2' cmd8a = "echo -e '\n\nPrzywracanie montowania.'" cmd9 = 'mv /etc/fstab.org /etc/fstab; sleep 2' cmd9a = "echo -e '\n\nNeoBoot odinstalowany, mozesz zrobic reinstalacje.'" self.session.openWithCallback(self.close, Console, _('NeoBoot is reinstall...'), [cmd0, cmd, cmd1, cmd1a, cmd2, cmd3, cmd4, cmd4a, cmd5, cmd6, cmd7, cmd7a, cmd8, cmd8a, cmd9, cmd9a]) self.close() class ReinstllNeoBoot(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="Update NeoBoot">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Przywrocic kopie NeoBoota z lokalizacji /media/neoboot ?') self['key_red'] = Label(_('Backup')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.reinstallMB}) def reinstallMB(self): system('/bin/tar -xzvf /media/neoboot/NeoBoot_Backup.tar.gz -C /') self.close() class UpdateNeoBoot(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="Update NeoBoot">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Aktualizowac neoboota na wszystkich obrazach ?') self['key_red'] = Label(_('Zainstaluj')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.mbupload}) def mbupload(self): self.session.open(MyUpgrade2) class MyUpgrade2(Screen): screenwidth = getDesktop(0).size().width() if screenwidth and screenwidth == 1920: skin = '<screen position="center,center" size="900,450" title="NeoBoot">\n\t\t<widget name="lab1" position="23,42" size="850,350" font="Regular;35" halign="center" valign="center" transparent="1" />\n</screen>' else: skin = '<screen position="center,center" size="400,200" title="NeoBoot">\n\t\t<widget name="lab1" position="10,10" size="380,180" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\t</screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label(_('[NeoBoot]Prosze czeka\xc4\x87, aktualizacja w toku...')) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.updateInfo) self.onShow.append(self.startShow) def startShow(self): self.activityTimer.start(10) def updateInfo(self): self.activityTimer.stop() f2 = open('/media/neoboot/ImageBoot/.neonextboot', 'r') mypath2 = f2.readline().strip() f2.close() if mypath2 != 'Flash': self.myClose(_('Sorry, NeoBoot can installed or upgraded only when booted from Flash STB')) self.close() else: system('chown -R root:root /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot') system('chmod -R a+x /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin') system('chmod a+x /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/nandsim.pyo') system('chmod a+x /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/ubi.pyo') for fn in listdir('/media/neoboot/ImageBoot'): dirfile = '/media/neoboot/ImageBoot/' + fn if isdir(dirfile): target = dirfile + '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot' cmd = 'rm -r ' + target + ' > /dev/null 2>&1' system(cmd) cmd = 'cp -r /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot ' + target system(cmd) cmd = 'cp -r /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/bin/multinit /sbin/multinit' system(cmd) out = open('/media/neoboot/ImageBoot/.version', 'w') out.write(PLUGINVERSION) out.close() self.myClose(_('NeoBoot successfully updated. You can restart the plugin now.\nHave fun !!')) def myClose(self, message): self.session.open(MessageBox, message, MessageBox.TYPE_INFO) self.close() class MBDeleUpload(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="NeoBoot - wyczy\xc5\x9b\xc4\x87 pobrane image">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Czy na pewno chcesz usun\xc4\x85\xc4\x87 obraz z katalogu ImagesUpload ?\n\nJe\xc5\x9bli wybierzesz czerwony przycisk na pilocie to usuniesz wszystkie obrazy ZIP z katalogu ImagesUpload') self['key_red'] = Label(_('Wyczy\xc5\x9b\xc4\x87')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.usunup}) def usunup(self): message = _('Czy napewno chcesz wyczy\xc5\x9bci\xc4\x87') ybox = self.session.openWithCallback(self.pedeleup, MessageBox, message, MessageBox.TYPE_YESNO) ybox.setTitle(_('Czyszenie z pobranych obraz\xc3\xb3w')) def pedeleup(self, answer): if answer is True: cmd = "echo -e '\n\n%s '" % _('Czekaj usuwam.....') cmd1 = 'rm /media/neoboot/ImagesUpload/*.zip' self.session.open(Console, _('Usuwanie pobranych obraz\xc3\xb3w....'), [cmd, cmd1]) self.close() class BackupMultiboot(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="590,330" title="Backup NeoBoot">\n\t\t<widget source="list" render="Listbox" position="10,16" size="570,300" scrollbarMode="showOnDemand" >\n\t\t\t<convert type="TemplatedMultiContent">\n \t\t{"template": [\n \t\t\tMultiContentEntryText(pos = (50, 1), size = (520, 36), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 0),\n \t\t\tMultiContentEntryPixmapAlphaTest(pos = (4, 2), size = (36, 36), png = 1),\n \t\t\t],\n \t\t\t"fonts": [gFont("Regular", 22)],\n \t\t\t"itemHeight": 36\n \t\t}\n \t\t</convert>\n\t\t</widget>\n </screen>' def __init__(self, session): Screen.__init__(self, session) self.list = [] self['list'] = List(self.list) self.downList() self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'ok': self.KeyOk, 'back': self.close}) def downList(self): self.list = [] mypixmap = '/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/ok.png' png = LoadPixmap(mypixmap) res = (_('Wykonac kompletna kopie NeoBoota ?'), png, 0) self.list.append(res) self['list'].list = self.list def KeyOk(self): self.sel = self['list'].getCurrent() if self.sel: self.sel = self.sel[2] if self.sel == 0: cmd = 'sh /usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/files/NeoBoot.sh -i' self.session.open(Console, _('Kopia zapasowa zostanie zapisana w lokalizacji /media/neoboot. Trwa wykonywanie....'), [cmd]) self.close() class SetPasswd(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="Zmiana Hasla">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Czy skasowac haslo ?') self['key_red'] = Label(_('Uruchom')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.passwd}) def passwd(self): os.system('passwd -d root') restartbox = self.session.openWithCallback(self.restartGUI, MessageBox, _('GUI needs a restart.\nDo you want to Restart the GUI now?'), MessageBox.TYPE_YESNO) restartbox.setTitle(_('Restart GUI now?')) def restartGUI(self, answer): if answer is True: self.session.open(TryQuitMainloop, 3) else: self.close() class ReinstallKernel(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="Module kernel">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Reinstalacja j\xc4\x85dra.\n\nZainstalowa\xc4\x87 ?') self['key_red'] = Label(_('Instalacja')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.kernel_image}) def kernel_image(self): if fileExists('/.multinfo'): if myboxname == 'vuuno4k' or myboxname == 'vuultimo4k' or myboxname == 'vusolo4k' or myboxname == 'bm750' or myboxname == 'vuduo' or myboxname == 'vuuno' or myboxname == 'vuultimo' or myboxname == 'vusolo' or myboxname == 'vusolo2' or myboxname == 'vusolose' or myboxname == 'vuduo2' or myboxname == 'vuzero' or myboxname == 'vuduo': cmd1 = 'opkg install --force-maintainer --force-reinstall --force-overwrite --force-downgrade /media/neoboot/ImagesUpload/.kernel/zImage.%s.ipk; opkg configure update-modules' % (vumodel, vumodel) self.session.open(Console, _('NeoBoot....'), [cmd1]) elif myboxname == 'sf4008' : cmd1 = 'opkg install --force-maintainer --force-reinstall --force-overwrite --force-downgrade /media/neoboot/ImagesUpload/.kernel/zImage.%s.ipk; opkg configure update-modules' % (boxtype, boxtype) self.session.open(Console, _('NeoBoot....'), [cmd1]) else: self.messagebox = self.session.open(MessageBox, _('Canceled ... NeoBoot will not work properly !!! NeoBoot works only on VuPlus box !!!'), MessageBox.TYPE_INFO, 20) self.messagebox = self.session.open(MessageBox, _('NeoBoot installd kernel-image...'), MessageBox.TYPE_INFO, 4) self.close() else: if myboxname == 'vuuno4k' or myboxname == 'vuultimo4k' or myboxname == 'vusolo4k' or myboxname == 'bm750' or myboxname == 'vuduo' or myboxname == 'vuuno' or myboxname == 'vuultimo' or myboxname == 'vusolo' or myboxname == 'vusolo2' or myboxname == 'vusolose' or myboxname == 'vuduo2' or myboxname == 'vuzero' or myboxname == 'vuduo': cmd1 = 'opkg download kernel-image; sleep 2; mv /home/root/*.ipk /media/neoboot/ImagesUpload/.kernel/zImage.%s.ipk; opkg install --force-maintainer --force-reinstall --force-overwrite --force-downgrade /media/neoboot/ImagesUpload/.kernel/zImage.%s.ipk; opkg configure update-modules' % (vumodel, vumodel) self.session.open(Console, _('NeoBoot....'), [cmd1]) elif myboxname == 'sf4008' : cmd1 = 'opkg download kernel-image; sleep 2; mv /home/root/*.ipk /media/neoboot/ImagesUpload/.kernel/zImage.%s.ipk; opkg install --force-maintainer --force-reinstall --force-overwrite --force-downgrade /media/neoboot/ImagesUpload/.kernel/zImage.%s.ipk; opkg configure update-modules' % (boxtype, boxtype) self.session.open(Console, _('NeoBoot....'), [cmd1]) else: self.messagebox = self.session.open(MessageBox, _('Canceled ... NeoBoot will not work properly !!! NeoBoot works only on VuPlus box !!!'), MessageBox.TYPE_INFO, 20) self.messagebox = self.session.open(MessageBox, _('NeoBoot installd kernel-image...'), MessageBox.TYPE_INFO, 4) self.close() out = open('/media/neoboot/ImagesUpload/.kernel/used_flash_kernel', 'w') out.write('Used Kernel: Flash') out.close() class ListTv(Screen): __module__ = __name__ screenwidth = getDesktop(0).size().width() if screenwidth and screenwidth == 1920: skin = '<screen position="center,center" size="900,450" title="NeoBoot">\n\t\t<widget name="lab1" position="23,42" size="850,350" font="Regular;35" halign="center" valign="center" transparent="1" />\n</screen>' else: skin = '<screen position="center,center" size="400,200" title="NeoBoot">\n\t\t<widget name="lab1" position="10,10" size="380,180" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\t</screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label(_('NeoBoot: Upgrading in progress\nPlease wait...')) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.updateInfo) self.onShow.append(self.startShow) def startShow(self): self.activityTimer.start(10) def updateInfo(self): self.activityTimer.stop() f2 = open('/media/neoboot/ImageBoot/.neonextboot', 'r') mypath2 = f2.readline().strip() f2.close() if mypath2 != 'Flash': self.myClose(_('Sorry, NeoBoot can installed or upgraded only when booted from Flash.')) self.close() else: os.system('mv /etc/enigma2 /etc/enigma2.tmp') os.system('mkdir -p /etc/enigma2') os.system('cp -f /etc/enigma2.tmp/*.tv /etc/enigma2') os.system('cp -f /etc/enigma2.tmp/*.radio /etc/enigma2') os.system('cp -f /etc/enigma2.tmp/lamedb /etc/enigma2') for fn in listdir('/media/neoboot/ImageBoot'): dirfile = '/media/neoboot/ImageBoot/' + fn if isdir(dirfile): target = dirfile + '/etc/' cmd = 'cp -r -f /etc/enigma2 ' + target system(cmd) target1 = dirfile + '/etc/tuxbox' cmd = 'cp -r -f /etc/tuxbox/satellites.xml ' + target1 system(cmd) target2 = dirfile + '/etc/tuxbox' cmd = 'cp -r -f /etc/tuxbox/terrestrial.xml ' + target2 system(cmd) os.system('rm -f -R /etc/enigma2') os.system('mv /etc/enigma2.tmp /etc/enigma2/') self.myClose(_('NeoBoot successfully updated list tv.\nHave fun !!')) def myClose(self, message): self.session.open(MessageBox, message, MessageBox.TYPE_INFO) self.close() class IPTVPlayer(Screen): __module__ = __name__ screenwidth = getDesktop(0).size().width() if screenwidth and screenwidth == 1920: skin = '<screen position="center,center" size="900,450" title="IPTVPlayer">\n\t\t<widget name="lab1" position="23,42" size="850,350" font="Regular;35" halign="center" valign="center" transparent="1" />\n</screen>' else: skin = '<screen position="center,center" size="400,200" title="IPTVPlayer">\n\t\t<widget name="lab1" position="10,10" size="380,180" font="Regular;24" halign="center" valign="center" transparent="1"/>\n\t</screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label(_('NeoBoot: Upgrading in progress\nPlease wait...')) self.activityTimer = eTimer() self.activityTimer.timeout.get().append(self.updateInfo) self.onShow.append(self.startShow) def startShow(self): self.activityTimer.start(10) def updateInfo(self): self.activityTimer.stop() f2 = open('/media/neoboot/ImageBoot/.neonextboot', 'r') mypath2 = f2.readline().strip() f2.close() if mypath2 != 'Flash': self.myClose(_('Sorry, NeoBoot can installed or upgraded only when booted from Flash.')) self.close() elif not fileExists('/usr/lib/enigma2/python/Plugins/Extensions/IPTVPlayer'): self.myClose(_('Sorry, IPTVPlayer not found.')) self.close() else: for fn in listdir('/media/neoboot/ImageBoot'): dirfile = '/media/neoboot/ImageBoot/' + fn if isdir(dirfile): target = dirfile + '/usr/lib/enigma2/python/Plugins/Extensions/IPTVPlayer' cmd = 'rm -r ' + target + ' > /dev/null 2>&1' system(cmd) cmd = 'cp -r /usr/lib/enigma2/python/Plugins/Extensions/IPTVPlayer ' + target system(cmd) self.myClose(_('NeoBoot successfully updated IPTVPlayer.\nHave fun !!')) def myClose(self, message): self.session.open(MessageBox, message, MessageBox.TYPE_INFO) self.close() class SetPasswd(Screen): __module__ = __name__ skin = '\n\t<screen position="center,center" size="700,300" title="Zmiana Hasla">\n\t\t<widget name="lab1" position="20,20" size="660,215" font="Regular;24" halign="center" valign="center" transparent="1"/><ePixmap position="280,250" size="140,40" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/NeoBoot/images/redcor.png" alphatest="on" zPosition="1" /><widget name="key_red" position="280,250" zPosition="2" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="red" transparent="1" /></screen>' def __init__(self, session): Screen.__init__(self, session) self['lab1'] = Label('Czy skasowac haslo ?') self['key_red'] = Label(_('Uruchom')) self['actions'] = ActionMap(['WizardActions', 'ColorActions'], {'back': self.close, 'red': self.passwd}) def passwd(self): os.system('passwd -d root') restartbox = self.session.openWithCallback(self.restartGUI, MessageBox, _('GUI needs a restart.\nDo you want to Restart the GUI now?'), MessageBox.TYPE_YESNO) restartbox.setTitle(_('Restart GUI now?')) def restartGUI(self, answer): if answer is True: self.session.open(TryQuitMainloop, 3) else: self.close() class MultiBootMyHelp(Screen): screenwidth = getDesktop(0).size().width() if screenwidth and screenwidth == 1920: skin = '<screen name=" NeoBoot" position="center,center" size="1920,1080" title="NeoBoot - Opis" flags="wfNoBorder">\n<eLabel text="INFORMACJE NeoBoot" font="Regular; 35" position="69,66" size="1777,96" halign="center" foregroundColor="yellow" backgroundColor="black" transparent="1" /><widget name="lab1" position="69,162" size="1780,885" font="Regular;35" />\n</screen>' else: skin = '<screen name=" NeoBoot" position="center,center" size="1280,720" title="NeoBoot - Opis">\n<widget name="lab1" position="18,19" size="1249,615" font="Regular;20" />\n</screen>' __module__ = __name__ def __init__(self, session): Screen.__init__(self, session) self['lab1'] = ScrollLabel('') self['actions'] = ActionMap(['WizardActions', 'ColorActions', 'DirectionActions'], {'back': self.close, 'ok': self.close, 'up': self['lab1'].pageUp, 'left': self['lab1'].pageUp, 'down': self['lab1'].pageDown, 'right': self['lab1'].pageDown}) self['lab1'].hide() self.updatetext() def updatetext(self): message = '' message += 'NeoBoot Wersja ' + PLUGINVERSION + ' Enigma2\n\n' message += 'NeoBoot opiera si\xc4\x99 na EGAMIBoot < mod by gutosie >\n\n' message += 'Autor EGAMIBoota zezwolil na rozwijanie i edycje NeoBoot - Thanks/Dzi\xc4\x99ki\n\n' message += 'nfidump by gutemine - Thanks/Dzi\xc4\x99ki\n\n' message += 'ubi_reader by Jason Pruitt - Thanks/Dzi\xc4\x99ki\n\n' message += 'T\xc5\x82umaczenie: gutosie\n\n' message += _('Podziekowania wszystkim tu niewspomnianym za udzielenie pomocy w ulepszaniu NeoBoota \n\n') message += _('Udanej zabawy :)\n\n') self['lab1'].show() self['lab1'].setText(message) def myboot(session, **kwargs): session.open(MBTools) def Plugins(path, **kwargs): global pluginpath pluginpath = path return PluginDescriptor(name='NeoBoot', description='MENU NeoBoot', icon=None, where=PluginDescriptor.WHERE_PLUGINMENU, fnc=myboot)
[ "noreply@github.com" ]
noreply@github.com
932c777e82f9b34d9552ecd5044100328cbcb95c
a140fe192fd643ce556fa34bf2f84ddbdb97f091
/.history/class스타크래프트프로젝트전반전_20200709105346.py
18786ac5676fbf66cb3c84a0ce24b862c00e37aa
[]
no_license
sangha0719/py-practice
826f13cb422ef43992a69f822b9f04c2cb6d4815
6d71ce64bf91cc3bccee81378577d84ba9d9c121
refs/heads/master
2023-03-13T04:40:55.883279
2021-02-25T12:02:04
2021-02-25T12:02:04
342,230,484
0
0
null
null
null
null
UTF-8
Python
false
false
4,135
py
# 일반 유닛 class Unit: def __init__(self, name, hp, speed): self.name = name self.hp = hp self.speed = speed print("{0} 유닛이 생성되었습니다.".format(name)) def move(self, location): print("[지상 유닛 이동]") print("{0} : {1} 방향으로 이동합니다. [속도 {2}]" .format(self.name, location, self.speed)) def damaged(self, damage): print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage)) self.hp -= damage print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp)) if self.hp <= 0: print("{0} : 파괴되었습니다.".format(self.name)) # 공격 유닛 class AttackUnit(Unit): def __init__(self, name, hp, speed, damage): Unit.__init__(self, name, hp, speed) self.damage = damage def attack(self, location): # 클래스 내에서 메소드 앞에는 항상 self를 적어주어야 한다. print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]" .format(self.name, location, self.damage)) # 마린 class Marine(AttackUnit): def __init__(self): AttackUnit.__init__(self, "마린", 40, 1, 5) # 스팀팩 : 일정 시간 동안 이동 및 공격 속도를 증가, 체력 10 감소 def stimpack(self): if self.hp > 10: self.hp -= 10 print("{0} : 스팀팩을 사용합니다. (HP 10 감소)".format(self.name)) else: print("{0} : 체력이 부족하여 스팀팩을 사용하지 않습니다.".format(self.name)) # 탱크 class Tank(AttackUnit): # 시즈모드 : 탱크를 지상에 고정시켜, 더 높은 파워로 공격 가능. 이동 불가. seize_developed = False # 시즈모드 개발 여부 def __init__(self): AttackUnit.__init__(self, "탱크", 150, 1, 35) self.seize_mode = False def set_seize_mode(self): if Tank.seize_developed == False: return # 현재 시즈모드가 아닐 때 -> 시즈모드 if self.seize_mode == False: print("{0} : 시즈모드로 전환합니다.".format(self.name)) self.damage *= 2 self.seize_mode = True # 현재 시즈모드일 때 -> 시즈모드 해제 else: print("{0} : 시즈모드를 해제합니다.".format(self.name)) self.damaged /= 2 self.seize_mode = False # 날 수 있는 기능을 가진 클래스 class Flyable: def __init__(self, flying_speed): self.flying_speed = flying_speed def fly(self, name, location): print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]" .format(name, location, self.flying_speed)) # 공중 공격 유닛 클래스 class FlyableAttackUnit(AttackUnit, Flyable): def __init__(self, name, hp, damage, flying_speed): AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0 Flyable.__init__(self, flying_speed) def move(self, location): print("[공중 유닛 이동]") self.fly(self.name, location) # 레이스 class Wraith(FlyableAttackUnit): def __init__(self): FlyableAttackUnit.__init__(self, "레이스", 80, 20, 5) self.clocked = False # 클로킹 모드 (해제 상태) def clocking(self): if self.clocked == True: # 클로킹 모드 -> 모드 해제 print("{0} : 클로킹 모드 해제합니다.".format(self.name)) self.clocked == False else: # 클로킹 모드 해제 -> 모드 설정 print("{0} : 클로킹 모드 설정합니다.".format(self.name)) self.clocked == True def game_start(): print("[알림] 새로운 게임을 시작합니다.") def game_over(): print("Player : gg") print("[Player] 님이 게임에서 퇴장하셨습니다.") # 실제 게임 진행 game_start() # 마린 3기 생성 m1 = Marine() m2 = Marine() m3 = Marine() # 탱크 2기 생성 t1 = Tank() t2 = Tank() # 레이스 1기 생성 w1 =
[ "sangha0719@gmail.com" ]
sangha0719@gmail.com
3d0e54171f99c5973fdb441873c4d1302c56d070
86d499787fb35024db798b0c1dbfa7a6936854e9
/py_tools/example/TV.py
4ec42492467c2b2392e40b3209a8fa35afb1b711
[]
no_license
Tomtao626/python-note
afd1c82b74e2d3a488b65742547f75b49a11616e
e498e1e7398ff66a757e161a8b8c32c34c38e561
refs/heads/main
2023-04-28T08:47:54.525440
2023-04-21T17:27:25
2023-04-21T17:27:25
552,830,730
0
1
null
null
null
null
UTF-8
Python
false
false
1,095
py
class TV: def __init__(self): self.channel = 1 # Default channel is 1 self.volumeLevel = 1 # Default volume level is 1 self.on = False # By default TV is off def turnOn(self): self.on = True def turnOff(self): self.on = False def getChannel(self): return self.channel def setChannel(self, channel): if self.on and 1 <= self.channel <= 120: self.channel = channel def getVolumeLevel(self): return self.volumeLevel def setVolume(self, volumeLevel): if self.on and \ 1 <= self.volumeLevel <= 7: self.volumeLevel = volumeLevel def channelUp(self): if self.on and self.channel < 120: self.channel += 1 def channelDown(self): if self.on and self.channel > 1: self.channel -= 1 def volumeUp(self): if self.on and self.volumeLevel < 7: self.volumeLevel += 1 def volumeDown(self): if self.on and self.volumeLevel > 1: self.volumeLevel -= 1
[ "gogs@fake.local" ]
gogs@fake.local
a79551a549cf4662d75e6a1db282c47be5aa9948
5c4c5b070bcf809e1a3850bbec69ca2e9bb5a519
/Exercises/Flask_Restfull_SQL/Flask_Restfull_SQL/Code/item.py
7d53ef8eef8f1d71bcc53832a922a65ce1ed59ca
[]
no_license
gerardoalfredo2/Rest_Api_Flask-and-Python
98560e19d5547b2d1c9f2b256f666a57b8d16735
1e7a87a545998485b1d74f1e85c6e7811f052e52
refs/heads/master
2022-10-14T07:19:47.969633
2018-02-20T22:02:54
2018-02-20T22:02:54
104,912,478
0
1
null
2022-10-05T20:04:20
2017-09-26T16:47:39
Python
UTF-8
Python
false
false
3,086
py
import sqlite3 from flask_restful import Resource, reqparse from flask_jwt import jwt_required class Item(Resource): parser = reqparse.RequestParser() parser.add_argument('price', type=float, required=True, help= "This field cannot be left blank!") @jwt_required() def get(self,name): # item=self.find_by_name(name) if item: return item return {'message':'Item not found'},404 @classmethod def find_by_name(cls, name): connection = sqlite3.connect('data.db') cursor=connection.cursor() query='SELECT * FROM items WHERE name=?' result = cursor.execute(query,(name,)) row=result.fetchone() connection.close() if row: return{'item':{'name':row[0],'price':row[1]}} def post(self,name): if self.find_by_name(name): return {'message':"An item with name '{}' already exists.".format(name)},400 data=Item.parser.parse_args() item={'name':name,'price':data['price']} try: self.insert(Item) except: return {'message':'An error ocurred inserting the item.'}, 500#internal server error return item,201 @classmethod def insert(cls,item): connection=sqlite3.connect('data.db') cursor=connection.cursor() query = 'INSERT INTO items VALUES(?,?)' cursor.execute(query,(item['name'], item['price'])) connection.commit() connection.close() def delete(self,name): connection=sqlite3.connect('data.db') cursor=connection.cursor() query = 'DELETE FROM items WHERE name=?' cursor.execute(query,(name,)) connection.commit() connection.close() return{'message':'Item deleted'} def put(self,name): data=Item.parser.parse_args() item=self.find_by_name(name) updated_item={'name':name,'price':data['price']} if item is None: try: self.insert(updated_item) except: return {'message':'An error ocurred inserting the item.'}, 500#internal server error else: try: self.update(updated_item) except: return {'message':'An error ocurred updating the item.'}, 500#internal server error return updated_item @classmethod def update(cls,item): connection=sqlite3.connect('data.db') cursor=connection.cursor() query = 'UPDATE items SET price=? WHERE name=?' cursor.execute(query,(item['price'],item['name'])) connection.commit() connection.close() class ItemList(Resource): def get(self): connection=sqlite3.connect('data.db') cursor=connection.cursor() query = 'SELECT * FROM items' result = cursor.execute(query) items = [] for row in result: items.append({'name':row[0],'price':row[1]}) connection.close() return {'items':items}
[ "gerardoalfredo2@gmail.com" ]
gerardoalfredo2@gmail.com
64d3820a24b6583218f8be48ea9a7f5c8b94859c
9d69a062aa2928d37d629b8cd145f6fd7b88f886
/src/user/migrations/0001_initial.py
092c833c399d9586fce9937c9be6d799c28e904e
[]
no_license
flous/Lycee_website
9756545ee30525c262b454de7bbb2e370a4ff591
99a62c6cd8522ed3f970a98d1342e4a4c0cc45c9
refs/heads/master
2022-12-20T00:53:13.436662
2020-10-05T19:38:16
2020-10-05T19:38:16
263,046,049
3
0
null
null
null
null
UTF-8
Python
false
false
777
py
# Generated by Django 3.0.6 on 2020-05-15 10:29 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(default='default.png', upload_to='profile_pics')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "tebritebri2@gmail.com" ]
tebritebri2@gmail.com
c5ad576cf8c85785dcbdd15d2a35fb33c5ac752e
b63d17e840d251f9c8fee3d336a38b8a8d13caa6
/KDC-Simulator/kdc.py
6732aefc1b1fa80cb9e91bfae8838cb00edb7bd8
[ "MIT" ]
permissive
pablo-grande/Aula
587f6e12bf5032d0207b6af1b91449cf9dda1009
9c560fb76e94bf846120ec202c6e14e651a53844
refs/heads/master
2022-05-01T05:54:53.327704
2018-05-31T10:46:04
2018-05-31T10:46:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,381
py
from node import Node from aes import * class KDC(Node): def connect(self, transmitter, encrypted_message): """ Given two nodes and a session key establish a connection from transmitter to receiver using session_key The node identity to send the message comes encrypted with its session key """ print "\n\t=== Entering in KDC ===" transmitter_id = transmitter.getId() print "Decrypt {0}'s message".format(transmitter_id) decrypted_message = decrypt(self.getKey(transmitter_id), encrypted_message) # once message is decrypted, we need to retrieve the id and session key id_key = decrypted_message.split(',') print "Message decrypted: {0}".format(id_key) receiver_node = getNode(id_key[0]) session_key = id_key[1] print "Receiver node is {0} and session key is {1}".format(receiver_node.getId(), session_key) # now sets in the receiver node the session key with the transmitter id receiver_node.setKey(transmitter_id,session_key) print "\t===== Leaving KDC =====\n" # Initialize a node list. # every node will be stored here node_list = [] def putNode(Node): node_list.append(Node) def getNode(id): """Find a node with its id""" for node in node_list: if node.getId() == id: return node
[ "pablo.riutort@gmail.com" ]
pablo.riutort@gmail.com
dd256bbf0eafa840962acd7ca0126fd0a34cc89f
de3aa32acb4d1c819d2a07239b34dcc745c255e4
/datadotworld/client/_swagger/models/catalog_table_hydration_dto.py
696b3eb2ea7624244da55bbde68c50736f319b68
[ "Apache-2.0" ]
permissive
datadotworld/data.world-py
8d3ccbdc3c68687528ffe3d2f9c42a6765ef9a4b
4f946160f374a9f717ab955d578c1737cae15218
refs/heads/main
2023-05-27T11:19:34.463247
2023-05-11T20:18:21
2023-05-11T20:18:21
79,499,370
103
30
Apache-2.0
2023-05-11T20:18:23
2017-01-19T21:57:19
Python
UTF-8
Python
false
false
13,442
py
# coding: utf-8 """ data.world API # data.world in a nutshell data.world is a productive, secure platform for modern data teamwork. We bring together your data practitioners, subject matter experts, and other stakeholders by removing costly barriers to data discovery, comprehension, integration, and sharing. Everything your team needs to quickly understand and use data stays with it. Social features and integrations encourage collaborators to ask and answer questions, share discoveries, and coordinate closely while still using their preferred tools. Our focus on interoperability helps you enhance your own data with data from any source, including our vast and growing library of free public datasets. Sophisticated permissions, auditing features, and more make it easy to manage who views your data and what they do with it. # Conventions ## Authentication All data.world API calls require an API token. OAuth2 is the preferred and most secure method for authenticating users of your data.world applications. Visit our [oauth documentation](https://apidocs.data.world/toolkit/oauth) for additional information. Alternatively, you can obtain a token for _personal use or testing_ by navigating to your profile settings, under the Advanced tab ([https://data.world/settings/advanced](https://data.world/settings/advanced)). Authentication must be provided in API requests via the `Authorization` header. For example, for a user whose API token is `my_api_token`, the request header should be `Authorization: Bearer my_api_token` (note the `Bearer` prefix). ## Content type By default, `application/json` is the content type used in request and response bodies. Exceptions are noted in respective endpoint documentation. ## HTTPS only Our APIs can only be accessed via HTTPS. # Interested in building data.world apps? Check out our [developer portal](https://apidocs.data.world) for tips on how to get started, tutorials, and to interact with the API endpoints right within your browser. OpenAPI spec version: 0.21.0 Contact: help@data.world Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class CatalogTableHydrationDto(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'agentid': 'str', 'catalogs': 'list[CatalogId]', 'created_by': 'AgentHydrationDto', 'description': 'str', 'entry_type_hierarchy': 'list[EntryType]', 'entry_type_label': 'str', 'id': 'str', 'referent': 'str', 'source_id': 'SourceId', 'tableid': 'str', 'title': 'str', 'type': 'str', 'updated': 'datetime' } attribute_map = { 'agentid': 'agentid', 'catalogs': 'catalogs', 'created_by': 'createdBy', 'description': 'description', 'entry_type_hierarchy': 'entryTypeHierarchy', 'entry_type_label': 'entryTypeLabel', 'id': 'id', 'referent': 'referent', 'source_id': 'sourceId', 'tableid': 'tableid', 'title': 'title', 'type': 'type', 'updated': 'updated' } def __init__(self, agentid=None, catalogs=None, created_by=None, description=None, entry_type_hierarchy=None, entry_type_label=None, id=None, referent=None, source_id=None, tableid=None, title=None, type=None, updated=None): """ CatalogTableHydrationDto - a model defined in Swagger """ self._agentid = None self._catalogs = None self._created_by = None self._description = None self._entry_type_hierarchy = None self._entry_type_label = None self._id = None self._referent = None self._source_id = None self._tableid = None self._title = None self._type = None self._updated = None if agentid is not None: self.agentid = agentid if catalogs is not None: self.catalogs = catalogs if created_by is not None: self.created_by = created_by if description is not None: self.description = description if entry_type_hierarchy is not None: self.entry_type_hierarchy = entry_type_hierarchy if entry_type_label is not None: self.entry_type_label = entry_type_label if id is not None: self.id = id if referent is not None: self.referent = referent if source_id is not None: self.source_id = source_id if tableid is not None: self.tableid = tableid if title is not None: self.title = title if type is not None: self.type = type if updated is not None: self.updated = updated @property def agentid(self): """ Gets the agentid of this CatalogTableHydrationDto. :return: The agentid of this CatalogTableHydrationDto. :rtype: str """ return self._agentid @agentid.setter def agentid(self, agentid): """ Sets the agentid of this CatalogTableHydrationDto. :param agentid: The agentid of this CatalogTableHydrationDto. :type: str """ self._agentid = agentid @property def catalogs(self): """ Gets the catalogs of this CatalogTableHydrationDto. :return: The catalogs of this CatalogTableHydrationDto. :rtype: list[CatalogId] """ return self._catalogs @catalogs.setter def catalogs(self, catalogs): """ Sets the catalogs of this CatalogTableHydrationDto. :param catalogs: The catalogs of this CatalogTableHydrationDto. :type: list[CatalogId] """ self._catalogs = catalogs @property def created_by(self): """ Gets the created_by of this CatalogTableHydrationDto. :return: The created_by of this CatalogTableHydrationDto. :rtype: AgentHydrationDto """ return self._created_by @created_by.setter def created_by(self, created_by): """ Sets the created_by of this CatalogTableHydrationDto. :param created_by: The created_by of this CatalogTableHydrationDto. :type: AgentHydrationDto """ self._created_by = created_by @property def description(self): """ Gets the description of this CatalogTableHydrationDto. :return: The description of this CatalogTableHydrationDto. :rtype: str """ return self._description @description.setter def description(self, description): """ Sets the description of this CatalogTableHydrationDto. :param description: The description of this CatalogTableHydrationDto. :type: str """ self._description = description @property def entry_type_hierarchy(self): """ Gets the entry_type_hierarchy of this CatalogTableHydrationDto. :return: The entry_type_hierarchy of this CatalogTableHydrationDto. :rtype: list[EntryType] """ return self._entry_type_hierarchy @entry_type_hierarchy.setter def entry_type_hierarchy(self, entry_type_hierarchy): """ Sets the entry_type_hierarchy of this CatalogTableHydrationDto. :param entry_type_hierarchy: The entry_type_hierarchy of this CatalogTableHydrationDto. :type: list[EntryType] """ self._entry_type_hierarchy = entry_type_hierarchy @property def entry_type_label(self): """ Gets the entry_type_label of this CatalogTableHydrationDto. :return: The entry_type_label of this CatalogTableHydrationDto. :rtype: str """ return self._entry_type_label @entry_type_label.setter def entry_type_label(self, entry_type_label): """ Sets the entry_type_label of this CatalogTableHydrationDto. :param entry_type_label: The entry_type_label of this CatalogTableHydrationDto. :type: str """ self._entry_type_label = entry_type_label @property def id(self): """ Gets the id of this CatalogTableHydrationDto. :return: The id of this CatalogTableHydrationDto. :rtype: str """ return self._id @id.setter def id(self, id): """ Sets the id of this CatalogTableHydrationDto. :param id: The id of this CatalogTableHydrationDto. :type: str """ self._id = id @property def referent(self): """ Gets the referent of this CatalogTableHydrationDto. :return: The referent of this CatalogTableHydrationDto. :rtype: str """ return self._referent @referent.setter def referent(self, referent): """ Sets the referent of this CatalogTableHydrationDto. :param referent: The referent of this CatalogTableHydrationDto. :type: str """ self._referent = referent @property def source_id(self): """ Gets the source_id of this CatalogTableHydrationDto. :return: The source_id of this CatalogTableHydrationDto. :rtype: SourceId """ return self._source_id @source_id.setter def source_id(self, source_id): """ Sets the source_id of this CatalogTableHydrationDto. :param source_id: The source_id of this CatalogTableHydrationDto. :type: SourceId """ self._source_id = source_id @property def tableid(self): """ Gets the tableid of this CatalogTableHydrationDto. :return: The tableid of this CatalogTableHydrationDto. :rtype: str """ return self._tableid @tableid.setter def tableid(self, tableid): """ Sets the tableid of this CatalogTableHydrationDto. :param tableid: The tableid of this CatalogTableHydrationDto. :type: str """ self._tableid = tableid @property def title(self): """ Gets the title of this CatalogTableHydrationDto. :return: The title of this CatalogTableHydrationDto. :rtype: str """ return self._title @title.setter def title(self, title): """ Sets the title of this CatalogTableHydrationDto. :param title: The title of this CatalogTableHydrationDto. :type: str """ self._title = title @property def type(self): """ Gets the type of this CatalogTableHydrationDto. :return: The type of this CatalogTableHydrationDto. :rtype: str """ return self._type @type.setter def type(self, type): """ Sets the type of this CatalogTableHydrationDto. :param type: The type of this CatalogTableHydrationDto. :type: str """ self._type = type @property def updated(self): """ Gets the updated of this CatalogTableHydrationDto. :return: The updated of this CatalogTableHydrationDto. :rtype: datetime """ return self._updated @updated.setter def updated(self, updated): """ Sets the updated of this CatalogTableHydrationDto. :param updated: The updated of this CatalogTableHydrationDto. :type: datetime """ self._updated = updated def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, CatalogTableHydrationDto): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[ "noreply@github.com" ]
noreply@github.com
76f34a5779885c8d75a5dffba7c7debce3ab6a8d
6d3d82bf628a1fd8b06dbe2ddf87c711e9d3737c
/LPTHW/ex40.py
b29480d6a04a49f3725c7a1e2904132cafc9a5fc
[ "CC0-1.0" ]
permissive
YYMaker/PythonStarter
d04458106b09809d4e336b4f7379f9af54f83c88
49f7af6c5f4acf50be5d761f372ecdff8993aff9
refs/heads/master
2021-01-19T06:50:16.951018
2016-08-04T05:46:50
2016-08-04T05:46:50
63,845,621
1
0
null
null
null
null
UTF-8
Python
false
false
57
py
import mystuff mystuff.apple() print mystuff.tangerine
[ "Y2Maker@gmail.com" ]
Y2Maker@gmail.com
c3c2826ebeb9ef75dc2b4c0a2add019a8c94cf32
27b3d59c7a37eaba49300fab3161667f2edc3ea3
/CodingBat/Python/Logic-1/love6.py
9d9db15446eaa765f03e370dfb2cd879a2c41d77
[]
no_license
robgoyal/CodeChallenges
934cf03640e9a8041caa21857b8b77cabd10863d
5f56f6cc20237ac5858fd40134b6e535a9173a0a
refs/heads/master
2021-01-15T15:27:38.285553
2016-08-30T04:42:33
2016-08-30T04:42:33
61,139,779
0
0
null
null
null
null
UTF-8
Python
false
false
244
py
#!/usr/bin/env/python # love6.py # Code written by Robin Goyal # Created on 18-08-2016 # Last updated on 18-08-2016 def love6(a, b): if (a == 6 or b == 6 or abs(a-b) == 6 or (a+b) == 6): return True else: return False
[ "robin_goyal@hotmail.com" ]
robin_goyal@hotmail.com
5f68deec102991311b8e484b3a064bf6c0f04eaf
1d0ab3c9937981b2ba6a3d37bab3bdb0a6d75c23
/strategy_mining/model_tuner.py
84c1c452abee887b4f192776485165f607bc44de
[]
no_license
darwinbeing/pytrade-1
178bbe903cd13a6f1ed9ed09a09782b450d44bb7
ca071cdeb967884fa1dc189ba9c97f307ecf2142
refs/heads/master
2021-01-22T06:54:14.554163
2016-05-12T04:05:25
2016-05-12T04:05:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,259
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import os,sys,json,datetime import numpy as np import math from math import log from sklearn import metrics,preprocessing,cross_validation from sklearn.feature_extraction.text import TfidfVectorizer import sklearn.linear_model as lm import pandas as p from time import gmtime, strftime import scipy import sys import sklearn.decomposition from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score from string import punctuation from sklearn.neighbors import RadiusNeighborsRegressor, KNeighborsRegressor import time from scipy import sparse from itertools import combinations from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, ExtraTreesClassifier import operator from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import GradientBoostingRegressor from sklearn import svm from sklearn import tree from sklearn import linear_model, metrics from sklearn.neural_network import BernoulliRBM from sklearn.pipeline import Pipeline # parse the command paramaters from optparse import OptionParser from model_base import get_date_str from model_train_base import TrainRegress from model_train_nothing import Nothing from model_train_god import God from model_train_gdbc1 import Gdbc1 import model_base as base def main(options, args): if options.utildate == None: assert(False) fsampleY = open(options.input + "/" + options.utildate + "/features.csv", "r") l_X = [] l_y = [] for line in fsampleY: tokens = line.split(",") features = [] for i in range(len(tokens)): if i < len(tokens)-1: features.append(float(tokens[i])) else: l_y.append(int(tokens[i])) l_X.append(features) print "features loaded!" X = np.array(l_X) y = np.array(l_y) assert(X.shape[0] == y.shape[0]) if int(options.short) > 0: print "using short data for test purpose" X = X[0:int(options.short)] y = y[0:int(options.short)] print "preparing models" trainModel = globals()[options.trainmodel]() print trainModel if options.isregress == True: if options.trainmodel == "Gdbc1": model_predictor = GradientBoostingRegressor(max_features=0.6, learning_rate = 0.05, max_depth=5, n_estimators=300) else: model_predictor = trainModel.get_model() else : model_predictor = GradientBoostingClassifier(max_features=0.6, learning_rate=0.05, max_depth=5, n_estimators=300) #model_predictor = GradientBoostingClassifier() X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.3, random_state=0) # print cross_validation.cross_val_score(model_predictor, X, y) clf = model_predictor.fit(X_train, y_train) if options.isregress: if options.trainmodel != "God": pred = model_predictor.predict(X_test) r2 = r2_score(y_test, pred) print "the r2 score is ", r2 else: pred = model_predictor.predict_proba(X_test) # calculate the R2score # tpred = model_predictor.predict(X_test) # score = model_predictor.score(X_test, tpred) # print "score=", score #assert(len(pred) == X_test.shape[0]) #{{{ prediction print "prediction ..." stock_predict_dir = options.output + "/"+ options.trainmodel +"/" + options.utildate if not os.path.exists(stock_predict_dir) : os.makedirs(stock_predict_dir) stock_predict_out = file(stock_predict_dir + "/predicted.csv", "w") metastr = file(options.input + "/" + options.utildate + "/meta.json", "r").readlines()[0] metajson = json.loads(metastr) for line in file(options.input + "/" + options.utildate + "/last.csv", "r"): tokens = line.split(",") l_features = [] for i in range(len(tokens)): if 0 == i: print >> stock_predict_out, "%s," % tokens[i], elif 1 == i: print >> stock_predict_out, "%s," % tokens[i], print >> stock_predict_out, "%d," % metajson["span"], else: l_features.append(float(tokens[i].strip())) l_features2 = [] l_features2.append(l_features) np_features = np.array(l_features2) if np_features.shape[1] != X.shape[1] : assert(false) if options.isregress: if options.trainmodel == "God": pred = model_predictor.predict(np_features, tokens[0], tokens[1], metajson["span"]) else: pred = model_predictor.predict(np_features) print >> stock_predict_out, "%f" % pred else: pred = model_predictor.predict_proba(np_features) print >> stock_predict_out, "%f" % pred[0,1] stock_predict_out.close() #}}} def parse_options(paraser): # {{{ """ parser command line """ parser.add_option("--input", dest="input",action = "store", default="data/prices_series/Extractor4_5/", help = "the input filename dir") parser.add_option("--output", dest="output",action = "store", default="data/prices_series/", help = "the input filename dir") parser.add_option("--short", dest="short",action = "store", default=-1, help = "using short data") parser.add_option("--utildate", dest="utildate",action = "store", default=None, help = "the last date to train") parser.add_option("--isregress", dest="isregress", action = "store_true", default=True, help = "using repgress model or classify?") parser.add_option("--trainmodel", dest="trainmodel", action = "store", default="Nothing", help = "the model class to train") return parser.parse_args() #}}} # execute start here if __name__ == "__main__": #{{{ parser = OptionParser() (options, args) = parse_options(parser) main(options, args) # }}}
[ "binred@outlook.com" ]
binred@outlook.com
2f517832d9c2beb436bf2a961ecad76ecd39ab83
4dcef270075f6b44dd8d78a23a9e8dbe5f983a6b
/tests/test_action_helper.py
5eb239cd48c593117ba31d6c117ba2c2efc626c3
[]
no_license
relusek/mgw
61f3828388fe0c4c45054be32aa8b8e2d12d2c36
544b7a34d5d5051084901e3156946ab86e836aea
refs/heads/master
2021-01-18T02:25:47.254169
2015-10-29T19:17:27
2015-10-29T19:17:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,246
py
import copy import os import sys import pytest # NOTE(prmtl): hack to allow imports of mgw.py # it should be replaced by a real life file but do we # really care about it? :) parent_dir = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, parent_dir) import mgw default_action = { 'check_if_armed': { 'default': True, 'except': [], }, 'action_interval': 0, 'threshold': 'lambda x: True', 'fail_count': 0, 'fail_interval': 0, } board_id = 1 check_test_data = ( ( { 'default': True, 'except': [], }, True ), ( { 'default': False, 'except': [], }, False ), ( { 'default': True, 'except': [board_id, ], }, False ), ( { 'default': False, 'except': [board_id, ], }, True ), ( { 'default': True, 'except': [board_id + 10, ], }, True ), ) @pytest.mark.parametrize('check_if_armed, expected', check_test_data) def test_should_check_if_armed(check_if_armed, expected): action_details = copy.deepcopy(default_action) action_details['check_if_armed'] = check_if_armed ada = mgw.ActionDetailsAdapter(action_details) assert ada.should_check_if_armed(board_id) == expected
[ "sebastian@kalinowski.eu" ]
sebastian@kalinowski.eu
25edd4be4fa0f232885138e0d5422bc1afc6fdda
8218eb20ad0edd1d60774f389a3118f4970315b1
/src/hierarchical_properties/clustering.py
c0f9346e7ad9048a9a749417ef1e8b15a419a184
[]
no_license
mona251/Intriguing-Properties-of-Contrastive-Losses
febb8a183ece5d3fbea7370a1a45e34b01f85344
6417de9841563c59552cd315755994ae5f26d9fb
refs/heads/main
2023-09-01T08:51:25.003914
2023-08-23T13:11:22
2023-08-23T13:11:22
557,820,273
3
0
null
null
null
null
UTF-8
Python
false
false
11,785
py
import cv2 as cv import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans, AgglomerativeClustering, BisectingKMeans from src.data_generation.utils import downsample_img, normalize_img def get_colors_of_clusters(n_clusters: int) -> np.ndarray: """ Gets the colors of each cluster for K-Means. Args: n_clusters: number of clusters Returns: The colors of each cluster for K-Means. """ blue = [0, 76, 153] orange = [255, 178, 102] red = [255, 102, 102] light_blue = [102, 255, 255] green = [0, 153, 76] yellow = [255, 255, 153] black = [0, 0, 0] white = [255, 255, 255] violet = [204, 153, 255] pink = [255, 153, 153] colors = [blue, orange, red, light_blue, green, yellow, violet, pink, black, white] centers = [] for i in range(n_clusters): centers.append(colors[i]) centers = np.uint8(centers) return centers def get_segmented_img(feature: np.ndarray, centers: np.ndarray, labels: np.ndarray, batch=False, plot=False) \ -> np.ndarray: """ Gets the segmented image of feature, given the centers and labels retrieved by a clustering algorithm. Args: feature: feature on which the clustering method was applied on centers: centers of the clusters labels: labels of the pixels batch: True if batch of features plot: True to plot the segmented image Returns: The segmented image. """ n_rgb_channels = 3 # convert all pixels to the color of the centroids segmented_image = centers[labels.flatten()] # reshape back to RGB image dimension if batch: segmented_image = segmented_image.reshape( feature.shape[0], feature.shape[1], feature.shape[2], n_rgb_channels) else: segmented_image = segmented_image.reshape( feature.shape[0], feature.shape[1], n_rgb_channels) if plot: # show the image plt.imshow(segmented_image) plt.show() return segmented_image def k_means_on_feature(feature: np.ndarray, n_clusters: int, max_iter=100, epsilon=0.2, attempts=10, normalize=False, n_channels=3, batch=False, plot=False) -> (np.ndarray, float): """ Applies K-Means on a feature extracted by a neural network. Args: feature: feature extracted by a neural network n_clusters: The number of clusters to form as well as the number of centroids to generate max_iter: max number of iterations after which K-Means will stop epsilon: required accuracy attempts: Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness. This compactness is returned as output. See also: https://docs.opencv.org/4.x/d1/d5c/tutorial_py_kmeans_opencv.html normalize: True if the image does not have values between 0 and 255 n_channels: number of dimensions of the vector on which to apply K-Means batch: True if batch of features plot: True to show the segmented image Returns: The image segmented with K-Means. """ if plot: # show the image plt.imshow(feature) plt.show() if normalize: min_value = 0 max_value = 255 feature = normalize_img(feature, min_value, max_value, return_int_values=True) # reshape the image to a 2D array of pixels and 3 color values (RGB) pixel_values = feature.reshape((-1, n_channels)) # convert to float pixel_values = np.float32(pixel_values) kmeans = KMeans(n_clusters=n_clusters, n_init=attempts, max_iter=max_iter, tol=epsilon).fit(pixel_values) # convert back to 8 bit values centers = get_colors_of_clusters(n_clusters=n_clusters) # get the labels array labels = kmeans.labels_ segmented_image = get_segmented_img(feature, centers, labels, batch, plot=plot) # Sum of squared distances of samples to their closest cluster center, # weighted by the sample weights if provided. compactness = kmeans.inertia_ return segmented_image, compactness def agglomerative_cl_on_feature(feature: np.ndarray, n_clusters: int, linkage='ward', normalize=False, n_channels=3, batch=False, plot=False) \ -> np.ndarray: """ Applies Agglomerative Clustering on a feature extracted by a neural network. Args: feature: feature extracted by a neural network n_clusters: The number of clusters to form as well as the number of centroids to generate linkage: type of the agglomerative clustering, default is Ward Hierarchical Clustering normalize: True if the image does not have values between 0 and 255 n_channels: number of dimensions of the vector on which to apply Agglomerative Clustering batch: True if batch of features plot: True to show the segmented image Returns: The image segmented with Agglomerative Clustering. """ if plot: # show the image plt.imshow(feature) plt.show() if normalize: min_value = 0 max_value = 255 feature = normalize_img(feature, min_value, max_value, return_int_values=True) # reshape the image to a 2D array of pixels and 3 color values (RGB) pixel_values = feature.reshape((-1, n_channels)) # convert to float pixel_values = np.float32(pixel_values) agg_ward = AgglomerativeClustering( n_clusters=n_clusters, linkage=linkage).fit(pixel_values) # convert back to 8 bit values centers = get_colors_of_clusters(n_clusters=n_clusters) # get the labels array labels = agg_ward.labels_ segmented_image = get_segmented_img(feature, centers, labels, batch, plot=plot) return segmented_image def bisecting_k_means_on_feature(feature: np.ndarray, n_clusters: int, normalize=False, n_channels=3, batch=False, plot=False) -> np.ndarray: """ Applies Bisecting K-Means, which is an iterative variant of KMeans using divisive hierarchical clustering, on a feature extracted by a neural network. Args: feature: feature extracted by a neural network n_clusters: The number of clusters to form as well as the number of centroids to generate normalize: True if the image does not have values between 0 and 255 n_channels: number of dimensions of the vector on which to apply Bisecting K-Means batch: True if batch of features plot: True to show the segmented image Returns: The image segmented with Bisecting K-Means Clustering. """ if plot: # show the image plt.imshow(feature) plt.show() if normalize: min_value = 0 max_value = 255 feature = normalize_img(feature, min_value, max_value, return_int_values=True) # reshape the image to a 2D array of pixels and 3 color values (RGB) pixel_values = feature.reshape((-1, n_channels)) # convert to float pixel_values = np.float32(pixel_values) bis_kmeans = BisectingKMeans( n_clusters=n_clusters).fit(pixel_values) # convert back to 8 bit values centers = get_colors_of_clusters(n_clusters=n_clusters) # get the labels array labels = bis_kmeans.labels_ segmented_image = get_segmented_img(feature, centers, labels, batch, plot=plot) return segmented_image def k_means_img_patch_rgb_raw(img: np.ndarray, patch_size: int, k: int, max_iter: int, epsilon: float, attempts: int, normalize: bool, weight_original_img=0.4, weight_colored_patch=0.4, gamma=0, n_channels=3, compute_also_nn_interpolation=True) \ -> (np.ndarray, np.ndarray): """ Steps: - Applies K-Means on a patch of img and upscale the result to the shape of img with bilinear interpolation - It then overlays the upscaled result of K-Means to the original image img - It can also do the first two steps using nearest neighbor interpolation if compute_also_nn_interpolation is True Args: img: original image patch_size: size of the patch of the image k: number of clusters required at end max_iter: max number of iterations after which K-Means will stop epsilon: required accuracy attempts: Flag to specify the number of times the algorithm is executed using different initial labellings. The algorithm returns the labels that yield the best compactness. This compactness is returned as output. See also: https://docs.opencv.org/4.x/d1/d5c/tutorial_py_kmeans_opencv.html normalize: True if the image does not have values between 0 and 255 weight_original_img: see https://docs.opencv.org/3.4/d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19 weight_colored_patch: see https://docs.opencv.org/3.4/d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19 gamma: see https://docs.opencv.org/3.4/d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19 n_channels = number of dimensions of the vector on which to apply K-Means n_channels: number of dimensions of the vector on which to apply K-Means compute_also_nn_interpolation: True to apply the described steps also using nearest neighbor interpolation Returns: The segmented patch of image img with K-Means upscaled with bilinear interpolation, and optionally also the segmented patch of image img with K-Means upscaled with nearest neighbor interpolation """ full_size = img.shape[0] patch = downsample_img(img, patch_size, patch_size, False) seg_patch, _ = k_means_on_feature( patch, n_clusters=k, max_iter=max_iter, epsilon=epsilon, attempts=attempts, normalize=normalize, n_channels=n_channels, plot=False) seg_full_bilinear_interp = downsample_img( seg_patch, full_size, full_size, False, interpolation_method=cv.INTER_LINEAR) # Convert the original image as grayscale image to put it in the background # to be able to put the patch (the output of Kmeans) over it in a # transparent way. # Single channel grayscale image img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # Repeat the grayscale image along all the 3 channels stacked_img = np.stack((img_gray,) * 3, axis=-1) final_img_bilinear_interp = cv.addWeighted( stacked_img, weight_original_img, seg_full_bilinear_interp, weight_colored_patch, gamma) final_img_nn_interp = None if compute_also_nn_interpolation: seg_full_nn_interp = downsample_img(seg_patch, full_size, full_size, False, interpolation_method=cv.INTER_NEAREST) final_img_nn_interp = cv.addWeighted( stacked_img, weight_original_img, seg_full_nn_interp, weight_colored_patch, gamma) return final_img_bilinear_interp, final_img_nn_interp
[ "lucamarini1998@gmail.com" ]
lucamarini1998@gmail.com
78dc61a748d062cdedaa16780063622eb8362252
287f9c6ffab205f0a290f774bff22e7bb8d1f5ac
/src/leap/bitmask_core/dispatcher.py
46b1948dae34769d384b6aa853686a8f5fd813ad
[]
no_license
kalikaneko/bitmask_core
1b85cfa09c071cc9cf53712bd86d72df42bddfe8
07736dbd52901298daf95116671b5b519af92e07
refs/heads/master
2020-12-24T16:25:03.188723
2016-03-04T04:33:35
2016-03-04T04:40:56
46,516,008
1
1
null
2016-02-16T20:07:20
2015-11-19T19:42:43
Python
UTF-8
Python
false
false
5,847
py
# -*- coding: utf-8 -*- # dispatcher.py # Copyright (C) 2016 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Command dispatcher. """ import json from twisted.internet import defer from twisted.python import failure, log # TODO implement sub-classes to dispatch subcommands (user, mail). class CommandDispatcher(object): def __init__(self, core): self.core = core def _get_service(self, name): try: return self.core.getServiceNamed(name) except KeyError: return None def dispatch(self, msg): cmd = msg[0] _method = getattr(self, 'do_' + cmd.upper(), None) if not _method: return defer.fail(failure.Failure(RuntimeError('No such command'))) return defer.maybeDeferred(_method, *msg) def do_STATS(self, *parts): return _format_result(self.core.do_stats()) def do_VERSION(self, *parts): return _format_result(self.core.do_version()) def do_STATUS(self, *parts): return _format_result(self.core.do_status()) def do_SHUTDOWN(self, *parts): return _format_result(self.core.do_shutdown()) def do_USER(self, *parts): subcmd = parts[1] user, password = parts[2], parts[3] bf = self._get_service('bonafide') if subcmd == 'authenticate': d = bf.do_authenticate(user, password) elif subcmd == 'signup': d = bf.do_signup(user, password) elif subcmd == 'logout': d = bf.do_logout(user, password) elif subcmd == 'active': d = bf.do_get_active_user() d.addCallbacks(_format_result, _format_error) return d def do_EIP(self, *parts): subcmd = parts[1] eip_label = 'eip' if subcmd == 'enable': return _format_result( self.core.do_enable_service(eip_label)) eip = self._get_service(eip_label) if not eip: return _format_result('eip: disabled') if subcmd == 'status': return _format_result(eip.do_status()) elif subcmd == 'disable': return _format_result( self.core.do_disable_service(eip_label)) elif subcmd == 'start': # TODO --- attempt to get active provider # TODO or catch the exception and send error provider = parts[2] d = eip.do_start(provider) d.addCallbacks(_format_result, _format_error) return d elif subcmd == 'stop': d = eip.do_stop() d.addCallbacks(_format_result, _format_error) return d def do_MAIL(self, *parts): subcmd = parts[1] mail_label = 'mail' if subcmd == 'enable': return _format_result( self.core.do_enable_service(mail_label)) m = self._get_service(mail_label) bf = self._get_service('bonafide') if not m: return _format_result('mail: disabled') if subcmd == 'status': return _format_result(m.do_status()) elif subcmd == 'disable': return _format_result(self.core.do_disable_service(mail_label)) elif subcmd == 'get_imap_token': d = m.get_imap_token() d.addCallbacks(_format_result, _format_error) return d elif subcmd == 'get_smtp_token': d = m.get_smtp_token() d.addCallbacks(_format_result, _format_error) return d elif subcmd == 'get_smtp_certificate': # TODO move to mail service # TODO should ask for confirmation? like --force or something, # if we already have a valid one. or better just refuse if cert # exists. # TODO how should we pass the userid?? # - Keep an 'active' user in bonafide (last authenticated) # (doing it now) # - Get active user from Mail Service (maybe preferred?) # - Have a command/method to set 'active' user. @defer.inlineCallbacks def save_cert(cert_data): userid, cert_str = cert_data cert_path = yield m.do_get_smtp_cert_path(userid) with open(cert_path, 'w') as outf: outf.write(cert_str) defer.returnValue('certificate saved to %s' % cert_path) d = bf.do_get_smtp_cert() d.addCallback(save_cert) d.addCallbacks(_format_result, _format_error) return d def do_KEYS(self, *parts): subcmd = parts[1] keymanager_label = 'keymanager' km = self._get_service(keymanager_label) bf = self._get_service('bonafide') if not km: return _format_result('keymanager: disabled') if subcmd == 'list_keys': d = bf.do_get_active_user() d.addCallback(km.do_list_keys) d.addCallbacks(_format_result, _format_error) return d def _format_result(result): return json.dumps({'error': None, 'result': result}) def _format_error(failure): log.err(failure) return json.dumps({'error': failure.value.message, 'result': None})
[ "kali@leap.se" ]
kali@leap.se
cde9e8c41184ee204fbf4f603084f018c667ea9d
4cb81903c4d07cd85d9bb8d37eab8ab399a6e276
/Array Sequences/Practice Problems/uniquechar.py
ac9f2e97f4e67e22a89c814f8168cfb1ea4cb2ad
[]
no_license
JitenKumar/Python-for-Algorithms--Data-Structures
0011881c8c8558a2e21430afc1aa7d9232392b2c
7ee8a3ef287761b00be1907c5bbad35e75c5bfd6
refs/heads/master
2020-03-18T22:02:47.673814
2018-08-05T06:07:17
2018-08-05T06:07:17
135,320,756
0
0
null
null
null
null
UTF-8
Python
false
false
477
py
''' Unique Characters in String Problem Given a string,determine if it is compreised of all unique characters. For example, the string 'abcde' has all unique characters and should return True. The string 'aabcde' contains duplicate characters and should return false. ''' # solution def unique_char(string): s = set() for i in string: if i in s: return False else: s.add(i) return True print(unique_char('ABCDEFGHI'))
[ "jitenderpalsra@gmail.com" ]
jitenderpalsra@gmail.com
33faf8462155b38ddd9b1154f5c8297b73e1268e
3eef49038fef01fa210e00fff1159f8177d94e76
/dev-docker/07-email-sender-service/backend/routes.py
095b9df3c598b9c9faf413a57213f7b72c415418
[]
no_license
rscabral/docker-studies
511f1e406021343a25d055bb40e7854b5a4d4094
a355fba93956570fd28f0fc38da3ee2c67c7f835
refs/heads/main
2023-01-19T17:17:45.240492
2020-11-20T20:00:34
2020-11-20T20:00:34
303,534,542
0
0
null
null
null
null
UTF-8
Python
false
false
375
py
from flask import Blueprint, request, jsonify from sender import Sender blueprint = Blueprint('sender', __name__) @blueprint.route('/', methods=['POST']) def sendMessage(): sender = Sender() subject = request.form['subject'] message = request.form['message'] returnedMessage = sender.sendMessage(subject=subject, message=message) return jsonify(returnedMessage)
[ "rafaelsantanacabral@gmail.coma" ]
rafaelsantanacabral@gmail.coma
01090ae466a7c03d9bc40715347e6a87454698fb
c87fb70617fe1f045d53ae4a360b1cc3d4074494
/junk-monitoring/monitor.py
13cb2abbcae87812f2317ee0a2b0f2fcd51ff26b
[]
no_license
yulyugin/helpers
eddcb6068606b41de78afcd2962da00766149df5
34a39950ef1f420c43e07aff96a6e4353a13aa98
refs/heads/main
2023-01-13T14:52:55.910061
2023-01-11T22:02:48
2023-01-11T22:02:48
212,777,181
0
0
null
null
null
null
UTF-8
Python
false
false
3,640
py
#!/usr/bin/env python3 import urllib.request import ssl from html.parser import HTMLParser import time import copy import argparse import threading class Item(): def __init__(self): self.url = None self.title = None def to_string(self): return f'{self.title} ({self.url})' def __repr__(self): return self.to_string() def __str__(self): return self.to_string() def __eq__(self, other): if self.url == other.url and self.title == other.title: return True return False class VendHTMLParser(HTMLParser): def __init__(self): super(VendHTMLParser, self).__init__() self.items = [] self.in_item = False self.in_header = False self.url_base = 'https://vend.se' def handle_starttag(self, tag, attrs): if tag == 'article': assert not self.in_item, 'Nested items?' self.in_item = True self.items.append(Item()) return if self.in_item: if tag == 'h4': self.in_header = True return if self.in_header: if tag == 'a': self.items[-1].url = self.url_base + attrs[0][1] def handle_endtag(self, tag): if tag == 'article': assert self.in_item, 'Nested items?' self.in_item = False self.url = None self.title = None if self.in_item and tag == 'h4': assert self.in_header, 'Nested header?' self.in_header = False def handle_data(self, data): if self.in_item: if self.items[-1].url and not self.items[-1].title: self.items[-1].title = data class UrlMonitor(threading.Thread): def __init__(self, url, interval): super().__init__() self.url = url self.interval = interval self.daemon = True def run(self): self.monitor_url() def get_list(self): data = urllib.request.urlopen( self.url, context=ssl._create_unverified_context()).read() parser = VendHTMLParser() parser.feed(data.decode('utf-8')) return parser.items def monitor_url(self): def get_new_items(new, current): new = copy.deepcopy(new) for c in current: try: new.remove(c) except ValueError: # It's okay for items to disappear from the new list pass return new print(f'Starting to check "{self.url}" every' f' {self.interval/60} minutes.') current = self.get_list() while True: time.sleep(self.interval) new = self.get_list() new_items = get_new_items(new, current) if new_items: print(new_items) current = new def main(): parser = argparse.ArgumentParser( description='Monitor specified URLs for new items to appear.') parser.add_argument('-i', '--interval', nargs='?', type=int, action='store', default=5 * 60, help='interval specifying how' ' often provided URLs should be checked') parser.add_argument('-u', '--url', required=True, nargs='?', type=str, action='store', help='URL to monitor') args = parser.parse_args() thread = UrlMonitor(args.url, args.interval) thread.start() thread.join() if __name__ == '__main__': try: main() except KeyboardInterrupt: print('Interrupted by user')
[ "yulyugin@gmail.com" ]
yulyugin@gmail.com
91f62217c7ebbd46b2d45992db0ba07ce6eb95da
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_197/ch36_2020_04_13_17_07_50_283710.py
6a077ebde6ef2622e4e4f67db4cfcdf80a8088b7
[]
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
111
py
def fatorial(n): resultado=1 m=1 while m<=n: resultado*=m m+=1 return resultado
[ "you@example.com" ]
you@example.com
6369983875524c118b7a4e2947ee83f556288f6c
2f9358bc68d82ef090521dd6ff91e6593108e23a
/Python/Code/20.py
36b6ccee16551b51fe626f08b6e036415f7cbeeb
[]
no_license
RithvikBhat/sangamOne-Python
c10c62ef9725227134b5a4b6b6b58821d5cbd24f
f857bae79611a0ff87eb1721e1ca0e60cee85d0e
refs/heads/main
2023-08-18T15:55:22.283271
2021-10-03T07:49:22
2021-10-03T07:49:22
412,962,267
0
0
null
null
null
null
UTF-8
Python
false
false
51
py
import calendar as cal print(cal.calendar(2021))
[ "noreply@github.com" ]
noreply@github.com