blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
abf8cc5b7dd5d9f13c1117c13dd24f9fae68202e
Python
PauloVilarinho/algoritmos
/problemas uri/Problema1289.py
UTF-8
323
3
3
[]
no_license
quantity = int(input()) for i in range (quantity): lista = input().split() n = int(lista[0]) p = float(lista[1]) j = int(lista[2]) q = (1-p)**(n) a1 = ((1-p)**(j-1))*p if 0<p<1 : probabilidade = a1/(1-q) elif p==1 and j==1 : probabilidade = 1.0000 else: probabilidade = 0.0000 print("%.4f" %probabilidade)
true
959c12e8acb5dfeb5d814d3896f6492e86ba9591
Python
BasiaKo/ZaliczenieSelenium
/pages/strona_zapytaj.py
UTF-8
1,513
2.625
3
[]
no_license
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver import ActionChains from locators import Strona_Zapytaj_Lokatory class StronaZapytaj: def __init__(self, driver): self.driver=driver def refresh(self): self.driver.refresh() def zweryfikuj_strone(self): self.driver.implicitly_wait(50) title="Ktomalek - Zapytaj farmaceutę" assert title==self.driver.title def wpisz_pytanie(self, pytanie): WebDriverWait(self.driver,50).until(EC.presence_of_element_located(Strona_Zapytaj_Lokatory.input_pytanie)).send_keys(pytanie) def kliknij_wyslij(self): WebDriverWait(self.driver,50).until(EC.element_to_be_clickable(Strona_Zapytaj_Lokatory.btn_wyslij)).click() def wyslij_pytanie(self): WebDriverWait(self.driver,50).until(EC.element_to_be_clickable(Strona_Zapytaj_Lokatory.btn_wyslij_pytanie)).click() def sprawdz_walidacja_dlugosci(self, error_info): error=self.driver.find_element(*Strona_Zapytaj_Lokatory.pole_walidacja_dlugosci) if error.is_displayed(): error=error.text.strip() print(error + ";" + error_info) assert error==error_info def sprawdz_walidacja_zgoda(self, error_info): error=self.driver.find_element(*Strona_Zapytaj_Lokatory.pole_walidacja_zgoda) if error.is_displayed(): error=error.text.strip() assert error==error_info
true
8da27209396f64dfb4c4b8cac9966a516275a788
Python
napo/osm_civici_trento
/get_street_names_comuni.py
UTF-8
1,282
2.53125
3
[]
no_license
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Sep 19 10:21:11 2017 @author: daniele """ import csv import sqlite3 import time def main(): db = '../db.sqlite' connection = sqlite3.connect(db) connection.row_factory = sqlite3.Row connection.enable_load_extension(True) cursor = connection.cursor() cursor.execute('SELECT load_extension("mod_spatialite")') start_time = time.time() csvfile = open("vie_comune_osm.csv", "w") filewriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(["Via comune", "Via osm"]) nn = list() with open("civici_comuni.csv") as f: filereader = csv.reader(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) f.readline() for r in filereader: if r[2] not in nn: q = "SELECT desvia FROM civici_prov WHERE pk_uid = " + str(r[0]) cursor.execute(q) rs = cursor.fetchone() if rs != None: filewriter.writerow([rs["desvia"], r[4]]) nn.append(r[2]) end_time = time.time() print "Tempo impiegato : ", end_time - start_time if __name__ == "__main__": main()
true
b5e1072cd714d974b9acfd59c4501ca4df001139
Python
alrivero/histogram_equalization
/equalize.py
UTF-8
1,444
3.140625
3
[]
no_license
import cv2 import sys from histogram_equalization import block_histogram_equalization, global_histogram_equalization from getopt import getopt def equalize_img(): # Use getopt to gather our arguments img_name = None result_path = None block_size = 0 opts, args = getopt(sys.argv[1:], "s:b:i:") for opt, arg in opts: if opt == "-b": block_size = int(arg) elif opt == "-s": result_path = arg elif opt == "-i": img_name = arg # Determine if global or block histogram equalization is occcuring and # proccess the image img = cv2.imread(img_name) if img is None: print("Image Error!") return if block_size == 0: equalized_img = global_histogram_equalization(img) else: equalized_img = block_histogram_equalization( img, (block_size, block_size)) # If necessary, save the resulting image if result_path is not None: cv2.imwrite(result_path, equalized_img) # Display the resulting image at a quarter of its size cv2.imshow("Equalized Image", cv2.resize( equalized_img, (int(img.shape[1] * 0.25), int(img.shape[0] * 0.25)))) cv2.imshow("Original Image", cv2.resize( img, (int(img.shape[1] * 0.25), int(img.shape[0] * 0.25)))) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": equalize_img()
true
91aa892e672aed7692b323253d529987c83fc19d
Python
aly50n/Python-Algoritmos-2019.2
/lista05ex03.py
UTF-8
199
3.890625
4
[]
no_license
vetor = [""] * 10 cont=0 for i in range(10): vetor[i]= int(input("Digite um valor inteiro: ")) if vetor[i] % 2 == 0: cont= cont+1 print("Dos valores do seu vetor", cont, "são pares")
true
0d0f726b0b494b84ca9b022c43dcc7c1b4875b1f
Python
luisgcastillos/LogoGenerator
/LogoGenerator.py
UTF-8
1,447
2.953125
3
[]
no_license
import svgwrite import argparse import string import os def pattern(name, logoText): dwg = svgwrite.Drawing(name, size=('20cm', '10cm'), profile='full', debug=True) #We use dwg.g to use different style fonts, this can be done using the css classes dir = os.path.dirname(__file__) filename = os.path.join(dir, 'Fonts.css') # set user coordinate space dwg.viewbox(width=200, height=150) dwg.add_stylesheet(filename, title="sometext") # same rules as for html files g = dwg.g(class_="myclass") g.add(dwg.text(logoText, insert=(10,30))) dwg.add(g) pattern = dwg.defs.add(dwg.pattern(size=(20, 20), patternUnits="userSpaceOnUse")) #We want to find icons that are of a similar meaning to Bail Bonds... handcuffs, jail, freedom. #We want to generate logos with different font styles using google font apis pattern.add(dwg.circle((10, 10), 5)) dwg.add(dwg.circle((100, 100), 50, fill=pattern.get_paint_server())) dwg.add(dwg.text(logoText,None, [40], [50])) dwg.save() #if we want this to be a genetic algorithm, how would we define a fitness function? #Well it wouldnt really apply to font style choice, but it might apply to location of text and logo if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('CompanyName', type=str) args = parser.parse_args() CompanyName = args.CompanyName pattern("pattern.svg", CompanyName)
true
64725c4b2ad5f80cedf9b14300af7e1951798ce3
Python
taylor-swift-1989/PyGameExamplesAndAnswers
/examples/minimal_examples/pygame_minimal_math_curve_sine.py
UTF-8
3,669
3.03125
3
[]
no_license
# pygame.math module # https://www.pygame.org/docs/ref/math.html # # Sine # https://en.wikipedia.org/wiki/Sine # # Gaps in a line while trying to draw them with a mouse problem # https://stackoverflow.com/questions/56379888/gaps-in-a-line-while-trying-to-draw-them-with-a-mouse-problem/56380523#56380523 # # GitHub - PyGameExamplesAndAnswers - Math and Vector - Curve - Lissajous curve # https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/pygame/pygame_math_vector_and_reflection.md import pygame import math import fractions pygame.init() window = pygame.display.set_mode((800, 600)) font20 = pygame.font.SysFont(None, 20) def draw(rect, center, vector, radius, currentPoint, axisColor, lineColor, curveColor): circlePt = round(center[0] + vector[0] * radius), round(center[1] + vector[1] * radius) xa = window.get_width() // 3 yb = window.get_height() // 2 curPt = (currentPoint[0] + xa, currentPoint[1] + yb) pygame.draw.line(window, axisColor, (xa, rect.top), (xa, rect.bottom), 1) pygame.draw.line(window, axisColor, (rect.left, rect.centery), (rect.right, rect.centery), 1) pygame.draw.circle(window, lineColor, center, radius, 3) pygame.draw.line(window, lineColor, (rect.left, circlePt[1]), (rect.right, circlePt[1]), 1) pygame.draw.line(window, lineColor, (circlePt[0], center[1]), circlePt, 1) pygame.draw.line(window, lineColor, center, circlePt, 1) pygame.draw.line(window, lineColor, curPt, (curPt[0], center[1]), 1) threshold = 10 for i in range(len(points)): dist_p = 0 if i==0 else points[i][0]-points[i-1][0] dist_s = 0 if i>len(points)-2 else points[i+1][0]-points[i][0] pt = (points[i][0] + xa, points[i][1] + yb) if dist_p > threshold and dist_s > threshold: pygame.draw.circle(window, curveColor, pt, 6, 0) elif 0 < dist_p < threshold: pygame.draw.line(window, curveColor, (points[i-1][0] + xa, points[i-1][1] + yb), pt, 2) lastQ, q, rotCount = 3, 0, -1 radius = 100 points = [] run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: lastQ, q, rotCount = 3, 0, -1 points = [] mouse = pygame.mouse.get_pos() rect = window.get_rect().inflate(-80, -80) center = (rect.centerx // 3, rect.centery) vector = (mouse[0]-center[0], mouse[1]-center[1]) distance = math.hypot(vector[0], vector[1]) normVector = vector if distance > 0: normVector = vector[0] / distance, vector[1] / distance vector = normVector[0] * radius, normVector[1] * radius angle = math.degrees(math.atan2(-normVector[1], normVector[0])) if angle < 0: angle += 360 q = angle // 90 if q == 0 and lastQ == 3: rotCount += 1 elif q == 3 and lastQ == 0: rotCount -= 1 lastQ = q angle = angle + 360 * rotCount sinC = round(normVector[1] * radius) point = (round(angle * (5/9)*3), sinC) if not any([x for x in points if x==point[0]]): points.append(point) points = sorted(points, key = lambda p : p[0]) text1 = font20.render(f"Angle: {angle: 0.3f}°", 2, (0, 0, 0)) text2 = font20.render(f"Sine: {vector[1]: 0.3f}", 2, (0, 0, 0)) window.fill((255, 255, 255)) window.blit(text1, (rect.left, rect.top+50)) window.blit(text2, (rect.left, rect.top+80)) draw(rect, center, normVector, radius, point, (0, 0, 0), (127, 127, 127), (255, 0, 0)) pygame.display.flip() pygame.quit() exit()
true
671ed4a3811204db7adf62ae35922cc8fdf4d054
Python
axetang/AxePython
/60days/17.py
UTF-8
2,316
4.0625
4
[ "Apache-2.0" ]
permissive
# Day 17:Python 列表生成式高效使用的 12 个案例 # Python 里使用 [] 创建一个列表。容器类型的数据进行运算和操作,生成新的列表最高效的办法——列表生成式。 from math import floor import os from random import random a = range(0, 11) b = [x**2 for x in a] print(b) c = [str(x) for x in a] print(c) a = [round(random(), 2) for _ in range(10)] print(a) a = range(11) d = [x**2 for x in a if x % 2 == 0] print(d) a = [i*j for i in range(1, 10) for j in range(1, i+1)] print(a) a = range(5) print(a) b = ['a', 'b', 'c', 'd', 'e'] c = [str(y)+str(x) for x, y in zip(a, b)] x = zip(a, b) print(type(x), x) print(c) a = {'a': 1, 'b': 2, 'c': 3} # b = [k+'='+v for k, v in a.items()] b = [k+'='+str(v) for k, v in a.items()] print(b) a = [d for d in os.listdir("./")] print(a) dirs = [d for d in os.listdir("./") if os.path.isdir(d)] print(dirs) fs = [f for f in os.listdir("./") if os.path.isfile(f)] print(fs) a = ["Hello", "World", "AXe", 2020] b = [str(w).lower() for w in a] print(b) c = [w.lower() for w in a if isinstance(w, str)] print(c) def filter_non_unique(lst): return [item for item in lst if lst.count(item) == 1] uni = filter_non_unique([1, 2, 3, 3, 5, 8, 1, 6, 9, 2, 4, 6]) print(uni) def bifurcate(lst, filter): return [ [x for i, x in enumerate(lst) if filter[i] == True], [x for i, x in enumerate(lst) if filter[i] == False] ] bif = bifurcate(['beep', 'boop', 'bar', 'foo'], [True, True, False, True]) print(bif) def bifurcate_by(lst, fn): return [ [x for x in lst if fn(x)], [x for x in lst if not fn(x)] ] bif_by = bifurcate_by( ['Python3', 'up', 'users', 'people'], lambda x: x[0] == 'u') print(bif_by) def difference(a, b): _a, _b = set(a), set(b) return [item for item in _a if item not in _b] dif = difference([1, 1, 2, 3, 3], [1, 2, 4]) print(dif) # from math import floor def difference_by(a, b, fn): _b = set(map(fn, b)) print("type(map(fn,b)) is ", type(map(fn, b)), map(fn, b)) print("type(_b) is ", type(_b), "_b:", _b) return [item for item in a if fn(item)not in _b] dif_by = difference_by([2.1, 1.2], [2.3, 3.4], floor) print(dif_by) dif_by = difference_by([{'x': 2}, {'x': 1}], [{'x': 1}], lambda v: v['x']) print(dif_by)
true
43a6359d5bec575f68f1a318155cf322ea3443e2
Python
Nithesh-Wayne/ML
/e14.py
UTF-8
707
2.53125
3
[]
no_license
import numpy as np from sklearn import preprocessing,neighbors from sklearn.model_selection import train_test_split import pandas as pd df=pd.read_csv('breast-cancer-wisconsin.data') df.replace('?', -99999,inplace=True) df.drop(['id'],1,inplace=True) X=np.array(df.drop(['class'],1)) y=np.array(df['class']) X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2) clf=neighbors.KNeighborsClassifier() clf.fit(X_train,y_train) accuracy=clf.score(X_test,y_test) print(accuracy) example_measures=np.array([[4,2,1,1,1,2,3,2,1],[4,2,1,1,1,2,3,2,1]]) example_measures=example_measures.reshape(len(example_measures),-1) prediction=clf.predict(example_measures) print(prediction) #check for branch
true
f1d2e07fa35dc2b2077ca3ee8c9578bb38b1a0d7
Python
mattpiccolella/StreetlightsBackendAPI
/models.py
UTF-8
2,019
2.8125
3
[]
no_license
from flask.ext.sqlalchemy import SQLAlchemy from datetime import datetime, timedelta db = SQLAlchemy() class User(db.Model): __tablename__ = 'users' uid = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(100)) email = db.Column(db.String(120), unique=True) password = db.Column(db.String(100)) biography = db.Column(db.String(150)) stream_items = db.relationship('StreamItem', backref='user', lazy='dynamic') def __init__(self, name, email, password, biography): self.name = name.title() self.email = email.lower() self.password = password self.biography = biography def toJSON(self): json = {} json['user_id'] = self.uid json['name'] = self.name return json class StreamItem(db.Model): __tablename__ = 'streamitems' stream_item_id = db.Column(db.Integer, primary_key = True) description = db.Column(db.String(150)) latitude = db.Column(db.Float) longitude = db.Column(db.Float) user_id = db.Column(db.Integer, db.ForeignKey('users.uid')) created = db.Column(db.DateTime) expiration = db.Column(db.DateTime) def __init__(self, description, latitude, longitude, user_id, expiration_minutes): self.description = description self.latitude = latitude self.longitude = longitude self.user_id = user_id self.created = datetime.now() self.expiration = self.created + timedelta(minutes = int(expiration_minutes)) def toJSON(self): json = {} json['stream_item_id'] = self.stream_item_id json['description'] = self.description json['latitude'] = self.latitude json['longitude'] = self.longitude json['created'] = unix_time_millis(self.created) json['expiration'] = unix_time_millis(self.expiration) return json def unix_time_millis(dt): epoch = datetime.utcfromtimestamp(0) delta = dt - epoch return delta.total_seconds()
true
9516be410b2bbda062777b1e7dc7fecf13a242cb
Python
aungminko93750/lira
/lira/parsers/nodes.py
UTF-8
5,968
3.125
3
[ "MIT" ]
permissive
from copy import copy from lira.validators import TestBlockValidator, get_validator_class def _get_attributes_proxy(attributes, **values): class AttributesProxy: __slots__ = attributes def __init__(self, **kwargs): for item, value in kwargs.items(): setattr(self, item, value) return AttributesProxy(**values) class Node: """ Base class for a node. :param content: Content for this node (usually only for terminal nodes). :param children: List of children. :param attributes: Dictionary of valid attributes. If it's a terminal node, it doesn't have children. Only attributes from `valid_attributes` are recognized. """ is_terminal = False """If it's a terminal node (without children)""" valid_attributes = set() """A set of valid attributes for this node.""" def __init__(self, content=None, *, children=None, attributes=None): if self.is_terminal and children: raise ValueError("A terminal node can't have children") if not self.is_terminal and content: raise ValueError("A no terminal node can't have content") self.content = content """Raw content of the node""" self.children = children or [] """List of children of this node.""" attributes = attributes or {} self.attributes = _get_attributes_proxy(self.valid_attributes, **attributes) """Named tuple with the attributes for this node""" self.parent = None """Parent node""" for child in self.children: child.parent = self self._initial_attributes = copy(self.attributes) self._initial_content = copy(self.content) def _trim_text(self, text, max_len=30): split = text.split("\n") text = split[0] if len(text) > max_len or len(split) > 1: text = text[:max_len] + "..." return text def reset(self): """Reset attributes and content of the node to their initial values.""" self.content = copy(self._initial_content) self.attributes = copy(self._initial_attributes) def text(self): """Text representation of the node.""" return self.content or "" @property def tagname(self): """Name of the node.""" return self.__class__.__name__ def __repr__(self): if self.is_terminal: text = self._trim_text(self.text()) return f'<{self.tagname}: "{text}">' return f"<{self.tagname}: {self.children}>" class NestedNode(Node): def text(self): content = [child.text() for child in self.children] return "\n\n".join(content) class Paragraph(Node): """ Container for inline nodes. Inline nodes are: - :py:class:`Text` - :py:class:`Strong` - :py:class:`Emphasis` - :py:class:`Literal` """ def text(self): content = [child.text() for child in self.children] return "".join(content) class Text(Node): """Plain text node.""" is_terminal = True class Strong(Node): """Text represented as **bold**.""" is_terminal = True class Emphasis(Node): """Text represented as *italics*.""" is_terminal = True class Literal(Node): """Text represented with a ``mono space font``.""" is_terminal = True class Section(NestedNode): """ Section representation. Attributes: - title Children can be any of: - :py:class:`Paragraph` - :py:class:`TestBlock` - :py:class:`CodeBlock` - :py:class:`Admonition` """ valid_attributes = {"title"} def __repr__(self): title = self.attributes.title return f"<{self.tagname} {title}: {self.children}>" class Admonition(NestedNode): """ Text inside a box, usually to give a warning or a note to the user. Attributes: - title: The title of the admonition, defaults to ``type``. - type: one of ``note``, ``warning``, or ``tip``. Children can be any of: - :py:class:`Paragraph` """ valid_attributes = {"title", "type"} def __repr__(self): title = self.attributes.title return f"<{self.tagname} {title}: {self.children}>" class CodeBlock(Node): """ Syntax highlighted block. The content of this node should be a list of lines. Attributes: - language """ is_terminal = True valid_attributes = {"language"} def text(self): return "\n".join(self.content) def __repr__(self): lang = self.attributes.language code = self._trim_text(self.text()) return f"<{self.tagname} {lang}: {code}>" class TestBlock(Node): """ Challenge/response block to interact with the user. Attributes: - validator: dotted path to a :py:class:`lira.validators.TestBlockValidator` class. - description - state - language - extension: used to open a new file when editing. """ is_terminal = True valid_attributes = {"validator", "description", "state", "language", "extension"} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._validator = self._get_validator() def _get_validator(self): class_ = get_validator_class( validator_path=self.attributes.validator, subclass=TestBlockValidator, ) return class_(node=self) def text(self): return "\n".join(self.content) def reset(self): super().reset() self._validator = self._get_validator() def validate(self): """Run the validator for this node.""" return self._validator.run() def __repr__(self): description = self.attributes.description validator = self.attributes.validator return f"<{self.tagname} {validator}: {description}>" class Prompt(Node): # TODO is_terminal = True
true
c151c2c1060141ed2e79192a2efe66e9d8e9a9bd
Python
dockerizeme/dockerizeme
/hard-gists/10010307/snippet.py
UTF-8
1,788
2.828125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python ''' Playing around with CoreWLAN to return information about the wi-fi connection Documentation: https://developer.apple.com/library/mac/documentation/CoreWLAN/Reference/CWInterface_reference/translated_content/CWInterface.html ''' import objc objc.loadBundle('CoreWLAN', bundle_path='/System/Library/Frameworks/CoreWLAN.framework', module_globals=globals()) class WiFi(object): ''' WiFI object''' def __init__(self): self.wifi = CWInterface.interfaceNames() for iname in self.wifi: self.interface = CWInterface.interfaceWithName_(iname) def get_wifistatus(self): if self.interface.powerOn() == 1: return "Yes" return "No" def get_ssid(self): return self.interface.ssid() def get_interface(self): return self.interface.interfaceName() def get_hardwareaddress(self): return self.interface.hardwareAddress() def get_aggregatenoise(self): return self.interface.aggregateNoise() def get_aggregaterssi(self): return self.interface.aggregateRSSI() def get_bssid(self): return self.interface.bssid() def get_channel(self): return self.interface.channel() def get_transmitrate(self): return self.interface.transmitRate() def get_mcsindex(self): return self.interface.mcsIndex() def main(): wifi = WiFi() print 'Interface: %s' % wifi.get_interface() print 'Hardware Address: %s' % wifi.get_hardwareaddress() print 'Active: %s' % wifi.get_wifistatus() print 'SSID: %s' % wifi.get_ssid() print 'Aggregate Noise: %s' % wifi.get_aggregatenoise() print 'BSSID: %s' % wifi.get_bssid() print 'RSSI: %s' % wifi.get_aggregaterssi() print 'Channel: %s' % wifi.get_channel() print 'Transmit Rate: %s' % wifi.get_transmitrate() print 'MCS Index: %s' % wifi.get_mcsindex() if __name__ == "__main__": main()
true
afb47e12ae9dcff5b4c029c65e1f780b2c926ca8
Python
salmonofdoubt/TECH
/PROG/PY/pyintro/coding/week9_demo_files/urllib/orginfo_basic.py
UTF-8
303
2.5625
3
[]
no_license
#!/usr/bin/python2.6 import re import urllib def UrlToText(url): url_file = urllib.urlopen(url) contents = url_file.read() return contents def main(): my_moma_page = 'https://orginfo.corp.google.com/alberthwang?format=xml' print UrlToText(my_moma_page) if __name__ == '__main__': main()
true
a158cae87455f0c9ec348759569d89fbfa57fcbf
Python
testkkj/Python-L
/ch04.py
UTF-8
5,942
4.59375
5
[]
no_license
# 함수 # 파이썬 함수의 구조 ''' def 함수명(입력 인수): 수행할 문장1 수행할 문장2 ... ''' def sum(a,b): return a + b a = 3 b = 4 c = sum(a,b) print(c) # 입력값과 결과값에 따른 함수의 형태 # 일반적인 함수 ''' def 함수명(입력 인수): 수행할 문장 ... return 결과값 ''' def sum(a,b): result = a + b return result a = sum(3,4) print(a) # 입력값이 없는 함수 def say(): return 'Hi' a = say() print(a) ''' 결과값을 받을 변수 = 함수명() ''' # 결과값이 없는 함수 def sum(a,b): print("%d, %d의 합은 %d입니다." % (a,b,a+b)) sum(3,4) ''' 함수명(입력 인수1, 입력 인수2, ...) ''' a = sum(3,4) print(a) # 입력값도 결과값도 없는 함수 def say(): print("Hi") say() ''' 함수명() ''' # 입력값이 몇 개가 될지 모를 때는 어떻게 해야 할까? ''' del 함수명(*입력 변수): 수행할 문장 ... ''' # 여러 개의 입력값을 받는 함수 만들기 def sum_many(*args): sum = 0 for i in args: sum = sum + i return sum result = sum_many(1,2,3) print(result) result = sum_many(1,2,3,4,5,6,7,8,9,10) print(result) def sum_mul(choice, *args): if choice == "sum": result = 0 for i in args: result = result + i elif choice == "mul": result = 1 for i in args: result = result * i return result result = sum_mul('sum', 1,2,3,4,5) print(result) result = sum_mul('mul', 1,2,3,4,5) print(result) # 함수의 결과값은 언제나 하나이다 def sum_and_mul(a,b): return a+b, a*b result = sum_and_mul(3,4) print(result) sum, mul = sum_and_mul(3,4) print(sum, mul) def sum_and_mul(a,b): return a+b return a*b result = sum_and_mul(2,3) print(result) ''' def sum_and_mul(a,b): return a+b return a*b 위 함수는 아래와 동일하다. def sum_and_mul(a,b): return a+b return에서 함수를 빠져 나옴 ''' # return의 또 다른 쓰임새 def say_nick(nick): if nick == '바보': return print("나의 별명은 %s입니다." % nick) say_nick('야호') say_nick('바보') # 입력 인수에 초기값 미리 설정하기 def say_myself(name, old, man=True): print("나의 이름은 %s입니다." % name) print("나이는 %d살입니다." % old) if man: print("남자입니다.") else: print("여자입니다.") say_myself("박응용", 27) say_myself("박응용", 27, True) say_myself("박응선", 27, False) # 함수 입력 인수에 초깃값을 설정할 때 주의할 사항 def say_myself(name, man=True, old): print("나의 이름은 %s입니다." % name) print("나이는 %d살입니다." % old) if man: print("남자입니다.") else: print("여자입니다.") say_myself("박응용", 27) # 함수 안에서 선언된 변수의 효력 범위 # vartest.py a = 1 def vartest(a): a = a + 1 vartest(a) print(a) # vartest_error.py def vartest(a): a = a + 1 vartest(3) print(a) # 함수 안에서 함수 밖의 변수를 변경하는 방법 # return 이용하기 # vartest_return.py a = 1 def vartest(a): a = a + 1 return a a = vartest(a) print(a) # global 명령어 이용하기 # vartest_global.py a = 1 def vartest(): global a a = a + 1 vartest() print(a) # 사용자 입력과 출력 # 사용자 입력 # input의 사용 a = input() # 프롬프트를 띄워서 사용자 입력 받기 number = input("숫자를 입력하세요: ") print(number) # print 자세히 알기 a = 123 print(a) a = 'Python' print(a) a = [1,2,3] print(a) # 큰따옴표(")로 둘러싸인 문자열은 + 연산과 동일하다 print("life""is""too short") print("life"+"is"+"too short") # 문자열 띄어쓰기는 콤마로 한다 print("life","is","too short") print("life", "is", "too short") # 한 줄에 결과값 출력하기 for i in range(10): print(i, end='') # 파일 읽고 쓰기 # 파일 생성하기 f = open("새파일.txt", 'w') f.close() ''' 파일 열기 모드 r 읽기 모드 - 파일을 읽기만 할 때 사용 w 쓰기 모드 - 파일에 내용을 쓸 때 사용 a 추가 모드 - 파일의 마지막에 새로운 내용을 추가할 때 사용 ''' # 파일을 쓰기 모드로 열어 출력값 적기 # writedata.py f = open("새파일.txt", 'w') for i in range(1, 11): data = "%d번째 줄입니다.\n" % i f.write(data) f.close() # 프로그램의 외부에 저장된 파일을 읽는 여러 가지 방법 # readline() 함수 이용하기 # readline.py f = open("새파일.txt",'r') line = f.readline() print(line) f.close() # readline_all.py f = open("새파일.txt",'r') while True: line = f.readline() if not line: break print(line) f.close() # readlines() 함수 이용하기 f = open("새파일.txt", 'r') lines = f.readlines() for line in lines: print(line) f.close() # read() 함수 이용하기 f = open("새파일.txt", 'r') data = f.read() print(data) f.close() # 파일에 새로운 내용 추가하기 # adddata.py f = open("새파일.txt", 'a') for i in range(11, 20): data = "%d번째 줄입니다.\n" % i f.write(data) f.close() # with문과 함께 사용하기 f = open("foo.txt", 'w') f.write("Life is too short, you need python") f.close() with open("foo.txt", "w") as f: f.write("Life is too short, you need python") ################################################## # 연습문제 ################################################## def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n-2) + fib(n-1) for i in range(10): print(fib(i)) f = open("sample.txt") lines = f.readlines() f.close() total = 0 for line in lines: score = int(line) total += score average = total / len(lines) f = open("result.txt", "w") f.write(str(average)) f.close()
true
b62b9704907feff5ca8eaee193df63eb91535881
Python
binthafra/Python
/4-Advance Python- Functional Programmimg/15-Pure Function.py
UTF-8
143
3.453125
3
[]
no_license
def multipy_by2(li): new_list = [] for item in li: new_list.append(item+2) return new_list print(multipy_by2([1, 2, 3]))
true
92b9e48bd6bf1683739cf8d0974e42c5b9fe63e9
Python
yuewuo/fusion-blossom
/benchmark/util.py
UTF-8
9,932
2.53125
3
[ "MIT" ]
permissive
import json, subprocess, os, sys, tempfile, math, scipy class Profile: """ read profile given filename; if provided `skip_begin_profiles`, then it will skip such number of profiles in the beginning, by default to 5 because usually the first few profiles are not stable yet """ def __init__(self, filename, skip_begin_profiles=20): assert isinstance(filename, str) with open(filename, "r", encoding="utf8") as f: lines = f.readlines() self.partition_config = None self.entries = [] skipped = 0 for line_idx, line in enumerate(lines): line = line.strip("\r\n ") if line == "": break value = json.loads(line) if line_idx == 0: self.partition_config = PartitionConfig.from_json(value) elif line_idx == 1: self.benchmark_config = value else: if skipped < skip_begin_profiles: skipped += 1 else: self.entries.append(value) def __repr__(self): return f"Profile {{ partition_config: {self.partition_config}, entries: [...{len(self.entries)}] }}" def sum_decoding_time(self): decoding_time = 0 for entry in self.entries: decoding_time += entry["events"]["decoded"] return decoding_time def decoding_time_relative_dev(self): dev_sum = 0 avr_decoding_time = self.average_decoding_time() for entry in self.entries: dev_sum += (entry["events"]["decoded"] - avr_decoding_time) ** 2 return math.sqrt(dev_sum / len(self.entries)) / avr_decoding_time def average_decoding_time(self): return self.sum_decoding_time() / len(self.entries) def sum_defect_num(self): defect_num = 0 for entry in self.entries: defect_num += entry["defect_num"] return defect_num def average_decoding_time_per_defect(self): return self.sum_decoding_time() / self.sum_defect_num() def sum_computation_cpu_seconds(self): total_computation_cpu_seconds = 0 for entry in self.entries: computation_cpu_seconds = 0 for event_time in entry["solver_profile"]["primal"]["event_time_vec"]: computation_cpu_seconds += event_time["end"] - event_time["start"] total_computation_cpu_seconds += computation_cpu_seconds return total_computation_cpu_seconds def average_computation_cpu_seconds(self): return self.sum_computation_cpu_seconds() / len(self.entries) def sum_job_time(self, unit_index): total_job_time = 0 for entry in self.entries: event_time = entry["solver_profile"]["primal"]["event_time_vec"][unit_index] total_job_time += event_time["end"] - event_time["start"] return total_job_time def average_job_time(self, unit_index): return self.sum_job_time(unit_index) / len(self.entries) class VertexRange: def __init__(self, start, end): self.range = (start, end) def __repr__(self): return f"[{self.range[0]}, {self.range[1]}]" def length(self): return self.range[1] - self.range[0] class PartitionConfig: def __init__(self, vertex_num): self.vertex_num = vertex_num self.partitions = [VertexRange(0, vertex_num)] self.fusions = [] self.parents = [None] def __repr__(self): return f"PartitionConfig {{ vertex_num: {self.vertex_num}, partitions: {self.partitions}, fusions: {self.fusions} }}" @staticmethod def from_json(value): vertex_num = value['vertex_num'] config = PartitionConfig(vertex_num) config.partitions.clear() for vertex_range in value['partitions']: config.partitions.append(VertexRange(vertex_range[0], vertex_range[1])) for pair in value['fusions']: config.fusions.append((pair[0], pair[1])) assert len(config.partitions) == len(config.fusions) + 1 unit_count = len(config.partitions) * 2 - 1 # build parent references parents = [None] * unit_count for fusion_index, (left_index, right_index) in enumerate(config.fusions): unit_index = fusion_index + len(config.partitions) assert left_index < unit_index assert right_index < unit_index assert parents[left_index] is None assert parents[right_index] is None parents[left_index] = unit_index parents[right_index] = unit_index for unit_index in range(unit_count - 1): assert parents[unit_index] is not None assert parents[unit_count - 1] is None config.parents = parents return config def unit_depth(self, unit_index): depth = 0 while self.parents[unit_index] is not None: unit_index = self.parents[unit_index] depth += 1 return depth git_root_dir = subprocess.run("git rev-parse --show-toplevel", cwd=os.path.dirname(os.path.abspath(__file__)) , shell=True, check=True, capture_output=True).stdout.decode(sys.stdout.encoding).strip(" \r\n") rust_dir = git_root_dir FUSION_BLOSSOM_COMPILATION_DONE = False if 'MANUALLY_COMPILE_QEC' in os.environ and os.environ["MANUALLY_COMPILE_QEC"] == "TRUE": FUSION_BLOSSOM_COMPILATION_DONE = True FUSION_BLOSSOM_ENABLE_UNSAFE_POINTER = False if 'FUSION_BLOSSOM_ENABLE_UNSAFE_POINTER' in os.environ and os.environ["FUSION_BLOSSOM_ENABLE_UNSAFE_POINTER"] == "TRUE": FUSION_BLOSSOM_ENABLE_UNSAFE_POINTER = True def compile_code_if_necessary(additional_build_parameters=None): global FUSION_BLOSSOM_COMPILATION_DONE if FUSION_BLOSSOM_COMPILATION_DONE is False: build_parameters = ["cargo", "build", "--release"] if FUSION_BLOSSOM_ENABLE_UNSAFE_POINTER: build_parameters += ["--features", "dangerous_pointer,u32_index,i32_weight,qecp_integrate"] if additional_build_parameters is not None: build_parameters += additional_build_parameters # print(build_parameters) process = subprocess.Popen(build_parameters, universal_newlines=True, stdout=sys.stdout, stderr=sys.stderr, cwd=rust_dir) process.wait() assert process.returncode == 0, "compile has error" FUSION_BLOSSOM_COMPILATION_DONE = True def fusion_blossom_command(): fusion_path = os.path.join(rust_dir, "target", "release", "fusion_blossom") return [fusion_path] def fusion_blossom_benchmark_command(d=None, p=None, total_rounds=None, r=None, noisy_measurements=None, n=None): assert d is not None assert p is not None command = fusion_blossom_command() + ["benchmark", f"{d}", f"{p}"] if total_rounds is not None: command += ["-r", f"{total_rounds}"] elif r is not None: command += ["-r", f"{r}"] if noisy_measurements is not None: command += ["-n", f"{noisy_measurements}"] elif n is not None: command += ["-n", f"{n}"] return command def fusion_blossom_qecp_generate_command(d, p, total_rounds, noisy_measurements): command = fusion_blossom_command() + ["qecp", f"[{d}]", f"[{noisy_measurements}]", f"[{p}]", f"-m{total_rounds}"] return command def fusion_blossom_bin_command(bin): fusion_path = os.path.join(rust_dir, "target", "release", bin) command = [fusion_path] return command FUSION_BLOSSOM_ENABLE_HIGH_PRIORITY = False if 'FUSION_BLOSSOM_ENABLE_HIGH_PRIORITY' in os.environ and os.environ["FUSION_BLOSSOM_ENABLE_HIGH_PRIORITY"] == "TRUE": FUSION_BLOSSOM_ENABLE_HIGH_PRIORITY = True """ Note: usually changing the nice value will require root privilege, but rust toolchain may not be installed for root In this case, change the default nice value for user: https://bencane.com/2013/09/30/changing-the-default-nice-value-for-a-user-or-group/ """ def run_command_get_stdout(command, no_stdout=False, use_tmp_out=False, stderr_to_stdout=False): compile_code_if_necessary() env = os.environ.copy() env["RUST_BACKTRACE"] = "full" stdout = subprocess.PIPE if use_tmp_out: out_file = tempfile.NamedTemporaryFile(delete=False) out_filename = out_file.name stdout = out_file if no_stdout: stdout = sys.stdout process = subprocess.Popen(command, universal_newlines=True, env=env, stdout=stdout, stderr=(stdout if stderr_to_stdout else sys.stderr) , bufsize=100000000, preexec_fn=(lambda : os.nice(-10)) if FUSION_BLOSSOM_ENABLE_HIGH_PRIORITY else None) stdout, _ = process.communicate() if use_tmp_out: out_file.flush() out_file.close() with open(out_filename, "r", encoding="utf8") as f: stdout = f.read() os.remove(out_filename) return stdout, process.returncode class GnuplotData: def __init__(self, filename): assert isinstance(filename, str) with open(filename, "r", encoding="utf8") as f: lines = f.readlines() self.titles = [] if lines[0].startswith("<"): # title line line = lines[0].strip("\r\n ") titles = line.split(" ") for title in titles: # assert title.startswith("<") and title.endswith(">") self.titles.append(title[1:-1]) lines = lines[1:] self.data = [] for line in lines: line = line.strip("\r\n ") self.data.append(line.split(" ")) def fit(self, x_column, y_column, x_func=lambda x:float(x), y_func=lambda y:float(y), starting_row=0, ending_row=None): X = [x_func(line[x_column]) for line in self.data[starting_row:ending_row]] Y = [y_func(line[y_column]) for line in self.data[starting_row:ending_row]] slope, intercept, r, _, _ = scipy.stats.linregress(X, Y) return slope, intercept, r
true
7593deba29e57c09a97b11dc7770f330aaad8051
Python
tgomez22/distanceVector
/updatedDistanceVector.py
UTF-8
3,112
3.25
3
[]
no_license
class node: def __init__(self, identifier): self.distanceVector = dict() self.distanceVector[identifier] = 0 self.name = identifier self.hasChanged = False def addNeighbor(self, neighbor, distance): self.distanceVector[neighbor] = distance def updateVector(self, neighbor, neighborVector): for node in neighborVector.keys(): if node in self.distanceVector.keys(): originalValue = self.distanceVector[node] self.distanceVector[node] = min(self.distanceVector[node], self.distanceVector[neighbor] + neighborVector[node] ) if(originalValue != self.distanceVector[node]): self.hasChanged = True return else: self.hasChanged = False else: self.distanceVector[node] = self.distanceVector[neighbor] + neighborVector[node] self.hasChanged = True return def displayVectorTable(self, iteration): print(f"For iteration {iteration}: \n") for nodes in self.distanceVector.keys(): print(f"Node: {nodes} - distance: {self.distanceVector[nodes]}\n") a = node("a") a.addNeighbor("b", 14) a.addNeighbor("c", 2) b = node("b") b.addNeighbor("a", 14) b.addNeighbor("c", 8) b.addNeighbor("f", 3) b.addNeighbor("e", 1) c = node("c") c.addNeighbor("a", 2) c.addNeighbor("b", 8) c.addNeighbor("g", 1) d = node("d") d.addNeighbor("e", 7) d.addNeighbor("f", 10) e = node("e") e.addNeighbor("d", 7) e.addNeighbor("f", 1) e.addNeighbor("b", 1) f = node("f") f.addNeighbor("b", 3) f.addNeighbor("g", 3) f.addNeighbor("h", 1) f.addNeighbor("e", 1) f.addNeighbor("d", 10) g = node("g") g.addNeighbor("c", 1) g.addNeighbor("f", 3) g.addNeighbor("h", 5) h = node("h") h.addNeighbor("g", 5) h.addNeighbor("f", 1) iteration = 0 a.displayVectorTable(iteration) a.updateVector("b", b.distanceVector) a.updateVector("c", c.distanceVector) iteration += 1 a.displayVectorTable(iteration) while(a.hasChanged == True): b.updateVector("a", a.distanceVector) b.updateVector("c", c.distanceVector) b.updateVector("e", e.distanceVector) b.updateVector("f", f.distanceVector) c.updateVector("a", a.distanceVector) c.updateVector("b", b.distanceVector) c.updateVector("g", g.distanceVector) d.updateVector("e", e.distanceVector) d.updateVector("f", f.distanceVector) e.updateVector("d", d.distanceVector) e.updateVector("b", b.distanceVector) e.updateVector("f", f.distanceVector) f.updateVector("b", b.distanceVector) f.updateVector("e", e.distanceVector) f.updateVector("g", g.distanceVector) f.updateVector("h", h.distanceVector) g.updateVector("c", c.distanceVector) g.updateVector("f", f.distanceVector) g.updateVector("h", h.distanceVector) h.updateVector("f", f.distanceVector) h.updateVector("g", g.distanceVector) iteration += 1 a.updateVector("b", b.distanceVector) a.updateVector("c", c.distanceVector) a.displayVectorTable(iteration)
true
dbba8fbef53d8b0ae19775c81ac4fbdf4d83b59c
Python
QuentinJol/Exercicessupplementaires
/Premiere Serie/Exo 6.py
UTF-8
127
3.171875
3
[]
no_license
# -*- coding: utf8 -*- A=0 B=1 C=0 i=0 while i != 10: C=A+B print(A, " + ", B, " = ", C) A=B B=C i += 1
true
362bdbf08c326b9907c5421c8abee85c120023a8
Python
zhang-wen/dynmt
/stream_with_dict.py
UTF-8
14,787
2.625
3
[]
no_license
# -*- coding: utf-8 -*- import numpy from fuel.datasets import TextFile from fuel.schemes import ConstantScheme from fuel.streams import DataStream from fuel.transformers import ( Merge, Batch, Filter, Padding, SortMapping, Unpack, Mapping) from six.moves import cPickle import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def ensure_special_tokens(vocab, bos_idx=0, eos_idx=0, unk_idx=1): """Ensures special tokens exist in the dictionary.""" # remove tokens if they exist in some other index # in vocab (dict), the v (index) of bos, eos, unk are 0, -1, and 1 tokens_to_remove = [k for k, v in vocab.items() if v in [bos_idx, eos_idx, unk_idx, -1]] # eos_idx is -1 in vocab, we remove it for token in tokens_to_remove: vocab.pop(token) # remove the bos, unk and eos in vocabulary # put corresponding item vocab['<S>'] = bos_idx # 0 vocab['</S>'] = eos_idx # 29999 vocab['<UNK>'] = unk_idx # 1 # for k, v in vocab.iteritems(): # print k, v return vocab # final vocabulary def _length(sentence_pair): """Assumes target is the second element in the tuple.""" # sort by target sentence length return len(sentence_pair[1]) class PaddingWithEOS(Padding): """Padds a stream with given end of sequence idx.""" def __init__(self, data_stream, bos_idx, eos_idx, **kwargs): # print eos_idx # [29999, 29999] kwargs['data_stream'] = data_stream self.bos_idx = bos_idx self.eos_idx = eos_idx super(PaddingWithEOS, self).__init__(**kwargs) def transform_batch(self, batch): # if you use next() function here, the final data_stream contain data every other batch, i do not know why doing like this # batch = next(self.child_epoch_iterator) # i annote here !!!!!!!!!!!!!!!!! data = list(batch) data_with_masks = [] self.mask_sources = ('source', 'target') # print self.mask_sources # ('source', 'target', 'dict') for i, (source, source_data) in enumerate( zip(self.data_stream.sources, data)): # 0 source [[0, 1, 29999], [0,2,3,29999]] # 1 target [[0, 1, 29999], [0,2,3,29999]] # 2 dict [[0, 1, 29999], [0,2,3,29999]] # print i, source, source_data if source not in self.mask_sources: data_with_masks.append(source_data) # do not add mask for this source continue # sample: [ 0, 1108, 66, 1, 29999] # numpy.asarray(sample) is a numpy.ndarray, shape is (5,), shape[0] == 5 # batch_size = 5, [(5,), (20,), (33,), (13,), (9,0)] shapes = [numpy.asarray(sample).shape for sample in source_data] lengths = [shape[0] for shape in shapes] # [5, 20, 33, 13, 9] max_sequence_length = max(lengths) # 33 rest_shape = shapes[0][1:] # here is () if not all([shape[1:] == rest_shape for shape in shapes]): raise ValueError("All dimensions except length must be equal") dtype = numpy.asarray(source_data[0]).dtype ''' padded_data = numpy.ones((len(source_data), max_sequence_length) + rest_shape, dtype=dtype) * self.eos_idx[i] # all array([[29999, 29999, 29999, 29999, 29999, 29999, 29999, 29999, 29999, ... , ] ''' padded_data = numpy.ones( (len(source_data), max_sequence_length) + rest_shape, dtype=dtype) * self.bos_idx[i] # all array([[0, 0, 0, 0, 0, 0, 0, 0, 0, ... , ] for i, sample in enumerate(source_data): # assign the real indexes value of the sentence, at the first len(sample) locations padded_data[i, :len(sample)] = sample data_with_masks.append(padded_data) # mask = numpy.zeros((len(source_data), max_sequence_length), # self.mask_dtype) # all array([[0, 0, 0, 0, 0, 0, 0, 0, 0, ... , ] mask = numpy.zeros((len(source_data), max_sequence_length), dtype='int32') # all array([[0, 0, 0, 0, 0, 0, 0, 0, 0, ... , ] for i, sequence_length in enumerate(lengths): # assign value 1 at the first len(sample) locations mask[i, :sequence_length] = 1 data_with_masks.append(mask) return tuple(data_with_masks) class _oov_to_unk(object): """Maps out of vocabulary token index to unk token index.""" def __init__(self, src_vocab_size=30000, trg_vocab_size=30000, unk_id=1): self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.unk_id = unk_id def __call__(self, sentence_pair): ''' return ([x if x < self.src_vocab_size else self.unk_id for x in sentence_pair[0]], [x if x < self.trg_vocab_size else self.unk_id for x in sentence_pair[1]]) ''' return ([x if x < self.src_vocab_size else self.unk_id for x in sentence_pair[0]], [x if x < self.trg_vocab_size else self.unk_id for x in sentence_pair[1]], [x if x < self.trg_vocab_size else self.unk_id for x in sentence_pair[2]]) # add dict class _too_long(object): """Filters sequences longer than given sequence length.""" def __init__(self, seq_len=50): self.seq_len = seq_len def __call__(self, sentence_pair): # include the padding length 0 and 29999 # print [len(sentence) <= self.seq_len for sentence in sentence_pair] #[True, False] # return all([len(sentence) <= self.seq_len # for sentence in sentence_pair]) # both length of source sentence and target sentence are less than seq_len return all([len(sentence_pair[0]) <= self.seq_len, len(sentence_pair[1]) <= self.seq_len]) def get_tr_stream(src_vocab, trg_vocab, src_data, trg_data, dict_data, src_vocab_size=30000, trg_vocab_size=30000, unk_id=1, seq_len=50, batch_size=80, sort_k_batches=12, **kwargs): """Prepares the training data stream.""" # Load dictionaries and ensure special tokens exist ''' actual_src_vocab_num = len(src_vocab) actual_trg_vocab_num = len(trg_vocab) src_vocab = ensure_special_tokens( src_vocab if isinstance(src_vocab, dict) else cPickle.load(open(src_vocab)), bos_idx=0, eos_idx=(actual_src_vocab_num - 1) if actual_src_vocab_num - 3 < src_vocab_size else (src_vocab_size + 3 - 1), unk_idx=unk_id) trg_vocab = ensure_special_tokens( trg_vocab if isinstance(trg_vocab, dict) else cPickle.load(open(trg_vocab)), bos_idx=0, eos_idx=(actual_trg_vocab_num - 1) if actual_trg_vocab_num - 3 < trg_vocab_size else (trg_vocab_size + 3 - 1), unk_idx=unk_id) ''' src_vocab = ensure_special_tokens( src_vocab if isinstance(src_vocab, dict) else cPickle.load(open(src_vocab)), bos_idx=0, eos_idx=src_vocab_size - 1, unk_idx=unk_id) trg_vocab = ensure_special_tokens( trg_vocab if isinstance(trg_vocab, dict) else cPickle.load(open(trg_vocab)), bos_idx=0, eos_idx=trg_vocab_size - 1, unk_idx=unk_id) # for example: # source: 第五 章 罚则 # target: chapter v penalty regulations # Get text files from both source and target src_dataset = TextFile([src_data], src_vocab) trg_dataset = TextFile([trg_data], trg_vocab) dict_dataset = TextFile([dict_data], trg_vocab) # for data in DataStream(src_dataset).get_epoch_iterator(): # print(data) # looks like: ([0, 1649, 1764, 7458, 29999],) # Merge them to get a source, target pair stream = Merge([src_dataset.get_example_stream(), trg_dataset.get_example_stream(), dict_dataset.get_example_stream()], ('source', 'target', 'dict')) # data_stream.sources = 'source' or 'target' ''' print 'init \n' num_before_filter = 0 for data in stream.get_epoch_iterator(): num_before_filter = num_before_filter + 1 # print(data) ''' # looks like: ([0, 1649, 1764, 7458, 29999], [0, 2662, 9329, 968, 200, 29999]) # Filter sequences that are too long # Neither source sentence or target sentence can beyond the length seq_len # the lenght include the start symbol <s> and the end symbol </s>, so the actual sentence # length can not beyond (seq_len - 2) stream = Filter(stream, predicate=_too_long(seq_len=seq_len)) ''' num_after_filter = 0 # print 'after filter ... \n' for data in stream.get_epoch_iterator(): num_after_filter = num_after_filter + 1 # print(data) logger.info('\tby filtering, sentence-pairs from {} to {}.'.format(num_before_filter, num_after_filter)) logger.info('\tfilter {} sentence-pairs whose source or target sentence exceeds {} words'.format( (num_before_filter - num_after_filter), seq_len)) ''' # Replace out of vocabulary tokens with unk token stream = Mapping(stream, _oov_to_unk(src_vocab_size=src_vocab_size, trg_vocab_size=trg_vocab_size, unk_id=unk_id)) # do not need ''' print 'after mapping unk ...' for data in stream.get_epoch_iterator(): print(data) ''' # still looks like: ([0, 1649, 1764, 7458, 29999], [0, 2662, 9329, 968, 200, 29999]) # Build a batched version of stream to read k batches ahead # do not sort on the whole training data, first split the training data into several blocks, # each block contain (batch_size*sort_k_batches) sentence-pairs, we juse sort in each block, # finally, i understand !!!!!!! # remainder stream = Batch(stream, iteration_scheme=ConstantScheme( batch_size * sort_k_batches)) ''' print 'after sorted batch ... ' for data in stream.get_epoch_iterator(): print(data) ''' # Sort all samples in the read-ahead batch # sort by the length of target sentence in (batch_size*sort_k_batches) # list for all training data, speed up stream = Mapping(stream, SortMapping(_length)) ''' print 'after sort ... ' for data in stream.get_epoch_iterator(): print(data) ''' # Convert it into a stream again stream = Unpack(stream) ''' print 'after unpack ... ' for data in stream.get_epoch_iterator(): print(data) ''' # still looks like: ([0, 1649, 1764, 7458, 29999], [0, 2662, 9329, 968, 200, 29999]) # remove the remainder ? # Construct batches from the stream with specified batch size stream = Batch( stream, iteration_scheme=ConstantScheme(batch_size)) # after sort, each batch has batch_size sentence pairs ''' print 'after final batch ... ' i = 0 for data in stream.get_epoch_iterator(): i = i + 1 print(data) print 'batchs: ', i ''' # Pad sequences that are short masked_stream = PaddingWithEOS( stream, bos_idx=[0, 0, 0], eos_idx=[src_vocab_size - 1, trg_vocab_size - 1, trg_vocab_size - 1]) # print 'after padding with mask ...' return masked_stream ''' def get_dev_stream(val_set=None, src_vocab=None, src_vocab_size=30000, unk_id=1, **kwargs): """Setup development set stream if necessary.""" dev_stream = None if val_set is not None and src_vocab is not None: src_vocab = ensure_special_tokens( src_vocab if isinstance(src_vocab, dict) else cPickle.load(open(src_vocab)), bos_idx=0, eos_idx=src_vocab_size - 1, unk_idx=unk_id) dev_dataset = TextFile([val_set], src_vocab) dev_stream = DataStream(dev_dataset) # no filter, no padding, no mask for dev_dataset return dev_stream ''' # validation set, no batch, not padding def get_dev_stream(val_set=None, valid_sent_dict=None, src_vocab=None, trg_vocab=None, src_vocab_size=30000, trg_vocab_size=30000, unk_id=1, **kwargs): """Setup development set stream if necessary.""" dev_stream = None if val_set is not None and src_vocab is not None: # Load dictionaries and ensure special tokens exist src_vocab = ensure_special_tokens( src_vocab if isinstance(src_vocab, dict) else cPickle.load(open(src_vocab)), bos_idx=0, eos_idx=src_vocab_size - 1, unk_idx=unk_id) trg_vocab = ensure_special_tokens( trg_vocab if isinstance(trg_vocab, dict) else cPickle.load(open(trg_vocab)), bos_idx=0, eos_idx=trg_vocab_size - 1, unk_idx=unk_id) dev_dataset = TextFile([val_set], src_vocab, None) dev_dictset = TextFile([valid_sent_dict], trg_vocab, None) #dev_stream = DataStream(dev_dataset) # Merge them to get a source, target pair dev_stream = Merge([dev_dataset.get_example_stream(), dev_dictset.get_example_stream()], ('source', 'valid_sent_trg_dict')) return dev_stream if __name__ == '__main__': import configurations configuration = getattr(configurations, 'get_config_cs2en')() trstream = get_tr_stream(**configuration) for data in trstream.get_epoch_iterator(): print data # print type(data[0]) # numpy.ndarray # print type(data) # data is a tuple # take the batch sizes 3 as an example: # tuple: tuple[0] is indexes of source sentence (numpy.ndarray) # like array([[0, 23, 3, 4, 29999], [0, 2, 1, 29999], [0, 31, 333, 2, 1, 29999]]) # tuple: tuple[1] is indexes of source sentence mask (numpy.ndarray) # like array([[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1]]) # tuple: tuple[2] is indexes of target sentence (numpy.ndarray) # tuple: tuple[3] is indexes of target sentence mask (numpy.ndarray) # print numpy.asarray(data) # break dev_stream = get_dev_stream(**configuration) # for data in dev_stream.get_epoch_iterator(): # print data # print numpy.asarray(data) # print data[0] # such as [0, 294, 430, 45, 1009, 560, 708, 283, 437, 1, 164, 321, 29999] # print type(data[0]) # list # print type(data) # tuple: ([0, 294, 430, 45, 1009, 560, 708, 283, # 437, 1, 164, 321, 29999],)
true
0a32c13ca24baed623fe6d9baacc6749a04b7fae
Python
wlgud0402/dev
/라이브러리/Counter.py
UTF-8
194
3.515625
4
[]
no_license
#Counter 라이브러리 from collections import Counter string = "hello" print(Counter(string)) print(Counter(string).items()) print(Counter(string).keys()) print(Counter(string).values())
true
0fb84b9259cf7a17a21d1ec8f93e73784e0ba9a8
Python
MarianCeap/citisim-bitool
/CitiSIM/login.py
UTF-8
912
2.609375
3
[]
no_license
#!flask/bin/python from flask import request from flask import flash from flask import redirect from flask import render_template from flask_login import login_user,logout_user,current_user from main import app from users import User @app.route('/login', methods=['GET','POST']) def loginPage(): if(current_user.is_authenticated): return redirect("/citisim/") email = request.form.get('email') password = request.form.get('password') if(email is not None): user = User() if(user.userAuthentication(email, password)): login_user(user.getUserByEmail(email)) return redirect("/citisim/") else: flash("Wrong email or password!") return render_template("login.html") @app.route('/logout', methods=['GET','POST']) def logOut(): if(current_user.is_authenticated): logout_user() return redirect("/citisim/login")
true
bbde312d2a3e0fcaa2984ae7f93a5d8716dffcf8
Python
Sylphy0052/PythonWebApplication
/Flask/OneDayFlaskBeginner/flaskworks/chap5.py
UTF-8
1,865
2.796875
3
[]
no_license
import os from flask import Flask, render_template, request, redirect, url_for, send_from_directory from werkzeug import secure_filename # appという変数にFlaskオブジェクトを作成するおまじない app = Flask(__name__) UPLOAD_FOLDER = './uploads' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and\ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS # ~/にアクセスしたときに実行される関数 @app.route('/') def index(): # 返り値の文字列をブラウザに表示する # return 'Hello World' # テンプレートを呼び出す # base.htmlの{{ message }}に'Hello'という文字列を渡している # return render_template('index.html', message='Hello') return render_template('index.html', message='indexページです') @app.route('/send', methods=['GET', 'POST']) def send(): if request.method == 'POST': # POSTのとき img_file = request.files['img_file'] if img_file and allowed_file(img_file.filename): filename = secure_filename(img_file.filename) img_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return render_template('index.html') else: return '''<p>許可されていない拡張子です</p>''' else: # GETのとき # indexメソッドを実行する return redirect(url_for('index')) # ファイルをブラウザで表示するメソッド @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) # mainで実行されたなら if __name__ == '__main__': # デバッグモードをオンにする app.debug = True # サーバ起動 app.run()
true
a03389e42ac5892af913c282b60a573b35fd1e43
Python
fare-xzy/LeetCode
/python/leetcode/algorithms/easy/7-整数翻转.py
UTF-8
426
3.03125
3
[]
no_license
class Solution: def reverse(self, x: int) -> int: maxInt = 2 ** 31 strX = str(abs(x)) strList = list(strX) newStr = ''.join(strList[-1::-1]) newInt = int(newStr) if newInt < -maxInt or newInt > maxInt - 1: return 0 if x < 0: return -newInt else: return newInt soloution = Solution() print(soloution.reverse(1534236469))
true
9b62542b41d1f0ce73ca8a553a984c8cba5d893a
Python
1Shivam12/SIOT
/Python/TwitterAPI.py
UTF-8
1,802
2.71875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Jan 4 08:47:17 2019 @author: Shivam Bhatnagar """ import json from twython import TwythonStreamer import csv credentials = {} credentials['CONSUMER_KEY'] = 'GUHAjTw17AGUss9kPzu8I9PNB' credentials['CONSUMER_SECRET'] = 'UAyXIwrL1qKSUrB3WaBIlvbH7bYgloj2ejFs247JxcAGD5Rgs4' credentials['ACCESS_TOKEN'] = '708230098-3kHy4jKQOemzA60pMT49flKPsaQh4XDAe6YnHzWX' credentials['ACCESS_SECRET'] = 'oKo8ElBjZr6iuJQaDsMDHxm6BaHcqIO0uSEHLKiFxpB8p' with open("twitter_credentials.json", "w") as file: json.dump(credentials, file) with open("twitter_credentials.json", "r", encoding='utf-8') as file: creds = json.load(file) def process_tweet(tweet): d = {} # d['hashtags'] = [hashtag['text'] for hashtag in tweet['entities']['hashtags']] d['text'] = tweet['text'] d['user'] = tweet['user']['screen_name'] d['user_loc'] = tweet['user']['location'] return d class MyStreamer(TwythonStreamer): #Succesful data received def on_success(self, data): # Only english tweets if data['lang'] == 'en': tweet_data = process_tweet(data) self.save_to_csv(tweet_data) def on_error(self, status_code, data): print(status_code, data) self.disconnect() def save_to_csv(self, tweet): with open(r'saved_tweets.csv', 'a', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(list(tweet.values())) stream = MyStreamer(creds['CONSUMER_KEY'], creds['CONSUMER_SECRET'], creds['ACCESS_TOKEN'], creds['ACCESS_SECRET'], timeout = 5) # ============================================================================= # Keywords to track are: # 1) Movies # 2) Film # 3) Cinema # ============================================================================= stream.statuses.filter(track='movie, film, cinema')
true
c5f9e8daa3d4d80fd28514b5ae0ca13b5a79e2c3
Python
Coobeliues/pp2_py
/inf_arr9/3852.py
UTF-8
331
3.109375
3
[]
no_license
s, x, y = list(), list(), list() n = 8 for i in range(n): b = list(map(int, input().split())) l, r = b[0], b[1] s.append(l + r) x.append(l) y.append(r) for i in range(n): for j in range(i+1, n): if s[i] == s[j] or x[i] == x[j] or y[i] == y[j]: print("YES") exit() print("NO")
true
b1e5b2034f966c79dae70bf6ccfeb9bf782d4f3c
Python
apprenticearnab/ReinforceBots
/load_embeddings.py
UTF-8
1,098
3.171875
3
[ "MIT" ]
permissive
''' This file loads a word2vec of user's choice For this project : Word2Vec model : 'word2vec-google-news-300' ''' import torch import gensim.downloader # Downloads Google news word2vec model def load_embeddings(word2vec_model='word2vec-google-news-300'): embed_model = gensim.downloader.load(word2vec_model) return embed_model # Transform sentence using word2vec def generate_word2vec_tensor(x,embed_model): return torch.Tensor(embed_model[x]) # Prepare batch dataset : returns tensor of dimension --> [batch_size,embedding_dimension,sentence_size] def sentence2embeddings(sentences,embed_model,sentence_size): sentence_batch = [] assert len(sentences[0]) == sentence_size for sentence in sentences: sentence_vector = torch.transpose(generate_word2vec_tensor(sentence,embed_model),0,1) sentence_vector = sentence_vector.reshape((1,sentence_vector.shape[0],sentence_vector.shape[1])) sentence_batch.append(sentence_vector) sentence_batch = torch.cat(sentence_batch,dim=0) return torch.Tensor(sentence_batch)
true
ba74600b06e5901a86a13e5ec93d6aad4bf782d2
Python
TestingIaCwithNewAccount/clouds-aws
/src/clouds_aws/local_stack/parameters.py
UTF-8
2,267
2.953125
3
[ "Apache-2.0" ]
permissive
""" Parameters class """ import logging from os import path, unlink from clouds_aws.local_stack.helpers import dump_yaml, load_yaml LOG = logging.getLogger(__name__) class ParameterError(Exception): """ Custom errors for Parameters class """ pass class Parameters: """ Parameters class """ def __init__(self, stack_path): """ Initialize empty parameters object :param stack_path: stack directory path """ LOG.debug("Initializing new parameters in path %s", stack_path) self.path = stack_path self.parameters = {} self.load() def __repr__(self): return "Parameters({})".format(self.path) def __str__(self): return str(self.parameters) def load(self): """ Load parameters from file :return: """ if not path.isfile(self._filename()): LOG.debug("Not loading empty parameters") return LOG.debug("Loading parameters from file %s", self._filename()) with open(self._filename()) as param_fp: self.parameters = load_yaml(param_fp) def save(self): """ Save parameters to file :return: """ LOG.debug("Saving parameters to file %s", self._filename()) if not self.parameters: if path.isfile(self._filename()): LOG.info("Deleting parameters file %s", self._filename()) unlink(self._filename()) return LOG.info("Skipping empty parameters") return with open(self._filename(), "w") as param_fp: param_fp.write(dump_yaml(self.parameters)) def as_list(self): """ Return params list :return: """ params = [] for key, val in self.parameters.items(): params.append({ "ParameterKey": key, "ParameterValue": val }) return params def _filename(self, with_path=True): """ Return file name (with path) :param with_path: include path :return: """ if with_path: return path.join(self.path, "parameters.yaml") return "parameters.yaml"
true
57a1459d7a8bfffc71d9e63538832c2ddab76709
Python
edbutcher/course
/xmllesson.py
UTF-8
322
2.78125
3
[]
no_license
import urllib import xml.etree.ElementTree as ET url = 'http://python-data.dr-chuck.net/comments_333665.xml' data = urllib.urlopen(url).read() mn = [] stuff = ET.fromstring(data) lst = stuff.findall('comments/comment') print len(lst) for item in lst: x = int(item.find('count').text) mn.append(x) print sum(mn)
true
4d50108480c4bced543c3ff77569d1f9ae356192
Python
ayoubkachkach/Buffon-s-Experiment
/flaskr/engine.py
UTF-8
2,175
3.328125
3
[]
no_license
import numpy as np import math MATCH_LEN = 1 #in pixels LINE_SPACING = 2*MATCH_LEN #spacing between consecutive lines DIM_SPACE = 240 class Point: '''Represents a 2D point''' def __init__(self, x, y): self.x = x self.y = y def get_coordinates(): return (x, y) class Match: '''Represents a match with its center and angle (rad) of tilt''' def __init__(self, center, angle): self.center = center self.angle = angle #projection of center to side of the match w.r.t. x and y axes resp. self.hor_projection = (MATCH_LEN/2)*math.cos(angle) self.ver_projection = (MATCH_LEN/2)*math.sin(angle) #upper_point --> point with higher x-coordinate self.upper_point = Point(self.center + self.hor_projection,self.center + self.ver_projection) self.lower_point = Point(self.center - self.hor_projection, self.center - self.ver_projection) self.touches = self.touches_line() def get_points(self): return (self.lower_point, self.upper_point) def touches_line(self): center_dist = self.center % LINE_SPACING return center_dist - self.ver_projection < 0 \ or center_dist + self.ver_projection >= LINE_SPACING # @classmethod # def throw_match(self): class Experiment: '''Represents an experiment with num_matches of matches each of which are of size match_len''' def __init__(self, num_matches): self.num_matches = num_matches self.matches = [] self.touching_matches = 0 #no matches touching line initially self.throw_matches(num_matches) def throw_matches(self, num_matches): centers = np.random.uniform(0, DIM_SPACE - MATCH_LEN/2, num_matches) angles = np.random.uniform(0, math.pi, num_matches) self.matches = [Match(center, angle) for center, angle in zip(centers, angles)] self.touching_matches = sum(1 for match in self.matches if match.touches) if(__name__ == "__main__"): num_matches = 90000 print(sum([num_matches/Experiment(num_matches).touching_matches for i in range(10)])/10)
true
63047843cb18a5ee696728c150b44699ae9f2865
Python
tahmid-tanzim/problem-solving
/codility/CountDiv.py
UTF-8
1,155
3.9375
4
[]
no_license
#!/usr/bin/python3 # https://app.codility.com/programmers/lessons/5-prefix_sums/count_div/ from typing import List # Time O(B - A) # Space O(1) def findCountDiv(A: int, B: int, K: int) -> int: counter = 0 for i in range(A, B + 1, K): if i % K == 0: counter += 1 return counter # Time O(1) # Space O(1) def findCountDiv2(A: int, B: int, K: int): return B // K - A // K + (1 if A % K == 0 else 0) if __name__ == '__main__': inputs = ( { "A": 6, "B": 11, "K": 2, "expected": 3 }, { "A": 1, "B": 2000000000, "K": 1, "expected": 2000000000 }, ) test_passed = 0 for idx, val in enumerate(inputs): output = findCountDiv2(val["A"], val["B"], val["K"]) if output == val['expected']: print(f"{idx}. CORRECT Answer\nOutput: {output}\nExpected: {val['expected']}\n") test_passed += 1 else: print(f"{idx}. WRONG Answer\nOutput:{output}\nExpected:{val['expected']}\n") print(f"Passed: {test_passed:3}/{idx + 1}\n")
true
dbb9d23e66fc1e370bafefbfbf8907f394e57fa2
Python
houfu/lsra-scraper
/lsra_scraper/lsra_scraper.py
UTF-8
6,445
2.59375
3
[ "MIT" ]
permissive
import dataclasses import os import click import requests from bs4 import BeautifulSoup from selenium import webdriver @click.command() @click.option('--site', '-s', help='Url to LSRA search page', default='https://eservices.mlaw.gov.sg/lsra/search-lawyer-or-law-firm') @click.option('--output', '-o', help='Output format. Accepts either "csv" or "excel"', type=click.Choice(['csv', 'excel'], case_sensitive=False), default='csv') @click.option('--out-file', '-O', help='Location of output file. If empty, default file name in root directory will be used', type=click.Path(), default=None) @click.option('--root', '-r', help='Root directory for downloading of output files. Ignored if out-file is set.', type=click.Path(file_okay=False), default=os.getcwd()) @click.argument('search_type', default='firms') def lsra_scraper(site, search_type, root, output, out_file): if root: os.chdir(root) if search_type.lower() == 'lawyers': print("Lawyers scraping is not supported at this moment.") return driver = setup_web_driver() result = scrape(driver, site, search_type) if output == 'csv': output_path = save_csv(result, out_file, root, search_type) print('CSV file saved at {}'.format(output_path)) return def setup_web_driver(): print('Setting up web driver') from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--no-sandbox') options.add_argument('--window-size=1920,1080') driver = webdriver.Chrome(options=options) driver.implicitly_wait(150) return driver def get_site(site, search_type='firm'): if search_type.lower() == 'lawyers': payload = {'searchType': 1} else: payload = {'searchType': 0} r = requests.get(site, params=payload) return r.url def scrape(driver, site, search_type): try: print("Begin scraping process.") driver.get(get_site(site, search_type)) pass_captcha(driver) result = process_pages(driver, search_type=search_type) finally: print("End scraping process.") driver.quit() return result def pass_captcha(driver: webdriver.Chrome): from selenium.webdriver.common.keys import Keys passed_captcha = False captcha = driver.find_element_by_id('txtCaptchCode') captcha.send_keys(Keys.END) print('In order to continue, you need to enter the captcha code on the web page.') code = input('Input the code in your screen now:') captcha.send_keys(code) driver.find_element_by_id('btnSearch').click() while not passed_captcha: element = driver.find_element_by_id('showValidationError') if element.is_displayed(): code = input('Validation failed. Please re-enter') driver.find_element_by_id('txtCaptchCode').send_keys(code) driver.find_element_by_id('btnSearch').click() break else: print('Captcha passed') passed_captcha = True driver.minimize_window() def process_pages(driver: webdriver.Chrome, search_type='firm') -> list: result = [] end_of_query = False while not end_of_query: table_element = driver.find_element_by_id('Tbl_Search').get_attribute('outerHTML') if search_type.lower() == 'lawyers': parse_lawyers_table(table_element, result) else: parse_firms_table(table_element, result) paging_footer = driver.find_element_by_id('pagingFooter') next_page = paging_footer.find_element_by_id('next') if 'disabledLink' in next_page.get_attribute('class'): end_of_query = True else: driver.execute_script("arguments[0].click();", next_page) return result def parse_lawyers_table(table, result): # TODO: A lawyer's table if there is demand. print("Lawyers scraping is not supported.") def parse_firms_table(table, result): soup = BeautifulSoup(table, features="html5lib") main_table = soup.body.table.tbody rows = [item for item in main_table.children] for row in rows: item = Firm() body = row.table.tbody descendants = [item for item in body.descendants] item.name_of_law_practice = descendants[7].get_text() item.type_of_law_practice = descendants[13].get_text() item.key_practice_areas = parse_key_practice_areas(descendants[21].get_text()) item.size_of_law_practice = descendants[28].get_text() item.telephone_no = descendants[34].get_text() item.website = descendants[41].get_text() item.email = descendants[47].get_text() item.address = descendants[54].get_text().replace('\n\n', " ") result.append(item) def parse_key_practice_areas(text): if text == 'N.A.': return [] else: return text.split(', ') def save_csv(results, outfile, root, search_type): import csv import dataclasses fields = ['name_of_law_practice', 'type_of_law_practice', 'key_practice_areas', 'size_of_law_practice', 'telephone_no', 'website', 'email', 'address'] if not outfile: outfile = get_save_file_path(root, search_type, 'csv') with open(outfile, 'w', newline='', encoding='utf-8') as outf: writer = csv.DictWriter(outf, fieldnames=fields) writer.writeheader() results_dict = [dataclasses.asdict(result) for result in results] writer.writerows(results_dict) return outfile def get_save_file_path(root, search_type, ext): import datetime return os.path.join(root, "{} {}.{}".format(search_type, datetime.date.today(), ext)) @dataclasses.dataclass class Firm: name_of_law_practice: str = '' type_of_law_practice: str = '' key_practice_areas: list = dataclasses.field(default_factory=list) size_of_law_practice: str = '' telephone_no: str = '' website: str = '' email: str = '' address: str = '' @dataclasses.dataclass class Lawyer: name: str registration_type: str = '' job_title: str = '' date_of_admission: str = '' key_practice_areas: list = dataclasses.field(default_factory=list) name_of_law_practice: str = '' telephone_no: str = '' website: str = '' email: str = '' address: str = '' if __name__ == '__main__': lsra_scraper()
true
30e67b7c9969de4b1f599583cbf2af042af409c1
Python
mxmaslin/dvmn
/async_python/dvmn_async_python_lesson1/frames/fire.py
UTF-8
900
3.296875
3
[ "MIT" ]
permissive
import asyncio import curses async def fire(canvas, start_row, start_column, rows_speed=-0.3, columns_speed=0): """Display animation of gun shot. Direction and speed can be specified.""" row, column = start_row, start_column canvas.addstr(round(row), round(column), '*') await asyncio.sleep(0) canvas.addstr(round(row), round(column), 'O') await asyncio.sleep(0) canvas.addstr(round(row), round(column), ' ') row += rows_speed column += columns_speed symbol = '-' if columns_speed else '|' rows, columns = canvas.getmaxyx() max_row, max_column = rows - 1, columns - 1 curses.beep() while 0 < row < max_row and 0 < column < max_column: canvas.addstr(round(row), round(column), symbol) await asyncio.sleep(0) canvas.addstr(round(row), round(column), ' ') row += rows_speed column += columns_speed
true
fd27aa3abbaa854f031d984b91ae65fe3a326c6b
Python
tony32769/sciquence
/sciquence/text_processing/text_generator.py
UTF-8
3,440
2.609375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- # Krzysztof Joachimiak 2017 # sciquence: Time series & sequences in Python # # Text generator # Author: Krzysztof Joachimiak # # License: MIT import theano import theano.tensor as T from sciquence.nn.neural_utils import init_weight import numpy as np from sklearn.utils import shuffle import matplotlib.pyplot as plt class TextGenerator(object): def __init__(self, D, M, V, learning_rate=10e-4, momentum=0.99, reg=1., activation=T.tanh, epochs=10, show_fig=True): self.D = D # przestrzeń wektorowa opisująca self.M = M self.V = V self.momentum = momentum self.learning_rate = learning_rate self.epochs = epochs self.show_fig = show_fig self.f = activation # Variables self.We = theano.shared(init_weight(V, D)) self.Wx = theano.shared(init_weight(D, M)) self.Wh = theano.shared(init_weight(M, M)) self.bh = theano.shared(np.zeros(M)) self.h0 = theano.shared(np.zeros(M)) self.Wo = theano.shared(init_weight(M, V)) self.bo = theano.shared(np.zeros(V)) # Theano variables self.Xvar = T.ivector('X') # wektor indeksów self.Yvar = T.ivector('Y') self.params = [self.We, self.Wx, self.Wh, self.bh, self.h0, self.Wo, self.bo] def fit(self, X): Ei = self.We[self.Xvar] def step(x_t, h_t1): h_t = self.f(x_t.dot(self.Wx) + h_t1.dot(self.Wh) + self.bh) y_t = T.nnet.softmax(h_t.dot(self.Wo) + self.bo) return h_t, y_t [h, y], _ = theano.scan( fn=step, outputs_info=[self.h0, None], sequences=Ei, n_steps=Ei.shape[0] ) py_x = y[:, 0, :] prediction = T.argmax(py_x, axis=1) cost = -T.mean(T.log(py_x[T.arange(self.Xvar.shape[0], self.Yvar)])) grads = T.grad(cost, self.params) dparams = [theano.shared(p.get_value()*0) for p in self.params] updates = [ (p, p + self.momentum * dp - self.learning_rate) for p, dp, g in zip(self.params, dparams, grads) ] + [ (dp, self.momentum*dp - self.learning_rate*g) for dp, g in zip(dparams, grads) ] self.predict_op = theano.function([self.Xvar], prediction) self.train_op = theano.shared( [self.Xvar, self.Yvar], [cost, prediction], updates=updates ) costs = [] n_total = sum((len(sentence) + 1) for sentence in X) for i in xrange(self.epochs): X = shuffle(X) n_correct = 0 cost = 0 for j in xrange(self.N): input_sequence = [0] + X[j] output_sentence = X[j] + [1] c, p = self.train_op(input_sequence, output_sentence) cost += c for pj, xj in zip(p, output_sentence): if pj == xj: n_correct += 1 print "i:", i, "cost:", "correct rate:", (float(n_correct) / n_total) costs.append(cost) if self.show_fig: plt.plot(costs) plt.show() def save(self, filename): np.savez(filename, *[p.get_value() for p in self.params]) @staticmethod def load(filename, activation): npz = np.load(filename) We = npz['']
true
2ab6b9e25060d15b74ed40203a41f0e05257f4dc
Python
thu-spmi/semi-EBM
/train/scorer.py
UTF-8
4,260
2.890625
3
[ "Apache-2.0" ]
permissive
# Copyright 2020 Tsinghua University, Author: Yunfu Song # Apache 2.0. # This script contrains functions to calculate F1 score. import abc def get_span_labels(sentence_tags, inv_label_mapping=None): """Go from token-level labels to list of entities (start, end, class).""" if inv_label_mapping: sentence_tags = [inv_label_mapping[i] for i in sentence_tags] span_labels = [] last = 'O' start = -1 for i, tag in enumerate(sentence_tags): pos, _ = (None, 'O') if tag in ['O','<s>','</s>'] else tag.split('-') if (pos == 'S' or pos == 'B' or tag == 'O') and last != 'O': span_labels.append((start, i - 1, last.split('-')[-1])) if pos == 'B' or pos == 'S' or last == 'O': start = i last = tag if sentence_tags[-1] != 'O': span_labels.append((start, len(sentence_tags) - 1, sentence_tags[-1].split('-')[-1])) return span_labels def get_tags(span_labels, length, encoding): """Converts a list of entities to token-label labels based on the provided encoding (e.g., BIOES). """ tags = ['O' for _ in range(length)] for s, e, t in span_labels: for i in range(s, e + 1): tags[i] = 'I-' + t if 'E' in encoding: tags[e] = 'E-' + t if 'B' in encoding: tags[s] = 'B-' + t if 'S' in encoding and s == e: tags[s] = 'S-' + t return tags class Scorer(object): __metaclass__ = abc.ABCMeta def __init__(self): self._updated = False self._cached_results = {} @abc.abstractmethod def update(self, examples, predictions): self._updated = True @abc.abstractmethod def _get_results(self): return [] def get_results(self, prefix=""): results = self._get_results() if self._updated else self._cached_results self._cached_results = results self._updated = False return [(prefix + k, v) for k, v in results] def results_str(self): return " - ".join(["{:}: {:.2f}".format(k, v) for k, v in self.get_results()]) class WordLevelScorer(Scorer): __metaclass__ = abc.ABCMeta def __init__(self): super(WordLevelScorer, self).__init__() self._total_words = 0 self._examples = [] self._preds = [] def update(self, examples, predictions): super(WordLevelScorer, self).update(examples, predictions) n_words = 0 for example, preds in zip(examples, predictions): self._examples.append(example[1:len(example) - 1]) self._preds.append(list(preds)[1:len(example) - 1]) n_words += len(example) - 2 self._total_words += n_words class F1Scorer(WordLevelScorer): __metaclass__ = abc.ABCMeta def __init__(self): super(F1Scorer, self).__init__() self._n_correct, self._n_predicted, self._n_gold = 0, 0, 0 def _get_results(self): if self._n_correct == 0: p, r, f1 = 0, 0, 0 else: p = 100.0 * self._n_correct / self._n_predicted r = 100.0 * self._n_correct / self._n_gold f1 = 2 * p * r / (p + r) return [ ("precision", p), ("recall", r), ("f1", f1) ] class EntityLevelF1Scorer(F1Scorer): def __init__(self, label_mapping=None): super(EntityLevelF1Scorer, self).__init__() self._inv_label_mapping=label_mapping def _get_results(self): self._n_correct, self._n_predicted, self._n_gold = 0, 0, 0 for example, preds in zip(self._examples, self._preds): sent_spans = set(get_span_labels( example, self._inv_label_mapping)) span_preds = set(get_span_labels( preds, self._inv_label_mapping)) self._n_correct += len(sent_spans & span_preds) self._n_gold += len(sent_spans) self._n_predicted += len(span_preds) return super(EntityLevelF1Scorer, self)._get_results() class AccuracyScorer(WordLevelScorer): def __init__(self, auto_fail_label=None): super(AccuracyScorer, self).__init__() self._auto_fail_label = auto_fail_label def _get_results(self): correct, count = 0, 0 for example, preds in zip(self._examples, self._preds): for y_true, y_pred in zip(example, preds): count += 1 correct += (1 if y_pred == y_true and y_true != self._auto_fail_label else 0) return [ ("accuracy", 100.0 * correct / count) ]
true
01df17c160a3324587cb89ba32ad9ef5372212ee
Python
ollamh/addressbook
/addressbook/tests.py
UTF-8
3,925
2.90625
3
[]
no_license
import os import unittest from addressbook.core import ( AddressBook, Group, Person, ValidationError ) from .tst import Node class ABTest(unittest.TestCase): def setUp(self): self.ab = AddressBook('test.dat') self.person = Person( 'Test', 'Person', 'Test address', '+18005555555', 'test@example.com') self.group = Group('Test group') def tearDown(self): os.remove('test.dat') def test_ab_add_person(self): self.assertEqual(len(self.ab._book), 0) self.ab.add(self.person) self.assertEqual(len(self.ab._book), 1) def test_create_person_fail_phone(self): self.assertEqual(len(self.ab._book), 0) with self.assertRaisesRegex(ValidationError, 'Phone \+180055555 is not valid'): person = Person( 'Test', 'Person', 'Test address', '+180055555', 'test@example.com') self.assertEqual(len(self.ab._book), 0) def test_create_person_fail_email(self): self.assertEqual(len(self.ab._book), 0) with self.assertRaisesRegex(ValidationError, 'Email testexample.com is not valid'): person = Person( 'Test', 'Person', 'Test address', '+18005555555', 'testexample.com') self.assertEqual(len(self.ab._book), 0) def test_person_full_name(self): self.assertEqual(self.person.full_name, 'Test Person') def test_person_string(self): self.assertEqual(self.person.__str__(), 'Test Person (+18005555555) Test address test@example.com') def test_ab_add_person_fail(self): with self.assertRaises(AssertionError): self.ab.add('Wrong type') def test_ab_add_group(self): self.assertEqual(len(self.ab._groups), 0) self.ab.add(self.group) self.assertEqual(len(self.ab._groups), 1) def test_ab_search(self): self.ab.add(self.person) person = Person( 'Test', 'Second', 'Test address', '+18005555555', 'noway@example.com') self.ab.add(person) result = self.ab.search('test') self.assertEqual(len(result), 2) result = self.ab.search('noway@example.com') self.assertEqual(len(result), 1) result = self.ab.search('noway') self.assertEqual(len(result), 1) result = self.ab.search('nothing') self.assertEqual(len(result), 0) def test_add_person_to_group(self): self.assertFalse(self.person.is_member_of('Test group')) self.group.add_person(self.person) self.assertTrue(self.person.is_member_of('Test group')) def test_remove_person_from_group(self): self.assertFalse(self.person.is_member_of('Test group')) self.group.add_person(self.person) self.assertTrue(self.person.is_member_of('Test group')) self.group.remove_person(self.person) self.assertFalse(self.person.is_member_of('Test group')) def test_get_group(self): self.ab.add(self.group) result = self.ab.get_group('Test group') self.assertEqual(len(result), 1) def test_tst_node_string(self): node = Node('a', key='b') self.assertEqual(node.__str__(), "Node: a {'b'}") def test_tst_in_tree(self): tree = self.ab._tst self.ab.add(self.person) self.assertTrue(tree.in_tree('test')) self.assertFalse(tree.in_tree('nothing')) def test_tst_traverse(self): tree = self.ab._tst self.ab.add(self.person) result = tree.traverse() self.assertSequenceEqual(result, [ 'p', 'e', 'r', 's', 'o', 'n', 't', 'e', 's', 't', 't', 'e', 's', 't', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', 't', 'e', 's', 't', 'p', 'e', 'r', 's', 'o', 'n']) if __name__ == '__main__': unittest.main()
true
9528de8144db8cf606205aa9ecae26f625dfcb75
Python
sureshkumarkadi/Pytest
/Library/Test.py
UTF-8
2,790
3.375
3
[]
no_license
s =[] for i in range(10): s.append(i**2) print(s) add = lambda x,y:x+y print(add(1,2)) #download a file from web ##import requests ##file_url = 'https://www.facebook.com/favicon.ico' ## ##image = requests.get(file_url) ##print(image) ## ##with open('D:/eTender/facebook.ico','wb') as f: ## f.write(image.content) dict = {'a':1,'b':2} print(dict.keys()) print(dict.values()) for i in dict.items(): print(i) string = 'SURESH' print(string.lower()) print(string.upper()) print(string.swapcase()) lower =[] upper = [] with open('D:/test.txt','r') as fh: count = 0 text = fh.read() for character in text: #if character.islower(): #a= lower.append(character) #print(character) if character.isupper(): print(len(character)) print(character) test = [1,5,3,9,8,34] test.sort() print(test) ##import xlrd ##import openpyxl #Reading data from Excel ##book=xlrd.open_workbook('D:/Test/details2.xlsx') ##sheet=book.sheet_by_name('Old') ## ##i=0 ##while i < 2: ## rows = sheet.row_values(i) ## print(rows) ## i=i+1 x = [1,5,6,9,10,14,34] x.sort() print(x) print(x[-1]) print(x[-2]) newlist =0 for i in x: newlist = i+newlist print(newlist) ##import random ## ##with open('D:/test.txt','r') as fh: ## value = fh.read().splitlines() ## print(value) ## print(random.choice(value)) print (sum(1 for line in open('D:/test.txt','r') )) #duplicate list1 = [1,1,2,2,3,3,4,5,6,6] newlist = [] for i in list1: if i not in newlist: newlist.append(i) print(newlist) #reverse a string string = 'suresh' emptystr ="" for i in string: emptystr= i+emptystr print(emptystr) #sorting without using sort menthod list2 = [1,3,4,56,1,2] newlist1 =[] for i in range(len(list2)): minvalue = min(list2) newlist1.append(minvalue) list2.remove(minvalue) print(newlist1) with open('D:\Test\employees - Copy.csv', 'r') as t1, open('D:\Test\employees.csv', 'r') as t2: fileone = t1.readlines() filetwo = t2.readlines() with open('D:/Test/update.csv', 'w') as outFile: for line in filetwo: #print(line) if line not in fileone: #print(line) outFile.write(line) with open('D:/test.txt','r') as f: value=f.read() upper=[] lower=[] for i in value: if i.isupper(): upper.append(i) else: lower.append(i) print(len(upper)) print(len(lower)) print(upper) print(lower) test1 = [1,2,2,3,1] newlist = [] for i in test1: if i not in newlist: newlist.append(i) print(newlist) #PyTest Fixures import pytest @pytest.fixture() def setup(): print("once efore every method") def testmethod1(setup): print("test method1") def testmethod2(setup): print("test method2")
true
50620ad4373512cfead7cbbd9cf2dc70a1eaf876
Python
roshancspro/Python_Starter
/doublecola.py
UTF-8
1,164
3.375
3
[]
no_license
import math def whoIsNext(names, r): if(names == None): return if(r == None or r == 0): return total = len(names) if(r <= total): return names[r-1] #Geometric Sequence find nth repetition logic currVal = r // total # 2 is geometric difference nVal = math.floor(math.log(currVal,2)) try: #print(nVal) twoPowVal = pow(2,nVal) #total is starting value sum = total * ((1 - twoPowVal)//(1-2)) #getting index of next value # Assumption is diff will never diffquo = (r - sum)//twoPowVal #print("quo",diffquo) diffrem = (r - sum)%twoPowVal #print("rem",diffrem) if(diffrem > 0): diffrem = 1 indexVal = (diffquo+diffrem)%total #print("index",indexVal) return names[indexVal-1] except IndexError: return names[0] print(whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 1)) print(whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 52)) print(whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 7230702951))
true
f3ce29dcdfa33b59bfe5b109533b78fa60e3b649
Python
luccavn/random_graphs
/random_graphs.py
UTF-8
11,808
2.765625
3
[ "MIT" ]
permissive
from collections import deque, namedtuple from random import randint, randrange, choice from itertools import permutations from time import time from math import sqrt import pygame global MAX_NODES global DEST_NODE COMPLETE_GRAPH = False INCLUDE_BRUTEFORCE_TRAVELLER = False MAX_NODES = 8 MAX_NEIGHBOURS = 2 MIN_COST = 1 MAX_COST = 14 SOURCE_NODE = '1' DEST_NODE = str(MAX_NODES) APP_FONT = 'Comic Sans MS' FONT_COLOR = (255,255,255) SCREEN_SIZE = 1280, 600 BG_COLOR = (255,255,255) NODE_COLOR = (0,0,0) PNODE_COLOR = (80,220,100) NODE_RADIUS = 16 inf = float('inf') Edge = namedtuple('Edge', 'start, end, cost') global gnodes global selected global path_dijkstra global path_trav_brute global path_trav_heur gnodes = None selected = 0 def timing(f): def wrap(*args): time1 = time() ret = f(*args) time2 = time() print('{:s} = {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0)) return ret return wrap def make_edge(start, end, cost=1): return Edge(start, end, cost) class Graph: def __init__(self, edges): wrong_edges = [i for i in edges if len(i) not in [2, 3]] if wrong_edges: raise ValueError('Wrong edges data: {}'.format(wrong_edges)) self.edges = [make_edge(*edge) for edge in edges] @property def vertices(self): return set( sum( ([edge.start, edge.end] for edge in self.edges), [] ) ) def get_node_pairs(self, n1, n2, both_ends=True): if both_ends: node_pairs = [[n1, n2], [n2, n1]] else: node_pairs = [[n1, n2]] return node_pairs def remove_edge(self, n1, n2, both_ends=True): node_pairs = self.get_node_pairs(n1, n2, both_ends) edges = self.edges[:] for edge in edges: if [edge.start, edge.end] in node_pairs: self.edges.remove(edge) def add_edge(self, n1, n2, cost=1, both_ends=True): node_pairs = self.get_node_pairs(n1, n2, both_ends) for edge in self.edges: if [edge.start, edge.end] in node_pairs: return ValueError('Edge {} {} already exists'.format(n1, n2)) self.edges.append(Edge(start=n1, end=n2, cost=cost)) if both_ends: self.edges.append(Edge(start=n2, end=n1, cost=cost)) @property def neighbours(self): neighbours = {vertex: set() for vertex in self.vertices} for edge in self.edges: neighbours[edge.start].add((edge.end, edge.cost)) return neighbours @timing def dijkstra(self, source, dest): # Verifica se aresta inicial existe no grafo assert source in self.vertices, 'Such source node doesn\'t exist' # Atribui uma distância infinita em cada vértice do grafo distances = {vertex: inf for vertex in self.vertices} previous_vertices = { vertex: None for vertex in self.vertices } distances[source] = 0 vertices = self.vertices.copy() while vertices: current_vertex = min( vertices, key=lambda vertex: distances[vertex]) vertices.remove(current_vertex) if distances[current_vertex] == inf: break for neighbour, cost in self.neighbours[current_vertex]: alternative_route = distances[current_vertex] + cost if alternative_route < distances[neighbour]: distances[neighbour] = alternative_route previous_vertices[neighbour] = current_vertex path, current_vertex = deque(), dest while previous_vertices[current_vertex] is not None: path.appendleft(current_vertex) current_vertex = previous_vertices[current_vertex] if path: path.appendleft(current_vertex) return path def get_node_bypos(pos): for node in gnodes: if node.get_pos() == pos: return node return None def translate_nodes_dijkstra(nodes): tnodes = list() for node in nodes: for neighbour in node.get_neighbours(): tnodes.append((node.get_name(), neighbour.get_name(), neighbour.get_cost())) return tnodes def draw(): global selected SCREEN.fill(BG_COLOR) for node in gnodes: node.update() for neighbour in node.get_neighbours(): pygame.draw.line(SCREEN, NODE_COLOR, node.get_pos(), neighbour.get_pos(), 2) if not selected: draw_pathlines(path_dijkstra) else: draw_pathlines(path_trav_heur) node.draw() neighbour.draw() def draw_pathlines(path): pathlist = list(path) for i in range(len(pathlist)-1): node1 = get_node_by_name(pathlist[i]) node2 = get_node_by_name(pathlist[i+1]) pygame.draw.line(SCREEN, PNODE_COLOR, node1.get_pos(), node2.get_pos(), 2) def get_node_by_name(name): for node in gnodes: if node.get_name() == name: return node return None class Node: def __init__(self, name, cost, pos, color): self.name = name self.neighbours = set() self.cost = cost self.pos = pos self.color = color def update(self): global selected if not selected: self.color = PNODE_COLOR if self.name in path_dijkstra else NODE_COLOR else: self.color = PNODE_COLOR if self.name in path_trav_heur else NODE_COLOR def draw(self): title_text = app_font3.render('Dijkstra' if not selected else 'Traveller', False, NODE_COLOR) name_text = app_font.render(self.name, False, FONT_COLOR if self.color == NODE_COLOR else NODE_COLOR) cost_text = app_font2.render(str(self.cost), False, NODE_COLOR) pygame.draw.circle(SCREEN, self.color, self.pos, NODE_RADIUS) SCREEN.blit(name_text, (self.pos[0]-NODE_RADIUS/1.5, self.pos[1]-NODE_RADIUS/1.5)) SCREEN.blit(cost_text, (self.pos[0]-NODE_RADIUS*1.75, self.pos[1]-NODE_RADIUS*1.5)) SCREEN.blit(title_text, (SCREEN_SIZE[0]/2.25, NODE_RADIUS)) def get_name(self): return self.name def get_cost(self): return self.cost def get_neighbours(self): return list(self.neighbours) def add_neighbour(self, node): self.neighbours.add(node) def get_pos(self): return self.pos def get_color(self): return self.color def repair_nodelist(points, start=None): if start is None: start = points[0] must_visit = points path = [start] must_visit.remove(start) while must_visit: nearest = min(must_visit, key=lambda x: distance(path[-1], x)) path.append(nearest) must_visit.remove(nearest) for i in range(len(path)-1): get_node_bypos(path[i]).add_neighbour(get_node_bypos(path[i+1])) @timing def random_graph(min_cost, max_cost): count = 1 nodes = list() for i in range(MAX_NODES): rand_pos = (randrange(NODE_RADIUS, SCREEN_SIZE[0]-NODE_RADIUS, 2*NODE_RADIUS), randrange(NODE_RADIUS, SCREEN_SIZE[1]-NODE_RADIUS, 2*NODE_RADIUS)) rand_cost = randint(min_cost, max_cost) node = Node(str(count), rand_cost, rand_pos, NODE_COLOR) if nodes: if COMPLETE_GRAPH: for n in nodes: neighbour = n node.neighbours.add(neighbour) neighbour.neighbours.add(node) else: for i in range(0, randrange(1, MAX_NEIGHBOURS)): neighbour = choice(nodes) node.neighbours.add(neighbour) neighbour.neighbours.add(node) nodes.append(node) count += 1 return nodes def distance(point1, point2): return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5 def total_distance(points): return sum([distance(point, points[index + 1]) for index, point in enumerate(points[:-1])]) @timing def travelling_salesman_bruteforce(points, start=None): if start is None: start = points[0] return min([perm for perm in permutations(points) if perm[0] == start], key=total_distance) @timing def travelling_salesman(start, end): must_visit = [node.get_pos() for node in gnodes] path = [start.get_pos()] must_visit.remove(start.get_pos()) while must_visit: nearest = min(must_visit, key=lambda x: distance(path[-1], x)) path.append(nearest) must_visit.remove(nearest) return path def fix_traveller_path(path): for neigh in get_node_bypos(path[-1]).get_neighbours(): if neigh.get_pos() == gnodes[-1].get_pos(): path.append(gnodes[-1].get_pos()) return path def init(): global SCREEN global app_font global app_font2 global app_font3 pygame.init() #SCREEN = pygame.display.set_mode(SCREEN_SIZE, pygame.FULLSCREEN) SCREEN = pygame.display.set_mode(SCREEN_SIZE) pygame.font.init() app_font = pygame.font.SysFont(APP_FONT, NODE_RADIUS+2, False) app_font2 = pygame.font.SysFont(APP_FONT, NODE_RADIUS-2, False) app_font3 = pygame.font.SysFont(APP_FONT, 22, False) def load(): global gnodes global path_dijkstra global path_trav_brute global path_trav_heur print('') gnodes = random_graph(MIN_COST, MAX_COST) repair_nodelist([node.get_pos() for node in gnodes]) graph = Graph(translate_nodes_dijkstra(gnodes)) path_dijkstra = graph.dijkstra(SOURCE_NODE, DEST_NODE) #print('Dijkstra path from node {} to node {} = {}'.format(SOURCE_NODE, DEST_NODE, list(path_dijkstra))) print(gnodes[0].get_name(), gnodes[MAX_NODES-1].get_name()) path_trav_heur = fix_traveller_path(travelling_salesman(gnodes[0], gnodes[MAX_NODES-1])) path_trav_heur = [get_node_bypos(node).get_name() for node in path_trav_heur] #print('Travelling Salesman (heuristic) path from node {} to node {} = {}'.format(SOURCE_NODE, DEST_NODE, path_trav_heur)) if INCLUDE_BRUTEFORCE_TRAVELLER: path_trav_brute = travelling_salesman_bruteforce([node.get_pos() for node in gnodes]) def main(): load() try: global selected global MAX_NODES global DEST_NODE init() while True: pygame.event.pump() if pygame.key.get_pressed()[pygame.K_ESCAPE]: break if pygame.key.get_pressed()[pygame.K_SPACE]: load() if pygame.key.get_pressed()[pygame.K_LEFT]: selected -= 1 if pygame.key.get_pressed()[pygame.K_RIGHT]: selected += 1 if pygame.key.get_pressed()[pygame.K_DOWN]: MAX_NODES = int(MAX_NODES/2) DEST_NODE = str(MAX_NODES) load() if pygame.key.get_pressed()[pygame.K_UP]: MAX_NODES *= 2 DEST_NODE = str(MAX_NODES) load() if selected < 0: selected = 1 elif selected > 1: selected = 0 draw() pygame.display.flip() pygame.time.delay(60) except Exception as ex: print(ex) finally: quit() if __name__ == "__main__": main()
true
bbb665758e69224351ade3e60cb790d37e1c2512
Python
ItManHarry/Python
/PythonCSDN/code/book/chapter10/code-counter.py
UTF-8
1,257
3.8125
4
[]
no_license
from collections import Counter print('-' * 80) c1 = Counter() print(c1) print('-' * 80) c2 = Counter('hahaIamHarry') print(c2) print('-' * 80) c3 = Counter(['a','Go','Java','Go','Python','Groovy','Kotlin','Java','C','a']) print(c3) print('-' * 80) c4 = Counter({'a':20,'b':30,'c':29}) print(c4) print('-' * 80) c5 = Counter(Java=100,Python=200,C=220,JavaScript=300) print(c5) #打印每个元素 print(list(c5.elements())) print('-' * 80) #求value总和 print(sum(c5.values())) print('-' * 80) #转换为list,只保留key print(list(c5)) print('-' * 80) #转换为set,至保留key print(set(c5)) print('-' * 80) #转换为字典dict print(dict(c5)) print('-' * 80) #转换为list,包含key和出现的次数 l = c5.items() print(l) print('-' * 80) #将转换后的"l"再转换为Counter c = Counter(dict(l)) print(c) print('-' * 80) #清空Counter c.clear() print(c) print('-' * 80) c1 = Counter(a=3,b=2,c=-1) c2 = Counter(a=1,b=-2,c=3) print('Count 1 is : ', c1) print('Count 2 is : ', c2) #执行加 print('Count1 + Counter2 : ', c1 + c2) #执行减 print('Count1 - Counter2 : ', c1 - c2) #交 print('Count1 & Counter2 : ', c1 & c2) #并 print('Count1 |Counter2 : ', c1 | c2) #求正 print('+c1 : ', +c1) #求负 print('-c2 : ', -c2) print('-' * 80)
true
fda0f7d0a0240de8ae9295e8c522e7f1235828b3
Python
xiaohaoxing/mioj
/problem110.py
UTF-8
1,034
3.59375
4
[]
no_license
def solution(line): num_p, p, q = line.split(' ') #计算出 base 10的数字 num_10 = 0; p = int(p) for char in num_p: num_10 *= p if char == 'a': num_10 += 10 elif char == 'b': num_10 += 11 elif char == 'c': num_10 += 12 elif char == 'd': num_10 += 13 elif char == 'e': num_10 += 14 elif char == 'f': num_10 += 15 else: num_10 += int(char) #转化为 q 进制的 q = int(q) reminder = num_10 num_q = '' while(reminder > 0): digit = reminder % q reminder = int(reminder / q) num_q = get_num_char(digit) + num_q return num_q def get_num_char(num): if num == 10: return 'a' elif num == 11: return 'b' elif num == 12: return 'c' elif num == 13: return 'd' elif num == 14: return 'e' elif num == 15: return 'f' else: return str(num) line = "31 10 16" result = solution(line) print(result)
true
0760854c66a6d9a4f7c7c189c27b7501ce188c43
Python
blibrano/PythonProjects
/minHeap.py
UTF-8
2,072
3.53125
4
[]
no_license
class minHeap: def __init__(self): self.array=[(0,0)] self.count=0 def is_empty(self): if self.count==0: return True else: return False def swap(self,x,y,vertices): a,b=self.array[x] c,d=self.array[y] vertices[b],vertices[d]=vertices[d],vertices[b] self.array[x],self.array[y]=self.array[y],self.array[x] def rise(self,i,vertices): while (i//2 > 0): if(self.array[i] < self.array[i//2]): self.swap(i,(i//2),vertices) i=i//2 def insert(self,key,value,vertices): item=(key,value) vertices[value]=self.count+1 self.array.append(item) self.count=self.count+1 self.rise(self.count,vertices) def sink(self,i,vertices): while (i*2) <= self.count: small_child=self.min_child(i) if self.array[i]> self.array[small_child] : self.swap(i,small_child,vertices) i=small_child def min_child(self,i): if ((i*2+1)>self.count): return i*2 else: if self.array[i*2]<self.array[i*2+1]: return i*2 else: return i*2+1 def delMin(self,vertices): self.swap(1, self.count,vertices) x,y = self.array[self.count] vertices[y]=-1 self.array.pop(self.count) self.count -= 1 self.sink(1,vertices) return x,y def length(self): return self.count if __name__ == "__main__": my_list = [[10,1],[9,3],[8,7],[7,5],[6,6],[5,2],[4,8],[3,9],[2,4],[1,10]] vertices= [-2 for i in range (11)] New=minHeap() New.insert(0,0,vertices) for i in range (len(my_list)): New.insert(my_list[i][0],my_list[i][1],vertices) #print(vertices) print (New.array) print(vertices) New.delMin(vertices) print (New.array) print(vertices)
true
794e0948f832a93844447a8f5af4e86736813c00
Python
turbcool/pymorphy-nltk
/main.py
UTF-8
2,312
3.84375
4
[]
no_license
#0. Включаем в программу сторонние библиотеки: import pymorphy2 import nltk import string from nltk.tokenize import sent_tokenize from nltk.corpus import stopwords #Эта штука докачивает нужные пакеты из интернета, если их у тебя нет: nltk.download("punkt") nltk.download("stopwords") #1. Задаём исходный текст, с которым будем работать: input_text = "Привет мир. Привет ещё раз. Привет! Тест програмы. Тест2. Да! Да? нет! К новому году я куплю килограмм мандаринов." print("Исходный текст:") print(input_text) #2. Превращаем строку с исходным текстом в массив слов: tokens = nltk.word_tokenize(input_text) #Вход - строка input_text, выход - массив слов. #3. Осуществляем "токенизацию" - очищаем слова, чтобы остался только их корень ("токен") #Удаляет знаки пунктуации из каждого элемента в массиве: tokens = [i for i in tokens if ( i not in string.punctuation )] #Удаляет слова-пустышки из массива слов: stop_words = stopwords.words('russian') stop_words.extend(['что', 'это', 'так', 'вот', 'быть', 'как', 'в', '—', 'к', 'на']) tokens = [i for i in tokens if ( i not in stop_words )] print("Слова:") print(tokens) #4. Считаем сколько раз нам встретилось каждое слово: count = {} #count - содержит пары значений [word: count] for word in tokens: #Для каждого слова: if (word not in count): #Мы не встречались с таким словом. Значит количество его вхождений равно 1. count[word]=1 #(добавляет пару значений [word: count]) else: #Мы повторно встречаемся с уже добавленным словом: count[word]+=1 #(прибавляет 1 к count в паре значений [word: count]) print(count)
true
43aec529d4c008f2b83ddf2ab3171ace6c201726
Python
Joie-Kim/python_ex
/chap3_exercise/chap3_ex4.py
UTF-8
108
3.828125
4
[]
no_license
# for 문을 사용해 1부터 100까지의 숫자를 출력해 보자. for i in range(1,101): print(i)
true
2a211e24398f99dfb9fc9e05fcb11c5b2b2044e5
Python
LKhushlani/leetcode
/arrays/minRewards.py
UTF-8
490
3.125
3
[]
no_license
def minRewards(scores): # Write your code here. rewards = [1 for _ in scores] for i in range(1, len(scores)): if scores[i] > scores[i-1]: rewards[i] = rewards[i-1] +1 for i in reversed(range(len(scores)-1)): print(i) print("s", scores[i], 's i+1',scores[i+1]) if scores[i] > scores[i+1]: rewards[i]= max(rewards[i], rewards[i+1]+1) return sum(rewards) print(minRewards([8, 4, 2, 1, 3, 6, 7, 9, 5]))
true
e706bd294cccbe165fa1e4c38dfb83581886be98
Python
A01377246/Mision-03
/Rendimiento de un auto.py
UTF-8
2,109
4.375
4
[]
no_license
# Autor: Humberto Carrillo Gómez """Descripción: Este programa calcula el rendimiento de un automóvil en kilometros/litro y millas/galón e imprime los litros de gasolina que necesitará para recorrer cierto kilometraje"}""" #Calcula el rendimiento en km por litro utlizando los km recorridos y los litros de gasolina utilizados def calcularRendimientoKm(km, litrosGas): rendimientoKm= km/litrosGas return rendimientoKm # Convierte los km recorridos a millas def calcularMillas(km): millas= km/1.6093 return millas # Convierte los litros de gasolina a galones def calcularGalones(litrosGas): galones= litrosGas*0.264 return galones # Calcula el rendimiento en millas por galón utilizando las millas recorridas y los galones de gasolina utilizados. def calcularRendimientoMillas(millas, galones): millasPorGalon= millas/galones return millasPorGalon # Calcula los litros de gasolina que serán necesarios para recorrer cierta distancia def calcularGas(km,litrosGas,kmPorRecorrer): gasolinaNecesaria= (kmPorRecorrer*litrosGas)/km return gasolinaNecesaria # Función principal, incorpora a las funciones anteriormente creadas para resolver el problema e impreme las salidas. def main(): km= int(input("Teclea el número de kilometros recorridos: ")) litrosGas= int(input("Teclea el número de litros de gasolina usados: ")) rendimientoKm= calcularRendimientoKm(km,litrosGas) millas=calcularMillas(km) galones=calcularGalones(litrosGas) rendimientoMillasPorGalon= calcularRendimientoMillas(millas,galones) print() print("Si recorres",km,"km con",litrosGas,"litros, el rendimiento es:") print(format(rendimientoKm,".2f"), "km/l") print(format(rendimientoMillasPorGalon,".2f"), "mi/gal") print() kmPorRecorrer = int(input("¿Cuántos kilometros vas a recorrer? ")) gasolinaNecesaria = calcularGas(km, litrosGas, kmPorRecorrer) print() print("Para recorrer",kmPorRecorrer,"necesitas",format(gasolinaNecesaria,".2f"),"litros de gasolina") # Llamar a la función principal main()
true
808d62eccb8831cdc0adda51e50b7d5612d37c6a
Python
JustinLee32/cai_niao_shua_ti
/10.5 双周赛/5081 步进数.py
UTF-8
2,714
3.84375
4
[]
no_license
# 如果一个整数上的每一位数字与其相邻位上的数字的绝对差都是 # 1,那么这个数就是一个「步进数」。 # # 例如,321 # 是一个步进数,而 # 421 # 不是。 # # 给你两个整数,low # 和 # high,请你找出在[low, high] # 范围内的所有步进数,并返回 # 排序后 # 的结果。 # # # # 示例: # # 输入:low = 0, high = 21 # 输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10_7 周赛, 12, 21] # # 提示: # # 0 <= low <= high <= 2 * 10_7 周赛 ^ 9 from typing import List class Solution: def countSteppingNumbers(self, low: int, high: int) -> List[int]: if high <= 10: return list(range(low, high + 1)) self.ans = [] if low <= 10: self.ans += list(range(low, 10)) def _recursive(low, high, num: int) -> None: num_string = str(num) if num_string[-1] == '0': if low <= int(num_string + '1') <= high: self.ans.append(int(num_string + '1')) _recursive(low, high, int(num_string + '1')) elif int(num_string + '1') < low: _recursive(low, high, int(num_string + '1')) elif int(num_string + '1') > high: return elif num_string[-1] == '9': if low <= int(num_string + '8') <= high: self.ans.append(int(num_string + '8')) _recursive(low, high, int(num_string + '8')) elif int(num_string + '8') < low: _recursive(low, high, int(num_string + '8')) elif int(num_string + '8') > high: return else: small_string = str(int(num_string[-1]) - 1) big_string = str(int(num_string[-1]) + 1) subtract_one = int(num_string + small_string) add_one = int(num_string + big_string) if low <= add_one <= high: self.ans.append(add_one) _recursive(low, high, add_one) if low <= subtract_one <= high: self.ans.append(subtract_one) _recursive(low, high, subtract_one) if subtract_one < low: _recursive(low, high, subtract_one) if add_one < low: _recursive(low, high, add_one) if subtract_one > high: return for i in range(1, 10): _recursive(low, high, i) return sorted(self.ans) if __name__ == '__main__': low = 0 high = 15 sol = Solution() print(sol.countSteppingNumbers(low, high))
true
e802da45ce8362f08f7f6ef30e285e265ec2b698
Python
Jake-Len/Rock-Paper-Scissors
/Rock Paper Scissors/HardMode.py
UTF-8
2,785
3.859375
4
[]
no_license
#hard game mode import random past_player_choices = [] #storing past player choices past_computer_choices = [] #storing past computer choices #in hard mode, past choices are stored and evaluated to check for biases toward a certain choice. #the computer checks to see if the player uses one choice more than others and changes its play appropriately. def play_game_hard(): player_choice = int(input("Make your choice! (1 = Rock, 2 = Paper, 3 = Scissors)")) if player_choice == 1: print "You chose Rock" past_player_choices.append(player_choice) elif player_choice == 2: print "You chose Paper" past_player_choices.append(player_choice) else: print "You chose Scissors" past_player_choices.append(player_choice) #appending to player choices works fine. #Computer's turn past_choice_maker() #score() #Play again, lets user pick yes or no play_again = int(input("Would you like to play again? (1 = yes, 2 = no) ")) if play_again == 1: play_game_hard() else: start_menu = int(input("Would you like to return to the main menu? (1 = yes, 2 = no) ")) if(start_menu == 1): introduction() else: print "Goodbye!" #Generate info on past choices to find patterns/most used choices so computer can learn. (markov algorithm) def past_choice_maker(): ch_1 = "Rock" ch_2 = "Paper" ch_3 = "Scissors" rocks = 0 papers = 0 scissors = 0 if len(past_player_choices) == 0: comp_choice = ch_1 #default to rock if there is not bias to base moves off of elif len(past_player_choices) != 0: #establish biases for choice in past_player_choices: if choice == 1: rocks += 1 elif choice == 2: papers += 1 elif choice == 3: scissors += 1 if rocks > scissors & rocks > papers: comp_choice = ch_2#paper past_computer_choices.append(comp_choice) print "Computer chose Paper!" print past_player_choices print rocks, papers, scissors elif papers > scissors & papers > rocks: comp_choice = ch_3#scissors past_computer_choices.append(comp_choice) print "Computer chose Scissors!" print past_player_choices print rocks, papers, scissors elif scissors > rocks & scissors > papers: comp_choice = ch_1 #rock past_computer_choices.append(comp_choice) print "Computer chose Rock!" print past_player_choices print rocks, papers, scissors #fix: not printing if using else statement #always using default otherwise
true
06fe639c9a071885fa0427bf284b718e3299f22e
Python
VenomzGaming/Sp-Battle-royal
/addons/source-python/plugins/battle_royal/menus/backpack.py
UTF-8
3,681
2.5625
3
[]
no_license
## IMPORTS from menus import SimpleMenu from menus import SimpleOption from menus import Text from messages import SayText2 from players.entity import Player from ..entity.battleroyal import _battle_royal from ..entity.player import Player as BrPlayer from ..items.item import Item __all__ = ( 'backpack_menu', ) ## SHOW ENNEMY BACKPACK CONTENT def _backpack_menu_build(menu, index): menu.clear() if hasattr(menu, 'backpack') and hasattr(menu, 'entity'): return br_player = _battle_royal.get_player(Player(index)) menu.append(Text('Inventory')) if len(menu.backpack.values()) != 0: i = 1 for item in menu.backpack.items.values(): menu.append(SimpleOption(i, item.name + ' (x'+str(item.amount)+')', (item_backpack_menu, item))) i += 1 else: menu.append(Text('Empty Backpack')) entity = _battle_royal.get_item_ent(menu.entity) entity.remove() menu.append(Text(' ')) menu.append(SimpleOption(9, 'Close', highlight=True)) def _backpack_menu_select(menu, index, choice): next_menu, item = choice.value if next_menu is not None: next_menu.item = item next_menu.previous_menu = menu return next_menu ## SHOW ITEM INFO def _item_backpack_menu_build(menu, index): menu.clear() br_player = _battle_royal.get_player(Player(index)) menu.append(Text('Item : ' + menu.item.name)) menu.append(Text('Type : ' + menu.item.item_type)) menu.append(Text('Amount : ' + str(menu.item.amount))) menu.append(Text('Total weight : ' + str(menu.item.weight * menu.item.amount) + ' Kg')) menu.append(Text(menu.item.description)) menu.append(Text(' ')) if menu.item.amount > 1: menu.append(SimpleOption(1, 'Take', menu.item)) else: menu.append(SimpleOption(1, 'Take', item_amount_menu)) menu.append(Text(' ')) menu.append(SimpleOption(7, 'Back', menu.previous_menu, highlight=True)) menu.append(SimpleOption(9, 'Close', highlight=True)) def _item_backpack_menu_select(menu, index, choice): br_player = _battle_royal.get_player(Player(index)) item = choice.value if isinstance(item, Item): item.pick_up(br_player) return menu.previous_menu else: amount_menu = item amount_menu.item = menu.item amount_menu.previous_menu = menu return amount_menu def _item_amount_menu_build(menu, index): menu.clear() br_player = _battle_royal.get_player(Player(index)) menu.append(Text('Take : ' + menu.item.name)) menu.append(Text('Amount : ')) menu.append(SimpleOption(1, '1', 1)) menu.append(SimpleOption(2, '5', 5)) menu.append(SimpleOption(3, '10', 10)) menu.append(SimpleOption(4, '15', 15)) menu.append(SimpleOption(5, '20', 20)) menu.append(SimpleOption(6, 'All', None)) menu.append(Text(' ')) menu.append(SimpleOption(7, 'Back', menu.previous_menu, highlight=True)) menu.append(SimpleOption(9, 'Close', highlight=True)) return menu def _item_amount_menu_select(menu, index, choice): br_player = _battle_royal.get_player(Player(index)) item = menu.item amount = choice.value if amount is not None: item.amount = amount item.pick_up(br_player) return menu.previous_menu item_amount_menu = SimpleMenu( build_callback=_item_amount_menu_build, select_callback=_item_amount_menu_select ) item_backpack_menu = SimpleMenu( build_callback=_item_backpack_menu_build, select_callback=_item_backpack_menu_select ) backpack_menu = SimpleMenu( build_callback=_backpack_menu_build, select_callback=_backpack_menu_select )
true
fd48252dd1bd8bd4ebf13673d108be84debba95a
Python
RibinMTC/DockerConfigShare
/unsup_features.py
UTF-8
5,362
2.953125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt from pathlib import Path import os import cv2 import numpy as np from pyemd import emd from PIL import Image import skimage.color from collections import defaultdict import pandas as pd def image_colorfulness(image): '''calculate colorfulness from picture https://www.pyimagesearch.com/2017/06/05/computing-image-colorfulness-with-opencv-and-python/''' # split the image into its respective RGB components B, G, R = cv2.split(image.astype("float")) # compute rg = R - G rg = np.absolute(R - G) # compute yb = 0.5 * (R + G) - B yb = np.absolute(0.5 * (R + G) - B) # compute the mean and standard deviation of both `rg` and `yb` (rbMean, rbStd) = (np.mean(rg), np.std(rg)) (ybMean, ybStd) = (np.mean(yb), np.std(yb)) # combine the mean and standard deviations stdRoot = np.sqrt((rbStd ** 2) + (ybStd ** 2)) meanRoot = np.sqrt((rbMean ** 2) + (ybMean ** 2)) # derive the "colorfulness" metric and return it return stdRoot + (0.3 * meanRoot) def image_colorfulness_emd(im_name): im = Image.open(im_name) pix = im.load() h1 = [1.0/64] * 64 h2 = [0.0] * 64 hist1 = np.array(h1) hist = cv2.calcHist([img], [0, 1, 2], None, [4,4,4], [0, 256, 0, 256, 0, 256]) w,h = im.size for x in range(w): for y in range(h): cbin = int(pix[x,y][0]/64*16 + pix[x,y][1]/64*4 + pix[x,y][2]/64) h2[cbin-1]+=1 hist2 = np.array(h2)/w/h # compute center of cubes c = np.zeros((64,3)) for i in range(64): b = (i%4) * 64 + 32 g = (i%16/4) * 64 + 32 r = (i/16) * 64 + 32 c[i]=(r,g,b) c_luv = skimage.color.rgb2luv(c.reshape(8,8,3)).reshape(64,3) d = np.zeros((64,64)) for x in range(64): d[x,x]=0 for y in xrange(x): dist = np.sqrt( np.square(c_luv[x,0]-c_luv[y,0]) + np.square(c_luv[x,1]-c_luv[y,1]) + np.square(c_luv[x,2]-c_luv[y,2])) d[x,y] = dist d[y,x] = dist colorfullness = emd(hist1, hist2, d) return colorfullness def compute_histogram(src, h_bins = 30, s_bins = 32, scale = 10): '''calculate histogram from picture''' #create images hsv = cv.CreateImage(cv.GetSize(src), 8, 3) hplane = cv.CreateImage(cv.GetSize(src), 8, 1) splane = cv.CreateImage(cv.GetSize(src), 8, 1) vplane = cv.CreateImage(cv.GetSize(src), 8, 1) planes = [hplane, splane] cv.CvtColor(src, hsv, cv.CV_BGR2HSV) cv.CvtPixToPlane(hsv, hplane, splane, vplane, None) #compute histogram hist = cv.CreateHist((h_bins, s_bins), cv.CV_HIST_ARRAY, ranges = ((0, 180),(0, 255)), uniform = True) cv.CalcHist(planes, hist) #compute histogram cv.NormalizeHist(hist, 1.0) #normalize histo return hist def compute_signatures(hist1, hist2, h_bins = 30, s_bins = 32): ''' demos how to convert 2 histograms into 2 signature ''' num_rows = h_bins * s_bins sig1 = cv.CreateMat(num_rows, 3, cv.CV_32FC1) sig2 = cv.CreateMat(num_rows, 3, cv.CV_32FC1) #fill signatures #TODO: for production optimize this, use Numpy for h in range(0, h_bins): for s in range(0, s_bins): bin_val = cv.QueryHistValue_2D(hist1, h, s) cv.Set2D(sig1, h*s_bins + s, 0, bin_val) #bin value cv.Set2D(sig1, h*s_bins + s, 1, h) #coord1 cv.Set2D(sig1, h*s_bins + s, 2, s) #coord2 #signature.2 bin_val2 = cv.QueryHistValue_2D(hist2, h, s) cv.Set2D(sig2, h*s_bins + s, 0, bin_val2) #bin value cv.Set2D(sig2, h*s_bins + s, 1, h) #coord1 cv.Set2D(sig2, h*s_bins + s, 2, s) #coord2 return (sig1, sig2) def compute_emd(src1, src2, h_bins, s_bins, scale): hist1 = compute_histogram(src1, h_bins, s_bins, scale) hist2 = compute_histogram(src2, h_bins, s_bins, scale) sig1, sig2 = compute_signatures(hist1, hist2) emd = cv.CalcEMD2(sig1, sig2, cv.CV_DIST_L2) return emd if __name__ == "__main__": ## TODO: get unsupervised metrics: ideas in The Interestingness of Images # vivid color/ color harmony, good lightning, saliency # alse check with partners data if there is something in common with the predicted features viz = True im_path = './prediction_images/' feat_dict = defaultdict(list) im_list = os.listdir(im_path) for im_name in im_list: # Load image im = cv2.imread(im_path+im_name) feat_dict['ImageFile'].append(im_name) # colorfulness: as the Earth Mover distance (in the LUV color space) of the color histogram of an image HI to a uniform color histogram Huni. # A uniform color histogram is the most colorful possible, thus the smaller the distance, the more colorful the image # im_luv = cv2.cvtColor(im, cv2.COLOR_RGB2Luv) #hist_i = cv2.calcHist([im_luv]) #compute_emd(im_luv, src2, h_bins, s_bins, scale) # version 2 colorfulness = image_colorfulness(im) feat_dict['colorfulness'].append(colorfulness) if viz: plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)) plt.show() print(colorfulness) df = pd.DataFrame(data=feat_dict)
true
8e96bfdf7fe4f90770b880b5f383066e04f9cf2b
Python
realpython/python-basics-exercises
/ch18-graphical-user-interfaces/4-introduction-to-tkinter.py
UTF-8
375
3.546875
4
[]
no_license
# 18.4 - Introduction to Tkinter # Review exercises import tkinter as tk # Exercise 1 window = tk.Tk() label = tk.Label(text="GUIs are great!") label.pack() window.mainloop() # Exercise 2 window = tk.Tk() label = tk.Label(text="Python rocks!") label.pack() window.mainloop() # Exercise 3 window = tk.Tk() label = tk.Label(text="Engage!") label.pack() window.mainloop()
true
d6878792526feac48e9f32d513f860ad13201c2e
Python
swong225/advent-of-code-2017
/shaw/15/sol.py
UTF-8
752
3.21875
3
[ "MIT" ]
permissive
INPUT_A = 703 INPUT_B = 516 a = INPUT_A b = INPUT_B count = 0 for i in range(40000000): a *= 16807 b *= 48271 a %= 2147483647 b %= 2147483647 if (a & 0xFFFF) == (b & 0xFFFF): count += 1 print('part 1', count) a = INPUT_A b = INPUT_B count = 0 comps = 0 change_a = True change_b = True while comps < 5000000: if change_a: a *= 16807 a %= 2147483647 if change_b: b *= 48271 b %= 2147483647 if a % 4 == 0: change_a = False if b % 8 == 0: change_b = False if (not change_a) and (not change_b): change_a = True change_b = True comps += 1 if (a & 0xFFFF) == (b & 0xFFFF): count += 1 print('part 2', count)
true
348d6688e2b3089c3eeafa05db43630e1f02eb19
Python
LeonardoPereirajr/Curso_em_video_Python
/des085b.py
UTF-8
389
4.09375
4
[ "MIT" ]
permissive
numeros=[[], []] valor = 0 for c in range(1,8): valor= int(input(f' Digite o {c}º valor: ')) if valor % 2 == 0: numeros[0].append(valor) if valor % 2 == 1: numeros[1].append(valor) print(numeros) numeros[0].sort() numeros[1].sort() print(f' Os valores pares digitados foram {numeros[0]}.') print(f' Os valores impares digitados foram {numeros[1]}.')
true
d503bab219b920e09d856a95dc85eb08ddcc2a39
Python
Aasthaengg/IBMdataset
/Python_codes/p02677/s799552735.py
UTF-8
159
3.109375
3
[]
no_license
import math a,b,h,m=map(int,input().split()) A=30*h+0.5*m B=6*m point=abs(A-B) C=math.cos(math.radians(min(point,360-point))) print((a**2+b**2-2*a*b*C)**0.5)
true
7d630101fede3bcf73adc416774af83eb87b7f87
Python
dsendik/Sudokunator
/driver_3.py
UTF-8
14,591
3.40625
3
[]
no_license
#!/usr/bin/env python #coding:utf-8 import random import time as time import os """ Each sudoku board is represented as a dictionary with string keys and int values. e.g. my_board['A1'] = 8 """ ROW = "ABCDEFGHI" COL = "123456789" myRowDict = [] myColDict = [] myBoxDict = [] traversal = [] mylist = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'D1', 'D2', 'D3', 'D4', 'D5', 'E6', 'D7', 'D8', 'D9', 'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9' ] mylist.reverse() empties = [] class TimeoutException(Exception): pass def timeout_handler(signum, frame): raise TimeoutException def print_board(board): """Helper function to print board in a square.""" print("-----------------") for i in ROW: row = '' for j in COL: row += (str(board[i + j]) + " ") print(row) def board_to_string(board): """Helper function to convert board dictionary to string for writing.""" ordered_vals = [] for r in ROW: for c in COL: ordered_vals.append(str(board[r + c])) return ''.join(ordered_vals) def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] def split_dict_equally(input_dict, chunks=2): "Splits dict by keys. Returns a list of dictionaries." # prep with empty dicts return_list = [dict() for idx in range(chunks)] idx = 0 for k,v in input_dict.items(): return_list[idx][k] = v if idx < chunks-1: # indexes start at 0 idx += 1 else: idx = 0 return return_list def makeColDict(board): myColDict = split_dict_equally(board, 9) return myColDict def makeRowDict(board, myRowDict): rowDict1 = {k: board[k] for k in board.keys() & {'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9'}} rowDict2 = {k: board[k] for k in board.keys() & {'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9'}} rowDict3 = {k: board[k] for k in board.keys() & {'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'}} rowDict4 = {k: board[k] for k in board.keys() & {'D1', 'D2', 'D3', 'D4', 'D5', 'E6', 'D7', 'D8', 'D9'}} rowDict5 = {k: board[k] for k in board.keys() & {'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9'}} rowDict6 = {k: board[k] for k in board.keys() & {'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9'}} rowDict7 = {k: board[k] for k in board.keys() & {'G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9'}} rowDict8 = {k: board[k] for k in board.keys() & {'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9'}} rowDict9 = {k: board[k] for k in board.keys() & {'I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9'}} if len(myRowDict) <= 9: myRowDict.append(rowDict1) myRowDict.append(rowDict2) myRowDict.append(rowDict3) myRowDict.append(rowDict4) myRowDict.append(rowDict5) myRowDict.append(rowDict6) myRowDict.append(rowDict7) myRowDict.append(rowDict8) myRowDict.append(rowDict9) else: myRowDict[0] = rowDict1 myRowDict[1] = rowDict2 myRowDict[2] = rowDict3 myRowDict[3] = rowDict4 myRowDict[4] = rowDict5 myRowDict[5] = rowDict6 myRowDict[6] = rowDict7 myRowDict[7] = rowDict8 myRowDict[8] = rowDict9 return myRowDict def makeBoxdict(board, myBoxDict): boxDict1 = {k: board[k] for k in board.keys() & {'A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'}} boxDict2 = {k: board[k] for k in board.keys() & {'A4', 'A5', 'A6', 'B4', 'B5', 'B6', 'C4', 'C5', 'C6'}} boxDict3 = {k: board[k] for k in board.keys() & {'A7', 'A8', 'A9', 'B7', 'B8', 'B9', 'C7', 'C8', 'C9'}} boxDict4 = {k: board[k] for k in board.keys() & {'D1', 'D2', 'D3', 'E1', 'E2', 'E3', 'F1', 'F2', 'F3'}} boxDict5 = {k: board[k] for k in board.keys() & {'D4', 'D5', 'D6', 'E4', 'E5', 'E6', 'F4', 'F5', 'F6'}} boxDict6 = {k: board[k] for k in board.keys() & {'D7', 'D8', 'D9', 'E7', 'E8', 'E9', 'F7', 'F8', 'F9'}} boxDict7 = {k: board[k] for k in board.keys() & {'G1', 'G2', 'G3', 'H1', 'H2', 'H3', 'I1', 'I2', 'I3'}} boxDict8 = {k: board[k] for k in board.keys() & {'G4', 'G5', 'G6', 'H4', 'H5', 'H6', 'I4', 'I5', 'I6'}} boxDict9 = {k: board[k] for k in board.keys() & {'G7', 'G8', 'G9', 'H7', 'H8', 'H6', 'I7', 'I8', 'I9'}} if len(myBoxDict) <= 9: myBoxDict.append(boxDict1) myBoxDict.append(boxDict2) myBoxDict.append(boxDict3) myBoxDict.append(boxDict4) myBoxDict.append(boxDict5) myBoxDict.append(boxDict6) myBoxDict.append(boxDict7) myBoxDict.append(boxDict8) myBoxDict.append(boxDict9) else: myBoxDict[0] = boxDict1 myBoxDict[1] = boxDict2 myBoxDict[2] = boxDict3 myBoxDict[3] = boxDict4 myBoxDict[4] = boxDict5 myBoxDict[5] = boxDict6 myBoxDict[6] = boxDict7 myBoxDict[7] = boxDict8 myBoxDict[8] = boxDict9 return myBoxDict def update(board, row, box): myRowDict = makeRowDict(board, row) myColDict = makeColDict(board) myBoxDict = makeBoxdict(board, box) def getCurrRow(each): if each[0] == 'A': return 0 if each[0] == 'B': return 1 if each[0] == 'C': return 2 if each[0] == 'D': return 3 if each[0] == 'E': return 4 if each[0] == 'F': return 5 if each[0] == 'G': return 6 if each[0] == 'H': return 7 if each[0] == 'I': return 8 # def getCurrRow(each): # if each == 0: return 'A' # if each == 1: return 'B' # if each == 2: return 'C' # if each == 3: return 'D' # if each == 4: return 'E' # if each == 5: return 'F' # if each == 6: return 'G' # if each == 7: return 'H' # if each == 0: return 'I' def getCurrBox(each): if each == 'A1' or each == 'A2' or each == 'A3' \ or each == "B1" or each == "B2" or each == "B3" \ or each == "C1" or each == "C2" or each == "C3": return 0 if each == "A4" or each == "A5" or each == "A6" \ or each == "B4" or each == "B5" or each == "B6" \ or each == "C4" or each == "C5" or each == "C6": return 1 if each == "A7" or each == "A8" or each == "A9" \ or each == "B7" or each == "B8" or each == "B9" \ or each == "C7" or each == "C8" or each == "C9": return 2 if each == "D1" or each == "D2" or each == "D3" \ or each == "E1" or each == "E2" or each == "E3" \ or each == "F1" or each == "F2" or each == "F3": return 3 if each == "D4" or each == "D5" or each == "D6" \ or each == "E4" or each == "E5" or each == "E6" \ or each == "F4" or each == "F5" or each == "F6": return 4 if each == "D7" or each == "D8" or each == "D9" \ or each == "E7" or each == "E8" or each == "E9" \ or each == "F7" or each == "F8" or each == "F9": return 5 if each == "G1" or each == "G2" or each == "G3" \ or each == "H1" or each == "H2" or each == "H3" \ or each == "I1" or each == "I2" or each == "I3": return 6 if each == "G4" or each == "G5" or each == "G6" \ or each == "H4" or each == "H5" or each == "H6" \ or each == "I4" or each == "I5" or each == "I6": return 7 if each == "G7" or each == "G8" or each == "G9" \ or each == "H7" or each == "H8" or each == "H9" \ or each == "I7" or each == "I8" or each == "I9": return 8 def inBox(board, boxRow, boxCol, val): for iter in range(0, 3): for j in range(0, 3): if (board[iter + boxRow][j + boxCol] == val): return True return False def is_safe(board, row, column, val): box = [row - row % 3, int(column) - int(column) % 3] for iter1 in range(9): if board[row][iter1] == val: return False for iter2 in range(9): if board[iter2][int(column)] == val: return False if inBox(board, box[0], box[1], val): return False return True def isEmpty(board, l, unassigned, domain, listGrid): # index = mrv(listGrid, board) for row in range(9): for col in range(9): # newRow = getCurrRow(index) if listGrid[row][col] == 0: empties.append(str(row) + str(col)) l[0] = row l[1] = col return False return True def convertToList(board): listConversion = [] listGrid = [] for each in board: listConversion.append(board[each]) listGrid = list(chunks(listConversion, 9)) i = 0 return listGrid def random_items(iterator, items_wanted=9): selected_items = [None] * items_wanted for item_index, item in enumerate(iterator): for selected_item_index in range(items_wanted): if not random.randint(0, item_index): selected_items[selected_item_index] = item return selected_items # # def mrv(domain, unassigned): # minIdx, minVal = -1, float('inf') # for i in unassigned: # if len(domain[i]) < minVal: # minVal = len(domain[i]) # minIdx = i # return minIdx # # # my mrv first gives a score to each column and each row, then combines these scores to give a score to each square # # it then send the location of the lowest score as the first grid square to fill in # def mrv(listGrid, board): # i = 0 # myColumn = makeColDict(board) # newColumn = [] # squareValsCol = [] # finalSquareVals = [] # boardWithScores = {} # for each in myColumn: # newColumn.append(list(each.values())) # squareVals = [] # # for each in newColumn: # myVal = sum(each) # squareValsCol.append(myVal) # myVal = each[0] # for each in listGrid: # myVal = sum(each) # squareVals.append(myVal) # myVal = each[0] # for rowNum in range(9): # for colNum in range(9): # finalSquareVals.append(squareVals[rowNum]+squareValsCol[colNum]) # k = 0 # for each in board: # boardWithScores[each] = finalSquareVals[k] # k+=1 # minVal = 2**10000 # minLocation = "" # for eachVal in boardWithScores: # if boardWithScores[eachVal] < minVal: # minVal = boardWithScores[eachVal] # minLocation = eachVal # result = minLocation # boardWithScores.__delitem__(minLocation) # return result def backtracking(listGrid, board): """Takes a board and returns solved board.""" start = time.time() emptiesList = [0, 0] domain = {} emptiesList2 = [] # for each in board: # emptiesList2.append(each) # for each in board: # if board[each] != 0: # domain[each] = set([board[each]]) # emptiesList2.remove(each) # else: # domain[each] = set(range(1, 10)) # index = mrv(listGrid, board) if isEmpty(board, emptiesList, emptiesList2, domain, listGrid): return True row = emptiesList[0] col = emptiesList[1] # print(empties) # newRow = getCurrRow(index) for n in range(10): # for n in range(10): if is_safe(listGrid, row, col, n): listGrid[row][col] = n # print_board(board) if backtracking(listGrid, board): return listGrid listGrid[row][col] = 0 return False def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] solved_board = board return solved_board def convertToDict(boardList): myVals = "" myDict = {} for each in boardList: for val in each: myVals = myVals+str(val) board = {ROW[r] + COL[c]: int(myVals[9 * r + c]) for r in range(9) for c in range(9)} return board if __name__ == '__main__': # Read boards from source. src_filename = 'sudokus_start.txt' try: srcfile = open(src_filename, "r") sudoku_list = srcfile.read() except: print("Error reading the sudoku file %s" % src_filename) exit() # Setup output file out_filename = 'output.txt' outfile = open(out_filename, "w") # Solve each board using backtracking i = 0 for line in sudoku_list.split("\n"): # print("trying to solve # " + str(i)) if len(line) < 9: continue # Parse boards to dict representation, scanning board L to R, Up to Down board = {ROW[r] + COL[c]: int(line[9*r+c]) for r in range(9) for c in range(9)} # Print starting board. TODO: Comment this out when timing runs. # print_board(board) boardList = convertToList(board) # Solve with backtracking start = time.time() solved_board = backtracking(boardList, board) solved_board = convertToDict(boardList) # Print solved board. TODO: Comment this out when timing runs. i+=1 outfile.write(board_to_string(solved_board)) print("solved board:") print_board(solved_board) outfile.write('\n') end = time.time() # print("solved " + str(i) + " in " + str(end - start))
true
274ca25126950a72661248de9b5050b3005b9978
Python
akhilpy/python-practice
/duplicate_ele.py
UTF-8
519
4.125
4
[]
no_license
""" This example remove the duplicate element from the list """ list_a=[1,2,3,4,4,5,7,2,5,6] #solution 1 b = list(set(list_a)) # convert list into set, and it remove the duplicate elements print(b) #Solution 2 new_list=[] for i in list_a: if i not in new_list: new_list.append(i) print(new_list) #solution 3 Using list comprihension x=[] [x.append(i) for i in list_a if i not in x] print(x) #solution 4 Using dict comprihension new_list ={i:1 for i in list_a}.keys() print(list(new_list))
true
4e879a773a3dab8a31ed4370fdf7080955fa39f5
Python
weifanhaha/digit-uda
/dann/train.py
UTF-8
6,731
2.515625
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import torch import torch.nn as nn import numpy as np from tqdm import tqdm from torch import optim from torch.utils.data import DataLoader import copy from models import DANN from image_dataset import ImageDataset # In[2]: ########## Arguments ########## num_epochs = 15 lr = 1e-3 batch_size = 128 # svhn, usps, mnistm d_source = "svhn" d_target = "usps" train_with_domain = True train_with_target = False assert (train_with_domain and train_with_target) == False if train_with_domain: output_model_path = "./models/{}_{}_domain.pth".format(d_source, d_target) elif train_with_target: output_model_path = "./models/{}_{}_target.pth".format(d_source, d_target) else: output_model_path = "./models/{}_{}.pth".format(d_source, d_target) ############################# # In[3]: source_dataset = ImageDataset("train", d_source) target_dataset = ImageDataset("train", d_target, is_target=True) val_dataset = ImageDataset("val", d_target, is_target=True) source_dataloader = DataLoader( source_dataset, batch_size=batch_size, shuffle=True) target_dataloader = DataLoader( target_dataset, batch_size=batch_size, shuffle=True) val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False) source_label = 0 target_label = 1 # In[4]: print(len(source_dataset), len(target_dataset), len(val_dataset)) # In[5]: model = DANN(drop_p=0.5) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = model.to(device) # In[6]: optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=2e-5) # Criterion class_criterion = nn.NLLLoss() domain_criterion = nn.NLLLoss() # In[7]: label_losses = [] domain_losses = [] # In[8]: def train_one_epoch(enum_dataloader, start_steps, total_steps, train_with_target=False): running_loss = 0.0 running_corrects = 0.0 for idx, (sources, targets) in enum_dataloader: source_images, labels = sources[0].to(device), sources[1].to(device) target_images = targets[0].to(device) source_bs = source_images.shape[0] target_bs = target_images.shape[0] source_labels = torch.full( (source_bs,), source_label, device=device).long() target_labels = torch.full( (target_bs,), target_label, device=device).long() p = (idx + start_steps) / total_steps alpha = 2.0 / (1.0 + np.exp(-10 * p)) - 1 optimizer.zero_grad() label_output, domain_output = model(source_images, alpha) label_loss = class_criterion(label_output, labels) running_loss += label_loss.item() * source_bs # calculate label acc _, pred_labels = torch.max(label_output, 1) corrects = torch.sum(pred_labels == labels.data) running_corrects += corrects # calculate domain loss if train_with_domain: _, domain_t_output = model(target_images, alpha) domain_s_loss = domain_criterion(domain_output, source_labels) domain_t_loss = domain_criterion(domain_t_output, target_labels) domain_loss = domain_s_loss + domain_t_loss running_loss += domain_loss.item() * source_bs else: domain_loss = 0.0 # update parameters loss = label_loss + domain_loss loss.backward() optimizer.step() # record label_losses.append(label_loss) domain_losses.append(domain_loss) postfix_dict = { "L/D": "{:.5f}/{:.5f}".format(label_loss, domain_loss), "SD / TD": "{:5f}/{:5f}".format(domain_s_loss, domain_t_loss), "acc": "{:.5f}".format(corrects.double() / source_bs), "alpha": "{:.5f}".format(alpha), } enum_dataloader.set_postfix(**postfix_dict) return running_loss, running_corrects # In[9]: def eval_one_epoch(model, enum_dataloader): running_loss = 0.0 running_corrects = 0.0 for idx, targets in enum_dataloader: target_images, labels = targets[0].to(device), targets[1].to(device) target_bs = target_images.shape[0] optimizer.zero_grad() with torch.no_grad(): label_output, domain_output = model(target_images, 1.0) label_loss = class_criterion(label_output, labels) loss = label_loss running_loss += label_loss.item() * target_bs # calculate label acc _, pred_labels = torch.max(label_output, 1) corrects = torch.sum(pred_labels == labels.data) running_corrects += corrects postfix_dict = { "L": "{:.5f}".format(label_loss), "acc": "{:.5f}".format(corrects.double() / target_bs) } enum_dataloader.set_postfix(**postfix_dict) return running_loss, running_corrects # In[10]: best_acc = 0.0 best_model = None losses = [] for epoch in range(num_epochs): model.train() if not train_with_target: _len = min(len(source_dataloader), len(target_dataloader)) trange = tqdm( enumerate(zip(source_dataloader, target_dataloader)), total=_len, desc="Epoch {}".format(epoch), ) else: _len = len(target_dataloader) # we don't need the second dalaloader in enumerate trange = tqdm( enumerate(zip(target_dataloader, target_dataloader)), total=_len, desc="Epoch {}".format(epoch), ) start_steps = epoch * _len total_steps = num_epochs * _len running_loss, running_corrects = train_one_epoch( trange, start_steps, total_steps) epoch_loss = running_loss / min(len(source_dataset), len(target_dataset)) epoch_acc = running_corrects.double() / min(len(source_dataset), len(target_dataset)) losses.append(epoch_loss) model.eval() _val_len = len(val_dataloader) trange = tqdm(enumerate(val_dataloader), total=_val_len, desc="Testing Epoch {}".format(epoch), ) eval_loss, eval_corrects = eval_one_epoch(model, trange) eval_epoch_loss = eval_loss / len(val_dataset) eval_epoch_acc = eval_corrects.double() / len(val_dataset) print("Epoch Loss: {:.5f} | Accuracy: {:.5f}".format( epoch_loss, epoch_acc)) print("Testing | Label Loss: {:.5f} | Accuracy: {:.5f}".format( eval_epoch_loss, eval_epoch_acc)) if eval_epoch_acc > best_acc: best_acc = eval_epoch_acc best_model = copy.deepcopy(model.state_dict()) if best_model != None: torch.save(best_model, output_model_path) # In[ ]: # from matplotlib import pyplot as plt # plt.plot(domain_losses) # In[ ]:
true
f7c855b374b7e2b838f163c8e5916d8b0b051473
Python
obtusedev/xkcd-web-scraper
/main.py
UTF-8
1,492
3.078125
3
[]
no_license
import os import requests from bs4 import BeautifulSoup from db import insert_comic_data num = 1 while num < 6: print(f"Scraping...{num}") url = f"https://xkcd.com/{num}/" res = requests.get(url) content = res.text soup = BeautifulSoup(content, "html.parser") comic_title = soup.find(id="ctitle").text partial_link = soup.find(id="comic").find("img")["src"] img_link = "https:" + partial_link img = requests.get(img_link).content # check if folder img exists if os.path.exists(os.getcwd() + "\\img"): with open( f"{os.path.abspath('img')}/{str(num)}) {comic_title}.jpg", "w+b" ) as f: f.write(img) else: os.mkdir(os.getcwd() + "\\img") with open( f"{os.path.abspath('img')}/{str(num)}) {comic_title}.jpg", "w+b" ) as f: f.write(img) file_path = f'{os.path.abspath("img")}\\{str(num)}) {comic_title}.jpg' insert_comic_data(title=comic_title, url=img_link, path_to_file=file_path) num += 1 print("Done") """ 1) Go through a x number of xkcd comics 2) Get the title, img_url, and download the actual img 3) Input into SQLite3 DB title, img_url, and link to img 4) Make dir for all the img @@@ TODO 1) Download files to img dir 2) Find way to get path to img; maybe os.path.abspath() 3) Insert the data into db 4) Add progress indicator 5) Make img folder/dir if it does not exist """
true
ee779c7f6affcb7acfbe119a1ceb13da2b2b2c69
Python
kokoa-naverAIboostcamp/algorithm
/Algorithm/solution/BOJ5052.py
UTF-8
1,925
3.8125
4
[]
no_license
### 무지 ### ## 풀이 1 -> 1중 for 문 import sys t = int(sys.stdin.readline()) answer = "" while t > 0: t -= 1 n = int(sys.stdin.readline()) phone_book = [sys.stdin.readline()[:-1] for _ in range(n)] phone_book.sort() ans = "YES\n" for s1, s2 in zip(phone_book[:-1], phone_book[1:]): if s2.startswith(s1): ans = "NO\n" break answer += ans print(answer) ## 풀이 2 -> 트라이 자료구조 (https://www.crocus.co.kr/1053), 라이언 풀이 import sys class Node: def __init__(self, key, end=False): self.key = key # 해당 노드의 문자 self.end = end # 문자열의 끝나는 위치 정보 self.children = {} # 자식 노드들의 정보를 담은 dict -> 연결된 문자(key)와 해당 문자의 노드(value) class Trie: def __init__(self): self.head = Node(None) def insert(self, string): curr_node = self.head # 입력 문자열의 각각의 문자들을 차례로 기존 노드에 연결되어 있는지 확인하며 순회 for ch in string: if ch not in curr_node.children: # 만약 존재하지 않으면 새롭게 생성 curr_node.children[ch] = Node(ch) curr_node = curr_node.children[ch] if curr_node.end: return True # 모든 문자열 순회 후 curr_node는 마지막 문자 -> 문자열의 끝 정보를 넣어준다. curr_node.end = True return False t = int(sys.stdin.readline()) answer = "" for _ in range(t): n = int(sys.stdin.readline()) trie = Trie() phone_book = [sys.stdin.readline()[:-1] for _ in range(n)] phone_book.sort() for num in phone_book: if trie.insert(num): answer += "NO\n" break else: answer += "YES\n" print(answer)
true
c3fbd3ef8adcab2ee8e760633ffa28af1b9fc3f7
Python
hemanthponnada/ML-Practice
/ts.py
UTF-8
1,590
3.046875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 16:23:32 2019 @author: saimohan """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime from pandas import Series %matplotlib inline import warnings train=pd.read_csv("Train_SU63ISt.csv") test=pd.read_csv("Test_0qrQsBZ.csv") train_original=train.copy() test_original=test.copy() train.columns, test.columns train.dtypes, test.dtypes train.shape, test.shape train['Datetime']=pd.to_datetime(train.Datetime, format='%d-%m-%Y %H:%M') test['Datetime']=pd.to_datetime(test.Datetime, format='%d-%m-%Y %H:%M') train_original['Datetime']=pd.to_datetime(train_original.Datetime, format='%d-%m-%Y %H:%M') test_original['Datetime']=pd.to_datetime(test_original.Datetime, format='%d-%m-%Y %H:%M') for i in (train, test, train_original, test_original): i['year']=i.Datetime.dt.year i['month']=i.Datetime.dt.month i['day']=i.Datetime.dt.day i['Hour']=i.Datetime.dt.hour train['Day of the week']=train['Datetime'].dt.dayofweek temp=train['Datetime'] def applyer(row): if row.dayofweek==5 or row.dayofweek==6: return 1 else: return 0 temp2=train['Datetime'].apply(applyer) train['weekend']=temp2 train.index=train['Datetime'] df=train.drop('ID',1) ts=df['Count'] plt.figure(figsize=(16,8)) plt.plot(ts, label='Passenger Count') plt.title('Time Series') plt.xlabel("Time(year-month)") plt.ylabel("passenger count") plt.legend(loc='best') train.groupby('year')['Count'].mean().plot.bar()
true
8b639991ec2bf0dc765073149aec3e168462c49d
Python
dhimasn/fuzzy-expert
/fuzzy_expert/mf.py
UTF-8
11,848
3.40625
3
[ "MIT" ]
permissive
""" Membership Functions ============================================================================== Functions in this module returns a standard membership function specificaion as a list of points (x_i, u_i). """ from __future__ import annotations from typing import Tuple, List import numpy as np ## pag. 27, FuzzyCLIPS class MembershipFunction: """Membership function constructor. :param n_points: Number base point for building the approximations. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=3) >>> mf(('gaussmf', 5, 1)) [(2, 0), (3.0, 0.1353352832366127), (3.8, 0.48675225595997157), (4.6, 0.9231163463866356), (5.0, 1.0), (5.4, 0.9231163463866356), (6.2, 0.48675225595997157), (7.0, 0.1353352832366127), (8, 0)] """ def __init__(self, n_points: int = 9): self.n_points: int = n_points def __call__(self, mfspec: tuple): """Generates a list of poinnts representing the membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=3) >>> mf(('gaussmf', 5, 1)) [(2, 0), (3.0, 0.1353352832366127), (3.8, 0.48675225595997157), (4.6, 0.9231163463866356), (5.0, 1.0), (5.4, 0.9231163463866356), (6.2, 0.48675225595997157), (7.0, 0.1353352832366127), (8, 0)] """ fn, *params = mfspec fn = { "gaussmf": self.gaussmf, "gbellmf": self.gbellmf, "pimf": self.pimf, "sigmf": self.sigmf, "smf": self.smf, "trapmf": self.trapmf, "trimf": self.trimf, "zmf": self.zmf, }[fn] return fn(*params) def gaussmf(self, center: float, sigma: float) -> List[Tuple[float, float]]: """Gaussian membership function. :param center: Defines the center of the membership function. :param sigma: Defines the width of the membership function, where a larger value creates a wider membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=3) >>> mf.gaussmf(center=5, sigma=1) [(2, 0), (3.0, 0.1353352832366127), (3.8, 0.48675225595997157), (4.6, 0.9231163463866356), (5.0, 1.0), (5.4, 0.9231163463866356), (6.2, 0.48675225595997157), (7.0, 0.1353352832366127), (8, 0)] """ xp: np.ndarray = np.linspace( start=center - 2 * sigma, stop=center + 2 * sigma, num=2 * self.n_points, ) xp = np.append(xp, center) xp = np.unique(xp) xp.sort() fp: np.ndarray = np.exp(-((xp - center) ** 2) / (2 * sigma)) return ( [(center - 3 * sigma, 0)] + [(x, f) for x, f in zip(xp, fp)] + [(center + 3 * sigma, 0)] ) def gbellmf( self, center: float, width: float, shape: float, ) -> List[Tuple[float, float]]: """Generalized bell-shaped membership function. :param center: Defines the center of the membership function. :param width: Defines the width of the membership function, where a larger value creates a wider membership function. :param shape: Defines the shape of the curve on either side of the central plateau, where a larger value creates a more steep transition. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=3) >>> mf.gbellmf(center=5, width=1, shape=0.5) [(-1, 0), (0.0, 0.16666666666666666), (1.0, 0.2), (2.0, 0.25), (3.0, 0.3333333333333333), (3.8, 0.45454545454545453), (4.0, 0.5), (4.6, 0.7142857142857141), (5.0, 1.0), (5.4, 0.7142857142857141), (6.0, 0.5), (6.2, 0.45454545454545453), (7.0, 0.3333333333333333), (8.0, 0.25), (9.0, 0.2), (10.0, 0.16666666666666666), (11, 0)] """ xp: np.ndarray = np.linspace( start=center - 2 * width, stop=center + 2 * width, num=2 * self.n_points ) delta = center + width * np.linspace(start=-5, stop=5, num=11) xp: np.ndarray = np.append(xp, delta) xp = np.unique(xp) xp.sort() fp: np.ndarray = 1 / (1 + np.abs((xp - center) / width) ** (2 * shape)) return ( [(center - 6 * width, 0)] + [(x, f) for x, f in zip(xp, fp)] + [(center + 6 * width, 0)] ) def pimf( self, left_feet: float, left_peak: float, right_peak: float, right_feet: float, ) -> List[Tuple[float, float]]: """Pi-shaped membership function. :param left_feet: Defines the left feet of the membership function. :param left_peak: Defines the left peak of the membership function. :param right_peak: Defines the right peak of the membership function. :param right_feet: Defines the right feet of the membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=4) >>> mf.pimf(left_feet=1, left_peak=2, right_peak=3, right_feet=4) [(1.0, 0.0), (1.3333333333333333, 0.22222222222222213), (1.6666666666666665, 0.7777777777777776), (2.0, 1.0), (3.0, 1.0), (3.3333333333333335, 0.7777777777777776), (3.6666666666666665, 0.22222222222222243), (4.0, 0.0)] """ return self.smf(foot=left_feet, shoulder=left_peak) + self.zmf( shoulder=right_peak, feet=right_feet ) def sigmf( self, center: float, width: float, ) -> List[Tuple[float, float]]: """Sigmoidal membership function. :param center: Defines the center of the membership function. :param width: Defines the width of the membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=3) >>> mf.sigmf(center=5, width=1) [(-1, 0), (0.0, 0.0066928509242848554), (2.0, 0.04742587317756678), (4.0, 0.2689414213699951), (5.0, 0.5), (6.0, 0.7310585786300049), (8.0, 0.9525741268224334), (10.0, 0.9933071490757153), (11, 1)] """ xp: np.ndarray = np.linspace( start=center - 5 * width, stop=center + 5 * width, num=2 * self.n_points ) xp: np.ndarray = np.append(xp, center) xp = np.unique(xp) xp.sort() fp: np.ndarray = 1 / (1 + np.exp(-np.abs(width) * (xp - center))) return ( [(center - 6 * width, 0)] + [(x, f) for x, f in zip(xp, fp)] + [(center + 6 * width, 1)] ) def smf( self, foot: float, shoulder: float, ) -> List[Tuple[float, float]]: """S-shaped membership function. :param foot: Defines the foot of the membership function. :param shoulder: Defines the shoulder of the membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=4) >>> mf.smf(foot=1, shoulder=2) [(1.0, 0.0), (1.3333333333333333, 0.22222222222222213), (1.6666666666666665, 0.7777777777777776), (2.0, 1.0)] """ xp: np.ndarray = np.linspace(start=foot, stop=shoulder, num=self.n_points) fp: np.ndarray = np.where( xp <= foot, 0, np.where( xp <= (foot + shoulder) / 2, 2 * ((xp - foot) / (shoulder - foot)) ** 2, np.where( xp <= shoulder, 1 - 2 * ((xp - shoulder) / (shoulder - foot)) ** 2, 1, ), ), ) return [(x, f) for x, f in zip(xp, fp)] def trapmf( self, left_feet: float, left_peak: float, right_peak: float, right_feet: float, ) -> List[Tuple[float, float]]: """Trapezoidal membership function. :param left_feet: Defines the left feet of the membership function. :param left_peak: Defines the left peak of the membership function. :param right_peak: Defines the right peak of the membership function. :param right_feet: Defines the right feet of the membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=4) >>> mf.trapmf(left_feet=1, left_peak=2, right_peak=3, right_feet=4) [(1.0, 0.0), (2.0, 1.0), (3.0, 1.0), (4.0, 0.0)] """ left_feet: np.ndarray = np.where( left_feet == left_peak, left_feet - 1e-4, left_feet ) right_feet: np.ndarray = np.where( right_feet == right_peak, right_feet + 1e-4, right_feet ) xp: np.ndarray = np.array([left_feet, left_peak, right_peak, right_feet]) fp: np.ndarray = np.where( xp <= left_feet, 0, np.where( xp <= left_peak, (xp - left_feet) / (left_peak - left_feet), np.where( xp <= right_peak, 1, np.where( xp <= right_feet, (right_feet - xp) / (right_feet - right_peak), 0, ), ), ), ) return [(x, f) for x, f in zip(xp, fp)] def trimf( self, left_feet: float, peak: float, right_feet: float, ) -> List[Tuple[float, float]]: """Triangular membership function. :param left_feet: Defines the left feet of the membership function. :param peak: Defines the peak of the membership function. :param right_feet: Defines the right feet of the membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=4) >>> mf.trimf(left_feet=1, peak=2, right_feet=4) [(1.0, 0.0), (2.0, 1.0), (4.0, 0.0)] """ left_feet: np.ndarray = np.where(left_feet == peak, left_feet - 1e-4, left_feet) right_feet: np.ndarray = np.where( peak == right_feet, right_feet + 1e-4, right_feet ) xp: np.ndarray = np.array([left_feet, peak, right_feet]) fp: np.ndarray = np.where( xp <= left_feet, 0, np.where( xp <= peak, (xp - left_feet) / (peak - left_feet), np.where(xp <= right_feet, (right_feet - xp) / (right_feet - peak), 0), ), ) return [(x, f) for x, f in zip(xp, fp)] def zmf( self, shoulder: float, feet: float, ) -> List[Tuple[float, float]]: """Z-shaped membership function. :param shoulder: Defines the shoulder of the membership function. :param feet: Defines the feet of the membership function. >>> from fuzzy_expert.mf import MembershipFunction >>> mf = MembershipFunction(n_points=4) >>> mf.zmf(shoulder=1, feet=2) [(1.0, 1.0), (1.3333333333333333, 0.7777777777777779), (1.6666666666666665, 0.22222222222222243), (2.0, 0.0)] """ xp: np.ndarray = np.linspace(start=shoulder, stop=feet, num=self.n_points) fp: np.ndarray = np.where( xp <= shoulder, 1, np.where( xp <= (shoulder + feet) / 2, 1 - 2 * ((xp - shoulder) / (feet - shoulder)) ** 2, np.where(xp <= feet, 2 * ((xp - feet) / (feet - shoulder)) ** 2, 0), ), ) return [(x, f) for x, f in zip(xp, fp)]
true
132c31dd5e3e2fb30af1996e564a519cefad1b8f
Python
RaghuMylapilli/Script-Evaluation-Assistant
/files/Prime_Number.py
UTF-8
235
3.6875
4
[ "MIT" ]
permissive
num=int(input("enter a number :")) if num>1: for i in range(2,num/2): if num%i==0: print(num,"is not a prime number") break else: print(num,"is a prime number") else: print(num,"is not a prime number")
true
b1594311efe8c85c0a3e1d52f2ae10e649d39c67
Python
alexandersoen/influencemap
/webapp/webapp/graph.py
UTF-8
2,381
2.53125
3
[]
no_license
import os, sys, json import numpy as np from operator import itemgetter BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PYTHON_DIR = os.path.join(os.path.dirname(BASE_DIR), 'python') sys.path.insert(0, PYTHON_DIR) def processdata(gtype, egoG): center_node = egoG.graph['ego'] # Radius of circle radius = 1.2 # Get basic node information from ego graph outer_nodes = list(egoG) outer_nodes.remove(center_node) outer_nodes.sort(key=lambda n : egoG.nodes[n]['ratiow']) links = egoG.edges(data=True) anglelist = np.linspace(np.pi, 0., num=len(outer_nodes)) x_pos = [0]; x_pos.extend(list(radius * np.cos(anglelist))) y_pos = [0]; y_pos.extend(list(radius * np.sin(anglelist))) # Outer nodes data nodedata = { key:{ "name": key, "weight": egoG.nodes[key]["nratiow"], "id": i, "gtype": gtype, "size": egoG.nodes[key]["sumw"], "xpos": x_pos[i], "ypos": y_pos[i], "coauthor": str(egoG.nodes[key]['coauthor']) } for i, key in zip(range(1, len(outer_nodes)+1), outer_nodes)} # Center node data nodedata[center_node] = { "name": center_node, "weight": 1, "id": 0, "gtype": gtype, "size": 1, "xpos": x_pos[0], "ypos": y_pos[0], "coauthor": str(False) } nodekeys = [v["name"] for v in sorted(nodedata.values(), key=itemgetter("id"))] linkdata = [{ "source": nodekeys.index(s), "target": nodekeys.index(t), "padding": nodedata[t]["size"], "id": nodedata[t]["id"] if v["direction"] == "in" else nodedata[s]["id"], "gtype": gtype, "type": v["direction"], "weight": v["nweight"] } for s, t, v in links] chartdata = [{ "id": nodedata[t]["id"] if v["direction"] == "in" else nodedata[s]["id"], "name": t if v["direction"] == "in" else s, "type": v["direction"], "gtype": gtype, "sum": nodedata[t]["weight"] if v["direction"] == "in" else nodedata[s]["weight"], "weight": v["weight"] } for s, t, v in links] chartdata = sorted(chartdata, key=itemgetter("sum")) return { "nodes": list(nodedata.values()), "links": linkdata, "bars": chartdata }
true
0dd23c900503b291ea9bcc0e97cf0e36beda6cf4
Python
LoadingByte/sts-inquiry
/sts_inquiry/structs.py
UTF-8
2,721
2.609375
3
[ "MIT" ]
permissive
from __future__ import annotations from dataclasses import dataclass from datetime import datetime from typing import Optional, List, FrozenSet from markupsafe import Markup @dataclass(frozen=True) class World: superregions: List[SuperRegion] regions: List[Region] stws: List[Stw] edges: List[Edge] @dataclass(frozen=True) class Edge: stws: FrozenSet[Stw] handover: bool def fst(self): stw, _ = self.stws return stw def snd(self): _, stw = self.stws return stw def __str__(self): stw_1, stw_2 = self.stws return f"{stw_1} {'<>' if self.handover else '..'} {stw_2}" def __repr__(self): return f"Edge {self}" @dataclass(eq=False) class SuperRegion: urid: int name: str regions: List[Region] def __eq__(self, other): return isinstance(other, SuperRegion) and self.urid == other.urid def __hash__(self): return hash((self.urid,)) @dataclass(eq=False) class Region: rid: int name: str superregion: SuperRegion stws: List[Stw] def __eq__(self, other): return isinstance(other, Region) and self.rid == other.rid def __hash__(self): return hash((self.rid,)) @dataclass(eq=False) class Stw: aid: int region: Region occupants: List[Player] neighbors: List[Neighbor] name: str description: Markup latitude: Optional[float] longitude: Optional[float] difficulty: Optional[float] # 1 through 4 entertainment: Optional[float] # 1 through 4 comments: List[Comment] def occupant_at(self, instance: int): return self.occupants[instance - 1] def __eq__(self, other): return isinstance(other, Stw) and self.aid == other.aid def __hash__(self): return hash((self.aid,)) def __str__(self): return self.name def __repr__(self): return f"Stw {self.name}" @dataclass(frozen=True) class Neighbor: stw: Stw handover: bool @dataclass(frozen=True) class Player: name: str stitz: bool start_time: datetime def format_playing_duration(self, short=False) -> str: secs = round((datetime.now() - self.start_time).total_seconds()) if secs < 60: return f"{secs}{'s' if short else (' Sekunde' if secs == 1 else ' Sekunden')}" mins = round(secs / 60) if mins < 60: return f"{mins}{'m' if short else (' Minute' if mins == 1 else ' Minuten')}" hours = round(mins / 60) return f"{hours}{'h' if short else (' Stunde' if hours == 1 else ' Stunden')}" @dataclass(frozen=True) class Comment: text: str playing_duration: Optional[str] year: int
true
feab659673be3a4fcf12e8092f2b8ce76f31e672
Python
chasmani/grinstead_and_snell_introduction_to_probability_solutions
/1_2_1_spinner.py
UTF-8
1,158
3.578125
4
[]
no_license
import random import numpy as np import matplotlib.pyplot as plt def spin(): return random.random() def run_experiment(): runs = 10000 semicircle_landed = 0 third_circle_landed = 0 sextant_landed = 0 for i in range(runs): result = spin() if 0 <= result < 0.5: semicircle_landed += 1 elif 0.5 <= result < 0.66666666666: sextant_landed += 1 else: third_circle_landed += 1 print("Results after {} runs".format(runs)) print("Semicircle: {}".format(semicircle_landed)) print("Sextant: {}".format(sextant_landed)) print("Third of a circle: {}".format(third_circle_landed)) semicircle_center = 0.25 semicircle_width = 0.5 semicircle_height = semicircle_landed/semicircle_width sextant_center = (0.5 + 1/12) sextant_width = (1/6) sextant_height = sextant_landed/sextant_width third_center = 1- (1/6) third_width = 1/3 third_height = third_circle_landed/third_width plt.bar([semicircle_center, sextant_center, third_center], [semicircle_height, sextant_height, third_height], [semicircle_width, sextant_width, third_width], color=["r","g", "b"]) plt.show() #plt.bar(x values, heights, width) run_experiment()
true
e4c02822b68e211747dbeed40c2c4e077f42ccce
Python
prashantkumar99/Hexapawn
/Human.py
UTF-8
551
3.59375
4
[]
no_license
from Player import Player class Human(Player): def __init__(self, name): Player.__init__(self, name) def readMoveCoordinates(self): print("Playing:", self.name) print("Select Pawn:-") pawn = self.readCoordinates() print("Select Position to move to:-") target = self.readCoordinates() return (pawn[0], pawn[1], target[0], target[1]) def readCoordinates(self): return (int(input("Row: ")), int(input("Column: "))) def result(self, won): pass
true
d4acd0573132db11761631eb70d341e1b6dfc318
Python
andreaippolito/computationalFinanceAssignment
/exercise3.py
UTF-8
2,490
3.234375
3
[]
no_license
import brownian_paths as bp import numpy as np import matplotlib.pyplot as plt def option_maturity_value(stock_price_1, stock_price_2, strike_price, discount_factor): euler_option_value = np.maximum(1/2 * stock_price_1 - 1/2 * stock_price_2, strike_price)*discount_factor number_of_processes = np.size(euler_option_value) present_option_value = sum(euler_option_value)/number_of_processes return present_option_value def main_calculation(stock_price_1_initial_value=100, stock_price_2_initial_value=10): maturity = 7 interest_rate = 0.06 drift_term_1 = 0.04 volatility_1 = 0.38 drift_term_2 = 0.1 volatility_2 = 0.15 discount_factor = np.exp(-maturity*interest_rate) strike_prices = np.linspace(0, 0.1, 10) brownian_paths = bp.BrownianPaths(1000, 365*maturity, 0, maturity) stock_price_1 = stock_price_1_initial_value*np.ones(brownian_paths.no_of_paths) stock_price_2 = stock_price_2_initial_value*np.ones(brownian_paths.no_of_paths) brownian_paths_neutral_measure_1 = brownian_paths.change_of_measure(drift_term_1, interest_rate, volatility_1) brownian_paths_neutral_measure_2 = brownian_paths.change_of_measure(drift_term_2, interest_rate, volatility_2) present_option_values = np.zeros(np.size(strike_prices)) time_step = (brownian_paths.ending_point - brownian_paths.starting_point)/brownian_paths.no_of_steps for i in range(0, brownian_paths.no_of_steps - 1): stock_price_1 = stock_price_1 * np.exp((interest_rate - 1 / 2 * volatility_1 ** 2) * time_step + \ volatility_1 * ( brownian_paths_neutral_measure_1.paths[:, i + 1] - brownian_paths_neutral_measure_1.paths[:, i])) stock_price_2 = stock_price_2 * np.exp((interest_rate - 1 / 2 * volatility_2 ** 2) * time_step + \ volatility_2 * ( brownian_paths_neutral_measure_2.paths[:, i + 1] - brownian_paths_neutral_measure_2.paths[:, i])) for i in range(0, np.size(present_option_values)): present_option_values[i] = option_maturity_value(stock_price_1, stock_price_2, strike_prices[i], discount_factor) plt.plot(strike_prices, present_option_values, linewidth=0, marker='o') plt.xticks(strike_prices) plt.yticks(present_option_values) plt.xlabel('Strike Values') plt.ylabel('V(t)') plt.savefig('exercise3.png', bbox_inches='tight') if __name__ == '__main__': main_calculation()
true
0bb3b799ad16d2545ceae8d25d11b3baea251741
Python
ishitsuka-hikaru/neural-wrappers
/neural_wrappers/utilities/running_mean.py
UTF-8
2,512
2.765625
3
[ "WTFPL" ]
permissive
import numpy as np from typing import Union, Optional from .utils import NWNumber, NWSequence, NWDict class RunningMeanNumber: def __init__(self, initValue : NWNumber): self.value = initValue self.count = 0 def update(self, value : NWNumber, count : Optional[int] = None): if not count: count = 1 self.value += value self.count += count def updateBatch(self, value : NWSequence): value = np.array(value) assert len(value.shape) == 1 self.update(value.sum(axis=0), value.shape[0]) def get(self): assert self.count > 0 return self.value / self.count class RunningMeanSequence: def __init__(self, initValue : NWSequence): self.value = np.array(initValue) self.count = 0 def update(self, value : NWSequence, count : Optional[int] = None): value = np.array(value) if not count: count = 1 self.value += value self.count += count def updateBatch(self, value : NWSequence): value = np.array(value) assert len(value.shape) == len(self.value.shape) + 1 self.update(value.sum(axis=0), value.shape[0]) def get(self): assert self.count > 0 return self.value / self.count class RunningMeanDict: def __init__(self, initValue : NWDict): self.value = initValue self.count = 0 def update(self, value : NWDict, count : Optional[int] = None): if not count: count = 1 self.value = {k : self.value[k] + value[k] for k in self.value} self.count += count def updateBatch(self, value : NWDict): assert False, "Only valid for NWNumber and NWSequence" def get(self): assert self.count > 0 return {k : self.value[k] / self.count for k in self.value} class RunningMean: def __init__(self, initValue:Union[NWNumber, NWSequence, NWDict]): if type(initValue) in NWNumber.__args__: # type: ignore self.obj = RunningMeanNumber(initValue) # type: ignore elif type(initValue) in NWSequence.__args__: # type: ignore self.obj = RunningMeanSequence(initValue) # type: ignore elif type(initValue) in NWDict.__args__: # type: ignore self.obj = RunningMeanDict(initValue) # type: ignore else: print("[RunningMean] Doing a running mean on unknown type %s" % type(initValue)) self.obj = RunningMeanNumber(initValue) def update(self, value:Union[NWNumber, NWSequence, NWDict], count:Optional[int] = 0): self.obj.update(value, count) def updateBatch(self, value : NWDict): self.obj.updateBatch(value) def get(self): return self.obj.get() def __repr__(self): return str(self.get()) def __str__(self): return str(self.get())
true
a8f1763d77b4e1475cfad5ad5a0b418f89ea2887
Python
sarim/qmltest
/main.py
UTF-8
1,655
2.609375
3
[]
no_license
#!/usr/bin/env python import sys from PySide import QtCore, QtGui, QtDeclarative class GittuCM( QtCore.QObject ): def __init__( self ): QtCore.QObject.__init__(self) @QtCore.Slot('QString') def printText(self,text): print text @QtCore.Slot() def quitMe(self): sys.exit() class dTypeView ( QtDeclarative.QDeclarativeView ): def __init__( self, parent=None ): super( dTypeView, self ).__init__( parent ) self.setSource( QtCore.QUrl.fromLocalFile( './Main.qml' ) ) self.setResizeMode( QtDeclarative.QDeclarativeView.SizeRootObjectToView ) self.gittuParent = parent @QtCore.Slot("QMouseEvent") def mouseMoveEvent(self,event): print event.globalPos(), event.pos() if (event.buttons() & QtCore.Qt.LeftButton ): self.gittuParent.move(event.globalPos() - self.dragpos ) event.accept() class MainWindow( QtGui.QMainWindow ): def __init__( self, parent=None ): super( MainWindow, self ).__init__( parent ) self.setWindowTitle( "Test" ) self.setWindowFlags(QtCore.Qt.FramelessWindowHint) self.dView = dTypeView(self) self.setCentralWidget(self.dView) @QtCore.Slot("QMouseEvent") def mousePressEvent(self,event): if (event.button() == QtCore.Qt.LeftButton): self.dView.dragpos = event.globalPos() - self.frameGeometry().topLeft() app = QtGui.QApplication( sys.argv ) window = MainWindow() context = window.dView.rootContext() context.setContextProperty("GittuCM",GittuCM()) window.show() sys.exit( app.exec_() )
true
c2f68f4c5b5ce85928a5c53951d50e4a6ed4819b
Python
grungi-ankhfire/ebenezer
/ebenezer/ui/menu.py
UTF-8
1,092
2.953125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Copyright (c) 2012 Bastien Gorissen # Licensed under the MIT license # See LICENSE file for licensing details import os class Menu: def __init__(self, app): self.app = app self.header = [] self.contents = [] self.footer = [] self.prompt = "" self.answers = {} self.callback = None def update(self): pass def display(self): self.update() os.system("clear") for l in self.header: print l print "" for l in self.contents: print l print "" for l in self.footer: print l print "" return self.ask() def ask(self): ans = raw_input(self.prompt + " ") if len(self.answers.keys()) > 0: while ans.lower() not in self.answers.keys(): return self.display() return self.answers[ans.lower()][0](self.answers[ans.lower()][1]) else: return self.callback() def change_menu(self, new_menu): self.app.current_menu = new_menu
true
fe737444c58539393a630c921d93555104391b3a
Python
jacegem/scrapy-news-crawling
/newscrawling/spiders/newsSpider.py
UTF-8
3,033
2.796875
3
[]
no_license
import scrapy import time import csv from newscrawling.items import NewscrawlingItem class NewsUrlSpider(scrapy.Spider): name = "newsUrlCrawler" def start_requests(self): print("start_requests") press = [8, 190, 200] # 8: 중앙 pageNum = 2 date = [20180501] # http://media.daum.net/cp/8?page=1&regDate=20170501&cateId=1002 for cp in press: for day in date: for i in range(1, pageNum, 1): url = "http://media.daum.net/cp/{0}?page={1}&regDate={2}&cateId=1002".format( cp, i, day ) print(url) time.sleep(1) yield scrapy.Request(url, self.parse_news, errback=self.errback) def errback(self, res): print(res) def parse_news(self, response): print("parse_news") # for sel in response.xpath('//*[@id="mArticle"]/div[2]/ul/li[1]/div' # print(response.text) # xpath = response.xpath('//*[@id="mArticle"]') # print(xpath) for sel in response.xpath('//*[@id="mArticle"]/div[2]/ul/li/div'): print(sel) item = NewscrawlingItem() item["source"] = sel.xpath( 'strong/span[@class="info_news"]/text()' ).extract()[0] item["category"] = "정치" item["title"] = sel.xpath('strong[@class="tit_thumb"]/a/text()').extract()[ 0 ] item["url"] = sel.xpath('strong[@class="tit_thumb"]/a/@href').extract()[0] item["date"] = sel.xpath( 'strong[@class="tit_thumb"]/span/span[@class="info_time"]/text()' ).extract()[0] print("*" * 100) print(item["title"]) yield item class NewsSpider(scrapy.Spider): name = "newsCrawler" def start_requests(self): with open("newsUrlCrawl.csv") as csvfile: reader = csv.DictReader(csvfile) for row in reader: yield scrapy.Request(row["url"], self.parse_news) def parse_news(self, response): item = NewscrawlingItem() item["source"] = response.xpath( '//*[@id="cSub"]/div[1]/em/a/img/@alt' ).extract()[0] item["category"] = "정치" item["title"] = response.xpath('//*[@id="cSub"]/div[1]/h3/text()').extract()[0] item["date"] = response.xpath( '/html/head/meta[contains(@property, "og:regDate")]/@content' ).extract()[0][:8] item["article"] = ( response.xpath( '//*[@id="harmonyContainer"]/section/div[contains(@dmcf-ptype, "general")]/text()' ).extract() + response.xpath( '//*[@id="harmonyContainer"]/section/p[contains(@dmcf-ptype, "general")]/text()' ).extract() ) print("*" * 100) print(item["title"]) print(item["date"]) time.sleep(5) yield item
true
ba568158f19d5d71d88f4d7cabd7c8d9f7cd9322
Python
nicolaslazzos/machine-learning-a-z
/Part 8 - Deep Learning/Unsupervised/2. Boltzmann Machines/restricted_boltzmann_machine.py
UTF-8
14,252
3.578125
4
[]
no_license
# BOLTZMANN MACHINES (BM) # Todos los tipos de redes vistos anteriormente tienen en comun que son modelos dirigidos, es decir, hay una direcccion # en la que el modelo funciona. En las Boltzmann Machines, no hay direccionalidad, son como un grafo conexo completo y # no dirigido. # Las BM, no tienen una capa de salida. Tiene nodos visibles y nodos ocultos, pero no discrimina nodos, sino que los # trata a todos de la misma forma. No tiene una capa de entrada debido a que no recibe informacion, sino que la genera. # Si lo comparamos con una planta nuclear por ejemplo, tiene muchas partes, de las cuales algunas se miden y otras no, y # entre todas, forman un unico sistema. En una BM los nodos visibles representan cosas que medimos o podemos medir, # mientras que los nodos ocultos son cosas que no medimos o no podemos medir. No se quedan esperando entradas, ya que # son capaces de generar por si mismas un conjunto de diferentes estados, variando cada uno de los parametros que cada # nodo representa. En el caso de compararlo con la planta nuclear, podria por ejemplo combinar distintas temperaturas # de ambiente, con distintas velocidades de viento y distintas presiones atmosfericas, etc. Por esto, no es un modelo # determinista, sino estocastico. # Lo que se hace, es entrenarla con datos para ayudarla a ajustar los distintos pesos del sistema acorde a los mismos y # de esta manera aprende los distintos valores que puede tomar cada parametro o caracteristica, como se combinan entre # ellos o como pueden afectarse, como interactuan, cuales son las conexiones y de esta forma nos permitiria, por ejemplo # en el caso de una planta nuclar, monitorearla, ya que la BM estaria modelando la planta nuclear. Del mismo modo, nos # permitiria identificar y recrear estados anormales de funcionamiento. # Energy-Based Models (EBM) # Las BM reciben este nombre debido a que usan la distribucion de Boltzmann para crear los diferentes estados. La # formula de Boltzmann para cada estado representa la probabilidad de ocurrencia del mismo, y dicha probabilidad es # inversamente proporcional a la cantidad de energia del sistema, es decir, mientras mas energia se necesita, mas # dificil es que el estado ocurra. # En las BM, la energia esta representada por los diferentes pesos de las sinapsis, por lo tanto, una vez entrenada la # red, buscara siempre el estado de menor energia. # Restricted Boltzmann Machines (RBM) # Es el mismo concepto, pero con la diferencia que los nodos visibles no se conectan entre ellos, al igual que los nodos # ocultos. Esto debido a que cuando el numero de neuronas aumenta, se vuelve muy costoso computar todas las conexiones # en una BM tradicional. # Durante el proceso de aprendizaje, lo que la RBM va a aprender, es como asignar sus nodos ocultos, a ciertas features # o variables de los datos que se estan analizando. Por ejemplo, en un sistema de recomendacion de peliculas, podria # aprender que ciertos generos son importantes, y ciertos actores y directores, por lo que los iria asignando a ciertos # nodos ocultos. No necesariamente deben ser esas features, solo son un ejemplo para nuestro entendimiento. Los nodos # ocultos se activaran segun si dicha feature esta presente en las peliculas que al usuario le han gustado. En el caso # contrario, no se encenderan. Por ejemplo, si un nodo representa el genero Accion, y al usuario le gustaron peliculas # de dicho genero, el mismo se encendera. Al ingresar una nueva pelicula, para saber si la recomienda o no, evaluara # sus conexiones con los nodos ocultos, en funcion de los pesos de las sinapsis, y si los nodos estan activados o no. # Contrastive Divergence # Es la forma en las que las RBM ajustan sus pesos. A partir de pesos inicializados aleatoriamente, la RBM calcula los # nodos ocultos, y luego, estos son capaces de reconstruir o recalcular las entradas o los nodos visibles usando estos # pesos. Cabe aclarar, que los valores resultantes no seran exactamente igual a los originales, ya que los nodos # visibles, no estan interconectados entre ellos, pero al ser recalculados por los nodos ocultos, estos estan ultimos # recibiendo informacion de todos los nodos visibles, por lo que el recalculo no sera exactamente el mismo. Este # proceso se repite por cada nueva entrada, es decir, se ingresan nuevos valores a los nodos visibles, se calculan los # nodos ocultos, y estos recalculan los nodos visibles. Termina cuando los nodos visibles recalculados no cambian, es # decir, converge. # Durante este proceso, el sistema al ajustar sus pesos, siempre tratara de buscar el estado de menor energia, y los # valores que obtendremos al final, en los nodos recalculados, no seran los que realmente buscamos. Entonces, lo que se # busca con este proceso es ver en que sentido va la "curva de energia" a medida que se entrena la red, para luego # modificar los pesos iniciales, de tal forma que al ingresar los datos de entrada o de entrenamiento (que son los # valores reales de los nodos visibles), la red se encuentre en su estado de menor energia. # (Ver video "Contrastive Divergence") # Sin embargo no hace falta realizar el proceso completo hasta la convergencia, sino que con unos primeros pasos ya es # suficiente para ver en que sentido va la "curva de energia" y ajusta los pesos iniciales. # Deep Belief Netowrks (DBN) # Surgen de apilar dos o mas RBM, y en este caso, excepto por la ultima capa, las demas estan dirigidas hacia abajo, # luego de ser entrenadas. Se entrena capa por capa. # Deep Boltzmann Machines (DBM) # Son como las anteriores, excepto que no direcciona las capas, sino que las deja todas sin dirigir. Ademas se especula # que las BBM pueden extraer features que son mas sofisticadas o complejas, y por lo tanto podrian ser usadas para # tareas mas complejas. import numpy as np import pandas as pd import torch import torch.nn as nn # modulo para nerual networks import torch.nn.parallel # modulo para procesamiento paralelo import torch.optim as optim import torch.utils.data from torch.autograd import Variable # para el stochastic gradient descend # Importando el dataset movies = pd.read_csv('Part 8 - Deep Learning/Unsupervised/2. Boltzmann Machines/ml-1m/movies.dat', sep='::', header=None, engine='python', encoding='latin-1') users = pd.read_csv('Part 8 - Deep Learning/Unsupervised/2. Boltzmann Machines/ml-1m/users.dat', sep='::', header=None, engine='python', encoding='latin-1') ratings = pd.read_csv('Part 8 - Deep Learning/Unsupervised/2. Boltzmann Machines/ml-1m/ratings.dat', sep='::', header=None, engine='python', encoding='latin-1') # Preparando el training set y el test set training_set = pd.read_csv('Part 8 - Deep Learning/Unsupervised/2. Boltzmann Machines/ml-100k/u1.base', delimiter='\t') training_set = np.array(training_set, dtype='int') test_set = pd.read_csv('Part 8 - Deep Learning/Unsupervised/2. Boltzmann Machines/ml-100k/u1.test', delimiter='\t') test_set = np.array(test_set, dtype='int') # Numero total de usuarios y peliculas nb_users = int(max(max(training_set[:, 0]), max(test_set[:, 0]))) nb_movies = int(max(max(training_set[:, 1]), max(test_set[:, 1]))) # Convirtiendo los datos a una matriz con filas = usuarios, columnas = peliculas e interseccion = rating def convert(data): new_data = [] for user_id in range(1, nb_users + 1): movies_id = data[:, 1][data[:, 0] == user_id] ratings_id = data[:, 2][data[:, 0] == user_id] ratings = np.zeros(nb_movies) ratings[movies_id - 1] = ratings_id new_data.append(list(ratings)) return new_data training_set = convert(training_set) test_set = convert(test_set) # Convirtiendo los sets en Torch tensors (matrices multidimensionales de un solo tipo de datos, en este caso, Float) training_set = torch.FloatTensor(training_set) test_set = torch.FloatTensor(test_set) # Implementando el sistema de recomendacion con RBM # Convirtiendo los ratings en binarios (Liked = 1, Not Liked = 0 y Sin Calificar = -1) training_set[training_set == 0] = -1 training_set[training_set == 1] = 0 training_set[training_set == 2] = 0 training_set[training_set >= 3] = 1 test_set[test_set == 0] = -1 test_set[test_set == 1] = 0 test_set[test_set == 2] = 0 test_set[test_set >= 3] = 1 # Creando la arquitectura de la red neuronal class RBM(): def __init__(self, nv, nh): # nv = cantidad de nodos visibles, nh = cantidad de nodos ocultos self.W = torch.randn(nh, nv) # inicializacion aleatoria de los pesos (vector de pesos) self.a = torch.randn(1, nh) # bias (probabilidad de los nodos ocultos dado los nodos visibles) self.b = torch.randn(1, nv) # bias (probabilidad de los nodos visibles dado los nodos ocultos) # El bias permite mover la funcion de activacion sobre el eje x para ajustarse mejor a las entradas. Es decir, # es basicamente otro peso. En este caso, con a y b se inicializan aleatoriamente lo bias para cada nodo. def sample_h(self, x): # Esta funcion va a tomar muestras de las activaciones de todos los nodos ocultos de la red. Para esto, los va a # activar, de acuerdo a una probabilidad p(h, v), es decir, la probabilidad de que el nodo h sea 1, dado el # valor de v. Esta probabilidad es igual a la funcion de activacion (la funcion de activacion sigmoid) y la # calcularemos en esta funcion. El parametro x, es el vector de valores de los nodos visibles (v en la formula). WX = torch.mm(x, self.W.t()) # se toma la transpuesta de W debido a que v se corresponde con las columnas activation = WX + self.a.expand_as(WX) # neuronas * pesos + bias p_h_given_v = torch.sigmoid(activation) # El primer parametro que se retorna, es la probabilidad de activacion de cada nodo oculto datos los valores de # los nodos visibles. Luego, el segundo parametro, es el muestreo de activacion de cada nodo oculto, es decir, # para cada uno se genera un numero aleatorio entre 0 y 1, y en funcion de su probabilidad de activacion, se # determina si el nodo se activaria o no. return p_h_given_v, torch.bernoulli(p_h_given_v) def sample_v(self, y): # Esta funcion hara lo mismo que sample_v, pero para los nodos visibles. Hay un nodo visible por cada pelicula # por lo que el vector de probabilidades tendra la probabilidad de que la pelicula le guste o no al usuario, # calculada en funcion de los valores de los nodos ocultos. WY = torch.mm(y, self.W) # neuronas * pesos activation = WY + self.b.expand_as(WY) # neuronas * pesos + bias p_v_given_h = torch.sigmoid(activation) return p_v_given_h, torch.bernoulli(p_v_given_h) def train(self, v0, vk, ph0, phk): # Esta funcion implementa la Contrastive Divergence. Lo que hace es, samplear los nodos ocultos a partir de los # valores de los nodos visibles. Luego con estos valores, samplea los nodos visibles y obtiene nuevos valores. # Y con estos valores, vuelve a samplear los nodos ocultos y obtiene nuevos valores, y asi sucesivamente. # v0 = valores iniciales de los nodos visibles (ratings de un usuario para cada pelicula) # vk = valores de los nodos visibles obtenidos luego de k muestreos # ph0 = las probabilidades de los nodos ocultos, durante el primer muestreo, dados los valores de los v0 # phk = las probabilidades de los nodos ocultos, luego de k muestreos, en funcion de los valores de los vk self.W += (torch.mm(v0.t(), ph0) - torch.mm(vk.t(), phk)).t() # self.W += torch.mm(v0.t(), ph0) - torch.mm(vk.t(), phk) self.b += torch.sum((v0 - vk), 0) self.a += torch.sum((ph0 - phk), 0) # Inicializando la RBM nv = len(training_set[0]) # un nodo visible por cada pelicula nh = 100 # el numero de nodos ocultos se elige, estimativamente, en funcion de la cantidad de nodos visibles batch_size = 100 rbm = RBM(nv, nh) # Entrenando la RBM nb_epoch = 10 for epoch in range(1, nb_epoch + 1): train_loss = 0 s = 0. # contador para normalizar el loss for user_id in range(0, nb_users - batch_size, batch_size): # se va tomando un batch de 100 usuarios vk = training_set[user_id: user_id + batch_size] v0 = training_set[user_id: user_id + batch_size] ph0, _ = rbm.sample_h(v0) for k in range(10): # Gibbs sampling _, hk = rbm.sample_h(vk) _, vk = rbm.sample_v(hk) vk[v0 < 0] = v0[v0 < 0] # volvemos los nodos de las pelis no calificadas a -1 para que la red no aprenda de ellos phk, _ = rbm.sample_h(vk) rbm.train(v0, vk, ph0, hk) train_loss += torch.mean(torch.abs(v0[v0 >= 0] - vk[v0 >= 0])) # Average Distance # train_loss += np.sqrt(torch.mean((v0[v0 >= 0] - vk[v0 >= 0]) ** 2)) # RMSE s += 1. print('Epoch: ' + str(epoch) + ' - Loss: ' + str(train_loss/s)) # dio una perdida del 25% aproximadamente # Testeando la RBM test_loss = 0 s = 0. # contador para normalizar el loss for user_id in range(nb_users): # se va tomando un batch de 100 usuarios # En este caso, como estamos testeando, el objetivo (vt) es predecir el reting de las peliculas del test set, y es # por eso, que como entrada, se continua usando el training set, ya que a partir de lo que la red aprenda de los # datos que conoce, buscara predecir aquellos que no conoce, o sea, el test set. v = training_set[user_id: user_id + 1] vt = test_set[user_id: user_id + 1] if len(vt[vt >= 0]) > 0: # si hay al menos una pelicula calificada, se pueden hacer predicciones _, h = rbm.sample_h(v) _, v = rbm.sample_v(h) test_loss += torch.mean(torch.abs(vt[vt >= 0] - v[vt >= 0])) # Average Distance # train_loss += np.sqrt(torch.mean((vt[vt >= 0] - v[vt >= 0]) ** 2)) # RMSE s += 1. print('Test Loss: ' + str(test_loss/s)) # dio una perdida similar al training, lo que es muy bueno
true
74037de7e9306289f0e67a4a3c56b7e75e750abc
Python
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/arc076/A/4253881.py
UTF-8
239
2.703125
3
[]
no_license
N,M=map(int,input().split()) ans=1 if(abs(N-M)<2) else 0 n=max(N,M) fa=0 for i in range(1,n+1): fa=ans ans=ans*i%(10**9+7) if(N==M): ans=(ans*ans*2)%(10**9+7) else: ans=((ans)*fa)%(10**9+7) print(ans)
true
bd620c3b238af64f5845487a4e539132c446ded4
Python
ChensonVan/orm.py
/test_orm.py
UTF-8
384
2.5625
3
[]
no_license
import unittest import orm class UtilTests(unittest.TestCase): def test_camel_to_under(self): t = 'TestClassName' r = 'test_class_name' self.assertEqual(r, orm.camel_to_underscores(t)) def test_under_to_under(self): t = 'test_class_name' self.assertEqual(t, orm.camel_to_underscores(t)) if __name__ == "__main__": unittest.main()
true
33e35247aace9d41bb20957c46a27df6c2668772
Python
wolfsinem/AnalyticalComputing
/rechtewegSnelheden.py
UTF-8
1,042
2.765625
3
[]
no_license
import csv import numpy as np import matplotlib.pyplot as plt with open('snelheden.csv', 'r') as csvFile: posities = csv.reader(csvFile, delimiter=';') tijd = [] beginPunt = [] auto1 = [] auto2 = [] auto3 = [] i=0 for row in posities: if i == 0: beginPunt = [float(row[1]), float(row[2]), float(row[3])] i = 1 else: tijd.append(float(row[0])) auto1.append(float(row[1])) auto2.append(float(row[2])) auto3.append(float(row[3])) auto_1 = [] auto_2 = [] auto_3 = [] def intBerekenen(autoSoort,autoLijst): for i in range(len(tijd) - 1): intgr = np.trapz(autoSoort[0:i+2],tijd[0:i+2]) autoLijst.append(intgr) return autoLijst print(intBerekenen(auto1,auto_1)[:10]) print(intBerekenen(auto2,auto_2)) print(intBerekenen(auto3,auto_3)) plt.plot(tijd[1:],auto_1, label='auto 1') plt.plot(tijd[1:],auto_2, label='auto 2') plt.plot(tijd[1:],auto_3, label='auto 3') plt.legend() plt.show() csvFile.close()
true
1c566cefb0a6e0d1bb139ece76cbf2dd7ad4c795
Python
jinnaiyuu/search-ja
/python/greedy_best_first_search.py
UTF-8
359
2.90625
3
[ "MIT" ]
permissive
from graph_search import GraphSearch def GreedyBestFirstSearch(problem): h = lambda node: problem.heuristic(node.state) return GraphSearch(problem, h) if __name__ == "__main__": from grid_pathfinding import GridPathfinding problem = GridPathfinding() path = GreedyBestFirstSearch(problem) for s in reversed(path): print(s)
true
6173f8e24063c6bcfa3f2cbcc3c593217b4507bb
Python
havealot/Python-for-DM-ITI-Tasks
/task3.py
UTF-8
1,695
2.671875
3
[]
no_license
import sqlalchemy as db import pandas as pd import numpy as np import json from keras.models import model_from_json # create connection with the database con = db.create_engine('postgresql://postgres:root@localhost/ammardb') #First run only to load table the unscored table.. #df = pd.read_csv("pima-indians-diabetes.data.csv") #df.to_sql('diabetes_unscored', con, if_exists='append', index=False) # Select query that retreive only unscored data query = """ select "Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI", "DiabetesPedigreeFunction", "Age" from "diabetes_unscored" except select "Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI", "DiabetesPedigreeFunction", "Age" from "diabetes_scored"; """ # Load the table diabetes = pd.read_sql(query, con) # open the json file for read json_file = open('model.json', 'r') model_json = json_file.read() json_file.close() # loading the model from the json file model = model_from_json(model_json) # loading weights to the model from h5 file model.load_weights("model.h5") # transforming the diabetes dataframe to numpy array to pass it to the predict function diabetes_arr = diabetes.to_numpy() prediction = model.predict(diabetes_arr) # transforming the outcome to 0 or 1 scores=[] for i in prediction: if i >= 0.5: scores.append(1) else: scores.append(0) # add new column for Outcome 'Score' to the dataframe diabetes['Outcome']= scores # Insert new scored data to the diabetes_scored table diabetes.to_sql(name = 'diabetes_scored', con=con, index = False, if_exists='append') # crontab -e # 0 * * * * /usr/bin/python /home/ammar/Desktop/task3/task3.py
true
43ea9b83e272b77facda4d4f3c3be6caccdfb292
Python
jacokyle/MTH325_Homework
/Programming Set 1.py
UTF-8
1,807
4.53125
5
[]
no_license
# Kyle Jacobson # Professor Taylor # MTH 325 - 02 # 24 February 2020 # The following function takes a graph represented by a # dictionary as input and outputs the degree sequence of # the graph as a list (in non-increasing order). def degree_sequence(dict): # The initiliazed list for the function. seq = [] # Parses through each element of the input. for vertex in dict: # Adds values to the list. seq.append(len(dict[vertex])) # Sorts the values of the list. seq.sort() # Reverses the list; the list is in non-increasing order. seq.reverse() return seq print(degree_sequence({"A": ["B", "C", "D"], "B":["A", "C", "D"], "C":["A", "B", "D"], "D":["A", "B", "C"]})) # This function takes a list of non-increasing integers as # input and uses the Erdos Gallai conditions to determine # whether or not this is the degree sequence of a graph. def Erdos_Gallai(list): # The initiliazed list for the function. seq = [] # Parses through each element of the input. for value in list: # Adds values to the list. seq.append(value) # Throws an error if any value is negative; return error message. if(value < 0): return("You cannot have a negative degree!") # Parses through the current list of values. for element in range(len(seq) - 1): # Checks if the inputted list is in non-increasing order; returns False if not. if(seq[element] < seq[element + 1]): return False # Checks if the list has at least one or more element. if(len(seq) >= 1): # Checks if the sum of the list is even; return True. if(sum(seq) % 2 == 0): return True # Checks if the sum of the list is odd; return False. else: return False print(Erdos_Gallai([6,5,2,2,2,2,1]))
true
f78a4897abf662b5faf605065758cd7b7067fbfd
Python
parthpankajtiwary/robotics-ai-final
/head_controller/scripts/headController.py
UTF-8
5,356
2.5625
3
[]
no_license
#!/usr/bin/env python import roslib roslib.load_manifest('head_controller') import rospy import actionlib from std_msgs.msg import Float64 import trajectory_msgs.msg import control_msgs.msg from trajectory_msgs.msg import JointTrajectoryPoint from control_msgs.msg import JointTrajectoryAction, JointTrajectoryGoal, FollowJointTrajectoryAction, FollowJointTrajectoryGoal import time from geometry_msgs.msg import Twist from dynamixel_controllers.srv import SetSpeed class Joint: def __init__(self): ''' self.jta = actionlib.SimpleActionClient('/f_arm_controller/follow_joint_trajectory', FollowJointTrajectoryAction) rospy.loginfo('Waiting for joint trajectory action') self.jta.wait_for_server() rospy.loginfo('Found joint trajectory action!') ''' self.sub = rospy.Subscriber("/cmd_vel", Twist, self.callbackCmd_vel, queue_size=1) # publishers for the pan and tilt servos # self.tiltSpeed = rospy.Publisher("/tilt_controller/set_speed", Float64, queue_size = 1) # self.panSpeed = rospy.Publisher("/pan_controller/set_speed", Float64, queue_size = 1) # Service for setting the speed rospy.loginfo('Waiting for set_speed service...') rospy.wait_for_service('tilt_controller/set_speed') rospy.wait_for_service('pan_controller/set_speed') rospy.loginfo('set_speed service found!') self.setTiltSpeed = rospy.ServiceProxy('tilt_controller/set_speed', SetSpeed) self.setPanSpeed = rospy.ServiceProxy('pan_controller/set_speed', SetSpeed) # The speed at which the servos should move self.tiltSpeed = 0.5 self.panSpeed = 0.5 # Set the speed values self.setTiltSpeed(self.tiltSpeed) self.setPanSpeed(self.panSpeed) self.tiltPosition = rospy.Publisher("tilt_controller/command", Float64, queue_size = 1) self.panPosition = rospy.Publisher("pan_controller/command", Float64, queue_size = 1) self.wasZero = False self.lastMove = (0, 0) # If difference between positions is less than the following numbers, the head won't move. self.minTiltDifference = 0 self.minPanDifference = 0 def callbackCmd_vel(self, data): maxPitch = 0.5 min_pitch = 0.33 min_pitch_turn = 0.5 maxPan = 0.50 maxVelocity = 0.3 maxTurn = 0.6 panBackward = 1.57 # position when driving backwards and rotation tilt_nav = 0 pan_nav = 0 if data.linear.x >= 0: # for forward movement or stopped convert = maxPitch / maxVelocity tilt_nav = max(convert * data.linear.x, min_pitch) convert = maxPan / maxTurn pan_nav = convert * data.angular.z if not self.difference_enough(tilt_nav, pan_nav): return # Movement ended completely if data.linear.x == 0: if self.wasZero == False: self.wasZero = True self.move_joint([tilt_nav, pan_nav]) # Moving forward else: self.wasZero = False self.move_joint([tilt_nav, pan_nav]) else: # moving backwards self.wasZero = False tilt_nav = min_pitch_turn if data.angular.z > 0: pan_nav = -panBackward if not self.difference_enough(tilt_nav, pan_nav): return self.move_joint([tilt_nav, pan_nav]) elif data.angular.z < 0: pan_nav = panBackward if not self.difference_enough(tilt_nav, pan_nav): return self.move_joint([tilt_nav, pan_nav]) # There are no more movement commands sent else: self.move_joint([tilt_nav, 0]) #print('{0}, {1}'.format(tilt_nav, pan_nav))# - self.lastMove[1])) def difference_enough(self, tilt, pan): return True # tilt, pan = abs(tilt), abs(pan) #return (abs(tilt - self.lastMove[0]) > self.minTiltDifference) and \ # (abs(pan - self.lastMove[1]) > self.minPanDifference) def move_joint(self, angles): # The speed values # self.tiltSpeed.publish(speed[0]) # self.panSpeed.publish(speed[1]) # The positions in radian # print "move joint" self.lastMove = [abs(x) for x in angles] self.tiltPosition.publish(angles[0]) # publish the tilt position self.panPosition.publish(angles[1]) # publish the pan position ''' goal = FollowJointTrajectoryGoal() goal.trajectory.joint_names = ['tilt_joint', 'pan_joint'] point = JointTrajectoryPoint() point.positions = angles point.time_from_start = rospy.Duration(0.01) goal.trajectory.points.append(point) self.jta.send_goal_and_wait(goal) ''' if __name__ == '__main__': rospy.init_node('head_controller') head = Joint() rospy.spin()
true
af5b7e16d5fe6b87363b775758541463ff8e758d
Python
CMS28/cms28.github.io
/practice/Yeet/diamond.py
UTF-8
298
3.546875
4
[]
no_license
for i in range(9): for j in range(9-i): print(" ", end="") for j in range(9-i,9+i+1): print("*", end="") print() for i in range(9,-1,-1): for j in range(9-i): print(" ", end="") for j in range(9-i,9+i+1): print("*", end="") print()
true
8f18225fc0b894949328d88e0d08105f8b7cbb15
Python
aaanneli/women-in-black
/bullet.py
UTF-8
4,391
3.015625
3
[]
no_license
from __future__ import print_function, division import pygame import random import math from constant import * def radians_to_degrees(radians): return (radians / math.pi) * 180.0 class Bullet(pygame.sprite.Sprite): side = 7 # small side of bullet rectangle vel = 250 # velocity maxlifetime = 10.0 # seconds def __init__(self, boss, *groups ): pygame.sprite.Sprite.__init__(self, *groups) # THE most important line ! self.boss = boss self.lifetime = 0.0 self.calculate_heading() # !!!!!!!!!!!!!!!!!!! self.pos = self.boss.pos[:] # copy (!!!) of boss position #self.pos = self.boss.pos # uncomment this linefor fun effect self.calculate_origin() self.update() # to avoid ghost sprite in upper left corner, # force position calculation. def calculate_heading(self): """ drawing the bullet and rotating it according to it's launcher""" self.radius = Bullet.side # for collision detection self.angle = -math.degrees(self.boss.angle) image = pygame.Surface((Bullet.side * 2, Bullet.side)) # rect 2 x 1 image.fill((128,128,128)) # fill grey pygame.draw.rect(image, BLACK, (0,0,int(Bullet.side * 1.5), Bullet.side)) # rectangle 1.5 length pygame.draw.circle(image, BLACK, (int(self.side *1.5) ,self.side//2), self.side//2) # circle image.set_colorkey((128,128,128)) # grey transparent self.image0 = image.convert_alpha() self.image = pygame.transform.rotate(self.image0, self.angle) self.rect = self.image.get_rect() self.dx = math.cos(self.boss.angle) * self.vel self.dy = math.sin(self.boss.angle) * self.vel if self.boss.isMoving: # add boss movement self.dx += math.cos(self.boss.angle) * MOVING_INDEX*FPS self.dy += math.sin(self.boss.angle) * MOVING_INDEX*FPS def calculate_origin(self): # - spawn bullet at end of turret barrel instead tank center - # cannon is around Tank.side long, calculatet from Tank center # later subtracted 20 pixel from this distance # so that bullet spawns closer to tank muzzle #self.pos[0] += math.cos(degrees_to_radians(self.boss.turretAngle)) #* (Tank.side-20) #self.pos[1] += math.sin(degrees_to_radians(-self.boss.turretAngle))#* (Tank.side-20) self.pos[0] = self.boss.rect.center[0] - 10 self.pos[1] = self.boss.rect.center[1] def update(self, seconds=0.0,game = None): # ---- kill if too old --- self.lifetime += seconds if self.lifetime > Bullet.maxlifetime: self.kill() # ------ calculate movement -------- self.pos[0] += self.dx * seconds self.pos[1] += self.dy * seconds # ----- kill if out of screen if self.pos[0] < 0: self.kill() elif self.pos[0] > SCREEN_WIDTH: self.kill() if self.pos[1] < 0: self.kill() elif self.pos[1] > SCREEN_HEIGHT: self.kill() # --------kill if hit wall --- if game is not None: for wall in game.walls: if self.rect.colliderect(wall): self.kill() # ----- kill if kill alien -- if game is not None: for alien in game.aliens: if self.rect.colliderect(alien.rect): killAlienSound = pygame.mixer.Sound("music/alien-dies.wav") killAlienSound.play() game.aliens.remove(alien) game.sprites.remove(alien) self.kill() # ---- kill if hit boss -- if game is not None and game.boss is not None: if self.rect.colliderect(game.boss): self.kill() killAlienSound = pygame.mixer.Sound("music/alien-dies.wav") killAlienSound.play() game.boss.life -= 1 if game.boss.life <= 0: print("fickin die") game.boss.kill() game.boss = None game.sprites.remove(game.boss) #------- move ------- self.rect.centerx = round(self.pos[0],0) self.rect.centery = round(self.pos[1],0)
true
b358a942a0bae493bd644d50ad68f4fa7e764e0b
Python
ssong38/PortfolioWeb
/test/testParse.py
UTF-8
6,611
2.859375
3
[]
no_license
import unittest from flask import Flask from flask import request, redirect, url_for, render_template import xml.etree.ElementTree as ET # This dictionary will take all of file information according to version dicttest = {} # This dictionary will take all of version message according to version versionmessage = {} # This dictionary will be passed into index.html webdict = {} # This dictionary will store information according to the assignment finaldict = {} # process data def processlist(): ''' This function is to process XML file and store them into dicttest according to the version Generally speaking, this keys of dicttest will be version. The value of dicttest will be another array(dict) Then it will take all of file of the certain version submission. Here, we build a new small xml file for testing purpose :return: ''' tree = ET.ElementTree(file='/Users/AMsong/Desktop/cs242portfolio/data/test_list.xml') root = tree.getroot() name = '' commit = 0 author = 'ssong38' date = 0 for i in range(len(root[0])): subnode = root[0][i] file1 = root[0][i].attrib['kind'] size = 0 if file1 == 'dir': for i in range(len(subnode)): if subnode[i].tag == 'name': name = subnode[i].text if i == 1: commit = subnode[i].attrib['revision'] for child in subnode[1]: if child.tag == 'author': author = child.text elif child.tag == 'date': date = child.text else: for i in range(len(subnode)): if subnode[i].tag == 'name': name = subnode[i].text if subnode[i].tag == 'size': size = subnode[i].text if i == 2: commit = subnode[i].attrib['revision'] for child in subnode[2]: if child.tag == 'author': author = child.text elif child.tag == 'date': date = child.text if commit not in dicttest.keys(): dict1 = {} dicttest[commit] = [] dict1[name] = {} dict1[name]['size'] = size dict1[name]['author'] = author dict1[name]['date'] = date dict1[name]['filetype'] = file1 dicttest[commit].append(dict1) else: dict1 = {} dict1[name] = {} dict1[name]['size'] = size dict1[name]['author'] = author dict1[name]['date'] = date dict1[name]['filetype'] = file1 dicttest[commit].append(dict1) def processlog(): ''' This function is to handle log.xml. This file contains submission message. It's too annoying to put all of information into one dict. Therefore, I put all of message information into a new dict The key of dict is the version of submission. The value of dict is the message coming with each submission Here, we build a new small xml file for testing purpose :return: ''' tree = ET.ElementTree(file='/Users/AMsong/Desktop/cs242portfolio/data/test_log.xml') root1 = tree.getroot() for i in range(len(root1)): root2 = root1[i] version = root2.attrib['revision'] message = root2[3].text versionmessage[version] = message def produceText(): ''' In this function, we have built two dicts. The first one is finaldict - categrized according to the homework The second one is webdict - I modified format of finaldict and add message into this webdict The goal of webdict is to build easy format for website to query Here, we build a new small xml file for testing purpose :return: ''' for i in dicttest: if dicttest[i][0].keys()[0][0:13] not in finaldict.keys(): finaldict[dicttest[i][0].keys()[0]] = {} finaldict[dicttest[i][0].keys()[0]][i] = dicttest[i] else: # print dicttest[i][0].keys()[0] finaldict[dicttest[i][0].keys()[0][0:13]][i] = dicttest[i] for i in finaldict: print i assiname = i webdict[assiname] = {} for j in finaldict[i]: versionname = j webdict[assiname][str(versionname)] = {} webdict[assiname][str(versionname)]['message'] = 'Version Messgae: ' + str(versionmessage[versionname]) webdict[assiname][str(versionname)]['file'] = [] webdict[assiname][str(versionname)]['file'].append(['filename', 'date', 'filetype', 'author', 'size']) for z in range(len(finaldict[i][j])): filename = finaldict[i][j][z].keys()[0] date = finaldict[i][j][z][filename]['date'] filetype = finaldict[i][j][z][filename]['filetype'] author = finaldict[i][j][z][filename]['author'] size = finaldict[i][j][z][filename]['size'] webdict[assiname][str(versionname)]['file'].append([filename, date, filetype, author, size]) class TestParse(unittest.TestCase): ''' This class is the unittest class. It's for testing the data parse ''' def testProcessList(self): ''' Use this function to check the dicttest dictionary :return: ''' processlist() self.assertEqual(dicttest.keys()[0], '2468') self.assertEqual(len(dicttest['2468']),4) def testProcessLog(self): ''' Use this function to test the versionmessage dictionary :return: ''' processlog() self.assertEqual(versionmessage.keys()[0], '2468') self.assertEqual(versionmessage['2468'],'previous project') def testProduceText(self): ''' Use this function to test the webdict and finaldict dictionary :return: ''' produceText() self.assertEqual(finaldict.keys(),['Assignment0']) self.assertEqual(finaldict['Assignment0'].keys(),['2468']) self.assertEqual(len(finaldict['Assignment0']['2468']), 4) self.assertEqual(webdict.keys(),['Assignment0']) self.assertEqual(len(webdict['Assignment0']),1) self.assertEqual(len(webdict['Assignment0']['2468']),2) self.assertEqual(webdict['Assignment0']['2468']['message'],'Version Messgae: previous project') self.assertEqual(len(webdict['Assignment0']['2468']['file']),5)
true
ae19a792764a5ee2a3840ad07da1209cce544887
Python
duxiaotxt/test
/UDPtest.py
UTF-8
1,062
2.78125
3
[]
no_license
# encoding : utf-8 from socket import * PORT = 5050 def main(): a = ["0","0","0","0","0","0","0"] while True: menuswitch = input("수정화면으로 가려면 E키 : ") if (menuswitch == "e" or menuswitch == "E"): while True: getnum = input('1.수분상태/2.부동액/3.밧데리/4.엔진수온/5.엔진오일/6.미션오일/7.안전상태, 나가려면 Q키') if(getnum=="Q" or getnum == "q"): break if(int(getnum)>7 and int(getnum)<1): continue getstat = input('해당 타입의 상태 입력') a[int(getnum)-1] = getstat continue client = socket(AF_INET, SOCK_DGRAM) parse = "/" str = "" for i in range(len(a)): str += a[i] str += parse sentence = (str).encode('utf-8') print(sentence) client.sendto(sentence,('127.0.0.1', PORT)) if __name__ == '__main__': main()
true
1c04c17c354963dbb65a7887ae2ea7782319a536
Python
AliceHincu/FP-Assignment11
/GUI/GUI.py
UTF-8
19,166
3.140625
3
[]
no_license
# ---- IMPORT ZONE ---- import pygame from win32api import GetSystemMetrics from start_game.start import Game from start_game.minimax import EasyMode, MediumMode, HardMode import math import numpy as np # ---- CLASS ZONE ---- class GuiElements(Game): def __init__(self): super().__init__() self._DISPLAY_WIDTH = GetSystemMetrics(0) self._DISPLAY_HEIGHT = GetSystemMetrics(1) self._GAME_DISPLAY = pygame.display.set_mode((self._DISPLAY_WIDTH, self._DISPLAY_HEIGHT)) self._SQUARE_SIZE = 100 self._RADIUS = self._SQUARE_SIZE / 2 - 5 self._transparent_black = (0, 0, 0, 200) self._black = (0, 0, 0, 255) self._white = (255, 255, 255) self._blue = (0, 0, 200) self._purple = (221, 160, 221) self._indigo = (138, 43, 226) # --- getters ---- def game_display(self): return self._GAME_DISPLAY def display_width(self): return self._DISPLAY_WIDTH def display_height(self): return self._DISPLAY_HEIGHT def square_size(self): return self._SQUARE_SIZE # --- objects --- def button(self, msg, color, x, y, w, h, ic, ac, action=None, actionArgs=None): """ Creates a button :param msg: What do you want the button to say on it (type: <str>) :param color: The color of the text inside the button :param x: The x location of the top left coordinate of the button box (type: <int>) :param y: The y location of the top left coordinate of the button box (type: <int>) :param w: Button width (type: <int>) :param h: Button height (type: <int>) :param ic: Inactive color (when a mouse is not hovering) :param ac: Active color (when a mouse is hovering) :param action: The function that is called after pressing the button :param actionArgs: Function arguments (type: tuple) :return: """ mouse = pygame.mouse.get_pos() # position of the mouse click = pygame.mouse.get_pressed(5) # if you click rect1 = pygame.Rect(x, y, w, h) rect1.center = (x, y) shape_surf = pygame.Surface(pygame.Rect(rect1).size, pygame.SRCALPHA) # if the cursor is on the button if x + w/2 > mouse[0] > x - w/2 and y + h/2 > mouse[1] > y - h/2: pygame.draw.rect(shape_surf, ac, shape_surf.get_rect()) if click[0] == 1: if actionArgs is not None: action(actionArgs) else: action() else: pygame.draw.rect(shape_surf, ic, shape_surf.get_rect()) self._GAME_DISPLAY.blit(shape_surf, rect1) # the text on the buttons self.text("comicsansms", 30, msg, color, x, y) def text(self, font, font_size, text, color, x, y): """ Display the text on screen ---Variables: :param font: the name of the font (type: <str>) :param font_size: the size of the font (type: <int>) :param text: the text to be displayed (type: <str>) :param color: the color of the text (type: <str>) :param x: The x location of the center coordinate of the text (type: <int>) :param y: The y location of the center coordinate of the text (type: <int>) """ font_text = pygame.font.SysFont(font, font_size) text_surf, text_rect = self.text_objects(text, font_text, color) text_rect.center = (x, y) self._GAME_DISPLAY.blit(text_surf, text_rect) def background(self, img): """ Load an image as the background :param img: the name of the image file (type: <str>) """ bg = pygame.image.load(img) # INSIDE OF THE GAME LOOP self.game_display().blit(bg, (0, 0)) def mini_background(self, x, y, w, h): """ Create a mini background which is a Rect --- Variables :param x: The x location of the top left coordinate of the mini background (type: <int>) :param y: The y location of the top left coordinate of the mini background (type: <int>) :param w: Mini background width (type: <int>) :param h: Mini background height (type: <int>) """ rect1 = pygame.Rect(x, y, w, h) rect1.center = (x, y) shape_surf = pygame.Surface(pygame.Rect(rect1).size, pygame.SRCALPHA) pygame.draw.rect(shape_surf, self._black, shape_surf.get_rect()) self._GAME_DISPLAY.blit(shape_surf, rect1) def draw_circle(self, pos_x, turn): """ Draw a circle (drop piece) :param pos_x: the center in the axis Ox of the circle :param turn: who needs to play """ self.mini_background(self._DISPLAY_WIDTH / 2, 100, self._DISPLAY_WIDTH / 2, 200) if turn == 'player1': pygame.draw.circle(self._GAME_DISPLAY, self.color('player1 color'), (pos_x, 100 + self._SQUARE_SIZE / 2), self._RADIUS) else: pygame.draw.circle(self._GAME_DISPLAY, self.color('player2 color'), (pos_x, 100 + self._SQUARE_SIZE / 2), self._RADIUS) self.text("comicsansms", 30, turn + str('\'s turn'), self._white, self._DISPLAY_WIDTH / 2, 50) # --- getter --- def color(self, color): """ Returns color :param color: the name of the color (type: <str>) :return: RGB value """ if color == 'black': return self._black if color == 'transparent_black': return self._transparent_black if color == 'white': return self._white if color == 'player1 color': return self._purple if color == 'player2 color' or color == 'ai color': return self._indigo if color == 'board color': return self._blue # --- helpful functions for objects --- @staticmethod def text_objects(text, font, color): """ Creates a new Surface with the specified text rendered on it :param text: the text (type: <str>) :param font: the font (type: <class 'pygame.font.Font'>) :param color: the color of the text (type: <str>) :return: a new surface (type: <class 'pygame.Surface'>) a new rect with the size of the image and the x, y coordinates (0, 0) (type: <class 'pygame.Rect'>) """ text_surface = font.render(text, True, color) return text_surface, text_surface.get_rect() class GUI(GuiElements): def __init__(self): super().__init__() self._ai = None self._board = None self._turn = None self._button_clicked = "start_main_menu" self._button_clicked_arg = None # ---- QUIT ---- @staticmethod def quit_game(): """ Quit the game """ pygame.quit() quit() # ---- WIN ---- def gui_winning(self, turn): """ When someone wins :param turn: the player who won (type: <str>) """ self.create_board() self.mini_background(self.display_width() / 2, 100, self.display_width() / 2, 200) self.text("comicsansms", 30, turn + str(' wins!!!!!!!!'), self.color('white'), self.display_width() / 2, 50) pygame.display.update() pygame.time.wait(2000) self.main_menu() # ---- DRAW BOARD ---- def draw_board(self, board): """ Draw the board :param board: type: <class> """ radius = self.square_size() / 2 - 5 matrix = np.flip(board.boardmatrix(), 0) for c in range(self.columncount()): for r in range(self.rowcount()): rect_x = c * self.square_size() + 415 rect_y = self.square_size()*(r+1)+100 pygame.draw.rect(self.game_display(), self.color('board color'), (rect_x, rect_y, self.square_size(), self.square_size())) if matrix[r][c] == 0: pygame.draw.circle(self.game_display(), self.color('black'), (rect_x + self.square_size()/2, rect_y + self.square_size()/2), radius) elif int(matrix[r][c]) == 1: pygame.draw.circle(self.game_display(), self.color('player1 color'), (rect_x + self.square_size()/2, rect_y + self.square_size()/2), radius) else: pygame.draw.circle(self.game_display(), self.color('player2 color'), (rect_x + self.square_size() / 2, rect_y + self.square_size() / 2), radius) pygame.display.update() # ---- MANAGE THE GAME ---- def player_turn(self, board, turn, event): """ --- Description Execute player's turn --- Parameters :param board: (type: <class>) :param turn: either player1 or player2 (type: <str>) :param event: get the events from the screen (from pygame) --- Return :return: if it is game over or not, the board, the turn """ game_over = False if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEMOTION: pos_x = event.pos[0] if 460 < pos_x < 1075: self.draw_circle(pos_x, turn) if event.type == pygame.MOUSEBUTTONDOWN: pos_x = event.pos[0] col = int(math.floor((pos_x - 415) / self.square_size())) if 460 < pos_x < 1075: game_over, board, turn = self.run_game(board, turn, col) self.draw_circle(pos_x, turn) self.draw_board(board) return game_over, board, turn def computer_turn(self, board, turn): """ --- Description Execute player's turn --- Parameters :param board: (type: <class>) :param turn: either player1 or player2 (type: <str>) --- Return :return: if it is game over or not, the board, the turn """ op = None if self.difficulty() == "easy": op = self._ai.calculate_move(board) elif self.difficulty() == "medium": op = self._ai.pick_best_move(board, 2) elif self.difficulty() == "hard": op, minimax_score = self._ai.minimax(board, 3, math.inf, -math.inf, True) game_over, board, turn = self.run_game(board, turn, op) return game_over, board, turn def gui_run_game(self, board, turn): """ --- Description The main function for the game, processing the information --- Parameters :param board: type: <class> :param turn: type: <str> """ game_over = False self._button_clicked = "start_main_menu" self.game_display().fill(self.color('white')) self.background("../GUI/galaxy.jpg") self.mini_background(self.display_width() / 2, self.display_height() / 2, self.display_width() / 2, self.display_height()) self.draw_board(board) pygame.display.update() while not game_over: for event in pygame.event.get(): game_over, board, turn = self.player_turn(board, turn, event) if turn == 'player_ai': self.mini_background(self.display_width() / 2, 100, self.display_width() / 2, 200) pygame.time.wait(1000) game_over, board, turn = self.computer_turn(board, turn) self.draw_circle(self.display_width()/2, turn) self.button("x", "white", 1400, 100, 50, 50, self.color('transparent_black'), self.color('black'), self.quit_game) self.draw_board(board) pygame.display.update() self.gui_winning(turn) self.quit_game() def gui_load_game(self): """ Load the game. If the game doesn't exist, it creates a new one """ board, turn, battle_mode = self.load_game() if battle_mode == 'player vs computer': self.set_ai(self.difficulty()) self.gui_run_game(board, turn) # --- FUNCTION FOR SWITCHING MENUS --- def change_button_clicked(self, func_args=None): if isinstance(func_args, str): self._button_clicked = str(func_args) else: self._button_clicked = str(func_args[0]) self._button_clicked_arg = func_args[1] pygame.time.wait(540) # --- SET AI --- def set_ai(self, dif): """ Set the class of ai """ difficulty = dif if difficulty == "easy": self._ai = EasyMode() elif difficulty == "medium": self._ai = MediumMode() elif difficulty == "hard": self._ai = HardMode() self.set_dif(dif) self._button_clicked = "run_new_game" # --- MENU STUFF --- def gui_difficulty_menu(self): """ --- Description Choose from easy, medium or hard """ self.game_display().fill(self.color('white')) self.background("../GUI/galaxy.jpg") self.text("gabriola", 215, "Connect Four", "black", (self.display_width() / 2), (self.display_height() / 4)) self.text("gabriola", 215, "Connect Four", "white", (self.display_width() / 2 + 15), (self.display_height() / 4)) self.button("Easy", "white", (self.display_width() / 2), (self.display_height() / 2), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, ("set_ai", "easy")) self.button("Medium", "white", (self.display_width() / 2), (self.display_height() * 2 / 3), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, ("set_ai", "medium")) self.button("Hard", "white", (self.display_width() / 2), (self.display_height() * 5 / 6), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, ("set_ai", "hard")) pygame.display.update() def gui_choose_battle_mode(self, ai_exists): """ --- Description Menu for choosing the battle mode. Options: player vs player or computer vs computer """ if ai_exists: self.set_battle_mode("player vs computer") self._button_clicked = "gui_difficulty_menu" else: self.set_battle_mode("player vs player") self._button_clicked = "run_new_game" def start_battle_mode_menu(self): """ --- Description Menu for choosing the battle mode(player vs player or player vs computer) Buttons: one player, two players, quit game """ self.game_display().fill(self.color('white')) self.background("../GUI/galaxy.jpg") self.text("gabriola", 215, "Connect Four", "black", (self.display_width() / 2), (self.display_height() / 4)) self.text("gabriola", 215, "Connect Four", "white", (self.display_width() / 2 + 15), (self.display_height() / 4)) self.button("One player", "white", (self.display_width() / 2), (self.display_height() / 2), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, ("gui_choose_battle_mode", True)) self.button("Two players", "white", (self.display_width() / 2), (self.display_height() * 2 / 3), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, ("gui_choose_battle_mode", False)) self.button("Quit game", "white", (self.display_width() / 2), (self.display_height() * 5 / 6), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, "quit_game") pygame.display.update() def main_menu(self): """ --- Description Shows the buttons for the main menu: new game, load game, quit game """ self.game_display().fill(self.color('white')) self.background("../GUI/galaxy.jpg") self.text("gabriola", 215, "Connect Four", "black", (self.display_width() / 2), (self.display_height() / 4)) self.text("gabriola", 215, "Connect Four", "white", (self.display_width() / 2 + 15), (self.display_height() / 4)) self.button("New game", "white", (self.display_width() / 2), (self.display_height() / 2), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, "start_battle_mode_menu") self.button("Load game", "white", (self.display_width() / 2), (self.display_height() * 2 / 3), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, "gui_load_game") self.button("Quit game", "white", (self.display_width() / 2), (self.display_height() * 5 / 6), 300, 100, self.color('transparent_black'), self.color('black'), self.change_button_clicked, "quit_game") pygame.display.update() def gui_start_main_menu(self): """ Show the windows (menus + game) """ game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if self._button_clicked == "start_main_menu": self.main_menu() # --- Main Menu --- elif self._button_clicked == "start_battle_mode_menu": self.start_battle_mode_menu() elif self._button_clicked == "gui_load_game": self.gui_load_game() elif self._button_clicked == "quit_game": self.quit_game() # --- Start Battle Mode Menu --- elif self._button_clicked == "gui_choose_battle_mode": self.gui_choose_battle_mode(self._button_clicked_arg) # --- Difficulty Menu --- elif self._button_clicked == "gui_difficulty_menu": self.gui_difficulty_menu() elif self._button_clicked == "set_ai": self.set_ai(self._button_clicked_arg) # --- Run game --- if self._button_clicked == "run_new_game": board, turn = self.new_game() self.create_board("player1", self.battle_mode()) self.gui_run_game(board, turn) # --- START GUI --- def start_gui(self): """ Start the GUI """ pygame.init() pygame.mixer.init() pygame.mixer.music.load("../GUI/main menu music.mp3") pygame.mixer.music.play(-1) self.gui_start_main_menu()
true
2a13253d4d815d9062cf17f973aa55d61a76821b
Python
edjuaro/HiC_dev
/testing.py
UTF-8
414
2.53125
3
[]
no_license
import pandas as pd import sklearn.cluster as skl # from sklearn.cluster import AgglomerativeClustering from scipy.cluster.hierarchy import fclusterdata as cluster df = pd.read_csv("test_dataset.gct", sep='\t', skiprows=2) # print(df) df.drop(['Name', 'Description'], axis=1, inplace=True) df = df.T print(df.shape) # print(cluster(df, t=1.15)) # print(skl.AgglomerativeClustering(n_clusters=2, connectivity=df))
true
18e5d05b25d6b4b00abb36306b9898f169ef7fb2
Python
syedibrahimhussain/Eagle-Eye
/searchnp.py
UTF-8
1,685
2.828125
3
[]
no_license
import mysql.connector def mysql_connect(): mydb = mysql.connector.connect(host="localhost", user="root", passwd="root786") if (mydb): return 1 else: return -1 def mysql_cdb(): mydb = mysql.connector.connect(host="localhost", user="root", passwd="root786") my_cursor=mydb.cursor() my_cursor.execute("CREATE DATABASE NPDATABASE") def mysql_ctb(): mydb = mysql.connector.connect(host="localhost", user="root", passwd="root786", database="NPDATABASE") my_cursor=mydb.cursor() my_cursor.execute("CREATE TABLE USERDATA(NP VARCHAR(250), NAME VARCHAR(250))") def mysql_enterdata(np, name): mydb = mysql.connector.connect(host="localhost", user="root", passwd="root786", database="NPDATABASE") my_cursor=mydb.cursor() v1 = (np, name) query="INSERT INTO USERDATA VALUES(%s,%s)" my_cursor.execute(query, v1) mydb.commit() def mysql_searchdata(np): mydb = mysql.connector.connect(host="localhost", user="root", passwd="root786", database="NPDATABASE") mycursor = mydb.cursor() sqlq = "select * from USERDATA where np like %s" mycursor.execute(sqlq,(np,)) result = mycursor.fetchone() if (result!=None): return(1) else: return(-1) def mysql_display(): mydb = mysql.connector.connect(host="localhost", user="root", passwd="root786", database="NPDATABASE") mycursor = mydb.cursor() sql= "select * from USERDATA" mycursor.execute(sql) result = mycursor.fetchall() for r in result: print("no plate :" + str(r[0])) print("name :" + str(r[1])) #print("address:" + str(r[2])) print("-----------------")
true
fad68c7a60c17880819b11d3b6ed8524c95763cb
Python
Desperado1/mini-projects
/practice problems(Data Structures)/NoOfWaysToMakeChange.py
UTF-8
385
3.59375
4
[]
no_license
"""DYNAMIC PROGRAMMING a given array representing coin denominations and a non negative target amount function returns ways to make change for that target amount. """ def numberOfWaysToMakeChange(n, denoms): # Write your code here. d = [0 for i in range(n + 1)] d[0] = 1 for denom in denoms: for i in range(1, n + 1): if denom <= i: d[i] += d[i - denom] return d[-1]
true
abbdbda70f49157e6bc18e7357754da55f36e330
Python
Mariano92m/commonTecInfo2016
/Ejercicios Clases/Complejo/Servicio.py
UTF-8
141
2.90625
3
[]
no_license
import os class Servicio: def __init__(self, tipo): self.tipo tipo def mostrarTipo(): print("El tipo de Servicio es %s" %(self.tipo))
true
c94e9d9adcf6771d505031a785763b5e3450c2b0
Python
Aasthaengg/IBMdataset
/Python_codes/p03723/s770560827.py
UTF-8
608
3.703125
4
[]
no_license
a, b, c = map(int, input().split()) # 少なくとも一つ、奇数が存在する場合 if a % 2 != 0 or b % 2 != 0 or c % 2 != 0: print(0) exit() # 全て偶数で、A=B=Cの場合 if a == b and b == c: print(-1) exit() cnt = 0 while True: cnt += 1 next_a = b // 2 + c // 2 next_b = a // 2 + c // 2 next_c = a // 2 + b // 2 a = next_a b = next_b c = next_c # 処理を行った結果、奇数が発生してしまったらそこで終了 # 奇数がなければwhileを続ける if a % 2 != 0 or b % 2 != 0 or c % 2 != 0: break print(cnt)
true
a6eaa666233ebe13d009f167a549c49ce836fb35
Python
elguneminov/Python-2021-Complete-Python-Bootcamp-Zero-Hero-Programming
/Exam_Control.py
UTF-8
655
4.5625
5
[]
no_license
""" Python Exception Handling Using try, except and finally statement""" def exam(first_exam, second_exam): if first_exam < 50 or second_exam < 50: raise Exception elif second_exam < 50 or first_exam > 50: raise Exception elif second_exam > 50 or first_exam < 50: raise Exception else: print('You got this') first_result = int(input('Enter first exam result:')) second_result = int(input('Enter second result:')) try: exam(first_result, second_result) except : print('One of your exam result is less than 50') else: print('Your all exam results are grater than 50')
true
91ab170e5c999008a18f47659c6190dadbf217c2
Python
arikel/ariclient
/gui/guiButton.py
UTF-8
5,944
2.609375
3
[]
no_license
#!/usr/bin/python # -*- coding: utf8 -*- import pygame import sys import math import re import string from guiFunctions import * from guiWidget import Widget from guiLabel import Label from guiFrame import Frame #----------------------------------------------------------------------- # Button #----------------------------------------------------------------------- class AbstractButton(Label): def __init__(self, text= "OK", font=FONT, width=0, height=0, bgcolor=(100,100,100), bordercolor=(255,255,255), hoverbordercolor=(255,255,255), borderwidth = 1): Label.__init__(self, text, font, width, height, bgcolor, bordercolor, hoverbordercolor, borderwidth) self.baseText = text self.padding = 2 self.font = font self.click = False self.setText(" " + self.baseText + " ") def OnClick(self): raise Exception('AbstractButton cannot be used directly, derivate it') def handleEvents(self, events): for event in events: if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1 and self.hover: self.click = True if event.type == pygame.MOUSEBUTTONUP: if self.click and self.hover: self.click = False self.OnClick() #print "AbstractButton OnClick" class ShowFrameButton(AbstractButton): def __init__(self, text= "Menu", font=FONT, width=0, height=0, widget=Frame()): AbstractButton.__init__(self, text, font, width, height, (86,111,175), (200,200,200), (255,255,255), 1) self.widget = widget self._auxtext = text.split(':') #self.setText(" " + self._auxtext[widget.is_visible()] + " ") self.setText(" " + self._auxtext[widget.visible] + " ") def OnClick(self): #fshow = not self.widget.is_visible() #fshow = not self.widget.visible if not self.visible: return if self.widget.visible: self.widget.hide() else: self.widget.show() #self.widget.show(fshow) #self.setText(" " + self._auxtext[fshow] + " ") #self.setText(" " + self._auxtext[self.visible] + " ") class ButtonBase(Widget): def blit(self, screen): if self.hover: screen.blit(self.surfaceHover, self) else: screen.blit(self.surface, self) def bind(self, func, params=None): self.func = func self.params = params def OnClick(self): if self.func: if self.params: self.func(self.params) else: self.func() else: pass #print "Error : no function bound for Button" def handleEvents(self, events): for event in events: if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1 and self.hover: self.click = True if event.type == pygame.MOUSEBUTTONUP: if self.click and self.hover: self.click = False self.OnClick() class TextButton(ButtonBase): def __init__(self, text= "OK", font=FONT, width=0, height=0, color = COLOR, color_bg = COLOR_BG, color_hover = COLOR_HOVER, color_bg_hover = COLOR_BG_HOVER, borderwidth = 1, parent = None): Widget.__init__(self, 0, 0, width, height, parent) self.color = color self.color_bg = color_bg self.color_hover = color_hover self.color_bg_hover = color_bg_hover self.borderWidth = borderwidth self.baseText = text self.padding = 2 self.font = font self.has_focus = False self.click = False self.setText(" " + self.baseText + " ") self.makeSurface() def autolayout(self, direction='vertical', autoexpand = False): x, y = 0, 0 for widget in self._children: padding = widget.getPadding() widget.setPos(x+padding, y+padding) if direction == 'horizontal': x += widget.getWidth() + 2 * padding elif direction == 'vertical': y += widget.getHeight() + 2 * padding if autoexpand: self.setWidth(x + widget.getWidth()) self.setHeight(y + widget.getWidth()) self.updateSurface() def setText(self, msg): self.baseText = msg self.text = ustr(msg) #unicode(msg, "utf-8") if self.has_focus: self.msg = self.font.render(self.text + "_", False, self.color) self.msgHover = self.font.render(self.text + "_", False, self.color_hover) else: self.msg = self.font.render(self.text, False, self.color) self.msgHover = self.font.render(self.text, False, self.color_hover) self.msgRect = self.msg.get_rect() if self.w < self.msgRect.width+self.padding*2: self.width = self.msgRect.width+self.padding*2 if self.height < self.msgRect.height+self.padding*2: self.height = self.msgRect.height+self.padding*2 self.makeSurface() self.updateSurface() def makeSurface(self): """Creates the widget surface""" self.surface = pygame.Surface((self.width, self.height)) self.surfaceHover = pygame.Surface((self.width, self.height)) # surface self.surface.fill(self.color) pygame.draw.rect(self.surface, self.color_bg, (self.borderWidth, self.borderWidth, self.width-2*self.borderWidth, self.height-2*self.borderWidth)) self.surface.blit(self.msg, (self.msgRect.left+self.padding,self.msgRect.top+self.padding,self.msgRect.width,self.msgRect.height)) # surface hover self.surfaceHover.fill(self.color_hover) pygame.draw.rect(self.surfaceHover, self.color_bg_hover, (self.borderWidth, self.borderWidth, self.width-2*self.borderWidth, self.height-2*self.borderWidth)) self.surfaceHover.blit(self.msgHover, (self.msgRect.left+self.padding,self.msgRect.top+self.padding,self.msgRect.width,self.msgRect.height)) return self.surface class ImgButton(ButtonBase): def __init__(self, x=0, y=0, width=0, height=0, imgPath= "OK", imgx=0, imgy=0, imghoverx=0, imghovery=0, parent = None): Widget.__init__(self, x, y, width, height, parent) self.has_focus = False self.click = False self.surface = ImgDB[imgPath].subsurface((imgx, imgy, self.w, self.h)) self.surfaceHover = ImgDB[imgPath].subsurface((imghoverx, imghovery, self.w, self.h))
true
b7e6ae69c26406badb16e126d10c8a950cd1a83f
Python
Zhen-hui/BioinformaticsProgramming
/Python3Scripts/parse_go_terms.py
UTF-8
1,937
3.03125
3
[]
no_license
''' Created on Oct 30, 2018 @author: cathytrinh ''' import re import os # define a class that will contain the necessary attribute values of a single GO term record. class GO_attributes(): def __init__(self, term): ID_pattern = re.compile(r"^id:\s+(GO:[0-9]+)", re.M) name_pattern = re.compile(r"^name:\s+(.*)\s+", re.M) namespace_pattern = re.compile(r"^namespace:\s+(.*?)\s+", re.M) is_a_pattern = re.compile(r"^is_a:\s+(GO:[0-9]+.*?\n)", re.M) self.ID = re.findall(ID_pattern, term) self.name = re.findall(name_pattern, term) self.namespace = re.findall(namespace_pattern, term) self.is_as = re.findall(is_a_pattern, term) def writeResult(self, outfile = "Outputs/parsed_go_terms.txt"): with open (outfile, "a") as p: p.write(self.ID[0] + "\t") p.write(self.namespace[0] + "\n") p.write("\t" + self.name[0] + "\n") for is_a in self.is_as: p.write("\t" + is_a) p.write("\n") # define a function for splitting the file into records. def splitRecords(file_path): with open(file_path) as f: allData = f.read() go_terms = re.split("\[Term\]", allData) # add each valid GO term object to a dictionary. GO_dict = {} for go_term in go_terms: info = GO_attributes(go_term) if info.ID: GO_dict.update({info.ID[0]: info}) # iterate through the dictionary and invoke the object's printing method for k in sorted (GO_dict.keys()): GO_dict[k].writeResult() if os.path.exists("Outputs/parsed_go_terms.txt"): os.remove("Outputs/parsed_go_terms.txt") splitRecords("../scratch/go-basic.obo") else: splitRecords("../scratch/go-basic.obo")
true
a7ca24e856d7b2e9bbcb2029fa15b38f3363b424
Python
AnotherdayBeaux/Blind_Ptychography_GUI
/blind_ptycho_fun.py
UTF-8
18,160
2.515625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 19 02:00:39 2018 @author: Zheqing Zhang email: zheqing@math.ucdavis.edu Oversampled ptycho-fft/ifft function + any necessary function required by blind_ptycho_fun.py """ import numpy as np import matplotlib.pyplot as plt import os from scipy.sparse import spdiags # oversampled_ifft & fft with different number of mask # one id mask def Nos_fft_num_mask0(X, os_rate, mask): Na, Nb = X.shape num_of_masks = 1 Y = np.zeros((os_rate * Na, os_rate * Nb), dtype=complex) for kk in range(os_rate): LL_vec = np.exp(-2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for ii in range(os_rate): RR_vec = np.exp(-2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) X1 = LL @ X @ RR Y1 = np.fft.fft2(X1) Y[kk:os_rate * Na:os_rate][:, ii:os_rate * Nb:os_rate] = Y1 Y = Y * 1 / np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return Y ####### one random mask def Nos_fft_num_mask1(X, os_rate, mask): Na, Nb = X.shape num_of_masks = 1 X = mask * X Y = np.zeros((os_rate * Na, os_rate * Nb), dtype=complex) for kk in range(os_rate): LL_vec = np.exp(-2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for ii in range(os_rate): RR_vec = np.exp(-2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) X1 = LL @ X @ RR Y1 = np.fft.fft2(X1) Y[kk:os_rate * Na:os_rate][:, ii:os_rate * Nb:os_rate] = Y1 Y = Y * 1 / np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return Y ######## two different random mask def Nos_fft_num_mask2(X, os_rate, mask): Na, Nb = X.shape num_of_masks = 2 mask1X = mask[0] * X mask2X = mask[1] * X Y = np.zeros((os_rate * Na, os_rate * Nb * 2), dtype=complex) for kk in range(os_rate): LL_vec = np.exp(-2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for ii in range(os_rate): RR_vec = np.exp(-2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) X1 = LL @ mask1X @ RR X2 = LL @ mask2X @ RR Y1 = np.fft.fft2(X1) Y2 = np.fft.fft2(X2) Y[kk:os_rate * Na:os_rate][:, ii:os_rate * Nb:os_rate] = Y1 Y[kk:os_rate * Na:os_rate][:, os_rate * Nb + ii:os_rate * Nb * 2:os_rate] = Y2 Y = Y * 1 / np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return Y ######### one id mask and one random mask def Nos_fft_num_mask3(X, os_rate, mask): Na, Nb = X.shape num_of_masks = 2 mask1X = mask[0] * X Y = np.zeros((os_rate * Na, os_rate * Nb * 2), dtype=complex) for kk in range(os_rate): LL_vec = np.exp(-2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for ii in range(os_rate): RR_vec = np.exp(-2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) X1 = LL @ mask1X @ RR X2 = LL @ X @ RR Y1 = np.fft.fft2(X1) Y2 = np.fft.fft2(X2) Y[kk:os_rate * Na:os_rate][:, ii:os_rate * Nb:os_rate] = Y1 Y[kk:os_rate * Na:os_rate][:, os_rate * Nb + ii:os_rate * Nb * 2:os_rate] = Y2 Y = Y * 1 / np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return Y ####### ifft part ###### one id mask def Nos_ifft_num_mask0(Y, os_rate, mask): Y_Na, Y_Nb = Y.shape Na = int(Y_Na / os_rate) Nb = int(Y_Nb / os_rate) num_of_masks = 1 X = np.zeros((Na, Nb), dtype=complex) for ii in range(os_rate): LL_vec = np.exp(2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for kk in range(os_rate): RR_vec = np.exp(2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) sub_Y = np.fft.ifft2(Y[ii:Y_Na:os_rate][:, kk:Y_Nb:os_rate]) X1 = LL @ sub_Y @ RR X = X + X1 X = X * np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return X ###### one random mask def Nos_ifft_num_mask1(Y, os_rate, mask): Y_Na, Y_Nb = Y.shape Na = int(Y_Na / os_rate) Nb = int(Y_Nb / os_rate) num_of_masks = 1 X = np.zeros((Na, Nb), dtype=complex) for ii in range(os_rate): LL_vec = np.exp(2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for kk in range(os_rate): RR_vec = np.exp(2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) sub_Y = np.fft.ifft2(Y[ii:Y_Na:os_rate][:, kk:Y_Nb:os_rate]) X1 = LL @ sub_Y @ RR X = X + X1 X = mask.conj() * X X = X * np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return X ###### two random mask def Nos_ifft_num_mask2(Y, os_rate, mask): Y_Na, Y_Nb = Y.shape Na = int(Y_Na / os_rate) Nb = int(Y_Nb / os_rate / 2) num_of_masks = 2 X2 = np.zeros((Na, Nb), dtype=complex) X = np.zeros((Na, Nb), dtype=complex) for ii in range(os_rate): LL_vec = np.exp(2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for kk in range(os_rate): RR_vec = np.exp(2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) sub_Y1 = np.fft.ifft2(Y[ii:Y_Na:os_rate][:, kk:int(Y_Nb / 2):os_rate]) X1 = LL @ sub_Y1 @ RR X = X + X1 sub_Y2 = np.fft.ifft2(Y[ii:Y_Na:os_rate][:, int(Y_Nb / 2) + kk:Y_Nb:os_rate]) X22 = LL @ sub_Y2 @ RR X2 = X2 + X22 X = mask[0].conj() * X X2 = mask[1].conj() * X2 X = X + X2 X = X * np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return X ###### 1.5 mask def Nos_ifft_num_mask3(Y, os_rate, mask): Y_Na, Y_Nb = Y.shape Na = int(Y_Na / os_rate) Nb = int(Y_Nb / os_rate / 2) num_of_masks = 2 X2 = np.zeros((Na, Nb), dtype=complex) X = np.zeros((Na, Nb), dtype=complex) for ii in range(os_rate): LL_vec = np.exp(2 * ii * 1j * np.pi / os_rate * np.linspace(0, (Na - 1) / Na, Na)) LL = np.diag(LL_vec) for kk in range(os_rate): RR_vec = np.exp(2 * kk * 1j * np.pi / os_rate * np.linspace(0, (Nb - 1) / Nb, Nb)) RR = np.diag(RR_vec) sub_Y1 = np.fft.ifft2(Y[ii:Y_Na:os_rate][:, kk:int(Y_Nb / 2):os_rate]) X1 = LL @ sub_Y1 @ RR X = X + X1 sub_Y2 = np.fft.ifft2(Y[ii:Y_Na:os_rate][:, int(Y_Nb / 2) + kk:Y_Nb:os_rate]) X22 = LL @ sub_Y2 @ RR X2 = X2 + X22 X = mask[0].conj() * X X = X + X2 X = X * np.sqrt(Na * Nb) / np.sqrt(num_of_masks * os_rate ** 2) return X # two projector P_X and P_Y where X represents linear space # and Y repre. multidim torus # num_mask2 = two different random masks def P_X2(q, os_rate, mask, nor_fac): x_new = Nos_ifft_num_mask2(q, os_rate, mask) / nor_fac P_Xq = Nos_fft_num_mask2(x_new, os_rate, mask) return P_Xq # num_mask3 = one id mask and one random mask def P_X3(q, os_rate, mask, nor_fac): x_new = Nos_ifft_num_mask3(q, os_rate, mask) / nor_fac P_Xq = Nos_fft_num_mask3(x_new, os_rate, mask) return P_Xq def P_Y(q, b): P_Yq = b * q / np.abs(q) return P_Yq ###### 3 mask case ######## to be continued. fft_dict = {'id mask': Nos_fft_num_mask0, 'one mask': Nos_fft_num_mask1, 'two mask': Nos_fft_num_mask2, '1.5 mask': Nos_fft_num_mask3} ifft_dict = {'id mask': Nos_ifft_num_mask0, 'one mask': Nos_ifft_num_mask1, 'two mask': Nos_ifft_num_mask2, '1.5 mask': Nos_ifft_num_mask3} #### in ptychography the num_mask is predetermined to be 1. ### image space fft/ifft # fft periodic boundary case def ptycho_Im_PeriB_fft(X, os_rate, mask, l_patch, x_c_p, y_c_p, BackGd): half_patch = int((l_patch - 1) / 2) Na, Nb = X.shape Big_X = np.kron(np.ones((3, 3), dtype=complex), X) subNa, subNb = x_c_p.shape Y = np.zeros((os_rate * l_patch * subNa, os_rate * l_patch * subNb), dtype=complex) for i in range(subNb): for j in range(subNa): center_x = Na + x_c_p[j][i] center_y = Nb + y_c_p[j][i] piece = Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch:center_y + half_patch + 1] piece_Y = Nos_fft_num_mask1(piece, os_rate, mask) Y[j * os_rate * l_patch: (j + 1) * os_rate * l_patch][:, i * os_rate * l_patch: (i + 1) * os_rate * l_patch] = piece_Y return Y # fft fixed boundary case def ptycho_Im_FixedB_fft(X, os_rate, mask, l_patch, x_c_p, y_c_p, BackGd): half_patch = int((l_patch - 1) / 2) Na, Nb = X.shape Big_X = BackGd # BackGd, if want to enforce the intensity, use BackGd = intensity Big_X[Na:2 * Na][:, Nb:2 * Nb] = X subNa, subNb = x_c_p.shape Y = np.zeros((os_rate * l_patch * subNa, os_rate * l_patch * subNb), dtype=complex) for i in range(subNb): for j in range(subNa): center_x = Na + x_c_p[j][i] center_y = Nb + y_c_p[j][i] piece = Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch:center_y + half_patch + 1] piece_Y = Nos_fft_num_mask1(piece, os_rate, mask) Y[j * os_rate * l_patch: (j + 1) * os_rate * l_patch][:, i * os_rate * l_patch: (i + 1) * os_rate * l_patch] = piece_Y return Y # ifft periodic boundary case def ptycho_Im_PeriB_ifft(Y, Na, Nb, os_rate, mask, l_patch, x_c_p, y_c_p): half_patch = int((l_patch - 1) / 2) Big_X = np.zeros((3 * Na, 3 * Nb), dtype=complex) subNa, subNb = x_c_p.shape for i in range(subNa): for j in range(subNb): center_x = x_c_p[i][j] + Na center_y = y_c_p[i][j] + Nb piece_Y = Y[i * os_rate * l_patch: (i + 1) * os_rate * l_patch][:, j * os_rate * l_patch: (j + 1) * os_rate * l_patch] piece_X = Nos_ifft_num_mask1(piece_Y, os_rate, mask) Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] = \ Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] + piece_X X = np.zeros((Na, Nb), dtype=complex) for i in range(3): for j in range(3): X = Big_X[i * Na:(i + 1) * Na][:, j * Nb:(j + 1) * Nb] + X return X, Big_X # ifft fixed boundary case def ptycho_Im_FixedB_ifft(Y, Na, Nb, os_rate, mask, l_patch, x_c_p, y_c_p): half_patch = int((l_patch - 1) / 2) Big_X = np.zeros((3 * Na, 3 * Nb), dtype=complex) subNa, subNb = x_c_p.shape for i in range(subNa): for j in range(subNb): center_x = x_c_p[i][j] + Na center_y = y_c_p[i][j] + Nb piece_Y = Y[i * os_rate * l_patch: (i + 1) * os_rate * l_patch][:, j * os_rate * l_patch: (j + 1) * os_rate * l_patch] piece_X = Nos_ifft_num_mask1(piece_Y, os_rate, mask) Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] = \ Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] + piece_X X = Big_X[Na:2 * Na][:, Nb:2 * Nb] return X, Big_X ### mask space fft/ifft def pr_phase_perib_fft(phase, os_rate, X, l_patch, x_c_p, y_c_p, BackGd): Na, Nb = X.shape Big_X = np.kron(np.ones((3, 3), dtype=complex), X) ### enforce the periodic boundary condition will improve performance ### while in fixed boundary case we don't half_patch = int((l_patch - 1) / 2) subNa, subNb = x_c_p.shape fft_phase = np.zeros((os_rate * l_patch * subNa, os_rate * l_patch * subNb), dtype=complex) for i in range(subNb): for j in range(subNa): center_x = x_c_p[j][i] + Na center_y = y_c_p[j][i] + Nb mask = Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] fft_patch_phase = Nos_fft_num_mask1(phase, os_rate, mask) fft_phase[os_rate * l_patch * j: os_rate * l_patch * (j + 1)][:, os_rate * l_patch * i: os_rate * l_patch * (i + 1)] = fft_patch_phase return fft_phase #### def pr_phase_perib_ifft(fft_phase, os_rate, X, l_patch, x_c_p, y_c_p, BackGd): Na, Nb = X.shape Big_X = np.kron(np.ones((3, 3), dtype=complex), X) half_patch = int((l_patch - 1) / 2) subNa, subNb = x_c_p.shape phase = np.zeros((l_patch, l_patch), dtype=complex) for i in range(subNb): for j in range(subNa): center_x = x_c_p[j][i] + Na center_y = y_c_p[j][i] + Nb mask = Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] fft_patch_phase = fft_phase[j * l_patch * os_rate:(j + 1) * l_patch * os_rate][:, i * l_patch * os_rate:(i + 1) * l_patch * os_rate] ifft_patch_phase = Nos_ifft_num_mask1(fft_patch_phase, os_rate, mask) phase = phase + ifft_patch_phase return phase def pr_phase_fixedb_fft(phase, os_rate, X, l_patch, x_c_p, y_c_p, BackGd): Na, Nb = X.shape Big_X = BackGd Big_X[Na:2 * Na][:, Nb:2 * Nb] = X half_patch = int((l_patch - 1) / 2) subNa, subNb = x_c_p.shape fft_phase = np.zeros((os_rate * l_patch * subNa, os_rate * l_patch * subNb), dtype=complex) for i in range(subNb): for j in range(subNa): center_x = x_c_p[j][i] + Na center_y = y_c_p[j][i] + Nb mask = Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] fft_patch_phase = Nos_fft_num_mask1(phase, os_rate, mask) fft_phase[os_rate * l_patch * j: os_rate * l_patch * (j + 1)][:, os_rate * l_patch * i: os_rate * l_patch * (i + 1)] = fft_patch_phase return fft_phase def pr_phase_fixedb_ifft(fft_phase, os_rate, X, l_patch, x_c_p, y_c_p, BackGd): Na, Nb = X.shape Big_X = BackGd Big_X[Na:2 * Na][:, Nb:2 * Nb] = X half_patch = int((l_patch - 1) / 2) subNa, subNb = x_c_p.shape phase = np.zeros((l_patch, l_patch), dtype=complex) for i in range(subNb): for j in range(subNa): center_x = x_c_p[j][i] + Na center_y = y_c_p[j][i] + Nb mask = Big_X[center_x - half_patch:center_x + half_patch + 1][:, center_y - half_patch: center_y + half_patch + 1] fft_patch_phase = fft_phase[j * l_patch * os_rate:(j + 1) * l_patch * os_rate][:, i * l_patch * os_rate:(i + 1) * l_patch * os_rate] ifft_patch_phase = Nos_ifft_num_mask1(fft_patch_phase, os_rate, mask) phase = phase + ifft_patch_phase return phase #### poisson likelihood function Z is the data we collected ~ fft(mask*X)**2 def poisson_likely(Q, Z, gamma): rot_z = (Q / gamma + np.sqrt(Q ** 2 / gamma ** 2 + 8 * (2 + 1 / gamma) * Z)) / (4 + 2 / gamma) return rot_z def gaussian_likely(Q, Z, gamma): rot_z = (np.sqrt(Z) + 1 / gamma * Q) / (1 + 1 / gamma) return rot_z # generate corelated mask's # m = mask size; c_l= corelation distance; convolve iid phase_arg def Cor_Mask(m, c_l): BigMask_phase = np.random.uniform(size=(m + c_l, m + c_l)) BigMask = np.exp((BigMask_phase - 0.5) * np.pi * 2j) Cor_mask = np.zeros((m, m), dtype=complex) for i in range(c_l): for j in range(c_l): Cor_mask = Cor_mask + BigMask[i:m + i][:, j:m + j] Cor_mask = Cor_mask / np.abs(Cor_mask) Cor_mask = np.angle(Cor_mask) / 2 / np.pi return Cor_mask # position is a list of tuples, [(p1x, p1y), (p2x, p2y), (p3x, p3y)] which picks three non zero point of mask/image # p1x p1y -- -- -- -- - - - - p2x p2y # \ # \ # \ # p3x p3y # n, size of mask/image def getrid_LPS_m(f_0, f_k, n): Na, Nb = n[0], n[1] exp_2pikn = f_0 * f_k.conj() calib_exp = exp_2pikn * exp_2pikn[0][0].conj() angle_exp = np.angle(calib_exp) rec_k1, rec_l1 = -angle_exp[9][0] / 9 / 2 / np.pi * Na, -angle_exp[0][9] / 9 / 2 / np.pi * Nb return rec_k1, rec_l1 def savefigs(Iter, resi_DR_y, relative_DR_yIMsmall1_5, relative_DR_maskLPS, x__t, savefig_path): # x__t is already changed to real value plt.figure(0) plt.title('Error Plot') plt.xlabel('epoch') plt.ylabel('error') plt.grid(True) plt.semilogy(Iter[0], resi_DR_y[0], 'ro-') plt.semilogy(Iter[0], relative_DR_yIMsmall1_5[0], 'b^:') plt.semilogy(Iter[0], relative_DR_maskLPS[0], 'k*--') plt.legend(('Residual', 'Image Error', 'Mask Error'), loc='lower left') plt.semilogy(Iter[0:-1:3], resi_DR_y[0:-1:3], 'ro') plt.semilogy(Iter[0:-1:3], relative_DR_yIMsmall1_5[0:-1:3], 'b^') plt.semilogy(Iter[0:-1:3], relative_DR_maskLPS[0:-1:3], 'k*') plt.semilogy(Iter, resi_DR_y, 'r-') plt.semilogy(Iter, relative_DR_yIMsmall1_5, 'b:') plt.semilogy(Iter, relative_DR_maskLPS, 'k--') error_plot_location = os.path.join(savefig_path, 'error_plot.png') plt.savefig(error_plot_location) plt.close(0) # plt.figure(1) plt.imshow(x__t, cmap='gray') x__t_plot_location = os.path.join(savefig_path, 'recon_im.png') plt.colorbar() plt.grid(False) plt.axis('off') plt.savefig(x__t_plot_location) plt.close(0)
true
b3ba1fbacd74cc9f4c2c445cc5bc4cdd2f01ee7a
Python
cshintov/python
/anand-python/chapter2/ex25map.py
UTF-8
257
3.015625
3
[]
no_license
def my_fun(item): return item+item def my_map(func,seq): list_c=[my_fun(item) for item in seq] return list_c print my_map(my_fun,['a','b','c','d']) print map(my_fun,['a','b','c','d']) print my_map(my_fun,[1,'b',3,'d']) print map(my_fun,[1,'b',3,'d'])
true
d2f752c33581581298c3ec1c8285a4a5de340fad
Python
mahvash-siavashpour/LinearAlgebra
/LUFactorization/substitution.py
UTF-8
1,875
2.953125
3
[]
no_license
import numpy def forward_substitution(matrix): n = len(matrix[:, 0]) m = len(matrix[0, :]) for i in range(n): # find a staring row with pivot position if matrix[i][i] == 0: for j in range(i + 1, n): if matrix[j][0] != 0: matrix[[0, j]] = matrix[[j, 0]] break if m == n + 1: matrix[i][m - 1] /= matrix[i][i] matrix[i][i] /= matrix[i][i] # row replacement operations to create # zeros in all positions below the pivot. for k in range(i + 1, n): if m == n + 1: matrix[k][m - 1] -= matrix[k][i] * matrix[i][m-1] matrix[k][i] -= matrix[k][i] # return matrix def backward_substitution(matrix): n = len(matrix[:, 0]) m = len(matrix[0, :]) for i in range(n - 1, -1, -1): # scaling to set value 1 to pivot positions if m == n + 1: matrix[i][m - 1] /= matrix[i][i] matrix[i][i] /= matrix[i][i] # row replacement operations to create # zeros in all positions above the pivot. for k in range(i - 1, -1, -1): if m == n + 1: matrix[k][m - 1] -= matrix[k][i] * matrix[i][m-1] matrix[k][i] -= matrix[k][i] # return matrix def find_inverse(matrixA, matrixL, matrixU): n = len(matrixA[:, 0]) identity = numpy.identity(n) AInverse = [] for i in range(n): augmentedMatrix = numpy.concatenate((matrixL, identity[:, [i]]), axis=1) forward_substitution(augmentedMatrix) augmentedMatrix = numpy.concatenate((matrixU, augmentedMatrix[:, [n]]), axis=1) backward_substitution(augmentedMatrix) AInverse.append(augmentedMatrix[:, n]) AInverse = numpy.array(AInverse) AInverse = numpy.transpose(AInverse) return AInverse
true
62c1f076a060b3346514f03c731b52dbff957843
Python
MDCGP105-1718/portfolio-err0rzzz
/Semester_1/Week04/ex10.py
UTF-8
397
4.15625
4
[]
no_license
##function definition testing ## x = 1 def f_fizzbuzz(x): """ checks if number is divisible by both 3 and 5 outputs fizzbuzz if it is """ if x %3 == 0: if x %5 == 0: print ("fizzbuzz") else: print ("Fizz") elif x %5 == 0: print ("Buzz") else: print (x) return x while (x<101): f_fizzbuzz(x) x += 1
true
34d0fc44db6e511632b635aa394ba1c7b7a4a3f0
Python
malannpren/geog5092-lab5
/lab5functions.py
UTF-8
2,396
3.375
3
[]
no_license
""" Author: Originally created by Galen Maclaurin, updated by Ricardo Oliveira Created: Created on 3.15.16, updated on 10.17.19 Purpose: Helper functions to get started with Lab 5 """ import numpy as np def slopeAspect(dem, cs): """Calculates slope and aspect using the 3rd-order finite difference method Parameters ---------- dem : numpy array A numpy array of a DEM cs : float The cell size of the original DEM Returns ------- numpy arrays Slope and Aspect arrays """ from math import pi from scipy import ndimage kernel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) dzdx = ndimage.convolve(dem, kernel, mode='mirror') / (8 * cs) dzdy = ndimage.convolve(dem, kernel.T, mode='mirror') / (8 * cs) slp = np.arctan((dzdx ** 2 + dzdy ** 2) ** 0.5) * 180 / pi ang = np.arctan2(-dzdy, dzdx) * 180 / pi aspect = np.where(ang > 90, 450 - ang, 90 - ang) return slp, aspect def reclassAspect(npArray): """Reclassify aspect array to 8 cardinal directions (N,NE,E,SE,S,SW,W,NW), encoded 1 to 8, respectively (same as ArcGIS aspect classes). Parameters ---------- npArray : numpy array numpy array with aspect values 0 to 360 Returns ------- numpy array numpy array with cardinal directions """ return np.where((npArray > 22.5) & (npArray <= 67.5), 2, np.where((npArray > 67.5) & (npArray <= 112.5), 3, np.where((npArray > 112.5) & (npArray <= 157.5), 4, np.where((npArray > 157.5) & (npArray <= 202.5), 5, np.where((npArray > 202.5) & (npArray <= 247.5), 6, np.where((npArray > 247.5) & (npArray <= 292.5), 7, np.where((npArray > 292.5) & (npArray <= 337.5), 8, 1))))))) def reclassByHisto(npArray, bins): """Reclassify np array based on a histogram approach using a specified number of bins. Returns the reclassified numpy array and the classes from the histogram. Parameters ---------- npArray : numpy array Array to be reclassified bins : int Number of bins Returns ------- numpy array umpy array with reclassified values """ histo = np.histogram(npArray, bins)[1] rClss = np.zeros_like(npArray) for i in range(bins): rClss = np.where((npArray >= histo[i]) & (npArray <= histo[i + 1]), i + 1, rClss) return rClss
true
c6c7198f7ca6be493b8f5085909f626969268898
Python
ref-humbold/AlgoLib_Python
/tests/maths/test_equation_system.py
UTF-8
1,869
3.46875
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- """Tests: Structure of linear equations system """ import unittest from assertpy import assert_that from algolib.maths import Equation, EquationSystem, InfiniteSolutionsError, NoSolutionError class EquationSystemTest(unittest.TestCase): @staticmethod def test__solve__when_single_solution__then_solution(): # given test_object = EquationSystem(Equation([2, 3, -2], 15), Equation([7, -1, 0], 4), Equation([-1, 6, 4], 9)) # when result = test_object.solve() # then assert_that(result).is_equal_to([1, 3, -2]) assert_that(test_object.is_solution(result)).is_true() assert_that(test_object.is_solution([-2, -18, -36.5])).is_false() @staticmethod def test__solve__when_no_solution__then_raise_no_solution_error(): # given test_object = EquationSystem(Equation([2, 3, -2], 15), Equation([7, -1, 0], 4), Equation([-1, -1.5, 1], -1)) # when def function(): test_object.solve() # then assert_that(function).raises(NoSolutionError) assert_that(test_object.is_solution([1, 3, -2])).is_false() assert_that(test_object.is_solution([-2, -18, -36.5])).is_false() @staticmethod def test__solve__when_infinite_solutions__then_raise_infinite_solutions_error(): # given test_object = EquationSystem(Equation([2, 3, -2], 15), Equation([7, -1, 0], 4), Equation([4, 6, -4], 30)) # when def function(): test_object.solve() # then assert_that(function).raises(InfiniteSolutionsError) assert_that(test_object.is_solution([1, 3, -2])).is_true() assert_that(test_object.is_solution([-2, -18, -36.5])).is_true()
true
4a1564fa6818ef55ffe4729bfbecda4bc4dc00a2
Python
pdrylo/kubenvz
/commands/__init__.py
UTF-8
1,480
2.515625
3
[ "MIT" ]
permissive
import os from typing import Union from sys import exit from .list import list_local, list_remote from .install import install from .uninstall import uninstall from .use import use def locate_file(file: str) -> Union[str, bool]: dir: str = os.path.realpath('.') while dir: if os.path.exists(f"{dir}/{file}"): return f"{dir}/{file}" if dir != '/': dir = os.path.dirname(dir) else: return False def get_install_path() -> str: install_path = "" for dir in ['bin', '.bin', '.local/bin']: if os.path.exists(f"{os.getenv('HOME')}/{dir}"): print(f"Trying to install in the following path: {os.getenv('HOME')}/{dir}/") if not os.access(f"{os.getenv('HOME')}/{dir}", os.W_OK): print(f"Warning: Path {os.getenv('HOME')}/{dir}/ is not writeable. Trying other possible paths.") else: install_path = f"{os.getenv('HOME')}/{dir}/" break if install_path == "": install_path = "/usr/local/bin" print(f"Trying default path: {install_path}") if not os.access(install_path, os.W_OK): print(f"Error: User doesn't have write permission of {install_path} directory.\ \n\nRun below command to grant permission and rerun 'kubenvz install' command.\ \nsudo chown -R $(whoami) {install_path}\n") exit(1) return install_path
true
d5dd7ed9e59390fb7eb07cb82dfd9db7959067cc
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_55/353.py
UTF-8
1,921
2.59375
3
[]
no_license
import sys def ride(q,k): t=0 i=0 while (i<len(q)) and (t+q[i]<=k): t+=q[i] i+=1 return i,t,q[i:]+q[0:i] def runride(R,k,N,q): ringfound=0 r=0 total=0 historic_indexes=[] historic_vals=map(lambda x:([],[]),range(N)) cur_index=0 ring_index=0 ring_pair=() while ringfound==0 and r<R: new_index,value,new_q=ride(q,k) historic_indexes.append(cur_index) for j in set(historic_indexes): last_indexes,index_values=historic_vals[j] last_indexes.append(new_index) index_values.append(value) historic_vals[j]=(last_indexes,index_values) # if a ring exists then the sum of its indexes divides N ring_list=filter(lambda x:x[1]==0 and len(historic_vals[x[0]][0])>0,enumerate(map(lambda x:sum(x[0])%N,historic_vals))) if len(ring_list)>0: ringfound=1 ring_index=ring_list[0][0] cur_index=(cur_index+new_index)%len(q) q=new_q r=r+1 total=total+value if ringfound==1 and r<R: # we found a ring and there are more runs left # so we should find how many resulting ring-runs there are # and add their value (plus the remainder) runs=R-r ring_indexes,ring_values=historic_vals[ring_index] ring_size=len(ring_indexes) ring_value=sum(ring_values) ring_runs=runs/ring_size remaining_runs=runs%ring_size ring_runs_value=ring_runs*ring_value nonring_final_runs=sum(ring_values[:remaining_runs]) total=total+ring_runs_value+nonring_final_runs return total if len(sys.argv)!=2: print 'Usage: themepark.py <inputfile>' exit(1) inputfile=open(sys.argv[1],'r') outputfile=open('themepark_results.txt','w') numoflines=int(inputfile.readline()) for i in range(numoflines): R,k,N=inputfile.readline().strip().split(' ') R=int(R) N=int(N) k=int(k) q=map(lambda x:int(x),inputfile.readline().strip().split(' ')) result=runride(R,k,N,q) outputfile.write("Case #%d: %s\n"% (i+1,result))
true
3a79742d4940d4506c6e4235b954640f6b5e9500
Python
OmarGP/Python1
/Secuencia_de_Ejercicio01/Ejercicio I.py
UTF-8
580
4.3125
4
[ "Apache-2.0" ]
permissive
#I1. Pregunta al operador 5 colores list_color = [] contador = 1 print(f" >>>>>Ingrese CINCO colores de uno a uno<<<<<") try: while(contador < 6): color = input("Dígame un color: \r\n") print("") list_color.append(color) contador += 1 finally: #I2. Muestra los colores ordenados print(" <<<-Ordenado en orden alfabético->>>") print(f"{sorted(list_color)}") #I3. Muestra el color que más letras contenga #I4. Muestra el color que más vocales contenga #I5. Muestra la cantidad de colores que comienza y finaliza por vocal
true