def make_hoods_quarters_averages(): hoods = cPickle.load(file("bniahood_foreclosures.pkl")) def mkquarter(fc): if not fc.dt: return None return str(fc.dt.year)+"Q"+str((fc.dt.month-1)/3) def bniahood(fc): if not getattr(fc, "bniahood", None): return None return fc.bniahood hoods = group(group(hoods, bniahood), mkquarter) avgs = {} for hood, quarters in hoods.iteritems(): quarters = sorted(list(quarters.iterkeys())) for quarter in quarters: q = hoods[hood][quarter] a = [fc.amt for fc in q if fc.amt] if not a: continue avg = sum(a) / float(len(a)) n = len(a) avgs.setdefault(hood, []).append((avg, n, quarter))
def __init__(self): self.PM = group("PM", 2, 30.0, 90.0) self.PS = group("PS", 1, 0.0, 60.0) self.ZR = group("ZR", 0, -30.0, 30.0) self.NS = group("NS", -1, -60.0, 0.0) self.NM = group("NM", -2, -90.0, -30.0) self.list_groups = [] self.list_groups.append(self.PM) self.list_groups.append(self.PS) self.list_groups.append(self.ZR) self.list_groups.append(self.NS) self.list_groups.append(self.NM) # tableau 2D pour representer les regles : axes des x la pos angulaire # axes des y la v angulaire self.rule_table = [ [-5, -5, self.NS, -5, -5], [-5, self.NS, self.ZR, self.ZR, -5], [self.NM, -5, self.ZR, -5, self.PM], [-5, self.ZR, self.ZR, self.PS, -5], [-5, -5, self.PS, -5, -5]] self.fuzzy_set_limit_angle = [(-90.0, -30.0), (-60.0, 0.0), (-30.0, 30.0), (0.0, 60.0), (30.0, 90.0)] self.angle_groups = [] self.fuzzy_set_limit_speed = [(-90.0, -30.0), (-60.0, 0.0), (-30.0, 30.0), (0.0, 60.0), (30.0, 90.0)] self.speed_groups = []
def make_hoods_quarters_averages(): hoods = cPickle.load(file("bniahood_foreclosures.pkl")) def mkquarter(fc): if not fc.dt: return None return str(fc.dt.year) + "Q" + str((fc.dt.month - 1) / 3) def bniahood(fc): if not getattr(fc, "bniahood", None): return None return fc.bniahood hoods = group(group(hoods, bniahood), mkquarter) avgs = {} for hood, quarters in hoods.iteritems(): quarters = sorted(list(quarters.iterkeys())) for quarter in quarters: q = hoods[hood][quarter] a = [fc.amt for fc in q if fc.amt] if not a: continue avg = sum(a) / float(len(a)) n = len(a) avgs.setdefault(hood, []).append((avg, n, quarter))
def run(): data = scrape() grouped_data = group(data) analysis(grouped_data) statistics(grouped_data) # define more tasks here print("Run Completed Successfully")
def find_white_points_in_gray(self, im): # if black image, this default settings return one point at (0, 0) x_line = np.array([0.0]) y_line = np.array([0.0]) thickness = np.array([0.0]) # Points beetwin color and 255 are selected color = 255 - self.cf["gray_max"] #--------------- Don't forget: y origine up left -------------# # All pixels table: filled with 0 if black, 255 if white all_pixels_table = cv2.inRange(im, color, 255) # Get a tuple(x array, y array) where points exists white_points = np.where(all_pixels_table > 0) # Convert tuple of 2 arrays to one array white_points = np.transpose(white_points) # (8, 2) # Line function y=f(x) isn't reflexive, id with one x, multiple y # For y from 0 to height, find all x of white pixel and get x average # group() is called only if white pixel in image # and white_points_xy.shape = (1, 2) minimum if white_points.shape[1] == 2: if white_points.shape[0] != 0: y_line, x_line, thickness = group(white_points, flip=False) # y_line = [0 1 3 4 5], x_line = [3 4 2 2 0] # x and y array in one array points = np.transpose(np.vstack((x_line, y_line))) return points, x_line, y_line
def sentence_sentiment(words_as_polarity): print(words_as_polarity) while any( len(phrase) > 2 or type(phrase[1]) == tuple for phrase in words_as_polarity): words_as_polarity = group(words_as_polarity) words_as_polarity = vote(words_as_polarity) print(words_as_polarity) sentiments = [] for i in range(0, len(words_as_polarity)): sentiments.append(words_as_polarity[i][1]) sentence_sentiment = sum(sentiments) if sentence_sentiment == 0: print('sentence is neutral') elif sentence_sentiment > 0: print('sentence is positive') elif sentence_sentiment < 0: print('sentence is negative') return sentence_sentiment
def create_group(self, cid): gid = self.generate_id(self.groups) g = group(cid, gid) self.groups[gid] = g self.last_created_group = g return g
def test_add_group(app): success = True app.login(username="******", password="******") app.create_group( group(name="test_group1", header="test_group1_header", footer="test_group1_footer")) app.logout()
def create_groups(self): for r_idx, row in enumerate(self.grid): for s_ind, square in enumerate(row): if square.get_is_used() and ( not (square.get_has_been_added_to_group())): my_group = group() self.fill_group(square, my_group) self.groups.append(my_group)
def max_consecutive(example_list): resulting_list = group(example_list) max_count = 0 for current_list in resulting_list: if len(current_list) > max_count: max_count = len(current_list) print(resulting_list) return max_count
def hexagon(): hex = group() for n in range(5): side = hexagon_side() set_transform(side, rotation_y(n * pi / 3)) add_child(hex, side) return hex
def createComunity(userInst,userList): name = input("Me diz o nome da panelinha: ") desc = input("Aproveita e joga uma descrição na roda: ") new = group.group(name, desc, userInst) att = attempt(userList.addCommunity, new) if (att == "Community name already in use"): print("Esse nome já tem! Pega outro.") else: print("Prooonto, agora pode fofocar à vontade.")
def __init__(self, remoteShell, domainAdmin="admin", domain=None): self.remoteShell = remoteShell self.vastoolPath = "/opt/quest/bin/vastool" self.domainAdmin = domainAdmin self.defaultDomain = domain self.info = info.info(self.run) self.flush = flush.flush(self.run) self.create = create.create(self.run, self.defaultDomain) self.delete = delete.delete(self.run) self.timesync = timesync.timesync(self.run) self.nss = nss.nss(self.run) self.group = group.group(self.run) self.isvas = isvas.isvas(self.run) self.list = list.list(self.run) self.auth = auth.auth(self.run, self.defaultDomain) self.cache = cache.cache(self.run) self.configure = configure.configure(self.run) self.configureVas = configureVas.configureVas(self.run) self.schema = schema.schema(self.run) self.merge = merge.merge(self.run) self.unmerge = unmerge.unmerge(self.run) self.user = User.user(self.run) self.ktutil = ktutil.ktutil(self.run) self.load = load.load(self.run) self._license = License.License(self.run) self.License = self._license.License self.parseLicense = self._license.parseLicense self.compareLicenses = self._license.compareLicenses #self.vasUtilities = vasUtilities.vasUtilities(self.remoteShell) self.unconfigure = unconfigure.unconfigure(self.run) self.nssdiag = nssdiag(self.run) isinstance(self.info, info.info) isinstance(self.flush, flush.flush) isinstance(self.create, create.create) isinstance(self.delete, delete.delete) isinstance(self.timesync, timesync.timesync) isinstance(self.nss, nss.nss) isinstance(self.group, group.group) isinstance(self.isvas, isvas.isvas) isinstance(self.list, list.list) isinstance(self.auth, auth.auth) isinstance(self.cache, cache.cache) isinstance(self.configure, configure.configure) isinstance(self.configureVas, configureVas.configureVas) isinstance(self.schema, schema.schema) isinstance(self.merge, merge.merge) isinstance(self.unmerge, unmerge.unmerge) isinstance(self.user, User.user) isinstance(self.ktutil, ktutil.ktutil) isinstance(self.load, load.load) #isinstance(self.vasUtilities, vasUtilities.vasUtilities) isinstance(self.unconfigure, unconfigure.unconfigure) isinstance(self.nssdiag, nssdiag)
def get_routes_from_file(self): with open(self.ROUTES_FILE, 'r') as fl: for data in fl: if len(data) > 1: data = data.replace('\n', '') split = data.split('|') group_name = split[0] if group_name not in self.groups.iterkeys(): self.groups[group_name] = (group( group_name, self.COOKIE_ROOT)) new_route = route(group_name, data, self.short) self.groups[group_name].routes.append(new_route)
def make_hoods_json(): hoods = cPickle.load(file("bniahood_foreclosures.pkl")) bniahoods = cPickle.load(file("bnia_hoods_centers.pkl")) def bniahood(fc): if not getattr(fc, "bniahood", None): return None return fc.bniahood #group by hood, then just count per hood values and calc an avg hoods = group(hoods, bniahood) hood_lens = dict((k, (len(v), len(v) and float(sum(vv.amt for vv in v if vv.amt))/len(v))) for k,v in hoods.iteritems() if k) for hood, v in hood_lens.iteritems(): bh = bniahoods[hood] hood_lens[hood] = (v[0], v[1], bh[0], bh[1], bh[2], clean_hood_name(hood)) simplejson.dump(hood_lens, file("hoods.json", "w"))
def concatenate_and_group(points_L, points_R): # If only one point, shape=(2,) not (1, 2) # I replace this point with array (1, 2) fill with 0 if points_L.shape == (2,): points_L = np.zeros((1, 2)) if points_R.shape == (2,): points_R = np.zeros((1, 2)) # Concatenate points_L and points_R points_LR = np.concatenate((points_L, points_R)) # Group points on the same b with point[b, a] y_line, x_line, thickness = group(points_LR, flip=True) # x and y array in one array points_new = np.transpose(np.vstack((x_line, y_line))) return points_new
def fun_page(page_id, onoma): pp = Pool(50) mega_list = [] start = time.time() pst = p(page_id, access_token) n = 50 group_post = group(pst, n) temp = 0 for j in group_post: temp += len(j) print(str(temp) + '/' + str(len(pst))) re = pp.map(pros, list(j)) for jj in re: mega_list.append(jj) duration = (time.time() - start) / float(60) print("Time:" + str(duration) + 'min') with open(onoma, 'w') as f: json.dump(mega_list, f) return mega_list
def make_hoods_json(): hoods = cPickle.load(file("bniahood_foreclosures.pkl")) bniahoods = cPickle.load(file("bnia_hoods_centers.pkl")) def bniahood(fc): if not getattr(fc, "bniahood", None): return None return fc.bniahood #group by hood, then just count per hood values and calc an avg hoods = group(hoods, bniahood) hood_lens = dict( (k, (len(v), len(v) and float(sum(vv.amt for vv in v if vv.amt)) / len(v))) for k, v in hoods.iteritems() if k) for hood, v in hood_lens.iteritems(): bh = bniahoods[hood] hood_lens[hood] = (v[0], v[1], bh[0], bh[1], bh[2], clean_hood_name(hood)) simplejson.dump(hood_lens, file("hoods.json", "w"))
def client_group_join(group_name, client): conn = client["CONN"] addr = client["ADDR"] group_exists = False group_is_member = False group_index = 0 for group_i in GROUPS: if group_name == group_i.get_group_name(): group_exists = True for member in group_i.get_members(): if conn == member["CONN"]: group_is_member = True break if group_is_member == False: group_i.add_member(conn, addr) break if not group_exists: new_group = group.group(group_name) new_group.add_member(conn, addr) GROUPS.append(new_group) if group_is_member: message = "User is already member of this group. You can't join a group that you're already a member of." send_error(message, client)
def find_white_points_in_gray(cf, im): # if black image, this default settings return one point at (0, 0) x_line = np.array([0.0]) y_line = np.array([0.0]) thickness = np.array([0.0]) color = 255 - cf["gray_max"] #--------------- Don't forget: y origine up left -------------# im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) # All pixels table: filled with 0 if black, 255 if white try: # Only if im isn't black all_pixels_table = cv2.inRange(im, color, 255) except: # If black image, set empty array all_pixels_table = np.asarray([]).reshape(0, 3) # Get a tuple(x array, y array) where points exists white_points = np.where(all_pixels_table > 0) # Convert tuple of 2 arrays to one array white_points = np.transpose(white_points) # (8, 2) # Line function y=f(x) isn't reflexive, id with one x, multiple y # For y from 0 to height, find all x of white pixel and get x average # group() is called only if white pixel in image # and white_points_xy.shape = (1, 2) minimum if white_points.shape[1] == 2: if white_points.shape[0] != 0: y_line, x_line, thickness = group(white_points, flip=False) # y_line = [0 1 3 4 5], x_line = [3 4 2 2 0] # x and y array in one array points = np.transpose(np.vstack((x_line, y_line))) # x_line, y_line only to plot return points, x_line, y_line
def GetGroup(): if 'group' not in g: g.group = group() return g.group
def compute_3D(cf, index, points_L, points_R, points): ''' Compute one frame: From 2D frame points coordinates left and right, - add left and right - get average - compute x y z of this point See sheme at: points = nparray(3, points_number) = all 3D points previously calculated points_L and points_R = nparray(2, points_number) = points in frame index = right frame number Return new points array ''' # Time start in this function tframe = time() ############################ TODO j'aime pas! height = cf["height"] width = cf["width"] scale = cf["scale"] # Points under mini and upper maxi are deleted mini = cf["z_down"] maxi = height - cf["z_up"] z_scale = cf["z_scale"] # Angles step = cf["nb_img"] angle_step = 2 * np.pi / step alpha = cf["ang_rd"] sin_cam_ang = np.sin(alpha) teta = angle_step * index # Perspective correction ph = cf["persp_h"] pv = cf["persp_v"] tg_alpha = 0.2 if ph != 0: tg_alpha = pv / ph print("Perspective: Tangente alpha = {0}".format(tg_alpha)) ############################ # Create empty array to fill with frame points 3D coordinates frame_points = np.asarray([]).reshape(0, 3) # Problem if only one point # TODO if one real point, it will be replace with 0, 0 if points_L.shape == (2,): points_L = np.zeros((1, 2)) if points_R.shape == (2,): points_R = np.zeros((1, 2)) # Concatenate points_L and points_R points_LR = np.concatenate((points_L, points_R)) # Group points on the same b with point[b, a] y_line, x_line, thickness = group(points_LR, flip=True) # x and y array in one array points_new = np.transpose(np.vstack((x_line, y_line))) # Number of points in frame nb = points_new.shape[0] # For all points (x, y) in txt file for pt in range(nb): # a_raw, b_raw = point coordinates in image with origine up, left a_raw = points_LR[pt][0] b_raw = points_LR[pt][1] AM = width/2 - a_raw if -300 < AM < 300: # Delete background laser line # Point position from turn table center OM = AM / sin_cam_ang FM = height - b_raw v = (height / 2) - b_raw a0 = -2* tg_alpha / height tg_beta = a0 * v OG = FM + AM * tg_beta if mini < OG < maxi: # Changement de repère orthonormé x = np.cos(alpha - teta) * OM * scale y = np.sin(alpha - teta) * OM * scale z = OG * scale * z_scale # Add this point frame_points = np.append(frame_points, [[x, y, z]], axis=0) points = np.append(points, frame_points, axis=0) tfinal = int(1000*(time() - tframe)) print(("Frame {0} compute in {1} milliseconds, {2} points founded".format(\ index, tfinal, frame_points.shape[0]))) return points
[[0, 1, 0, 0], [-1, 1, 0, 0], [0, 0, 1, 0.5]], [[1, -1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0.5]], [[0, -1, 0, 0], [-1, 0, 0, 0], [0, 0, 1, 0]], [[-1, 1, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]], [[1, 0, 0, 0], [1, -1, 0, 0], [0, 0, 1, 0]], [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0.5]], [[1, -1, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0.5]], [[-1, 0, 0, 0], [-1, 1, 0, 0], [0, 0, 1, 0.5]]] gk = [] for i in g: tmp = element() tmp.init(i) gk.append(tmp) #''' G = group() G.init(gk) print("multiply table: ", G.mtable) cl = G.find_class() print("class: ", cl) elist = G.subset_product(cl[1], cl[2]) print("element list: ", elist) H = G.class_mul_constants() #print("class multiply constants",H) #''' ''' character_table = G.burnside_class_table() np.set_printoptions(precision=3) print("character table: ",character_table)
chrome_profiles = { "linux": '/home/{}/.config/google-chrome/default'.format(user), "mac": '/Users/{}/Library/Application Support/Google/Chrome/Default'.format( user), "windows": 'C:\\Users\\{}\\AppData\\Local\\Google\\Chrome\\User Data\\Default'. format(user) } # Set options and use cache of the chrome browser options = webdriver.ChromeOptions() if args.cache: options.add_argument('--user-data-dir=' + chrome_profiles[args.system]) options.add_argument('--profile-directory=Default') # open chrome and whatsapp chrome = webdriver.Chrome(driver_path, options=options) chrome.get("https://web.whatsapp.com/") print("press ENTER once whatsapp has loaded.") input("") group_name = args.name open_chat(group_name) group = group(group_name, chrome) print(group.name, group.birth, group.desc, group.size) while not stop: group.read_latest_msg(chrome)
print("{:s}:{:s} = {:n}".format(p1, p2, group_mate_factor)) # increment both people's grouping factor with each other history_df.set_value( p1, p2, history_df.loc[p1, p2] + group_mate_factor) history_df.set_value( p2, p1, history_df.loc[p2, p1] + group_mate_factor) # Create Groups logging.info("## Initial Group Placements") num_groups = math.floor(num_people / target_group_size) logging.info("Making {:n} groups".format(num_groups)) # Make the groups for i in range(num_groups): new_g = group(history_df) current_group_set.append(new_g) people_to_place = all_people """ For however many people there are to place, loop through the groups and put a random person in each group until there are no more people to place. """ logging.info("{:n} people to place".format(len(people_to_place))) for i in range(num_people): current_g = current_group_set[i % num_groups] # Pick a random person and remove them from people_to_place p_rand = randrange(len(people_to_place)) p = people_to_place.pop(p_rand) # Add them to the current group
if __name__ == '__main__': from group import group else: from .group import group #from .Worker import group group=group() def main(): menu = {"1":("Add Seller", group.insertSeller), "2":("Add Manager", group.insertManager), "3":("Add Cleaner", group.insertCleaner), "4":("Special action", group.execute), "5":("Edit", group.edit), "6":("Delete", group.delete), "7":("Show", group.show), "8":("Read in file", group.readfile), "9":("Write in file", group.writefile), "10":("Clean", group.clean), "11":("Exit", None)} while True: print('') print('Menu:') for k in range(1,12): print(k, " : ", menu[str(k)][0]) x = input() if int(x)==11: break if int(x) >= 1 and int(x) < 12: menu[x][1]()
def add_group(self, program): my_group = group() if(not self.has_been_visited(program)): self.add_to_group(program,my_group) self.groups.append(my_group)
def hexagon_side(): side = group() add_child(side, hexagon_corner()) add_child(side, hexagon_edge()) return side
def step_impl(context): context.g2 = group()
for g in nets: g.fitness += 5 pipes.append(Pipe(WIN_WIDTH)) for r in rem: pipes.remove(r) for x, bird in enumerate(birds): if bird.y + bird_images[0].get_height() - 10 >= FLOOR or bird.y < 0: birds.pop(x) nets.pop(x) base.move() draw_window(WIN, birds, pipes, base, score, gen) if __name__ == '__main__': g = group(20, fitness, 3, 5, 1, 0.01) g = group(20, fitness, 3, 5, 1, False, 0.01, 0.2, 0.5, 3, save_to_file=True) g.run()
def max_consecutive(items): return max([len(x) for x in [x for x in group(items)]])
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from openmdao.api import Problem, ScipyOptimizeDriver, view_model from openmdao.api import pyOptSparseDriver from group import group prob = Problem() prob.model = group() prob.model.add_design_var('x') prob.model.add_constraint('C', equals=0) prob.model.add_objective('obj') # prob.driver = ScipyOptimizeDriver() # prob.driver.options['optimizer'] = 'SLSQP' prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = 'SNOPT' # prob.driver.options['tol'] = 1e-9 # prob.driver.options['obj'] = True prob.setup() prob.run_model() prob.run_driver() print(prob['obj']) print(prob['C']) print(prob['x'])
[[0, -1, 0, 0], [-1, 0, 0, 0], [0, 0, 1, 0]], [[-1, 1, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]], [[1, 0, 0, 0], [1, -1, 0, 0], [0, 0, 1, 0]], [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0.5]], [[1, -1, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0.5]], [[-1, 0, 0, 0], [-1, 1, 0, 0], [0, 0, 1, 0.5]] ] gk = [] for i in g: tmp = element() tmp.init(i) gk.append(tmp) #''' G = group() G.init(gk) print("multiply table: ", G.mtable) cl = G.find_class() print("class: ",cl) elist = G.subset_product(cl[1],cl[2]) print("element list: ",elist) H = G.class_mul_constants() #print("class multiply constants",H) #''' ''' character_table = G.burnside_class_table() np.set_printoptions(precision=3) print("character table: ",character_table)
def main(): group().f()
#! /usr/bin/env python2 """ This is the ORIGINAL FILE THAT IS GOING TO BE USED. Please copy any changes made to this file to the backup file, create new file for each version and update the current version that is used here. Version 1.2 """ import ari import logging import threading from group import group logging.basicConfig() client = ari.connect('http://localhost:8088', 'asterisk', 'asterisk') #Create the object of the classes grp = group(client) def ari_start(grup): #Set the listener for Asterisk ARI client.on_channel_event('StasisStart', grup.stasis_start) client.on_channel_event('StasisEnd', grup.stasis_end) #Run the app for asterisk, for easy config, I use channel-dump as all of the app name client.run(apps='channel-dump') ari_start(grp)
def obj_to_group(parser): g = group() for grp in parser.groups.values(): for tri in grp: g.children.append(tri) return g
total=filenum, desc="shingling"): pass # compare signatures results = [] for s in tqdm(p.imap_unordered(hashcount_wrapper, range(1, filenum), chunksize=100), total=filenum - 1, desc="comparing"): if s is not None: updated = False for r in results: if len(r.intersection(s)) > 0: r.update(s) updated = True break if updated is False: results.append(s) results = group.group(results) count = 0 for s in results: count += len(s) for index in s: print(files[index], end='\n') print("---") print("%d files in %d groups" % (count, len(results)))
new_ground.draw() clouds.draw(screen) scb.draw() if high_score != 0: highsc.draw() screen.blit(HI_image, HI_rect) cacti.draw(screen) pteras.draw(screen) for dino in dinos: dino.update() dino.draw() pygame.display.update() clock.tick(FPS) if __name__ == '__main__': g = group(51, gameplay, 7, 14, 2, False, 0.04, 0.2, 0.5, 3, save_to_file=True) g.run()
def max_consecutive(items): return max([len(item) for item in group(items)])
if __name__ == '__main__': from group import group else: from .group import group gr = group() Menu = [["0 - Выход", None], ["1 - Добавить объект типа 'студент'", gr.addStudent], ["2 - Добавить объект типа 'староста'", gr.addStarosta], ["3 - Добавить объект типа 'профорг'", gr.addProforg], ["4 - Вывести список учеников", gr.show_list], ["5 - Изменить данные ученика", gr.change], ["6 - Удалить ученика из списка группы", gr.delete_card], ["7 - Сохранить список группы в файл", gr.write_file], ["8 - Считать список группы из файла", gr.read_file]] def menu(): print() print("Меню программы:") for i, item in enumerate(Menu): print(f'{item[0]}') print() return int(input('Введите номер пункта меню: ')) def main(): try: while True: