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
f4240c657712fe883ee5699a16a0a4dddd834211
Python
thakur-nishant/LeetCode
/1003. Check If Word Is Valid After Substitutions.py
UTF-8
1,703
3.765625
4
[]
no_license
""" We are given that the string "abc" is valid. From any valid string V, we may split V into two pieces X and Y such that X + Y (X concatenated with Y) is equal to V. (X or Y may be empty.) Then, X + "abc" + Y is also valid. If for example S = "abc", then examples of valid strings are: "abc", "aabcbc", "abcabc", "abcabcababcc". Examples of invalid strings are: "abccba", "ab", "cababc", "bac". Return true if and only if the given string S is valid. Example 1: Input: "aabcbc" Output: true Explanation: We start with the valid string "abc". Then we can insert another "abc" between "a" and "bc", resulting in "a" + "abc" + "bc" which is "aabcbc". Example 2: Input: "abcabcababcc" Output: true Explanation: "abcabcabc" is valid after consecutive insertings of "abc". Then we can insert "abc" before the last letter, resulting in "abcabcab" + "abc" + "c" which is "abcabcababcc". Example 3: Input: "abccba" Output: false Example 4: Input: "cababc" Output: false Note: 1 <= S.length <= 20000 S[i] is 'a', 'b', or 'c' """ class Solution: def isValid(self, S: str) -> bool: count = {'a': 0, 'b': 0, 'c': 0} for i in range(len(S)): count[S[i]] += 1 if S[i] == 'b': if count['a'] < count['b'] or (i > 0 and S[i] == S[i - 1]): return False if S[i] == 'c': if (count['a'] < count['c'] or count['b'] < count['c']) or (i > 0 and S[i - 1] == 'a'): return False # check = count['a'] # for key in count: # if count[key] != check: # return False # return True return count['a'] == count['b'] == count['c']
true
c311d38138c64e384f3e350b157496870661f711
Python
Kafonin/Python
/soccerTeamRoster.py
UTF-8
517
3.765625
4
[]
no_license
playerRoster = dict() myNum = 1 try: while myNum <= 5: jersey = input("Enter player %d's jersey number:\n" % myNum) rating = input("Enter player %d's rating:\n" % myNum) print(end='\n') myNum += 1 playerRoster.update({jersey: rating}) finally: print('ROSTER') for k in sorted(playerRoster.items()): print('Jersey number: ' + k[0] + ',' + ' Rating:' + k[1], end='\n') #print('Jersey number: ' + str(k) + ',' + ' Rating:' + str(v), end='\n')
true
621e488a7b744ce44a9e40e97cd1712a3ae1611f
Python
daegu-algo-party-210824/younghang_algo
/dfs/bfs/5-9.py
UTF-8
508
3.265625
3
[]
no_license
from collections import deque def bfs (graph, start, visited) : visited[start] = True q = deque([start]) while q : temp = q.popleft() print(temp) for i in graph[temp]: if visited[i] == False : q.append(i) visited[i] = True #adj 리스트 graph = [ [], [2,3,8], #1은 2,3,8과 연결됨. [1,7], [1,4,5], [3,5], [3,4], [7], [2,6,8], [1,7] ] visited = [False] * 9 bfs(graph,1,visited)
true
6e63101d99215ceba16670471613b5994fd1923d
Python
DevIcEy777/Recording-Bot
/recordingbot/__init__.py
UTF-8
2,564
3
3
[ "MIT" ]
permissive
import speech_recognition as sr import wave import sys import os class Bot(object): def __init__(self, datapath, voiceapi_cred_file, frame_threshold=60000, clearfiles=True): """ Initialize a bot. Parameters ---------- datapath : str Path for voice files voiceapi_cred_file : str Path for cred json frame_threshold : int Number a frames and audio file must be to be considered a voice clearfiles : bool True will clear files after each run """ self.datapath = datapath self.clearfiles = clearfiles with open(voiceapi_cred_file, 'r') as cred: self.API_JSON = cred.read() self.frame_threshold = frame_threshold def message(self, msg): """Sends a message in the Discord text channel.""" print("msg:" + msg) def play(self, fn): """Plays an audio file into the Discord voice channel.""" print("play:" + fn) def run(self): """Converts input to .wav and runs the bot's process.""" if len(sys.argv) == 5: pcmfn = sys.argv[2] opusfn = pcmfn.replace(".pcm_raw", ".opus_hex") wavefn = os.path.join(self.datapath, sys.argv[4] + '.wav') memberid = sys.argv[3] timestamp = sys.argv[4] with open(pcmfn, 'rb') as pcm: pcmdata = pcm.read() with wave.open(wavefn, 'wb') as wavfile: # Converts pcm to wave wavfile.setparams((2, 2, 48000, 0, 'NONE', 'NONE')) wavfile.writeframes(pcmdata) frames = wavfile.getnframes() if frames > self.frame_threshold: # Checks for minimum time requirement r = sr.Recognizer() with sr.AudioFile(wavefn) as source: audio = r.record(source) result = r.recognize_google_cloud(audio, credentials_json=self.API_JSON).strip() try: self.process(result, memberid, timestamp, wavefn) except Exception as e: print(e) if self.clearfiles: os.remove(pcmfn) os.remove(wavefn) else: raise Exception("Bot must be run with commands passed from main.js") def process(self, text, memberid, timestamp, wavefn): # Override """Does something once the file has been converted.""" pass
true
326691397555269e45160eef63f09dfdf52413ac
Python
kanyuanzhi/cache-simulator
/src/poisson.py
UTF-8
1,516
2.625
3
[]
no_license
from scipy import integrate from scipy.optimize import fsolve import math import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt from mcav.zipf import Zipf from che import Che def F(t): # return (math.exp(-rate * t)-math.exp(-rate * staleness)) * t # return t*rate*math.exp(-rate*t) return (1-math.exp(-rate*t))/Ts def F2(t): # return (math.exp(-rate * t)-math.exp(-rate * staleness)) * t # return t*rate*math.exp(-rate*t) return (1-math.exp(-rate*t))/Tc if __name__ == "__main__": amount = 1000 z = 0.8 cachesize = 100 total_rate = 10 Ts = 20 zipf = Zipf(amount, z) popularity = zipf.popularity() che = Che(amount, cachesize, popularity, total_rate) print(total_rate*popularity[1], total_rate*popularity[2]) Tc = che.T print("Tc: ", Tc) index = [] result = [] for i in range(1, 51): index.append(i) rate = total_rate * popularity[i] # result.append( # integrate.quad(F, 0, Ts)[0] * # (1 - math.exp(-rate * Ts))) Pv = integrate.quad(F, 0, Ts)[0] # result.append(integrate.quad(F, 0, Ts)[0]) result.append(Tc/Ts*integrate.quad(F2, 0, Tc)[0] + (1-Tc/Ts)*(1-math.exp(-rate*Tc))) for i in range(11): print(result[i]) plt.plot(index, result, "+-", label="simulation") plt.xlabel("content ID") plt.ylabel("hit ratio") plt.grid(True) # plt.axis([0, 51, 0, 1]) plt.legend() plt.show()
true
be4d5c1fb8e00e82178cd8d0993933ce02ff5655
Python
voynow/ConvNet-Architectures
/Residual_network.py
UTF-8
5,271
2.796875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Aug 14 22:08:27 2020 @author: voyno """ from keras import Model from keras.layers import Conv2D, AvgPool2D, Flatten, Dense, BatchNormalization, Input, Add, Activation from keras.preprocessing import image class ResNet: def __init__(self, num_layers=20): self.stack_size = (num_layers - 2) // 6 self.model = self.build(self.stack_size) self.model.compile(optimizer='adam', loss='mse', metrics=['acc']) def train(self, train, test, batch_size=256, epochs=200, verbose=2, augment=False): """ Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - train tuple : x_train and y_train data tests tuple : x_test and y_test data batch_size int : number of inputs per gradient update epochs int : number of iterations of training verbose bool : if True training output else no ouput argument bool : if true use data augmentation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """ if augment: datagen = image.ImageDataGenerator( rotation_range=30, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.1, zoom_range=0.1, horizontal_flip=True) return self.model.fit_generator(datagen.flow(train[0], train[1], batch_size=batch_size), steps_per_epoch=len(train[0])//batch_size, epochs=epochs, verbose=verbose, validation_data=(test[0], test[1])) else: return self.model.fit(train[0], train[1], batch_size=batch_size, epochs=epochs, verbose=verbose, validation_data=(test[0], test[1])) def build(self, stack_size, summary=False): """ Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - stack_size int : number of layers per filter_size stack summary bool : display model summary if true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """ input_shape=(32, 32, 3) num_filter = 16 num_stacks = 3 x_in = Input(shape=input_shape) x = Conv2D(num_filter, kernel_size=3, padding='same', activation='relu')(x_in) for i in range(num_stacks): for j in range(stack_size): if i != 0 and j == 0: x = self.conv_block(x, num_filter, projection=True) else: x = self.conv_block(x, num_filter) num_filter *= 2 x = AvgPool2D(8)(x) x = Flatten()(x) x_out = Dense(10)(x) model = Model(inputs=x_in, outputs=x_out) if summary: print(model.summary()) return model def conv_block(self, x, num_filter, projection=False): """ Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - x tensor: output from previous conv layer num_filter int : number of filters for conv layer projection bool : logic for 1x1 conv on residual path - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """ x_resid = x if projection: x_resid = self.conv_layer(x_resid, num_filter, kernel_size=1, strides=2) x = self.conv_layer(x, num_filter, strides=2) x = BatchNormalization()(x) x = Activation('relu')(x) else: x = self.conv_layer(x, num_filter) x = BatchNormalization()(x) x = Activation('relu')(x) x = self.conv_layer(x, num_filter) x = BatchNormalization()(x) x = Add()([x, x_resid]) x = Activation('relu')(x) return x @staticmethod def conv_layer(inputs, filters, kernel_size=3, strides=1): """ Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - inputs tensor: output from previous conv layer filters int : number of filters for conv layer kernel_size int : size of sliding conv filter (n x n) strides int : size of movement per filter slide - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """ x = Conv2D(filters=filters, kernel_size=kernel_size, strides=strides, padding='same')(inputs) return x
true
12a32b32ba09a3dc62f5d8c6ed31c883df7fdc4e
Python
loventheair/instagram_autoposter
/fetch_hubble.py
UTF-8
850
2.6875
3
[]
no_license
from aux_funcs import get_file_extension, download_a_pic import requests from pathlib import Path def fetch_hubble_photo(image_id): response = requests.get(f'http://hubblesite.org/api/v3/image/{image_id}') response.raise_for_status() image_files = response.json()['image_files'] image_url = image_files[-1]['file_url'] file_extension = get_file_extension(image_url) download_a_pic('https:' + image_url, f'hubble_{image_id}{file_extension}') def fetch_hubble_collection(collection_name): response = requests.get(f'http://hubblesite.org/api/v3/images/{collection_name}') response.raise_for_status() images = response.json() for image in images: fetch_hubble_photo(image['id']) if __name__ == '__main__': Path('images').mkdir(parents=True, exist_ok=True) fetch_hubble_collection('starships')
true
18dec81455c670be913108a8096bcff48912248a
Python
hxdaze/finite-state-machine
/finite_state_machine/state_machine.py
UTF-8
5,142
2.828125
3
[ "MIT" ]
permissive
import asyncio from enum import Enum import functools import types from typing import NamedTuple, Union from .exceptions import ConditionsNotMet, InvalidStartState class StateMachine: def __init__(self): try: self.state except AttributeError: raise ValueError("Need to set a state instance variable") class TransitionDetails(NamedTuple): name: str source: Union[list, bool, int, str] target: Union[bool, int, str] conditions: list on_error: Union[bool, int, str] class transition: def __init__(self, source, target, conditions=None, on_error=None): allowed_types = (str, bool, int, Enum) if isinstance(source, allowed_types): source = [source] if not isinstance(source, list): raise ValueError("Source can be a bool, int, string, Enum, or list") for item in source: if not isinstance(item, allowed_types): raise ValueError("Source can be a bool, int, string, Enum, or list") self.source = source if not isinstance(target, allowed_types): raise ValueError("Target needs to be a bool, int or string") self.target = target if not conditions: conditions = [] if not isinstance(conditions, list): raise ValueError("conditions must be a list") for condition in conditions: if not isinstance(condition, types.FunctionType): raise ValueError("conditions list must contain functions") self.conditions = conditions if on_error: if not isinstance(on_error, allowed_types): raise ValueError("on_error needs to be a bool, int or string") self.on_error = on_error def __call__(self, func): func._fsm = TransitionDetails( func.__name__, self.source, self.target, self.conditions, self.on_error, ) @functools.wraps(func) def sync_callable(*args, **kwargs): try: state_machine, rest = args except ValueError: state_machine = args[0] if state_machine.state not in self.source: exception_message = ( f"Current state is {state_machine.state}. " f"{func.__name__} allows transitions from {self.source}." ) raise InvalidStartState(exception_message) conditions_not_met = [] for condition in self.conditions: if condition(*args, **kwargs) is not True: conditions_not_met.append(condition) if conditions_not_met: raise ConditionsNotMet(conditions_not_met) if not self.on_error: result = func(*args, **kwargs) state_machine.state = self.target return result try: result = func(*args, **kwargs) state_machine.state = self.target return result except Exception: # TODO should we log this somewhere? # logger.error? maybe have an optional parameter to set this up # how to libraries log? state_machine.state = self.on_error return @functools.wraps(func) async def async_callable(*args, **kwargs): try: state_machine, rest = args except ValueError: state_machine = args[0] if state_machine.state not in self.source: exception_message = ( f"Current state is {state_machine.state}. " f"{func.__name__} allows transitions from {self.source}." ) raise InvalidStartState(exception_message) conditions_not_met = [] for condition in self.conditions: if asyncio.iscoroutinefunction(condition): condition_result = await condition(*args, **kwargs) else: condition_result = condition(*args, **kwargs) if condition_result is not True: conditions_not_met.append(condition) if conditions_not_met: raise ConditionsNotMet(conditions_not_met) if not self.on_error: result = await func(*args, **kwargs) state_machine.state = self.target return result try: result = await func(*args, **kwargs) state_machine.state = self.target return result except Exception: # TODO should we log this somewhere? # logger.error? maybe have an optional parameter to set this up # how to libraries log? state_machine.state = self.on_error return if asyncio.iscoroutinefunction(func): return async_callable else: return sync_callable
true
1749b1d8c306fad3e01df2b7be157bcb1a507107
Python
john531026/guess-num
/3-2.py
UTF-8
487
4.375
4
[]
no_license
# 產生一個隨機整數1~100 (不要印出來) # 讓使用者重複輸入數字去猜 # 猜對的話 印出 "終於猜對了!" # 猜錯的話 要告訴他比答案大/小 import random r = random.randint(1, 100) n = 0 while n != r: n = input('請猜1-100的數字,請輸入數字:') n = int(n) if n > r: print('你的數字比答案大') elif n < r: print('你的數字比答案小') print('猜到了數字為', n) #else # print('猜到了數字為', n) # break
true
b017f5627eb741d8856f6e0eba1216b5ebcf424f
Python
QAlgebra/qalgebra
/tests/algebra/test_equation.py
UTF-8
4,880
2.671875
3
[ "MIT" ]
permissive
"""Test for the symbolic_equation package. This is maintained as an external package, but we want to test that it integrates well with qalgebra """ import pytest import sympy from symbolic_equation import Eq from sympy.core.sympify import SympifyError from qalgebra import ( Create, Destroy, IdentityOperator, OperatorSymbol, ZeroOperator, latex, ) # These only cover things not already coveraged in the doctest def test_apply_to_lhs(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq = eq0.apply_to_lhs(lambda expr: expr + E0).tag('new') assert eq.lhs == H_0 + E0 assert eq.rhs == eq0.rhs assert eq._tag == 'new' def test_apply_mtd(): H_0 = OperatorSymbol('H_0', hs=0) H = OperatorSymbol('H', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq = eq0.apply('substitute', {H_0: H, E0: 0}).tag('new') assert eq.lhs == H assert eq.rhs == ω * Create(hs=0) * Destroy(hs=0) assert eq._tag == 'new' def test_eq_copy(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq = eq0.copy() assert eq == eq0 assert eq is not eq0 def test_eq_add_const(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq = eq0 + E0 assert eq.lhs == H_0 + E0 assert eq.rhs == eq0.rhs + E0 assert eq._tag is None def test_eq_mult_const(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq = 2 * eq0 assert eq == eq0 * 2 assert eq.lhs == 2 * eq0.lhs assert eq.rhs == 2 * eq0.rhs assert eq._tag is None def test_eq_div_const(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq = eq0 / 2 assert eq.lhs == eq0.lhs / 2 assert eq.rhs == eq0.rhs / 2 assert eq._tag is None def test_eq_equals_const(): H_0 = OperatorSymbol('H_0', hs=0) eq0 = Eq(H_0, IdentityOperator) assert eq0 - 1 == ZeroOperator def test_eq_sub_eq(): ω, E0 = sympy.symbols('omega, E_0') H_0 = OperatorSymbol('H_0', hs=0) H_1 = OperatorSymbol('H_1', hs=0) mu = OperatorSymbol('mu', hs=0) eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq1 = Eq(H_1, mu + E0, tag='1') eq = eq0 - eq1 assert eq.lhs == H_0 - H_1 assert eq.rhs == ω * Create(hs=0) * Destroy(hs=0) - mu assert eq._tag is None def test_eq_sub_const(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq = eq0 - E0 assert eq.lhs == H_0 - E0 assert eq.rhs == ω * Create(hs=0) * Destroy(hs=0) assert eq._tag is None def test_repr_latex(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') Eq.latex_renderer = staticmethod(latex) eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') repr1 = eq0._repr_latex_() repr2 = latex(eq0) assert repr1 == repr2 def test_eq_str(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') assert str(eq0) == "%s = %s (0)" % (str(eq0.lhs), str(eq0.rhs)) def test_eq_repr(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') assert repr(eq0) == "%s = %s (0)" % (repr(eq0.lhs), repr(eq0.rhs)) def test_no_sympify(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') with pytest.raises(SympifyError): sympy.sympify(eq0) def test_eq_substitute(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') eq1 = eq0.apply('substitute', {E0: 0}).reset() eq2 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0)) assert eq1 == eq2 def test_unchanged_apply(): H_0 = OperatorSymbol('H_0', hs=0) ω, E0 = sympy.symbols('omega, E_0') eq0 = Eq(H_0, ω * Create(hs=0) * Destroy(hs=0) + E0, tag='0') assert eq0.apply(lambda s: s.expand()).reset() == eq0 assert eq0.apply(lambda s: s.expand()) == eq0 assert eq0.apply(lambda s: s.expand())._lhs is None assert eq0.apply('expand').reset() == eq0 assert eq0.apply('expand') == eq0 assert eq0.apply('expand')._lhs is None
true
47f6345dfa27d586a40861a569ad8cfe5c47bd36
Python
Coder2Programmer/Leetcode-Solution
/twentySecondWeek/capacity_to_ship_packages_within_d_days.py
UTF-8
591
3.203125
3
[]
no_license
class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: def helper(threshold): cur, need = 0, 1 for w in weights: if cur + w > threshold: cur = 0 need += 1 cur += w return need > D low, high = max(weights), sum(weights) while low < high: mid = (low + high) >> 1 if helper(mid): low = mid + 1 else: high = mid return low
true
38c323a23d43db5c0687cc8ac6702eda83bfe8dd
Python
lfunderburk/Math-Modelling
/modelling-salmon-life-cycle/scripts/web_scrapping.py
UTF-8
1,976
3.265625
3
[ "MIT", "CC-BY-4.0", "LicenseRef-scancode-public-domain" ]
permissive
# Authors: Rachel Dunn, Laura GF, Anouk de Brouwer, Courtney V, Janson Lin # Date created: Sept 12 2020 # Date modified: # Import libraries from datetime import datetime import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup import sys ##usage: python web_scrapping.py https://www.waterlevels.gc.ca/eng/data/table/2020/wlev_sec/7965 2020-01-01 2020-04-30 def parseData(dataURL, startTime, endTime): r = requests.get(dataURL) soup = BeautifulSoup(r.text, 'html.parser') tables = soup.find_all(class_='width-100') date = [] height = [] for table in tables: # get month and year from caption month_year = table.find("caption").text.strip() [month,year] = month_year.split() # get all cells by looking for 'align-right' class cell = table.find_all(class_="align-right") # loop over cells in table # every 1st cell has the day, every 2nd cell has the time, every 3rd cell has the height for index in range(len(cell)): # get day if ((index % 3) == 0): d = cell[index].text.strip() # get time if ((index % 3) == 1): t = cell[index].text.strip() # paste year, month, day and time together, and append to date list ymdt_str = '-'.join([year,month,d,t]) #ymdt = datetime.strptime(ymdt_str,'%Y-%B-%d-%I:%M %p') date.append(ymdt_str) # get tide height if ((index % 3) == 2): height.append(cell[index].text.strip()) #add lists to dataframe tides = pd.DataFrame() tides['Date'] = pd.to_datetime(date) tides['Height_m'] = pd.to_numeric(height) #index dataframe by date tides.set_index('Date',inplace=True) #subset dataframe to only output data between requested dates tidesSubset = tides.loc[startTime:endTime,] print(tidesSubset) tidesSubset.to_csv(r'./tidesSubset.csv', header = True) if __name__ == "__main__": #parse arguments str(sys.argv) dataURL = str(sys.argv[1]) startTime = str(sys.argv[2]) endTime = str(sys.argv[3]) parseData(dataURL, startTime, endTime)
true
eaf0b529df29e4c66365128fbc6a864da60cd4cb
Python
crypto-com/incubator-teaclave
/tests/scripts/simple_http_server.py
UTF-8
470
2.546875
3
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import SimpleHTTPServer import BaseHTTPServer class HTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_PUT(self): length = int(self.headers["Content-Length"]) path = self.translate_path(self.path) with open(path, "wb") as dst: dst.write(self.rfile.read(length)) self.send_response(200) self.end_headers() if __name__ == '__main__': SimpleHTTPServer.test(HandlerClass=HTTPRequestHandler)
true
171880606625e9a6def6361ac8eb696b8462429f
Python
Charles-IV/python-scripts
/scrolling-screen/basic.py
UTF-8
2,331
3.734375
4
[]
no_license
from colorama import Back from random import randint from time import sleep height = 50 width = 100 ground = 2*(height//3) board = [] for y in range(0, height): board.append([]) for x in range(0, width + 5): # 5 buffer """ if y < ground: # if top two thirds board[y].append(Back.BLACK + " ") elif y == ground: board[y].append(Back.YELLOW + " ") elif y > ground: board[y].append(Back.GREEN + " ") """ board[y].append(Back.RESET + " ") print("\033[2J \033[H") # clear screen def up(): global ground # shutup its bad practice, i just wanna see if this works num = randint(1, 8) if num == 1 and ground < height - 2: # stop from going off bottom ground += 2 elif num > 1 and num < 4 and ground < height - 1: # stop from going off top ground += 1 # between 4, 5, stay same elif num > 5 and num < 8 and ground > 3: # keep a few away from top ground -= 1 elif num == 8 and ground > 4: # keep a few away from top ground -= 2 for y in range(0, height): if y < ground: board[y].append(Back.BLACK + " ") # add new to end of line elif y == ground: board[y].append(Back.YELLOW + " ") elif y > ground: board[y].append(Back.GREEN + " ") # remove first item board[y].pop(0) return board # return new board def draw(): global board # shutup its bad practice, i just wanna see if this works # create old board to compare new board oldBoard = [] for row in range(0, height): oldBoard.append([]) for item in range(0, width): oldBoard[row].append(board[row][item]) # only copy literals to avoid pythons stupid linking # update board and console board = up() # update new board console = "" # draw snake and food, update board for y in range(1, height+1): # go across screen for x in range(1, width+1): if board[y-1][x-1] != oldBoard[y-1][x-1]: # if the colour of this position has changed console += "\033[{};{}H{}".format(y+2, ((x+2)*2)-1, board[y-1][x-1]) # log position as to be overwritten print(console) # update screen while True: draw() sleep(0.1)
true
e2066135ef9c583feb6a96f04bf0cb1c85360522
Python
0921nihkxzu/meik
/utils/misc.py
UTF-8
530
2.6875
3
[]
no_license
# misc.py # contains miscellaneous helper functions import numpy as np import matplotlib.pyplot as plt def plot_training_loss(model, loss='binary_crossentropy', mode='epoch'): # or mode = 'batch' losses = getattr(model, mode+"_metrics") iters = len(losses) if loss == 'binary_crossentropy': getloss = lambda i: losses[i]['loss_tot'] elif loss == 'categorical_crossentropy': getloss = lambda i: losses[i][-1]['loss_tot'] loss = np.zeros((1,iters)) for i in range(iters): loss[0,i] = getloss(i) plt.plot(loss.T)
true
d1111596e4193822e6c7d3a3b4ba2cf3524f90eb
Python
Clauudia/Curso-Python
/Curso-Python/Tareas/Tarea2.py
UTF-8
438
3.53125
4
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- #UNAM-CERT numero = input('ingresa el número de primos que quieres calcular: ' ) primos = [2] contador = 1 n = 3 def calcula_primos(numero): if(numero < 1): print "Ingresa un entero mayor 0" else: while(contador <= numero): if(n % 2 != 0 and n % (n - 1) != 0): primos.append(n) contador + 1 calcula_primos(numero + 2) else: calcula_primos(numero + 1) print primos
true
8489d917d7a9132ebfb20a30658e48d2c1336583
Python
TianheWu/Keystone
/Interface_Fea_SVM/Get_SVM_Line.py
UTF-8
785
3.578125
4
[]
no_license
# Date: 2020.10.17 # File function: Transform the matrix to lower triangle and append the label to construct a SVM input line # Person write this file: Zijian Feng, Tianhe Wu class Connect: # Send mutual information matrix def __init__(self, matrix_: [[list]], label_: int) -> None: self.matrix = matrix_ self.label = label_ # Transform the matrix to lower triangle and append the label def get_line(self) -> list: print('start get line:') vec_ = [] for z in self.matrix: for i in range(1, len(z)): for j in range(i): print(self.matrix[z][i][j]) vec_.append(self.matrix[z][i][j]) print('write the label') vec_.append(self.label) return vec_
true
d2a10c39f1270168fddaf13ff1669ce36ac187d7
Python
magniff/bugvoyage
/tests/test_std_types/test_bytearray.py
UTF-8
359
2.65625
3
[]
no_license
import sys from hypothesis import strategies, given, settings, assume if sys.version_info.major == 3 and sys.version_info.minor >= 5: @given( binary_data=strategies.binary().map(bytearray), ) @settings(max_examples=100000) def test_is_integer(binary_data): assert bytearray.fromhex(bytearray.hex(binary_data)) == binary_data
true
a5d0167b550b8030f7b80312366947b48429d2be
Python
bada0707/hellopython
/문제/ch3/pch03ex04.py
UTF-8
199
3.859375
4
[]
no_license
x = int(input("x1: ")) y = int(input("y1: ")) x_ = int(input("x2: ")) y_ = int(input("y2: ")) #연산 also = ((x - x_)**2 + (y - y_)**2)**0.5 print("두점 사이에 거리: ",also)
true
edda038f720ddb3e610a2a15bde925d49f7a49ca
Python
theethaj/ku-polls
/polls/tests/test_auth.py
UTF-8
1,502
2.71875
3
[]
no_license
import datetime from django.contrib.auth import get_user_model from django.test import TestCase from django.utils import timezone from django.urls import reverse from polls.models import Question def create_question(question_text, days, duration=1): """ Create a question with the given question_text, given number of days offset to now. """ time = timezone.now() + datetime.timedelta(days=days) end = time + datetime.timedelta(days=duration) return Question.objects.create(question_text=question_text, pub_date=time, end_date=end) class AuthenticationTests(TestCase): """ Test authentication. """ def setUp(self): User = get_user_model() user = User.objects.create_user("Daniel", "daniel.j@ku.th", "abc007") user.first_name = 'Daniel' user.last_name = "James" user.save() def test_user_with_authentication(self): """ Test authenticated user. """ self.client.login(username="Daniel", password="abc007") url = reverse("polls:index") response = self.client.get(url) self.assertContains(response, "Daniel") self.assertContains(response, "James") def test_user_with_no_authentication(self): """Test unauthenticated user.""" url = reverse("polls:index") response = self.client.get(url) self.assertNotContains(response, "Daniel") self.assertNotContains(response, "James")
true
03a2e50f46035986c48d425fd227dca3eea66b7a
Python
cgao/IP
/ip.py
UTF-8
228
2.59375
3
[ "MIT" ]
permissive
import socket import os from time import strftime myIP=socket.gethostbyname(socket.gethostname()) time=strftime("updated at %Y-%m-%d %H:%M:%S") f=open('myIP.txt','w') f.write(myIP+'\n') f.write(time+'\n') f.close()
true
ef9432159c9ff4700295cd06d8c15336565d1e4c
Python
Jack-HFK/hfklswn
/pychzrm course/journey_two/day7_PM/day1/signal_.py
UTF-8
300
2.640625
3
[]
no_license
""" 信号方法处理僵尸进程 """ import signal import os # 子进程退出时父进程会忽略,此时子进程自动由系统处理 signal.signal(signal.SIGCHLD,signal.SIG_IGN) pid = os.fork() if pid < 0: pass elif pid == 0: print("Child pid:",os.getpid()) else: while True: pass
true
4b53eeed24fee01914ab4e4e73426d2ce6f6440d
Python
kampfschlaefer/pilite-misc
/gameoflive/src/gol.py
UTF-8
1,996
3.40625
3
[]
no_license
# -*- coding: utf8 -*- # import logging import random class GameOfLive(object): def __init__(self, sizex, sizey): self.logger = logging.getLogger(self.__class__.__name__) self.resizeboard(sizex, sizey) def createboard(self, sizex, sizey): return [ [ 0 for y in range(sizey) ] for x in range(sizex) ] def resizeboard(self, sizex, sizey): self.sizex = sizex self.sizey = sizey self.board = self.createboard(sizex, sizey) def printboard(self): output = [] for row in self.board: line = ' '.join([ '{}'.format([' ', '0'][i]) for i in row ]) output.append(line) self.logger.info('current state of the board is:\n{}'.format('\n'.join(output))) def getaliveneighbors(self, x, y): neighbors = 0 for i,j in ((x-1, y-1), (x-1, y), (x-1, y+1), (x, y-1), (x, y+1), (x+1, y-1), (x+1, y), (x+1, y+1)): try: neighbors += self.board[i % self.sizex][j % self.sizey] except IndexError: #self.logger.warn('Reached outside the board with {}, {}'.format(i, j)) pass return neighbors def calculatenextboard(self): nextboard = self.createboard(self.sizex, self.sizey) for x in range(self.sizex): for y in range(self.sizey): neighbors = self.getaliveneighbors(x, y) if self.board[x][y] and neighbors in [2, 3]: nextboard[x][y] = 1 if not self.board[x][y] and neighbors == 3: nextboard[x][y] = 1 self.board = nextboard if __name__=='__main__': logging.basicConfig(level='DEBUG') random.seed() x, y = (10, 16) gol = GameOfLive(x, y) for i in range(random.randint(x*y/10, x*y/4)): gol.board[random.randrange(x)][random.randrange(y)] = 1 gol.printboard() for i in range(10): gol.calculatenextboard() gol.printboard()
true
8ba65630c48a0feea3636cd0b44da8baccf4c0df
Python
alzaia/applied_machine_learning_python
/linear_regression/linear_regression_crime_dataset.py
UTF-8
4,691
3.1875
3
[ "MIT" ]
permissive
# Various linear regression models using the crime dataset (ridge, normalization, lasso) import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from adspy_shared_utilities import load_crime_dataset from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import Lasso # Communities and Crime dataset (X_crime, y_crime) = load_crime_dataset() # standard linear regression approach --------------------------------------- X_train, X_test, y_train, y_test = train_test_split(X_crime, y_crime, random_state = 0) linreg = LinearRegression().fit(X_train, y_train) print('Crime dataset') print('linear model intercept: {}'.format(linreg.intercept_)) print('linear model coeff:\n{}'.format(linreg.coef_)) print('R-squared score (training): {:.3f}'.format(linreg.score(X_train, y_train))) print('R-squared score (test): {:.3f}'.format(linreg.score(X_test, y_test))) # ridge regression approach -------------------------------------------------- X_train, X_test, y_train, y_test = train_test_split(X_crime, y_crime, random_state = 0) linridge = Ridge(alpha=20.0).fit(X_train, y_train) print('Crime dataset') print('ridge regression linear model intercept: {}'.format(linridge.intercept_)) print('ridge regression linear model coeff:\n{}'.format(linridge.coef_)) print('R-squared score (training): {:.3f}'.format(linridge.score(X_train, y_train))) print('R-squared score (test): {:.3f}'.format(linridge.score(X_test, y_test))) print('Number of non-zero features: {}'.format(np.sum(linridge.coef_ != 0))) # ridge regression with normalization approach -------------------------------- scaler = MinMaxScaler() X_train, X_test, y_train, y_test = train_test_split(X_crime, y_crime, random_state = 0) X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) linridge = Ridge(alpha=20.0).fit(X_train_scaled, y_train) print('Crime dataset') print('ridge regression linear model intercept: {}'.format(linridge.intercept_)) print('ridge regression linear model coeff:\n{}'.format(linridge.coef_)) print('R-squared score (training): {:.3f}'.format(linridge.score(X_train_scaled, y_train))) print('R-squared score (test): {:.3f}'.format(linridge.score(X_test_scaled, y_test))) print('Number of non-zero features: {}'.format(np.sum(linridge.coef_ != 0))) # selecting the best alpha param for ridge regression ------------------------- print('Ridge regression: effect of alpha regularization parameter\n') for this_alpha in [0, 1, 10, 20, 50, 100, 1000]: linridge = Ridge(alpha = this_alpha).fit(X_train_scaled, y_train) r2_train = linridge.score(X_train_scaled, y_train) r2_test = linridge.score(X_test_scaled, y_test) num_coeff_bigger = np.sum(abs(linridge.coef_) > 1.0) print('Alpha = {:.2f}\n num abs(coeff) > 1.0: {},\ r-squared training: {:.2f}, r-squared test: {:.2f}\n'.format(this_alpha, num_coeff_bigger, r2_train, r2_test)) # lasso regression approach ---------------------------------------------------- scaler = MinMaxScaler() X_train, X_test, y_train, y_test = train_test_split(X_crime, y_crime, random_state = 0) X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) linlasso = Lasso(alpha=2.0, max_iter = 10000).fit(X_train_scaled, y_train) print('Crime dataset') print('lasso regression linear model intercept: {}'.format(linlasso.intercept_)) print('lasso regression linear model coeff:\n{}'.format(linlasso.coef_)) print('Non-zero features: {}'.format(np.sum(linlasso.coef_ != 0))) print('R-squared score (training): {:.3f}'.format(linlasso.score(X_train_scaled, y_train))) print('R-squared score (test): {:.3f}\n'.format(linlasso.score(X_test_scaled, y_test))) print('Features with non-zero weight (sorted by absolute magnitude):') for e in sorted (list(zip(list(X_crime), linlasso.coef_)), key = lambda e: -abs(e[1])): if e[1] != 0: print('\t{}, {:.3f}'.format(e[0], e[1])) # comparing alpha param in lasso regression ----------------------------------- print('Lasso regression: effect of alpha regularization\n\parameter on number of features kept in final model\n') for alpha in [0.5, 1, 2, 3, 5, 10, 20, 50]: linlasso = Lasso(alpha, max_iter = 10000).fit(X_train_scaled, y_train) r2_train = linlasso.score(X_train_scaled, y_train) r2_test = linlasso.score(X_test_scaled, y_test) print('Alpha = {:.2f}\nFeatures kept: {}, r-squared training: {:.2f}, \ r-squared test: {:.2f}\n'.format(alpha, np.sum(linlasso.coef_ != 0), r2_train, r2_test))
true
a03e7e84b0003e23b575a7e881122065b0abf5e7
Python
amidos2006/gym-pcgrl
/gym_pcgrl/envs/probs/ddave/engine.py
UTF-8
12,573
3.296875
3
[ "MIT" ]
permissive
from queue import PriorityQueue directions = [{"x":0, "y":0}, {"x":-1, "y":0}, {"x":1, "y":0}, {"x":0, "y":-1}] class Node: balance = 0.5 def __init__(self, state, parent, action): self.state = state self.parent = parent self.action = action self.depth = 0 if self.parent != None: self.depth = parent.depth + 1 def getChildren(self): children = [] for d in directions: childState = self.state.clone() childState.update(d["x"], d["y"]) children.append(Node(childState, self, d)) return children def getKey(self): return self.state.getKey() def getCost(self): return self.depth def getHeuristic(self): return self.state.getHeuristic() def checkWin(self): return self.state.checkWin() def checkLose(self): return self.state.checkLose() def checkOver(self): return self.state.checkOver() def getGameStatus(self): return self.state.getGameStatus() def getActions(self): actions = [] current = self while(current.parent != None): actions.insert(0,current.action) current = current.parent return actions def __str__(self): return str(self.depth) + "," + str(self.state.getHeuristic()) + "\n" + str(self.state) def __lt__(self, other): return self.getHeuristic()+Node.balance*self.getCost() < other.getHeuristic()+Node.balance*other.getCost() class Agent: def getSolution(self, state, maxIterations): return [] class BFSAgent(Agent): def getSolution(self, state, maxIterations=-1): iterations = 0 bestNode = None queue = [Node(state.clone(), None, None)] visisted = set() while (iterations < maxIterations or maxIterations <= 0) and len(queue) > 0: iterations += 1 current = queue.pop(0) if current.checkLose(): continue if current.checkWin(): return current.getActions(), current, iterations if current.getKey() not in visisted: if bestNode == None or current.getHeuristic() < bestNode.getHeuristic(): bestNode = current elif current.getHeuristic() == bestNode.getHeuristic() and current.getCost() < bestNode.getCost(): bestNode = current visisted.add(current.getKey()) queue.extend(current.getChildren()) return bestNode.getActions(), bestNode, iterations class DFSAgent(Agent): def getSolution(self, state, maxIterations=-1): iterations = 0 bestNode = None queue = [Node(state.clone(), None, None)] visisted = set() while (iterations < maxIterations or maxIterations <= 0) and len(queue) > 0: iterations += 1 current = queue.pop() if current.checkLose(): continue if current.checkWin(): return current.getActions(), current, iterations if current.getKey() not in visisted: if bestNode == None or current.getHeuristic() < bestNode.getHeuristic(): bestNode = current elif current.getHeuristic() == bestNode.getHeuristic() and current.getCost() < bestNode.getCost(): bestNode = current visisted.add(current.getKey()) queue.extend(current.getChildren()) return bestNode.getActions(), bestNode, iterations class AStarAgent(Agent): def getSolution(self, state, balance=1, maxIterations=-1): iterations = 0 bestNode = None Node.balance = balance queue = PriorityQueue() queue.put(Node(state.clone(), None, None)) visisted = set() while (iterations < maxIterations or maxIterations <= 0) and queue.qsize() > 0: iterations += 1 current = queue.get() if current.checkLose(): continue if current.checkWin(): return current.getActions(), current, iterations if current.getKey() not in visisted: if bestNode == None or current.getHeuristic() < bestNode.getHeuristic(): bestNode = current elif current.getHeuristic() == bestNode.getHeuristic() and current.getCost() < bestNode.getCost(): bestNode = current visisted.add(current.getKey()) children = current.getChildren() for c in children: queue.put(c) return bestNode.getActions(), bestNode, iterations class State: def __init__(self): self.solid = [] self.spikes = [] self.diamonds = [] self.player = None self.key = None self.door = None self._airTime = 3 self._hangTime = 1 def stringInitialize(self, lines): # clean the input for i in range(len(lines)): lines[i]=lines[i].replace("\n","") for i in range(len(lines)): if len(lines[i].strip()) != 0: break else: del lines[i] i-=1 for i in range(len(lines)-1,0,-1): if len(lines[i].strip()) != 0: break else: del lines[i] i+=1 #get size of the map self.width=0 self.height=len(lines) for l in lines: if len(l) > self.width: self.width = len(l) #set the level for y in range(self.height): l = lines[y] self.solid.append([]) for x in range(self.width): if x > len(l)-1: self.solid[y].append(False) continue c=l[x] if c == "#": self.solid[y].append(True) else: self.solid[y].append(False) if c == "$": self.diamonds.append({"x": x, "y": y}) elif c == "*": self.spikes.append({"x": x, "y": y}) elif c == "@": self.player = {"x": x, "y": y, "health": 1, "airTime": 0, "diamonds": 0, "key": 0, "jumps": 0} elif c == "H": self.door = {"x": x, "y": y} elif c == "V": self.key = {"x": x, "y": y} def clone(self): clone = State() clone.width = self.width clone.height = self.height clone.solid = self.solid clone.door = self.door clone.spikes = self.spikes clone.key = self.key clone.player = {"x":self.player["x"], "y":self.player["y"], "health":self.player["health"], "airTime": self.player["airTime"], "diamonds":self.player["diamonds"], "key": self.player["key"], "jumps":self.player["jumps"]} for d in self.diamonds: clone.diamonds.append(d) return clone def checkMovableLocation(self, x, y): return not (x < 0 or y < 0 or x >= self.width or y >= self.height or self.solid[y][x]) def checkSpikeLocation(self, x, y): for s in self.spikes: if s["x"] == x and s["y"] == y: return s return None def checkDiamondLocation(self, x, y): for d in self.diamonds: if d["x"] == x and d["y"] == y: return d return None def checkKeyLocation(self, x, y): if self.key is not None and self.key["x"] == x and self.key["y"] == y: return self.key return None def updatePlayer(self, x, y): self.player["x"] = x self.player["y"] = y toBeRemoved = self.checkDiamondLocation(x, y) if toBeRemoved is not None: self.player["diamonds"] += 1 self.diamonds.remove(toBeRemoved) return toBeRemoved = self.checkSpikeLocation(x, y) if toBeRemoved is not None: self.player["health"] = 0 return toBeRemoved = self.checkKeyLocation(x, y) if toBeRemoved is not None: self.player["key"] += 1 self.key = None return def update(self, dirX, dirY): if self.checkOver(): return if dirX > 0: dirX=1 if dirX < 0: dirX=-1 if dirY < 0: dirY=-1 else: dirY=0 ground = self.solid[self.player["y"] + 1][self.player["x"]] cieling = self.solid[self.player["y"] - 1][self.player["x"]] newX = self.player["x"] newY = self.player["y"] if abs(dirX) > 0: if self.checkMovableLocation(newX + dirX, newY): newX = newX + dirX elif dirY == -1: if ground and not cieling: self.player["airTime"] = self._airTime self.player["jumps"] += 1 if self.player["airTime"] > self._hangTime: self.player["airTime"] -= 1 if self.checkMovableLocation(newX, newY - 1): newY = newY - 1 else: self.player["airTime"] = self._hangTime elif self.player["airTime"] > 0 and self.player["airTime"] <= self._hangTime: self.player["airTime"] -= 1 else: if self.checkMovableLocation(newX, newY + 1): newY = newY + 1 self.updatePlayer(newX, newY) def getKey(self): key = str(self.player["x"]) + "," + str(self.player["y"]) + "," + str(self.player["health"]) + "|" key += str(self.door["x"]) + "," + str(self.door["y"]) + "|" if self.key is not None: key += str(self.key["x"]) + "," + str(self.key["y"]) + "|" for d in self.diamonds: key += str(d["x"]) + "," + str(d["y"]) + "," key = key[:-1] + "|" for s in self.spikes: key += str(s["x"]) + "," + str(s["y"]) + "," return key[:-1] def getHeuristic(self): playerDist = abs(self.player["x"] - self.door["x"]) + abs(self.player["y"] - self.door["y"]) if self.key is not None: playerDist = abs(self.player["x"] - self.key["x"]) + abs(self.player["y"] - self.key["y"]) + (self.width + self.height) diamondCosts = -self.player["diamonds"] return playerDist + 5*diamondCosts def getGameStatus(self): gameStatus = "running" if self.checkWin(): gameStatus = "win" if self.checkLose(): gameStatus = "lose" return { "status": gameStatus, "health": self.player["health"], "airTime": self.player["airTime"], "num_jumps": self.player["jumps"], "col_diamonds": self.player["diamonds"], "col_key": self.player["key"] } def checkOver(self): return self.checkWin() or self.checkLose() def checkWin(self): return self.player["key"] > 0 and self.player["x"] == self.door["x"] and self.player["y"] == self.door["y"] def checkLose(self): return self.player["health"] <= 0 def __str__(self): result = "" for y in range(self.height): for x in range(self.width): if self.solid[y][x]: result += "#" else: spike=self.checkSpikeLocation(x,y) is not None diamond=self.checkDiamondLocation(x,y) is not None key=self.checkKeyLocation(x,y) is not None player=self.player["x"]==x and self.player["y"]==y door=self.door["x"]==x and self.door["y"]==y if player: if spike: result += "-" elif door: result += "+" else: result += "@" elif spike: result +="*" elif diamond: result +="$" elif key: result += "V" elif door: result += "H" else: result += " " result += "\n" return result[:-1]
true
78d18a9cd4d9ff37dd567101af56cd5035ab2019
Python
WielkiZielonyMelon/itbs
/src/apply_attack/apply_attack_set_on_fire.py
UTF-8
676
2.5625
3
[]
no_license
import copy from src.apply_attack.apply_attack import fire_tile from src.helpers.convert_tile_if_needed import convert_tile_if_needed from src.helpers.kill_object import kill_object_if_possible from src.helpers.update_dict_if_key_not_present import update_dict_if_key_not_present def apply_attack_set_on_fire(board, attack): attack_pos = attack.get_attacker() ret = {attack_pos: copy.deepcopy(board[attack_pos])} fire_tile(board, attack_pos) convert_tile_if_needed(board, attack_pos) obj = board[attack_pos].get_object() if obj is not None: update_dict_if_key_not_present(ret, kill_object_if_possible(board, attack_pos, obj)) return ret
true
c4418b9a815e1faa5dc82a6a71b7ba284ddbcc70
Python
nrhint/GitGames
/solver/Solve.py
UTF-8
6,084
2.671875
3
[]
no_license
##Nathan Hinton def test(rowCol): box = [] ## for x in finalLst:#Find numbers in the box if 0 <= rowCol[0] <= 2: l = finalLst[0:3] print(l) if 0 <= rowCol[1] <= 2: for x in l:box+=x[0:3] elif 3 <= rowCol[1] <= 5: for x in l:box+=x[3:6] else:#It is on the last COL: for x in l:box+=x[6:9] ############## elif 3 <= rowCol[0] <= 5: l = finalLst[3:6] if 0 <= rowCol[1] <= 2: for x in l:box+=x[0:3] elif 3 <= rowCol[1] <= 5: for x in l:box+=x[3:6] else:#It is on the last COL: for x in l:box+=x[6:9] ############## else:#It is on the last ROW: l = finalLst[6:9] if 0 <= rowCol[1] <= 2: for x in l:box+=x[0:3] elif 3 <= rowCol[1] <= 5: for x in l:box+=x[3:6] else:#It is on the last COL: for x in l:box+=x[6:9] print(box) ##TO DO: from time import sleep file = 'File0.txt' numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] ignore = ['n', 'm'] waitTime = 0 state = 'init' while state != 'solved': if state == 'init': rowCol = (0, 0) rawData = "ERROR!" try: rawData = open(file, 'r').read() except FileNotFoundError: print("File not found. check the name.") #Load data to list: tempLst = [] finalLst = [] for i in rawData: if i in ignore: tempLst.append(0) elif i == ' ': pass elif i == '\n': finalLst.append(tempLst) tempLst = [] else: tempLst.append(int(i)) tempLst = [] lastSolved = None state = 'findSpace' ################################################ elif state == 'findSpace': if rowCol == lastSolved: state = 'failed' row = finalLst[(rowCol[0]+1)%9] for x in range(len(rowCol[1::])): if row[x] == 0: rowCol = ((rowCol[0]+1)%9, x) state = 'solveSpace' else: state = 'change' #print(rowCol) ################################################ elif state == 'solveSpace': subState = 'methodA' while state == 'solveSpace': ################################################ count = 0 if subState == 'methodA':#Check row and colum against possible numbers if finalLst[rowCol[0]][rowCol[1]] != 0: print("Space (%s, %s) already solved"%rowCol) subState = 'solved' notNums = [] for x in finalLst[rowCol[0]]:#Find numbers in row if x != 0: notNums.append(x) for x in finalLst:#Find numbers in colum if x[rowCol[1]] != 0: if x[rowCol[1]] not in notNums: notNums.append(x[rowCol[1]]) ############## box = [] if 0 <= rowCol[0] <= 2: l = finalLst[0:3] if 0 <= rowCol[1] <= 2: for x in l:box+=x[0:3] elif 3 <= rowCol[1] <= 5: for x in l:box+=x[3:6] else:#It is on the last COL: for x in l:box+=x[6:9] ############## elif 3 <= rowCol[0] <= 5: l = finalLst[3:6] if 0 <= rowCol[1] <= 2: for x in l:box+=x[0:3] elif 3 <= rowCol[1] <= 5: for x in l:box+=x[3:6] else:#It is on the last COL: for x in l:box+=x[6:9] ############## else:#It is on the last ROW: l = finalLst[6:9] if 0 <= rowCol[1] <= 2: for x in l:box+=x[0:3] elif 3 <= rowCol[1] <= 5: for x in l:box+=x[3:6] else:#It is on the last COL: for x in l:box+=x[6:9] cnt = 0 for num in box:####Filter the 0's out of box if num == 0:cnt += 1 for d in range(cnt): box.remove(0) #print(box) notNums += box #print(notNums) if len(notNums) < len(numbers) -1: subState = 'failed' else: notNums.sort() for x in range(len(numbers)): if notNums[x] != numbers[x]: number = numbers[x] break #print(rowCol) #print(number) finalLst[rowCol[0]][rowCol[1]] = number lastSolved = rowCol subState = 'solved' print('solved a space...') ################################################ elif subState == 'failed' or count > 9: state = 'change' break ################################################ elif subState == 'solved': state = 'findSpace' else: print('SUBsTATE ERROR! Not matching subState for state %s'%subState) #print(subState) sleep(1) count += 1 elif state == 'change': if rowCol[1] == 8: rowCol = ((rowCol[0]+1)%9, 0) else: rowCol = (rowCol[0], (rowCol[1]+1)%9) state = 'findSpace' elif state == 'failed': print("Program failed to solve this puzzle.") else: print('STATE ERROR! Not matching state for state %s'%state) break #print(state) sleep(waitTime) ################################################
true
e9641e193215b5626b11be36523efda9961829e8
Python
loneharoon/Dominos
/experimental_py/find_slope.py
UTF-8
4,640
2.75
3
[]
no_license
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Here, in this script, I learn how to fit regresssion line to temperature data. Created on Sat Jul 28 08:59:58 2018 @author: haroonr """ import numpy as np import pandas as pd import matplotlib.pyplot as plt #%% dir = "/Volumes/MacintoshHD2/Users/haroonr/Detailed_datasets/Dominos/" store = 'Dominos-22' power = "temp_makeline.csv" df = pd.read_csv(dir + store + '/' + power,index_col="Datetime") df.index = pd.to_datetime(df.index) df_samp_temp = df.resample('1T',label = 'right', closed ='right').mean() #%% #df_1 = df_samp['2018-02-01'] #datex = '2018-06-25' df_2 = df_samp_temp['2018-06-27 10:00:00':'2018-06-27 13:00:00'] #df_2 = df_samp_temp['2018-06-27 13:00:00':'2018-06-27 23:00:00'] savepath = "/Volumes/MacintoshHD2/Users/haroonr/Dropbox/zenatix/paper/pics/" filename = 'reg-plot-D25-27-06-2018-eve.pdf' # change this name while saving file compute_slope_diagram(df_2) # this one only plots #compute_slope_and_save_diagram(df_2,savepath,filename) # it also saves pdf, #%% import copy from scipy.stats import linregress def compute_slope_diagram(df_temp): df_temp = copy.copy(df_temp) df_temp = df_temp.dropna() df_temp.columns = ['Temperature'] df_temp['num_ind'] = range(1,df_temp.shape[0]+1) lf = linregress(df_temp['num_ind'].values, df_temp['Temperature'].values) df_temp['Regression line'] = [lf.slope*num + lf.intercept for num in df_temp['num_ind'].values] df_temp[['Temperature','Regression line']].plot() plt.xlabel('Timestamp') plt.ylabel('Temperature (C)') plt.show() return lf.slope #%% def compute_slope_and_save_diagram(df_temp,savepath, filename): df_temp = copy.copy(df_temp) df_temp = df_temp.dropna() df_temp.columns = ['Temperature'] df_temp['num_ind'] = range(1,df_temp.shape[0]+1) lf = linregress(df_temp['num_ind'].values, df_temp['Temperature'].values) df_temp['Regression line'] = [lf.slope*num + lf.intercept for num in df_temp['num_ind'].values] df_temp[['Temperature','Regression line']].plot(figsize=(6,4)) plt.xlabel('Timestamp') plt.ylabel('Temperature (C)') plt.savefig(savepath+filename) plt.close() return lf.slope #%% def get_train_test_dates(store_name): store_dic = {} dic_values = {} store_dic['Dominos-22'] = {'train_duration':{'start':'2018-02-10','end': '2018-02-20'},'test_duration':{'start':'2018-03-01','end':'2018-06-30'}} store_dic['Dominos-25'] = {'train_duration':{'start':'2018-02-01','end': '2018-02-07'},'test_duration':{'start':'2018-03-01','end':'2018-06-30'}} try: dic_values = store_dic[store_name] except: print('the store is not registered in the database: please update this in the method get_train_test_datas method') return dic_values #%% clustering check samp = testdata.to_frame() samp = samp[not samp == 0] # remove intial readings if store started late, otherwise it results in wrong clustering # handle nans in data nan_obs = int(samp.isnull().sum()) #rule: if more than 50% are nan then I drop that day from calculcations othewise I drop nan readings only if nan_obs: if nan_obs >= 0.50*samp.shape[0]: print("More than 50percent missing hence dropping context {}".format(k)) return (False) elif nan_obs < 0.50*samp.shape[0]: print("dropping {} nan observations for total of {} in context {}".format(nan_obs, samp.shape[0], k)) samp.dropna(inplace=True) samp.columns = ['power'] samp_val = samp.values samp_val = samp_val.reshape(-1,1) #FIXME: you can play with clustering options if len(samp_val) == 0: # when data is missing or no data recoreded for the context return(False) # if np.std(samp_val) <= 0.3:# contains observations with same values, basically forward filled values # print("Dropping context {} of day {} from analysis as it contains same readings".format(k,samp.index[0].date())) # return (False) if np.std(samp_val) <= 0.3: # when applaince reamins ON for full context genuinely print("Only one state found in context {} on day {}\n".format(k,samp.index[0].date())) if samp_val[2] > 2: temp_lab = [1]* (samp_val.shape[0]-1) temp_lab.append(0) samp['cluster'] = temp_lab else:# when applaince reamins OFF for full context genuinely temp_lab = [0]* (samp_val.shape[0]-1) temp_lab.append(1) samp['cluster'] = temp_lab else: # normal case, on and off states of appliance kobj = perform_clustering(samp_val,clusters=2) samp['cluster'] = kobj.labels_ samp = re_organize_clusterlabels(samp)
true
54c2b6f6ccd377d9ed3c3a99f4c7a73a159f5fe0
Python
KienNguyen2021/BMI_calculation
/main.py
UTF-8
228
3.578125
4
[]
no_license
weight = float(input ("enter your weights in kg : ")) height = float(input ("enter your height in meter : ")) bmi = float (weight / (height ** 2)) // 2 power 2 bmi_integer = int(bmi) print ("your BMI is : " + str(bmi_integer))
true
b5c6e3883702de45ea13582ecd4a656e3badba23
Python
craiig/keychain-tools
/compiler_analysis/tag_optimizations.py
UTF-8
8,586
2.53125
3
[]
no_license
#!/usr/bin/env python import json import subprocess from pprint import pprint import argparse import os from bs4 import BeautifulSoup import sys import tempfile import collections import re def load_database(filename): #database = {} database = collections.OrderedDict() if filename and os.path.exists(filename): print "loading existing program json" try: with open(filename) as fh: #https://stackoverflow.com/questions/6921699/can-i-get-json-to-load-into-an-ordereddict-in-python database = collections.OrderedDict(json.load(fh, object_pairs_hook=collections.OrderedDict)) except ValueError as e: print "error parsing json" print e database = None return database def write_database(db, filename): with open(filename, "w+") as out: json.dump(db, out, indent=4) def parse_gcc(db, filename): with open(filename) as fh: soup = BeautifulSoup(fh, "lxml") # for GCC we only include optimizations included in the default # optimizations ignoring experimental and elective floating point opts # if we wish to include these later, change what gets added to opt_list lists = soup.select('dl') opt_list = [c for c in lists[1].children] all_opts = [] current_opt = None seen_desc = False #while len(opt_list) > 0: for c in opt_list: #c = opt_list.pop(0) if c.name == 'dt': if current_opt: if not seen_desc: current_opt['alternate_names'] = current_opt.get('alternate_names', []) current_opt['alternate_names'].append(c.text) else: all_opts.append( current_opt ) current_opt = { "name": c.text } seen_desc = False else: current_opt = { "name": c.text } seen_desc = False if c.name == 'dd': assert current_opt, "saw dd without a dt" assert current_opt.get('name', None) != None, "must have opt name" assert current_opt.get('description', False) == False, "dont overwrite a previous description" seen_desc = True current_opt['description'] = c.text.encode('utf-8') #insert last element if current_opt and seen_desc: all_opts.append( current_opt ) #apply to db # TODO tag these optimizations as coming from GCC for o in all_opts: if not o['name'] in db: db[o['name']] = {} else: #safety assert db[o['name']]['origin'] == 'gcc' ##ordered dict hack, do a removal and reinsert to establish good order (to fix a badly ordered file) ## can remove after this is done once? #entry = db[o['name']] #del db[o['name']] #db[o['name']] = entry entry = db[o['name']] entry['description'] = o.get('description', None) if 'alternate_names' in o: entry['alternate_names'] = o['alternate_names'] entry['origin'] = 'gcc' return all_opts def parse_llvm(db, filename): with open(filename) as fh: soup = BeautifulSoup(fh, "lxml") transforms = soup.select('#transform-passes .section') entries = [] for transform in transforms: name = transform.select('a')[0].text #remove name and return char #desc = transform.select('p')[0].text transform.select('a')[0].extract() transform.select('a')[0].extract() desc = transform.text.strip() if name not in db: db[name] = {} else: #safety assert db[name]['origin'] == 'llvm' entry = db[name] entry['description'] = desc entry['name'] = name entry['origin'] = 'llvm' entries.append(entry) return entries def remove_old_entries(db, new_entries): for k,v in db.iteritems(): if k not in new_entries: print "delete {}".format(k) def manually_tag_opts(db, args): # show a vim window with the opt description and a window to add tags for name,o in db.iteritems(): name = name.encode('utf-8') if args.manually_skip_tagged and 'tags' in o and len(o['tags']) > 0: print "skipping {}".format(name) continue if args.filter_tags: skip = False for ft in (args.filter_tag_skip if args.filter_tag_skip != None else []): for t in o.get('tags', []): m = re.match(ft, t) if m: skip = True if skip: print "skipping {} due to skip tag".format(name) continue visit = False for ft in args.filter_tags: for t in o.get('tags', []): m = re.match(ft, t) if m: print "{} re.match {}, visiting".format(ft, t) visit = True break if visit: break if not visit: print "skipping {} due to no filter match".format(name) continue tags_fh = tempfile.NamedTemporaryFile(mode="w+", delete=True) tags_file = tags_fh.name if 'tags' in o: tags_fh.write(", ".join(o['tags'])) tags_fh.flush() desc_fh = tempfile.NamedTemporaryFile(mode="w+", delete=True) desc_file = desc_fh.name if 'description' in o and o['description'] != None: desc_fh.write(name) desc_fh.write("\n") if 'alternate_names' in o: desc_fh.write(" ".join(o['alternate_names'])) desc_fh.write("\n") desc_fh.write(o['description'].encode('utf-8')) desc_fh.flush() #loop in case we make mistakes cont = 'r' #repeat by default unless we go next or no while cont != 'y': # btw vim works only when we aren't redirecting stdin cmd_args = ['vim', "survey_questions.md", desc_file, "-O" , "+:bot split +:edit {}".format(tags_file) , "+:resize 5" ] subprocess.call(cmd_args) tags_fh.seek(0) tags = tags_fh.read() tags = [s.strip() for s in tags.split(',')] o['tags'] = tags print "parsed tags for variant {}: {}".format(name, tags) cont = raw_input('continue? (y|n|r)') if cont == 'n': return write_database(db, args.db) if __name__ == "__main__": parser = argparse.ArgumentParser(description='read json files and implement a basic interface to tag each optimization') parser.add_argument('--opt_inputs', '-oi', help="a structure list of optimizations") parser.add_argument('--db', help="where to store data on the optimizations", required=True) parser.add_argument('--gcc_parse', '-g', help='parse gcc html docs and enrich database') parser.add_argument('--llvm_parse', '-l', help='parse gcc html docs and enrich database') parser.add_argument('--manually_tag', '-m', help='manually tag the optimizatins with tags', action='store_true') parser.add_argument('--manually_skip_tagged', '-mst', help='skip already tagged', action='store_true') parser.add_argument('--filter_tags', '-f', help='filter tags when manually tagging', action='append') parser.add_argument('--filter_tag_skip', '-fs', help='tags to skip when manually tagging', action='append') parser.add_argument('--remove_old_entries', help="remove old entries", action='store_true') args = parser.parse_args() db = load_database(args.db) gcc_entries = [] if args.gcc_parse: gcc_entries = parse_gcc(db, args.gcc_parse) llvm_entries = [] if args.llvm_parse: llvm_entries = parse_llvm(db, args.llvm_parse) if args.gcc_parse and args.llvm_parse: # todo fix this up after llvm has been implemented if args.remove_old_entries: new_entries = [e['name'] for e in gcc_entries] + [e['name'] for e in llvm_entries] remove_old_entries(db, new_entries) elif args.remove_old_entries: print "error: specific all optimizations to parse if you want to remove old entries" sys.exit(1) if args.manually_tag: manually_tag_opts(db, args) write_database(db, args.db)
true
2ebcdb69c09776f75bdb9ff1196ec25892d23eef
Python
chenjuntu/Projects
/CSC108/assignment 2/a2_type_checker.py
UTF-8
6,049
3.453125
3
[]
no_license
import builtins import stress_and_rhyme_functions # Check for use of functions print and input. our_print = print our_input = input def disable_print(*args): raise Exception("You must not call built-in function print!") def disable_input(*args): raise Exception("You must not call built-in function input!") builtins.print = disable_print builtins.input = disable_input # Type checks and simple checks for stress_and_rhyme_functions module # A small pronouncing table that can be used in docstring examples. SMALL_TABLE = [['A', 'BOX', 'CONSISTENT', 'DON\'T', 'FOX', 'IN', 'SOCKS'], [['AH0'], ['B', 'AA1', 'K', 'S'], ['K', 'AH0', 'N', 'S', 'IH1', 'S', 'T', 'AH0', 'N', 'T'], ['D', 'OW1', 'N', 'T'], ['F', 'AA1', 'K', 'S'], ['IH0', 'N'], ['S', 'AA1', 'K', 'S']]] # Type check and simple check stress_and_rhyme_functions.get_word result = stress_and_rhyme_functions.get_word('BOX B AA1 K S') assert isinstance(result, str), \ '''stress_and_rhyme_functions.get_word should return a str,''' \ ''' but returned {0}.'''.format(type(result)) assert result, \ '''stress_and_rhyme_functions.get_word('BOX B AA1 K S')''' \ ''' should return 'BOX', but ''' \ '''returned {0}.'''.format(result) # Type check and simple check stress_and_rhyme_functions.get_pronunciation result = stress_and_rhyme_functions.get_pronunciation('BOX B AA1 K S') assert isinstance(result, list), \ """stress_and_rhyme_functions.get_pronunciation should return a list,""" \ """ but returned {0}.""".format(type(result)) assert result == ['B', 'AA1', 'K', 'S'], \ """stress_and_rhyme_functions.get_pronunciation('BOX B AA1 K S')""" \ """ should return ['B', 'AA1', 'K', 'S'] but """ \ """returned {0}.""".format(result) # Type check and simple check stress_and_rhyme_functions.make_pronouncing_table result = stress_and_rhyme_functions.make_pronouncing_table(['BOX B AA1 K S']) assert isinstance(result, list), \ """stress_and_rhyme_functions.make_pronouncing_table should return a list,""" \ """ but returned {0}.""".format(type(result)) assert result == [['BOX'], [['B', 'AA1', 'K', 'S']]], \ """stress_and_rhyme_functions.make_pronouncing_table(['BOX B AA1 K S'])""" \ """ should return [['BOX'], [['B', 'AA1', 'K', 'S']]] but """ \ """returned {0}.""".format(result) # Type check and simple check stress_and_rhyme_functions.look_up_pronunciation result = stress_and_rhyme_functions.look_up_pronunciation("Don't!", SMALL_TABLE) assert isinstance(result, list), \ """stress_and_rhyme_functions.look_up_pronunciation should return a list,""" \ """ but returned {0}.""".format(type(result)) assert result == ['D', 'OW1', 'N', 'T'], \ """stress_and_rhyme_functions.look_up_pronunciation("Don't!", SMALL_TABLE)""" \ """ should return ['D', 'OW1', 'N', 'T'] but """ \ """returned {0}.""".format(result) # Type check and simple check stress_and_rhyme_functions.is_vowel_phoneme result = stress_and_rhyme_functions.is_vowel_phoneme("AE0") assert isinstance(result, bool), \ """stress_and_rhyme_functions.is_vowel_phoneme should return a bool,""" \ """ but returned {0}.""".format(type(result)) assert result == True, \ """stress_and_rhyme_functions.is_vowel_phoneme("AE0")""" \ """ should return True but """ \ """returned {0}.""".format(result) # Type check and simple check stress_and_rhyme_functions.last_syllable result = stress_and_rhyme_functions.last_syllable(['D', 'OW1', 'N', 'T']) assert isinstance(result, list), \ """stress_and_rhyme_functions.last_syllable should return a list,""" \ """ but returned {0}.""".format(type(result)) assert result == ['OW1', 'N', 'T'], \ """stress_and_rhyme_functions.last_syllable(['D', 'OW1', 'N', 'T'])""" \ """ should return ['OW1', 'N', 'T'] but """ \ """returned {0}.""".format(result) # Type check and simple check stress_and_rhyme_functions.convert_to_lines result = stress_and_rhyme_functions.convert_to_lines('\nOne,\n\n\ntwo,\nthree.\n\n') assert isinstance(result, list), \ """stress_and_rhyme_functions.convert_to_lines should return a list,""" \ """ but returned {0}.""".format(type(result)) assert result == ['One,', '', 'two,', 'three.'], \ """stress_and_rhyme_functions.convert_to_lines('\nOne,\n\n\ntwo,\nthree.\n\n'])""" \ """ should return ['One,', '', 'two,', 'three.'] but """ \ """returned {0}.""".format(result) # Type check and simple check stress_and_rhyme_functions.detect_rhyme_scheme result = stress_and_rhyme_functions.detect_rhyme_scheme(['BOX','FOX'], SMALL_TABLE) assert isinstance(result, list), \ """stress_and_rhyme_functions.detect_rhyme_scheme should return a list,""" \ """ but returned {0}.""".format(type(result)) assert result == ['A', 'A'], \ """stress_and_rhyme_functions.detect_rhyme_scheme(['BOX','FOX'], SMALL_TABLE)""" \ """ should return ['A', 'A'] but """ \ """returned {0}.""".format(result) # Type check and simple check stress_and_rhyme_functions.get_stress_pattern result = stress_and_rhyme_functions.get_stress_pattern('consistent', SMALL_TABLE) assert isinstance(result, str), \ """stress_and_rhyme_functions.get_stress_pattern should return a str,""" \ """ but returned {0}.""".format(type(result)) assert result == 'x / x ', \ """stress_and_rhyme_functions.get_stress_pattern('consistent', SMALL_TABLE)""" \ """ should return 'x / x ' but """ \ """returned {0}.""".format(result) builtins.print = our_print builtins.input = our_input print(""" The type checker passed. This means that the functions in stress_and_rhyme_functions.py: - are named correctly, - take the correct number of arguments, and - return the correct types. This does NOT mean that the functions are correct! Run the doctests to execute one test case per required stress_and_rhyme_functions.py function. Be sure to thoroughly test your functions yourself before submitting. """)
true
e3733dbe6fa60498b7bd17a1d92e57c1f00f3657
Python
Cenibee/PYALG
/python/fromBook/chapter6/string/4_most_common_word/4-s.py
UTF-8
519
3.28125
3
[]
no_license
from typing import Counter, List import re class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: banned = set(banned) words = re.findall('\w+', paragraph.lower()) for word, count in sorted(Counter(words).items(), key=lambda x: x[1], reverse=True): if word not in banned: return word sol = Solution() paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] print(sol.mostCommonWord(paragraph, banned))
true
f0fe6ffdb51c9f8989d8af9f1b0766388dbd4694
Python
jkbockstael/leetcode
/2020-07-month-long-challenge/day09.py
UTF-8
2,693
4.1875
4
[ "Unlicense" ]
permissive
#!/usr/bin/env python3 # Day 9: Maximum Width of Binary Tree # # Given a binary tree, write a function to get the maximum width of the given # tree. The width of a tree is the maximum width among all levels. The binary # tree has the same structure as a full binary tree, but some nodes are null. # The width of one level is defined as the length between the end-nodes (the # leftmost and right most non-null nodes in the level, where the null nodes # between the end-nodes are also counted into the length calculation. # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: def height(root: TreeNode) -> int: if root is None: return 0 else: return 1 + max(height(root.left), height(root.right)) def traverse(root: TreeNode) -> dict: # This tree is a monstruosity where empty nodes sometimes count values = {} queue = [] queue.append([root, 0, 0]) while queue: node, level, position = queue.pop(0) if level not in values: values[level] = [position] else: values[level].append(position) if node.left is not None: queue.append([node.left, level + 1, 2 * position + 1]) if node.right is not None: queue.append([node.right, level + 1, 2 * position + 2]) return values values = traverse(root) return max(max(values[level]) - min(values[level]) + 1 \ for level in range(height(root))) # Tests test_tree = TreeNode(1) test_tree.left = TreeNode(3) test_tree.right = TreeNode(2) test_tree.left.left = TreeNode(5) test_tree.left.right = TreeNode(3) test_tree.right.right = TreeNode(9) assert Solution().widthOfBinaryTree(test_tree) == 4 test_tree = TreeNode(1) test_tree.left = TreeNode(3) test_tree.left.left = TreeNode(5) test_tree.left.right = TreeNode(3) assert Solution().widthOfBinaryTree(test_tree) == 2 test_tree = TreeNode(1) test_tree.left = TreeNode(3) test_tree.right = TreeNode(2) test_tree.left.left = TreeNode(5) assert Solution().widthOfBinaryTree(test_tree) == 2 test_tree = TreeNode(1) test_tree.left = TreeNode(3) test_tree.right = TreeNode(2) test_tree.left.left = TreeNode(5) test_tree.right.right = TreeNode(9) test_tree.left.left.left = TreeNode(6) test_tree.right.right.right = TreeNode(7) assert Solution().widthOfBinaryTree(test_tree) == 8
true
0f0ea6e1bee503a70a0df0df6edfd60f7ac7133e
Python
akapne01/gym_tower_of_london
/training/utils/planning_helper.py
UTF-8
4,680
2.609375
3
[ "CC-BY-2.0" ]
permissive
from typing import List import numpy as np from networkx.tests.test_convert_pandas import pd from envs.custom_tol_env_dir import ToLTaskEnv from envs.custom_tol_env_dir.tol_2d.mapping import int_to_state, state_to_int from envs.custom_tol_env_dir.tol_2d.state import TolState FILL_VALUE = -100 def init_q_table() -> pd.DataFrame: """ Initializes q_value table. State is represented by columns, actions that can be taken in this state is represented as row. Actions that are not possible to be taken are initialized to FILL_VALUE = -100 """ poss_states = 36 poss_actions = 36 q_table = pd.DataFrame( np.array([[FILL_VALUE] * poss_actions] * poss_states)) int_states = int_to_state.keys() # contains all possible state numbers q_table.index = int_states q_table.columns = int_states for i in int_states: actions = get_possible_actions(i) for a in actions: q_table.loc[a, i] = 0 return q_table def get_best_Q_value(state: int, Q: pd.DataFrame) -> float: """ Gets the next actions and find the max of the action Q values for specified state. Returns max Q-value """ actions = get_possible_actions(state) df = Q.loc[actions] max_s = df[state].max() return max_s def get_a_with_max_q(state: int, Q: pd.DataFrame) -> List: """ Gets the next actions and find the max of the action Q values for specified state. Returns list of actions that have max q_values from specified state. """ best = [] actions = get_possible_actions(state) df = Q.loc[actions] # slices df to only possible actions max_s = df[state].max() for a in actions: value = Q.loc[a, state] if value == max_s: best.append(a) return best def get_min_q(state: int, Q: pd.DataFrame) -> List: """ Gets the next actions and find the max of the action Q values for specified state. Returns list of actions that have max q_values from specified state. """ worst = [] actions = get_possible_actions(state) df = Q.loc[actions] # slices df to only possible actions min_s = df[state].min() for a in actions: value = Q.loc[a, state] if value == min_s: worst.append(a) return worst def get_possible_actions(state: int) -> List: """ Calculates which actions can be taken from specified state. Returns a list of action numbers. Length of this list can vary from 2 actions minimum to 4 actions maximum that can be taken from state. """ color_permutation_no = int_to_state.get(state).permutation_no arrangement = int_to_state.get(state).arrangement_number possible_actions = { 1: [(color_permutation_no * 10 + 2), (color_permutation_no * 10 + 3)], 2: [(color_permutation_no * 10 + 1), (color_permutation_no * 10 + 3), state_to_int.get(TolState( (ToLTaskEnv.clamp(color_permutation_no - 1), ToLTaskEnv.clamp(color_permutation_no + 1) )[color_permutation_no % 2 == 1], 5 )) ], 3: [(color_permutation_no * 10 + 1), (color_permutation_no * 10 + 2), (color_permutation_no * 10 + 4), (color_permutation_no * 10 + 5)], 4: [(color_permutation_no * 10 + 3), (color_permutation_no * 10 + 5), state_to_int.get(TolState( (ToLTaskEnv.clamp(color_permutation_no + 1), ToLTaskEnv.clamp(color_permutation_no - 1), )[color_permutation_no % 2 == 1], 6 )) ], 5: [(color_permutation_no * 10 + 3), (color_permutation_no * 10 + 4), (color_permutation_no * 10 + 6), state_to_int.get(TolState( (ToLTaskEnv.clamp(color_permutation_no - 1), ToLTaskEnv.clamp(color_permutation_no + 1) )[color_permutation_no % 2 == 1], 2 )) ], 6: [(color_permutation_no * 10 + 5), state_to_int.get(TolState( (ToLTaskEnv.clamp(color_permutation_no + 1), ToLTaskEnv.clamp(color_permutation_no - 1) )[color_permutation_no % 2 == 1], 4 )) ] }[arrangement] return possible_actions
true
3ca7e1a1bfdb46404dc4a2da02347e72ed43f140
Python
jmxdbx/code_challenges
/encryption.py
UTF-8
625
3.359375
3
[]
no_license
""" Solution to hackerrank.com/challenges/encryption """ import math s = input().strip() l_s = len(s) r_f = math.floor(math.sqrt(l_s)) r_c = math.ceil(math.sqrt(l_s)) if (r_f * r_f) >= l_s: row = col = r_f elif (r_f * r_c) >= l_s: row, col = r_f, r_c else: row = col = r_c row_list = [] j = 0 for i in range(row): row_list.append(s[j:j+col]) j += col new_list = [] for i in range(col): try: new_list.append("".join([j[i] for j in row_list])) except: new_list.append("".join([j[i] for j in row_list[:-1]])) print(" ".join([i for i in new_list]))
true
554c73485edcfa5a3a0b8b6b18db623a1df03ea2
Python
JavierOramas/FAQ-Chat-Bot-Nous
/main.py
UTF-8
6,518
2.921875
3
[]
no_license
from similarity import find_most_similar, find_most_similar_interaction from corpus import CORPUS,TALK_TO_HUMAN # from telegrambot import send_to_user class Bot: def __init__(self): self.event_stack = [] self.interact = [] self.settings = { "min_score": 0.3, "help_email": "fakeEmail@notArealEmail.com", "faq_page": "www.NotActuallyAnFAQ.com" } # print ("Ask a question:") # while(True): # text = input() # self.allow_question(text) def allow_question(self, user,text): # Check for event stack potential_event = None # print(self.interact) if(len(self.event_stack)): potential_event = self.event_stack.pop() if len(self.interact): self.interact.pop() # text = input("Question to Human: ") # send question to humans # print("ok, wait until a human answers") return {'answer': 'Hemos Recibido tu pregunta, pronto una persona se pondrá en contacto contigo'} if potential_event: # text = input("Response: ") potential_event.handle_response(text, self) else: # print('here') # text = input("Question: ") answer = self.pre_built_responses_or_none(text) person = find_most_similar_interaction(text) if not answer: # print('here') if person['score'] > 0.3: self.interact.append(True) # print('Asking what to send to a human') return {'answer': 'Que desea preguntarle a una persona real?'} answer = find_most_similar(text) # print(answer['score']) if answer['score'] < 0.1: # send the question to humans # print('No puedo responder eso, pronto una persona se pondrá en contacto contigo') return False # return {'answer': 'No puedo responder eso, pronto una persona se pondrá en contacto contigo'} # print(self.answer_question(answer, text)) return self.answer_question(answer, text) return True def answer_question(self, answer, text): if answer['score'] > self.settings['min_score']: # set off event asking if the response question is what they were looking for return {'most_similar_question':answer['question'], 'similarity_percentage':answer['score'], 'answer':answer['answer']} else: return {'most_similar_question':'', 'similarity_percentage':0.0, 'answer': 'I could not understand you, Would you like to see the list of questions that I am able to answer?\n'} # set off event for corpus dump self.event_stack.append(Event("corpus_dump", text)) def pre_built_responses_or_none(self, text): # only return answer if exact match is found pre_built = [ { "Question": "Hello", "Answer": "Hello, What can I Help you with?\n" }, { "Question": "Who made you?", "Answer": "I was created by NousCommerce Team.\n" }, { "Question": "When were you born?", "Answer": "I said my first word on march 26, 2021.\n" }, { "Question": "What is your purpose?", "Answer": "I assist user experience by providing an interactive FAQ chat.\n" }, { "Question": "Thanks", "Answer": "Glad I could help!\n" }, { "Question": "Thank you", "Answer": "Glad I could help!\n" } ] for each_question in pre_built: if each_question['Question'].lower() in text.lower(): print (each_question['Answer']) return each_question def dump_corpus(self): # Get json from backend question_stack = [] for each_item in CORPUS: question_stack.append(each_item['Question']) return question_stack class Event: def __init__(self, kind, text): self.kind = kind self.CONFIRMATIONS = ["yes", "sure", "okay", "that would be nice", "yep", "ok", "fine"] self.NEGATIONS = ["no", "don't", "dont", "nope", "nevermind"] self.original_text = text def handle_response(self, text, bot): if self.kind == "corpus_dump": self.corpus_dump(text, bot) def corpus_dump(self, text, bot): for each_confirmation in self.CONFIRMATIONS: for each_word in text.split(" "): if each_confirmation.lower() == each_word.lower(): corpus = bot.dump_corpus() corpus = ["-" + s for s in corpus] print ("%s%s%s" % ("\n", "\n".join(corpus), "\n")) return 0 for each_negation in self.NEGATIONS: for each_word in text.split(" "): if each_negation.lower() == each_word.lower(): print ("Feel free to ask another question or send an email to %s.\n" % bot.settings['help_email']) bot.allow_question() return 0 # text = input("Question: ") answer = self.pre_built_responses_or_none(text) if not answer: answer = find_most_similar(text) self.answer_question(answer, text) # base case, no confirmation or negation found # print ("I'm having trouble understanding what you are saying. At the time, my ability is quite limited, " \ # "please refer to %s or email %s if I was not able to answer your question. " \ # "For convenience, a google link has been generated below: \n%s\n" % (bot.settings['faq_page'], # bot.settings['help_email'], # "https://www.google.com/search?q=%s" % # ("+".join(self.original_text.split(" "))))) return 0
true
d5ea5eab3c7de63c249189b9964714e445451547
Python
timeicher/natural-selection
/test.py
UTF-8
141
2.78125
3
[]
no_license
import pygame pygame.init() win = pygame.display.set_mode((1000, 1000)) while True: win.fill ((10,10,10)) pygame.display.update()
true
e760a83031ed7e3003a9a0aa6c66c3e2eefc186b
Python
ken8203/leetcode
/algorithms/partition-list.py
UTF-8
784
3.40625
3
[]
no_license
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ if head is None: return [] smaller = [] bigger = [] while head: if head.val < x: smaller.append(head.val) else: bigger.append(head.val) head = head.next merged = smaller + bigger newHead = ListNode(merged[0]) ptr = newHead for val in merged: ptr.next = ListNode(val) ptr = ptr.next ptr = newHead.next return ptr
true
fafab6946720e7e9c5f6756519566d1542f67e16
Python
littlewindcc/Image-Processing
/Sharping&Smoothing/smooth/smoothing.py
UTF-8
791
3.078125
3
[]
no_license
import cv #function for Smoothing def MedianFilter(image): w = image.width h = image.height size = (w,h) iMFilter = cv.CreateImage(size,8,1) for i in range(h): for j in range(w): if i in [0,h-1] or j in [0,w-1]: iMFilter[i,j] = image[i,j] else: a= [0]*9 for k in range(3): for l in range(3): a[k*3+l] = image[i-1+k,j-1+l] a.sort() iMFilter[i,j] = a[4] return iMFilter #load image image_name=raw_input('Please input the image name:')+'.jpg' image = cv.LoadImage(image_name,0) cv.ShowImage('Original',image) #show aftersmoothing image iMF = MedianFilter(image) cv.ShowImage('AfterSmoothing',iMF) cv.WaitKey(0)
true
b20efbf6b85997c1b4115a72d8d8f8d7ff826bd3
Python
kivi239/ML
/LinearRegression/linreg.py
UTF-8
775
3.4375
3
[]
no_license
import random import numpy as np from numpy.linalg import * from numpy import * import matplotlib.pyplot as plt def generate(): N = random.randint(20, 60) a = random.randint(1, 10) b = random.randint(-15, 15) print(a, b) x = np.zeros(N) y = np.zeros(N) for i in range(N): x[i] = random.randint(0, 20) y[i] = a * x[i] + b + random.randint(-5, 5) return x, y x, y = generate() n = len(x) plt.plot(x, y, 'ro') arr = np.zeros(shape=(n, 2)) for i in range(n): arr[i][0] = 1 arr[i][1] = x[i] a = np.asmatrix(arr) at = a.transpose() mn = inv(matmul(at, a)) w = matmul(matmul(mn, at), y) a = w.item(1) b = w.item(0) print(a, b) def y(x): return a * x + b t = np.arange(0, 20, 0.1) plt.plot(t, y(t)) plt.show()
true
2467d880ae64a433e5d3ce40bc6b60aa4b346a03
Python
trinnawat/leetcode-problems
/find-median-from-data-stream.py
UTF-8
1,248
4.03125
4
[]
no_license
''' https://leetcode.com/problems/find-median-from-data-stream/ ''' class MedianFinder: def __init__(self): """ initialize your data structure here. [1, 3, 4] [7, 13, 20] max_heap will maintain left order [-4, -3, -1] min_heap will maintain right order [7, 13, 20] """ self.max_heap = [] self.min_heap = [] def addNum(self, num: int) -> None: if len(self.max_heap) == len(self.min_heap): # check with max_heap (left order) first max_num_from_left_order = -heapq.heappushpop(self.max_heap, -num) # then check with right order heapq.heappush(self.min_heap, max_num_from_left_order) else: max_num_from_right_order = heapq.heappushpop(self.min_heap, num) heapq.heappush(self.max_heap, -max_num_from_right_order) def findMedian(self) -> float: if len(self.max_heap) == len(self.min_heap): return (-self.max_heap[0] + self.min_heap[0])/2 else: return self.min_heap[0] # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()
true
a84550029a570946d3c7bbef63137a304c85b63c
Python
gohar67/IntroToPython
/Practice/lecture4/practice3.py
UTF-8
280
3.234375
3
[]
no_license
name = 'Hovhannes' age = 18 password = '182516*' if name == 'Batman': print('Welcome Mr. Batman!') elif age <16: print('Dear %s, you are too young to register' % name) elif '*' not in password or '&' not in password: print('Please enter a different password.')
true
1fc73137bf7fd1a7dd55a4fbbe0f8722ab4ceec1
Python
agus2207/ESCOM
/Evolutionary_Computing/Greedy.py
UTF-8
1,199
4.15625
4
[]
no_license
""" Lab Session 1 Python & Greedy Algorithm -Who created Python? -Explain the game of the name -What is the current version of Python? -Explain the term "pythonic" -Explain the difference between the following: -list -tuple -set -dictionary -array """ import numpy as np def kp(): c = 10 value = 0 w = [5,4,3,2] v = [3,3,1,3] print("C = "+str(c)) print("W = "+str(w)) print("V = "+str(v)) z = tuple(zip(w,v)) z = sorted(z, reverse=True) for i in range(len(z)): if(z[i][0] <= c): print("weight: "+str(z[i][0])+" value: "+str(z[i][1])) #print("weight: "+str(z[i][0])) value = value + z[i][1] c = c - z[i][0] print("Total value = "+str(value)) def cmp(): t = 6 count = 0 d = [4, 3, 1] print("T = "+str(t)) print("d = "+str(d)) for i in range(len(d)): while d[i]<=t: print("Value = "+str(d[i])) t = t-d[i] count = count + 1 print("Number of coins = "+str(count)) def main(): #print("KP 0/1 with Greedy algorithm:") # kp() #print("\n") #print("CMP with Greedy algorithm:") cmp() main()
true
f3bfb2ed36f3a43bd8374b737ba03e7bf84a8d94
Python
mycoal99/AlconCapstone
/patient_recognition/segmentation/linecoords.py
UTF-8
583
3.25
3
[ "MIT" ]
permissive
import cv2 import numpy as np def linecoords(lines, imsize): """ Description: Find x-, y- coordinates of positions along a line. Input: lines: Parameters (polar form) of the line. imsize: Size of the image. Output: x,y: Resulting coordinates. """ # print("linecoords") xd = np.arange(imsize[1]) yd = (-lines[0,2] - lines[0,0] * xd) / lines[0,1] coords = np.where(yd >= imsize[0]) coords = coords[0] yd[coords] = imsize[0]-1 coords = np.where(yd < 0) coords = coords[0] yd[coords] = 0 x = xd y = yd return x, y
true
5ebf85fc384b18927be9857a38c96713fb91814f
Python
maroro0220/PythonStudy
/BOJ_Python/Math1/BOJ_2775_BunyuKing.py
UTF-8
1,496
3.71875
4
[]
no_license
''' 문제 평소 반상회에 참석하는 것을 좋아하는 주희는 이번 기회에 부녀회장이 되고 싶어 각 층의 사람들을 불러 모아 반상회를 주최하려고 한다. 이 아파트에 거주를 하려면 조건이 있는데, “a층의 b호에 살려면 자신의 아래(a-1)층의 1호부터 b호까지 사람들의 수의 합만큼 사람들을 데려와 살아야 한다” 는 계약 조항을 꼭 지키고 들어와야 한다. 아파트에 비어있는 집은 없고 모든 거주민들이 이 계약 조건을 지키고 왔다고 가정했을 때, 주어지는 양의 정수 k와 n에 대해 k층에 n호에는 몇 명이 살고 있는지 출력하라. 단, 아파트에는 0층부터 있고 각층에는 1호부터 있으며, 0층의 i호에는 i명이 산다. 입력 첫 번째 줄에 Test case의 수 T가 주어진다. 그리고 각각의 케이스마다 입력으로 첫 번째 줄에 정수 k, 두 번째 줄에 정수 n이 주어진다. (1 <= k <= 14, 1 <= n <= 14) 출력 각각의 Test case에 대해서 해당 집에 거주민 수를 출력하라. 예제 입력 1 2 1 3 2 3 예제 출력 1 6 10 ''' T=int(input()) while(T): k=int(input()) n=int(input()) a=[[0 for i in range(n+1)] for i in range(k+1) ] for i in range(0,k+1): a[k][1]=1 for j in range(1,n+1): if(i==0): a[i][j]=j continue a[i][j]=a[i][j-1]+a[i-1][j] print("%d"%a[k][n]) T-=1
true
4fdd7a2cc3a27901858e195d2de172905d417822
Python
powerzbt/reinforcement-learning-code
/第一讲 gym 学习及二次开发/qlearning.py
UTF-8
12,250
2.9375
3
[]
no_license
import sys import gym import random random.seed(0) import time import matplotlib.pyplot as plt grid = gym.make('GridWorld-v0') #grid is a instance of class GridEnv #grid=env.env #创建网格世界 states = grid.env.getStates() #获得网格世界的状态空间. available states actions = grid.env.getAction() #获得网格世界的动作空间 gamma = grid.env.getGamma() #获得折扣因子 #计算当前策略和最优策略之间的差 best = dict() #储存最优行为值函数 #? def read_best(): #obtain the best qfunction by reading a file, actual best qfunction, used to plot graph at last step, for #comparition only, not used in policy iteration f = open("best_qfunc") #best_qfunc: ''' 1_n:0.512000 1_e:0.640000 1_s:-1.000000 1_w:0.512000 2_n:0.640000 2_e:0.800000 2_s:0.640000 2_w:0.512000 3_n:0.800000 3_e:0.640000 3_s:1.000000 3_w:0.640000 4_n:0.640000 4_e:0.512000 4_s:0.640000 4_w:0.800000 5_n:0.512000 5_e:0.512000 5_s:-1.000000 5_w:0.640000 6_n:0.000000 6_e:0.000000 6_s:0.000000 6_w:0.000000 7_n:0.000000 7_e:0.000000 7_s:0.000000 7_w:0.000000 8_n:0.000000 8_e:0.000000 8_s:0.000000 8_w:0.000000 ''' for line in f: #per line as well as empty line between two lines: ''' >>> f = open("best_qfunc") >>> for line in f: ... print(line) ... 1_n:0.512000 1_e:0.640000 1_s:-1.000000 1_w:0.512000 2_n:0.640000 2_e:0.800000 2_s:0.640000 2_w:0.512000 3_n:0.800000 ... ''' line = line.strip() #strip by "/n" if len(line) == 0: continue #do not process empty line eles = line.split(":") #sepreat the line to key and value best[eles[0]] = float(eles[1]) '''add to dictionary called best which stores the best action value of all states using dict[key]=value''' #计算值函数的误差 #sum of squared errors between current qfunction and the best qfunction #qfunction: q(S,A); a dictionary where S_A is key, q(S,A) is value def compute_error(qfunc): #input:a qfunction (a dictionary) output:sum of squared errors sum1 = 0.0 for key in qfunc: error = qfunc[key] -best[key] sum1 += error *error return sum1 # 贪婪策略 def greedy(qfunc, state): '''input:q(S,A) of all S_A; s' a qfunction (a dictionary containing q(S,A) of all S and all A) and state (a certain S') output:argmax_a q(s',a) the best action of s' according to greedy ''' amax = 0 #the index of best action for s' #regard the first action as best action, then compare with others key = "%d_%s" % (state, actions[0]) # s'_a0 qmax = qfunc[key] # value of qfunc[s'_a0], i.e. q(s',a0) for i in range(len(actions)): # 扫描动作空间得到最大动作值函数 key = "%d_%s" % (state, actions[i]) # s'_ai q = qfunc[key] # qfunc[s'_ai], i.e. q(s',ai) if qmax < q: qmax = q amax = i #index of action corresponding to qmax return actions[amax] #return action that give maximum action value to s' #######epsilon贪婪策略 def epsilon_greedy(qfunc, state, epsilon): '''input:q(S,A) of all S_A; s; ε output:action a the selected action of s according to ε greedy ''' amax = 0 #index of a key = "%d_%s"%(state, actions[0]) # s_a0 qmax = qfunc[key] # value of qfunc[s_a0], i.e. q(s,a0) for i in range(len(actions)): '''#扫描动作空间得到最大动作值函数,which may be used later with probability 1-ε no matter used it or not, just calculate it first''' key = "%d_%s"%(state, actions[i]) # s_ai q = qfunc[key] # qfunc[s_ai], i.e. q(s,ai) if qmax < q: qmax = q amax = i #概率部分 pro = [0.0 for i in range(len(actions))] #pro = [0.0, 0.0, ..., 0.0] ##of 0.0 = len(actions) pro[amax] += 1-epsilon #greedy action:pro=1-ε for i in range(len(actions)): #other actions:pro=ε/n pro[i] += epsilon/len(actions) ##选择动作 r = random.random() #float number lies in 0 to 1 s = 0.0 for i in range(len(actions)): s += pro[i] if s>= r: return actions[i] return actions[len(actions)-1] #return the action upto which the accumulate probability lager than random # r def qlearning(num_iter1, alpha, epsilon): #input n; α; ε #n is iteration depth x = [] y = [] qfunc = dict() #行为值函数为字典 #初始化行为值函数为0 for s in states: #set all q(S,A) as 0 for a in actions: key = "%d_%s"%(s,a) qfunc[key] = 0.0 for iter1 in range(num_iter1): #number of state-initiallization times. i.e. how many chains are selected x.append(iter1) y.append(compute_error(qfunc)) #very large now #初始化初始状态 s = grid.reset() #s=states[int(random.random() * len(self.states))] #randomly select one from 1 to 8 a = actions[int(random.random()*len(actions))] #randomly select action from ['n','e','s','w'] t = False #terminal or not count = 0 #in each while loop: #count of "state go on depth" #after line 210, value iteration, s = s1, go on next state point #each for loop, the "state go on depth" same, each chain same length while False == t and count <100: key = "%d_%s"%(s, a) #与环境进行一次交互,从环境中得到新的状态及回报 s1, r, t1, i =grid.step(a) ''' def step(self, action): #input: a #user assigned action #output: next_state, reward, is_terminal,{} #系统当前状态 state = self.state if state in self.terminate_states: return state, 0, True, {} key = "%d_%s"%(state, action) #将状态和动作组成字典的键值 #状态转移 if key in self.t: next_state = self.t[key] else: next_state = state self.state = next_state is_terminal = False if next_state in self.terminate_states: is_terminal = True if key not in self.rewards: r = 0.0 else: r = self.rewards[key] return next_state, r,is_terminal,{} ''' key1 = "" #s1处的最大动作 a1 = greedy(qfunc, s1) key1 = "%d_%s"%(s1, a1) #利用qlearning方法更新值函数 qfunc[key] = qfunc[key] + alpha*(r + gamma * qfunc[key1]-qfunc[key]) #转到下一个状态 s = s1 a = epsilon_greedy(qfunc, s1, epsilon) count += 1 plt.plot(x,y,"-.,",label ="q alpha=%2.1f epsilon=%2.1f"%(alpha,epsilon)) plt.show() #show the plot return qfunc read_best() qlearning(100, 0.8, 0.1) #test
true
9a6263a4a57bc79fb4adc5240a8ac6dbe08e971f
Python
jonahhill/xone
/xone/plots.py
UTF-8
6,238
2.71875
3
[ "Apache-2.0" ]
permissive
import pandas as pd from xone import utils from matplotlib import pyplot as plt def plot_ts( data: (pd.Series, pd.DataFrame), fld='close', tz=None, vline=None, **kwargs ): """ Time series data plots Args: data: data in pd.Series or pd.DataFrame fld: which field to plot for multi-index tz: tz info - applied to merged time series data vline: kwargs for verticle lines Returns: matplotlib plot """ to_plot = data if isinstance(data, pd.DataFrame): if isinstance(data.columns, pd.MultiIndex) and \ (fld in data.columns.get_level_values(1)): to_plot = data.xs(fld, axis=1, level=1) elif fld in data.columns: to_plot = data[fld] if isinstance(to_plot, pd.Series): pl_val = pd.Series(data.values, name=data.name) else: pl_val = pd.DataFrame(data.values, columns=data.columns) # Proper raw datetime index idx = data.index if isinstance(idx, pd.MultiIndex): for n in range(len(idx.levels))[::-1]: sidx = idx.get_level_values(n) if isinstance(sidx, pd.DatetimeIndex): idx = sidx break # Standardize timezone assert isinstance(idx, pd.DatetimeIndex), idx if tz is not None: idx = idx.tz_convert(tz) raw_idx = idx.to_series(keep_tz=True).reset_index(drop=True) dt_idx = pd.Series(raw_idx.dt.date.unique()) diff = raw_idx.diff() is_day = diff.min() >= pd.Timedelta(days=1) num_days = dt_idx.size if num_days >= kwargs.pop('month_min_cnt', 90): # Monthly ticks xticks = raw_idx.loc[raw_idx.dt.month.diff().ne(0)] elif num_days >= kwargs.pop('week_min_cnt', 15): # Weekly ticks xticks = raw_idx.loc[raw_idx.dt.weekofyear.diff().ne(0)] elif is_day: xticks = raw_idx.index else: # Daily ticks - to be improved xticks = raw_idx.loc[raw_idx.dt.day.diff().ne(0)] # Plot ax = pl_val.plot(**kwargs) plt.xticks(ticks=xticks.index.tolist(), labels=xticks.dt.date, rotation=30) if not isinstance(vline, dict): vline = dict() vline['color'] = vline.get('color', '#FFFFFF') vline['linestyle'] = vline.get('linestyle', '-') vline['linewidth'] = vline.get('linewidth', 1) for xc in xticks: plt.axvline(x=xc, **vline) return ax def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs): """ Plot data with multiple scaels together Args: data: DataFrame of data cols: columns to be plotted spacing: spacing between legends color_map: customized colors in map plot_kw: kwargs for each plot **kwargs: kwargs for the first plot Returns: ax for plot Examples: >>> import pandas as pd >>> import numpy as np >>> >>> idx = range(5) >>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx) >>> # plot_multi(data=data, cols=['a', 'b'], plot_kw=[dict(style='.-'), dict()]) """ from pandas import plotting if cols is None: cols = data.columns if plot_kw is None: plot_kw = [{}] * len(cols) if len(cols) == 0: return num_colors = len(utils.flatten(cols)) # Get default color style from pandas colors = getattr( getattr(plotting, '_style'), '_get_standard_colors' )(num_colors=num_colors) if color_map is None: color_map = dict() fig = plt.figure() ax, lines, labels, c_idx = None, [], [], 0 for n, col in enumerate(cols): if isinstance(col, (list, tuple)): ylabel = ' / '.join(cols[n]) color = [ color_map.get(cols[n][_ - c_idx], colors[_ % len(colors)]) for _ in range(c_idx, c_idx + len(cols[n])) ] c_idx += len(col) else: ylabel = col color = color_map.get(col, colors[c_idx % len(colors)]) c_idx += 1 if 'color' in plot_kw[n]: color = plot_kw[n].pop('color') if ax is None: # First y-axes legend = plot_kw[0].pop('legend', kwargs.pop('legend', False)) ax = data.loc[:, col].plot( label=col, color=color, legend=legend, zorder=n, **plot_kw[0], **kwargs ) ax.set_ylabel(ylabel=ylabel) line, label = ax.get_legend_handles_labels() ax.spines['left'].set_edgecolor('#D5C4A1') ax.spines['left'].set_alpha(.5) else: # Multiple y-axes legend = plot_kw[n].pop('legend', False) ax_new = ax.twinx() ax_new.spines['right'].set_position(('axes', 1 + spacing * (n - 1))) data.loc[:, col].plot( ax=ax_new, label=col, color=color, legend=legend, zorder=n, **plot_kw[n] ) ax_new.set_ylabel(ylabel=ylabel) line, label = ax_new.get_legend_handles_labels() ax_new.spines['right'].set_edgecolor('#D5C4A1') ax_new.spines['right'].set_alpha(.5) ax_new.grid(False) # Proper legend position lines += line labels += label fig.legend(lines, labels, loc=8, prop=dict(), ncol=num_colors).set_zorder(len(cols)) ax.set_xlabel(' \n ') return ax def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs): """ Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot Returns: axes for plots Examples: >>> import pandas as pd >>> import numpy as np >>> >>> idx = range(5) >>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx) >>> # plot_h(data=data, cols=['a', 'b'], wspace=.2, plot_kw=[dict(style='.-'), dict()]) """ if plot_kw is None: plot_kw = [dict()] * len(cols) _, axes = plt.subplots(nrows=1, ncols=len(cols), **kwargs) plt.subplots_adjust(wspace=wspace) for n, col in enumerate(cols): data.loc[:, col].plot(ax=axes[n], **plot_kw[n]) return axes
true
01ee3879ac783f9ce94cb88a90e5f10d63da1f21
Python
olokorre/Project
/main.py
UTF-8
2,408
3.359375
3
[]
no_license
import pygame import random class Player(object): def __init__(self, img, largura, altura): self.spritePlayer = pygame.image.load(img) self.hitBox = pygame.Rect(32, 32, 32, 32) self.x = (largura * 0.45) self.y = (altura * 0.8) def mover(self, tecla, bloco): (x, y) = (self.x, self.y) if keys[275]: self.x += 3 #letra D elif keys[276]: self.x -= 3 #letra A if keys[273]: self.y -=3 #letra W elif keys[274]: self.y += 3 #letra S self.teleportar() if self.hitBox.colliderect(bloco): (self.x, self.y) = (x, y) print ("Colisão!!!!!!!!") gameDisplay.blit(self.spritePlayer, (self.x,self.y)) def teleportar(self): if self.x >= 800: self.x = 0 elif self.x <= 0: self.x = 800 if self.y >= 600: self.y = 0 elif self.y <= 0: self.y = 600 class Ground(object): def __init__(self, img): self.spriteWall = pygame.image.load(img) def montar(self, x, y): gameDisplay.blit(self.spriteWall, (x ,y)) class Wall(Ground): def __init__(self, img, x, y): self.x = x self.y = y self.spriteWall = pygame.image.load(img) self.hitBox = pygame.Rect(32, 32, 32, 32) def montar(self): gameDisplay.blit(self.spriteWall, (self.x ,self.y)) pygame.init() display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Project: Game!') black = (0,0,0) white = (255,255,255) clock = pygame.time.Clock() crashed = False Jogador = Player("assets/img/spritePlayer.png", display_width, display_height) Chao = Ground("assets/img/T6.png") Parede = Wall("assets/img/P6.png", random.randint(0, 800), random.randint(0, 600)) x = (display_width * 0.45) y = (display_height * 0.8) while not crashed: for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = True if pygame.key.get_focused(): keys = pygame.key.get_pressed() gameDisplay.fill(white) for i in range(0, 800, 64): for l in range(0, 600, 64): Chao.montar(i ,l) Jogador.mover(keys, Parede.hitBox) Parede.montar() pygame.display.update() clock.tick(60) # cont = 0 # for i in keys: # if i == 1: print(cont) # else: cont += 1 pygame.quit() quit()
true
e0f78e5fa708498953962588462495e8f3a2b395
Python
denysfarias/project-euler-net
/problem-010/main.py
UTF-8
480
3.984375
4
[ "MIT" ]
permissive
from time import perf_counter """ https://projecteuler.net/problem=10 Summation of primes Problem 10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ def naive_approach(): pass def main(): start = perf_counter() primes, primes_sum = naive_approach() stop = perf_counter() time_in_sec = stop - start print(f'{primes=}, {primes_sum} in {time_in_sec=}') if __name__ == "__main__": main()
true
17249022982908ee6c67f62d7f4d7b41e170aff1
Python
roiti46/Contest
/yukicoder/001-099/024.py
UTF-8
208
2.921875
3
[]
no_license
N = int(raw_input()) s = set(range(10)) for loop in xrange(N): A = raw_input().split() if A[-1] == "YES": s &= set(map(int,A[:-1])) else: s -= set(map(int,A[:-1])) print list(s)[0]
true
b560fbe1d4c7ed9e5b0c77bab17cb2d45f492841
Python
luctivud/Coding-Trash
/weird-sort.py
UTF-8
407
2.765625
3
[]
no_license
for _ in range(int(input())): n, m = map(int, input().split()) arr = list(map(int, input().split())) ind = set(map(int, input().split())) brr = sorted(arr) flag = True for i in range(len(arr)): if arr[i]!=brr[i]: if i not in ind and i-1 not in ind: flag = False break if flag: print("YES") else: print("NO")
true
e87e54f4458b583b98fdbcd306fad6bbbaf47c2e
Python
HuyaneMatsu/hata
/hata/discord/activity/activity_metadata/tests/test__put_assets_into.py
UTF-8
585
2.578125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
permissive
import vampytest from ...activity_assets import ActivityAssets from ..fields import put_assets_into def test__put_assets_into(): """ Tests whether ``put_assets_into`` is working as intended. """ assets = ActivityAssets(image_large = 'hell') for input_value, defaults, expected_output in ( (None, False, {}), (assets, False, {'assets': assets.to_data()}), (assets, True, {'assets': assets.to_data(defaults = True)}), ): data = put_assets_into(input_value, {}, defaults) vampytest.assert_eq(data, expected_output)
true
a8178a3aaf6ad4312ee46e6463ba890b0c1fb8c1
Python
nayeon-hub/daily-python
/baekjoon/#1449.py
UTF-8
215
2.828125
3
[]
no_license
n,l = map(int,input().split()) pipe = sorted(list(map(int,input().split()))) p = pipe[0] cnt = 1 for i in pipe: leng = p+l-1 if i <= leng: continue else: p = i cnt += 1 print(cnt)
true
e892aa0cfe5afaae12a550c13af8b59f55176385
Python
freshklauser/_Repos_HandyNotes
/_FunctionalCodeSnippet/ClassTools/constant.py
UTF-8
686
2.796875
3
[]
no_license
# -*- coding: utf-8 -*- # @Author : Administrator # @DateTime : 2020/6/1 23:20 # @FileName : constant.py # @SoftWare : PyCharm import sys class _Constant: """ 自定义常量类 """ class ConstError(PermissionError): pass class ConstCaseError(ConstError): pass def __setattr__(self, key, value): if key in self.__dict__: raise self.ConstError( "No permission to change a constant {}".format(key)) if not key.isupper(): raise self.ConstCaseError( "Constant {} should be all uppercase.".format(key)) self.__dict__[key] = value sys.modules[__name__] = _Constant()
true
a3e6d5c267a1c161fd93b20903d400c011d85fa3
Python
Bharanij27/bharanirep
/PyproS23.py
UTF-8
246
3.421875
3
[]
no_license
n=input() x=y=z=0 for i in range(0,len(n)): if n[i]=='G': x+=1 elif n[i]=='L': y+=1 else: z+=1 if x%2==0 and ((y%2!=0 and (z==0 or z%2!=0)) or (z%2!=0 and (y==0 or y%2!=0))): print("yes") else: print("no")
true
d4002303c6f1a6f2ecf696a233ef7fe0271b5ff5
Python
jconning/glittercreate
/glitterproj/glitter/glitterasset.py
UTF-8
7,307
2.546875
3
[]
no_license
import random from glitter.assetactor import AssetActor from glitter.models import Asset from glitter.models import AssetType from xml.dom.minidom import getDOMImplementation from xml.dom.minidom import parseString class GlitterAsset(AssetActor): def setUrl(self, url): self.url = url return def setImageFileType(self, imageFileType): self.imageFileType = imageFileType return def setAccessKey(self, accessKey): self.accessKey = accessKey return def generateAccessKey(self): self.accessKey = random.randint(1, 99999) return def setFileSize(self, fileSize): self.fileSize = fileSize return def setWidth(self, width): self.width = width return def setHeight(self, height): self.height = height return def setText(self, text): self.text = text return def setFontName(self, fontName): self.fontName = fontName return def setPointSize(self, pointSize): self.pointSize = pointSize return def setTopBackgroundColor(self, topBackgroundColor): self.topBackgroundColor = topBackgroundColor return def setBottomBackgroundColor(self, bottomBackgroundColor): self.bottomBackgroundColor = bottomBackgroundColor return def setGradientType(self, gradientType): self.gradientType = gradientType return def setFillColor(self, fillColor): self.fillColor = fillColor return def setFillTile(self, fillTile): self.fillTile = fillTile return def setStrokeColor(self, strokeColor): self.strokeColor = strokeColor return def setStrokeWidth(self, strokeWidth): self.strokeWidth = strokeWidth return def setNumBlankLinesAboveText(self, numBlankLinesAboveText): self.numBlankLinesAboveText = numBlankLinesAboveText return def setNumBlankLinesBelowText(self, numBlankLinesBelowText): self.numBlankLinesBelowText = numBlankLinesBelowText return def getAssetType(self): return AssetType.objects.get(asset_type_name='glitter') def getWidth(self): return int(self.width) def getHeight(self): return int(self.height) def getUrl(self): return self.url def getFileName(self): return self.url.split('/')[-1] def getFileSize(self): return int(self.fileSize) def getAccessKey(self): if not self.accessKey: return 0 return int(self.accessKey) def getImageFileType(self): return self.imageFileType def getContentType(self): if self.imageFileType == 'gif': return "image/gif" else: return "unknown" def getText(self): return self.text def getFontName(self): return self.fontName def getPointSize(self): return int(self.pointSize) def getTopBackgroundColor(self): return self.topBackgroundColor def getBottomBackgroundColor(self): return self.bottomBackgroundColor def getGradientType(self): return self.gradientType def getFillColor(self): return self.fillColor def getFillTile(self): return self.fillTile def getStrokeColor(self): return self.strokeColor def getStrokeWidth(self): if not (self.strokeWidth): return 0 return int(self.strokeWidth) def getNumBlankLinesAboveText(self): if not (self.numBlankLinesAboveText): return 0 return int(self.numBlankLinesAboveText) def getNumBlankLinesBelowText(self): if not (self.numBlankLinesBelowText): return 0 return int(self.numBlankLinesBelowText) def marshal(self): if not self.asset: self.asset = Asset( user=self.user, asset_type=self.getAssetType() ) domImpl = getDOMImplementation() doc = domImpl.createDocument(None, "glitterAsset", None) self.addTextElement(doc, 'url', self.url) self.addTextElement(doc, 'imageFileType', self.imageFileType) self.addTextElement(doc, 'accessKey', str(self.accessKey)) self.addTextElement(doc, 'fileSize', str(self.fileSize)) self.addTextElement(doc, 'width', str(self.width)) self.addTextElement(doc, 'height', str(self.height)) self.addTextElement(doc, 'text', self.text) self.addTextElement(doc, 'fontName', self.fontName) self.addTextElement(doc, 'pointSize', str(self.pointSize)) self.addTextElement(doc, 'topBgColor', str(self.topBackgroundColor)) self.addTextElement(doc, 'bottomBgColor', str(self.bottomBackgroundColor)) self.addTextElement(doc, 'gradientType', str(self.gradientType)) self.addTextElement(doc, 'fillColor', str(self.fillColor)) self.addTextElement(doc, 'fillTile', str(self.fillTile)) self.addTextElement(doc, 'strokeColor', str(self.strokeColor)) self.addTextElement(doc, 'strokeWidth', str(self.strokeWidth)) self.addTextElement(doc, 'numBlankLinesAboveText', str(self.numBlankLinesAboveText)) self.addTextElement(doc, 'numBlankLinesBelowText', str(self.numBlankLinesBelowText)) self.asset.state = doc.toxml() return def unmarshal(self): doc = parseString(self.asset.state) self.url = self.getElementValue(doc, 'url') self.imageFileType = self.getElementValue(doc, 'imageFileType') self.accessKey = self.getElementValue(doc, 'accessKey') self.fileSize = self.getElementValue(doc, 'fileSize') self.width = self.getElementValue(doc, 'width') self.height = self.getElementValue(doc, 'height') self.text = self.getElementValue(doc, 'text') self.fontName = self.getElementValue(doc, 'fontName') self.pointSize = self.getElementValue(doc, 'pointSize') self.topBackgroundColor = self.getElementValue(doc, 'topBgColor') self.bottomBackgroundColor = self.getElementValue(doc, 'bottomBgColor') self.gradientType = self.getElementValue(doc, 'gradientType') self.fillColor = self.getElementValue(doc, 'fillColor') self.fillTile = self.getElementValue(doc, 'fillTile') self.strokeColor = self.getElementValue(doc, 'strokeColor') self.strokeWidth = self.getElementValue(doc, 'strokeWidth') self.numBlankLinesAboveText = self.getElementValue(doc, 'numBlankLinesAboveText') self.numBlankLinesBelowText = self.getElementValue(doc, 'numBlankLinesBelowText') return def render(self, assetPlacement, isEdit=False): innerContent = '<img border=0 src="%s">' % (self.url) innerContent += \ '\n<br><a href="/glitter/editglitter/?assetid=%d">edit glitter</a>' % (self.asset.id) innerContent += \ '\n<a href="/glitter/repopublish/?assetid=%d">publish</a>' % (self.asset.id) return AssetActor.render(self, assetPlacement, innerContent, isEdit)
true
ec5a721064f4885948e31fca789b8753bd4fd8a4
Python
jzsampaio/dit-reporter
/ditlib.py
UTF-8
2,160
2.515625
3
[]
no_license
import json from datetime import datetime, timedelta local_tz = datetime.now().astimezone().tzinfo def load_issue(f): with open(f, 'r') as fp: out = json.load(fp) out["properties"]["filename"] = f return out def write_issue(fn, issue): with open(fn, 'w') as fp: json.dump(issue, fp, indent=4, sort_keys=True) with open('.index', 'r') as fp: index = json.load(fp) def parse_duration(td): t = datetime.strptime(td, "%H:%M") return timedelta(hours=t.hour, minutes=t.minute, seconds=0) def parse_time(t): return datetime.strptime(t, "%H:%M") def parse_date(d, infer_year=False): if infer_year: d = datetime.strptime(d, "%m-%d").date() n = datetime.now() return datetime(n.year, d.month, d.day).date() return datetime.strptime(d, "%Y-%m-%d").date() def parse_date_as_datetime(d, infer_year=False): if infer_year: d = datetime.strptime(d, "%m-%d").date() n = datetime.now() return datetime(n.year, d.month, d.day).replace(tzinfo=local_tz) return datetime.strptime(d, "%Y-%m-%d").replace(tzinfo=local_tz) def parse_logbook_time_into_date(d): return datetime.strptime(d, "%Y-%m-%d %H:%M:%S %z").date() def parse_logbook_time_into_time(d): if d: return datetime.strptime(d, "%Y-%m-%d %H:%M:%S %z") return None def date_to_logbook_time(d): return d.strftime("%Y-%m-%d %H:%M:%S %z") def get_time(d): if d: return parse_logbook_time_into_time(d).time().strftime("%H:%M:%S") return "None" def get_day_of_week(d): return d.strftime('%Y-%m-%d - %A') def index_of_needle(key_getter, l, needle): idx=[key_getter(x) for x in l].index(needle) return idx, l[idx] def get_id_of_issue(issue_name): project, sub_project, name=issue_name.split("/") project_idx, project_obj=index_of_needle(lambda x: x[0], index, project) sub_project_idx, sub_project_obj=index_of_needle(lambda x: x[0], project_obj[1], sub_project) name_idx, name_obj=index_of_needle(lambda x: x, sub_project_obj[1], name) return "/".join([str(project_idx), str(sub_project_idx), str(name_idx)])
true
6cbfff7776bf2061d3f19d89425bc1e7cc34137b
Python
xvwvx/python-test
/tmp.py
UTF-8
36
2.890625
3
[]
no_license
for i in range(0, -5): print(i)
true
dddf8305b0fb2466887fa02659c5746afe2f2cf0
Python
taikeung/tf
/cnn/mnist.py
UTF-8
2,687
2.796875
3
[]
no_license
# _*_ coding: utf-8 _*_ ''' Created on 2018年3月22日 卷积神经网络识别mnist @author: hudaqiang ''' from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #忽略烦人的警告 def weight_variable(shape): """ 构建权重矩阵 """ initial = tf.truncated_normal(shape, stddev =1) return tf.Variable(initial) def bias_variable(shape): """ 构建偏置量 """ initial = tf.constant(0.1,shape=shape) return tf.Variable(initial) def conv2d(x,W): return tf.nn.conv2d(x, W, strides = [1,1,1,1], padding = 'SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize = [1,2,2,1], strides = [1,2,2,1], padding = 'SAME') mnist = input_data.read_data_sets('MNIST_data',one_hot = True) sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, [None,784]) y_ = tf.placeholder(tf.float32, [None,10]) x_images = tf.reshape(x, [-1,28,28,1]) #第一个卷积层:卷积核 5 * 5, 1个通道 ,32个卷积核 W_conv1 = weight_variable([5,5,1,32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_images, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) #第二个卷积层: 卷积核 5 * 5,1个通道, 64个卷积核 W_conv2 = weight_variable([5,5,32,64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) h_pool2_flat = tf.reshape(h_pool2, [-1,7 * 7 * 64]) #全连接层 W_fc1 = weight_variable([7 * 7 * 64,1024]) b_fc1 = bias_variable([1024]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1) + b_fc1) #dropout层 keep_prob = tf.placeholder(tf.float32) h_fc1_drop_out = tf.nn.dropout(h_fc1, keep_prob) #softmax层 W_fc2 = weight_variable([1024,10]) b_fc2 = bias_variable([10]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop_out, W_fc2) + b_fc2) #定义loss函数和优化器 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices = [1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #准确率 correct_prediction = tf.equal(tf.argmax(y_,1), tf.argmax(y_conv,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.global_variables_initializer().run() for i in range(2000): batch = mnist.train.next_batch(50) if i % 100 == 0: train_accuracy = accuracy.eval(feed_dict = {x:batch[0],y_:batch[1],keep_prob:1.0}) print('step %d,training accuracy %g' % (i,train_accuracy)) train_step.run(feed_dict = {x:batch[0],y_:batch[1],keep_prob:0.5}) print("final accuracy: %g" % accuracy.eval(feed_dict = {x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))
true
d71b419b5266b18ffe1b28bb23b08396348ce5d4
Python
Nisoka/nan
/machine_learning/base_algorithm/softmax/kmean.py
UTF-8
6,684
3.140625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # K 均值聚类方法 import load_mnist from numpy import * def loadDataSet(fileName): #general function to parse tab -delimited floats numFeat = len(open(fileName).readline().split('\t')) print(numFeat) dataMat = [] #assume last column is target value fr = open(fileName) for line in fr.readlines(): lineArr = [] curLine = line.strip().split('\t') for i in range(numFeat): lineArr.append(float(curLine[i])) dataMat.append(lineArr) return dataMat # 欧氏距离(x1a -x1b)**2 + (xa2 - xb2)**2 .. def distEclud(vecA, vecB): return sqrt(sum(power(vecA - vecB, 2))) ''' >>> from numpy import * >>> k = random.rand(5, 1 >>> k array([[ 0.7078714 ], [ 0.731313 ], [ 0.59188232], [ 0.73207634], [ 0.43258146]]) dataMat = mat([[1, 2, 3], [2, 3, 4]]) dataMat.A = array([[1, 2, 3],[2, 3, 4]]) ''' # 生成K个分类中心点 def randCent(dataSet, k): n = shape(dataSet)[1] centRoids = mat(zeros( (k, n) )) for j in range(n): minJ = min(dataSet[:, j]) rangeJ = float(max(dataSet[:, j]) - minJ) centRoids[:, j] = mat(minJ + rangeJ*random.rand(k, 1)) return centRoids ''' 返回 1 centRoids 聚类结果k行[质心位置] 2 clusterAssment 聚类信息 m行[所属, 到质心距离] ''' def kMeans(dataSet, k, distMeas = distEclud, createCent = randCent): m = shape(dataSet)[0] clusterAssment = mat(zeros((m, 2))) centRoids = createCent(mat(dataSet), k) clusterChanged = True while clusterChanged: clusterChanged = False # iterator all the point and assign it to the closest centRoid # 更新每个点的群属 for i in range(m): minDist = inf minIndex = -1 for j in range(k): distJI = distMeas(centRoids[j, :], dataSet[i, :]) # 查找最小距离群属 if distJI < minDist: minDist = distJI minIndex = j # I点 的群属 发生改变 if clusterAssment[i, 0] != minIndex: clusterChanged = True clusterAssment[i, :] = minIndex, minDist**2 print(centRoids) # 更新每个族 的位置 for cent in range(k): # 获得该族下每个点 ptsInClust = dataSet[nonzero(clusterAssment[:, 0].A == cent)[0]] # 按最低维求均值(矩阵 只有两个维度 这里表示按列 - 即所有point 的对应特征求均值) centRoids[cent, :] = mean(ptsInClust, axis=0) return centRoids, clusterAssment def binKmeans(dataSet, k, distMeas = distEclud): m = shape(dataSet)[0] # 每point [所属,距离] 默认所属 都是0 质心 clusterAssment = mat(zeros((m, 2))) # ??? 直接均值mean 不就是中心了么 ''' axis = 0 按最低维度方向, 列方向 | axis = 1 按次低维度方向, 行方向 -- print(mean(dataSet, axis = 0)) print(centRoid0) 因为 dataSet 是一个 matrix mxn 直接mean 得到的是一个matrix [[-0.10361321 0.0543012 ]] 通过tolist()[0] 得到列表类型 [-0.10361321250000004, 0.05430119999999998] 如果是个list 那么结果就完全不一样了那么不会得到一个 点向量,只会是一个数值. 如果是个ndarray 会和 matrix 类型的结果一样 因为matrix 就是ndarray的继承. ''' # print(type(dataSet)) centRoid0 = mean(dataSet, axis = 0).tolist()[0] # print(mean(dataSet, axis = 0)) # print(mean(dataSet, axis = 0).tolist()) # print(centRoid0) # 此时只有一个分类中心 centRoid0 cenList = [centRoid0] for j in range(m): clusterAssment[j, 1] = distMeas(mat(centRoid0), dataSet[j, :])**2 while len(cenList) < k: lowestSSE = inf # 每个族 进行二分 for i in range(len(cenList)): ptsInCurClust = dataSet[nonzero(clusterAssment[:, 0].A == i)[0], :] # 该族二分后 聚类结果, 聚类信息(- 每point[所属, 距离]) centRoidMat, splitClusAss = kMeans(ptsInClust, 2, distMeas) #calc the SSE of 当前族 当前聚类方案的 SSE 误差平方和 sseSplit = sum(splitClusAss[:, 1]) #calc the SSE of 非当前族 的SSE误差平方和 sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:, 0].A != i)[0], 1]) # bestCentToSplit 二分后SSE最好的当前类ID # bestNewCents 二分聚类结果 # bestClusAss 二分聚类结果信息 # lowestSSE 当前的SSE 误差平方和 if (sseSplit + sseNotSplit) < lowestSSE: bestCentToSplit = i bestNewCents = centRoidMat bestClusAss = splitClusAss.copy() lowestSSE = sseSplit + sseNotSplit ''' bestClusAss[:, 0] 第一列 bestClusAss[:, 0].A 第一列变为Array类型 bestClusAss[:, 0].A == 1 新的Array 做 == 1比较 筛选构成 true false的Array nonzero(bestClusAss[:, 0].A == 1)[0] nonzero() 返回生成的trueFalseArray中的True构成的array,内容是 [array, type] 所以 nonzero()[0] 得到array. 描述 bestClusAss[:, 0].A == 1条件的array bestClusAss[array, 0] ==> 返回了bestClusAss 中 bestClusAss[:, 0].A == 1 的数据子集. ''' # bestClusAss 原bestCentToSplit 需要二分类的族数据 二分后结果信息 # 执行二分类 将聚类结果信息中 分为0类的 其类别ID 不变还用原本bestCentToSplit # 分为1 类的 其类别ID 在原类别总数上增加1,作为其类别 bestClusAss[nonzero(bestClusAss[:, 0].A == 1)[0], 0] = len(cenList) bestClusAss[nonzero(bestClusAss[:, 0].A == 0)[0], 0] = bestCentToSplit print("the bestCentToSplit is %d" %bestCentToSplit) cenList[bestCentToSplit] = bestNewCents[0, :].tolist()[0] cenList.append(bestNewCents[1, :].tolist()[0]) #reassign new clusters, and SSE clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],:] \ = bestClustAss return mat(cenList), clusterAssment def main(): dataSet, labels = load_mnist.loadDataSet("trainingDigits") centerMat, clusterAsg = binKmeans(mat(dataSet), 10) def easyToUse(): dataMat = mat(loadDataSet('testSet.txt')) binKmeans(dataMat, 1) if __name__ == "__main__": easyToUse()
true
56112b3bcd59b39898f0ffe1b9bfc0bd1783da3e
Python
marikelo12/geekbrains_python
/lesson_8/hw_8_4.py
UTF-8
2,780
3.1875
3
[]
no_license
from abc import abstractmethod, ABC class Technics(ABC): def __init__(self, model, serial_no): self.model = model self.serial_no = serial_no self.department = None def _set_department(self, department): self.department = department @abstractmethod def __call__(self, data): pass @abstractmethod def __str__(self): pass class Printer(Technics): def print_smth(self, data: str): return f'Printer model {self.model} s/n {self.serial_no} printed {data}' def __call__(self, data): self.print_smth(data) def __str__(self): return f'Printer model {self.model} s/n {self.serial_no}' class Xerox(Technics): def copy_smth(self, data: str): return f'Xerox model {self.model} s/n {self.serial_no} copied {data}' def __call__(self, data): self.copy_smth(data) def __str__(self): return f'Xerox model {self.model} s/n {self.serial_no}' class Scanner(Technics): def scan_smth(self, data: str): return f'Scanner model {self.model} s/n {self.serial_no} scanned {data}' def __call__(self, data): self.scan_smth(data) def __str__(self): return f'Scanner model {self.model} s/n {self.serial_no}' class Warehouse: def __init__(self, max_volume): self.max_volume = max_volume self.storage = { "scanners": set(), "xeroxes": set(), "printers": set() } self.add_mapper = {Scanner: "scanners", Printer: "printers", Xerox: "xeroxes"} self.total = 0 def get_several_tecs_to_warehouse(self, num: int, tech_list): if type(num) != int: raise ValueError("Введите число!") for tech in tech_list[:num]: self.get_several_tecs_to_warehouse(tech) def get_tech_to_warehouse(self, technics: Technics): if self.total == self.max_volume: raise OverflowError("Склад заполнен до отказа!") self.storage[self.add_mapper[type(technics)]].add(technics) technics._set_department("warehouse") self.total += 1 def get_tech_to_departament(self, tech_type, department): tech_to_dept = self.storage[tech_type].pop() tech_to_dept._set_department(department) self.total -= 1 def __call__(self, *args, **kwargs): self.get_tech_to_warehouse(*args, **kwargs) def __str__(self): return f'Warehouse max capacity {self.max_volume} current {self.total} ' printer = Printer(1, 2) printer_2 = Printer(1, 3) scanner = Scanner(2, 3) scanner_2 = Scanner(2, 5) warehouse = Warehouse(10) warehouse.get_tech_to_warehouse(printer) warehouse.get_tech_to_departament("printers", "service")
true
3e6780e11f2af8d1019bc6ce9f3878d5ee6f9dda
Python
DevinLayneShirley/Intro_Biocomp_ND_318_Tutorial5
/analysis5.py
UTF-8
2,534
3.515625
4
[]
no_license
##### Python Script for Ex 5 # Biocomputing - 9/22/17 # Brittni Bertolet and Devin Shirley ======= # Script for Ex 5 CHALLENGE #Task 1 (Brittni) #SET WORKING DIRECTORY WITH 'wages.csv' INSIDE FOR FOLLOWING CODE TO WORK # For Brittni: os.chdir('/Users/brittnibertolet/Desktop/Intro_Biocomp_ND_318_Tutorial5/') # Read in the data set import pandas as pd data = pd.read_csv("wages.csv") # Sort the data by gender first, then yearsExperience data = data.sort_values(by = ['gender', 'yearsExperience']) # Drop the other columns that we don't care about data = data.iloc[:,0:2] # Remove duplicates data = data.drop_duplicates(subset=['gender', 'yearsExperience']) # Write file data.to_csv("uniqueGenderExperience.txt", sep=" ", index=False) #Task 2 (devin) #Part1: gender, yearsExperience, and wage for the highest earner #add data again because 'data' dataframe now only contains gender/experience combo wages= pd.read_csv("wages.csv") #sort by wage wagesSorted=wages.sort_values(['wage'], ascending=False) highest_earner=wagesSorted.head(1) highest_earner #need to remove yearsSchool print("Highest Earner Info:", highest_earner[['gender','yearsExperience','wage']]) #Part2: gender, yearsExerience, and wage for the lowest earner #use the already sorted dataframe lowest_earner=wagesSorted.tail(1) lowest_earner #need to remove yearsSchool print("Lowest Earner Info:", lowest_earner[['gender','yearsExperience','wage']]) #Part3: number of females in the top ten earners in this dataset #use the already sorted dataframe topTenEarners=wagesSorted.head(10) topTenEarnersFemale=topTenEarners[topTenEarners.gender=="female"] numberTopTenEarnersFemale=topTenEarnersFemale.shape#the first value in the tuple print("Number of females in the top ten earners:",numberTopTenEarnersFemale[0]) #Task 3 (together) #add numpy so we can math... import numpy as np #'wages' dataframe is still unaltered and can be used again #first we want non-college graduates' average minimum wages schoolTwelve=wages[wages.yearsSchool==12] NoCollegeMinimum=np.average(schoolTwelve.wage) #second we want college graduates' average minimum wages schoolSixteen=wages[wages.yearsSchool==16] CollegeMinimum=np.average(schoolSixteen.wage) print("Minimum Starting Wage For Individuals with No College:",NoCollegeMinimum,"Minimum Starting Wage for Individuals with College:",CollegeMinimum) #take the difference between the two groups Difference=np.subtract(CollegeMinimum, NoCollegeMinimum) print("Difference in Starting Wage Between College Graduates and Not:", Difference)
true
009f3a4e9409c44a18776923ffe178f9d8a42dab
Python
dijx/python-simple-games
/war_card_game/war_game.py
UTF-8
2,429
3.5625
4
[]
no_license
from war import classlib import time play_game = 'y' while play_game == 'y': new_game = None prisoners = -1 print('\n'*5) print('================= NEW GAME =================') while new_game not in ['y', 'n']: new_game = input('Play new game? (y/n): ').lower() if new_game == 'n': play_game = 'n' break else: while prisoners not in range(0,10): try: prisoners = int(input('prisoners of war? (0 - 10): ')) except Exception as err: print('Error occured: %s'%err) new_deck = classlib.Deck() player_1 = classlib.Player("Player 1") player_2 = classlib.Player("Player 2") new_table = classlib.Table() new_deck.shuffle() hands = new_deck.deal_cards() player_1.hand = hands[0] player_2.hand = hands[1] #print(player_1, player_2, new_deck) #print(len(new_deck)) #player_1.print_hand() #player_2.print_hand() while len(player_1.hand) > 0 and len(player_2.hand) > 0: print("New deal") print(player_1, player_2) if len(new_table.player_1) > 0: print('WAR: the table is:') print(new_table) print('Now battle begins!!!') new_table.add_card(player_1.deal_card(), 1) new_table.add_card(player_2.deal_card(), 2) new_table.print_last_deal() winner = new_table.check_winner() if winner == 0: print("WAR!") print('Betting %s cards as prisoners' % prisoners) for f in range(0,prisoners): new_table.add_card(player_1.deal_card(), 1) new_table.add_card(player_2.deal_card(), 2) #new_table.print_last_deal() #time.sleep(2) if winner == 1: player_1.add_cards(new_table.return_cards()) if winner == 2: player_2.add_cards(new_table.return_cards()) for player in [player_1, player_2]: if len(player.hand) > 0: print("Winner is %s, another player out of cards!"%player.name)
true
1498aa325e50aaf0d1b713d2b00cbffa88023dc7
Python
iarmankhan/Software-Engineering
/Python/hasPairWithSum.py
UTF-8
486
3.65625
4
[]
no_license
# Naive solution def hasPairWithSumNaive(arr, sumX): for i in range(0, len(arr)): for j in range(i+1, len(arr)): if arr[i] + arr[j] == sumX: return True return False def hasPairWithSumBetter(arr, sumX): mySet = {} for i in range(len(arr)): if arr[i] in mySet: return True mySet[sumX - arr[i]] = True return False arr = [1, 2, 9, 8, 5, 3, 363] sumX = 8 print(hasPairWithSumBetter(arr, sumX))
true
d584b7c00887a1e83bf22ea9ab001cf1f028edfc
Python
niteesh2268/coding-prepation
/leetcode/Problems/1590--Make-Sum-Divisible-by-P-Medium.py
UTF-8
626
2.84375
3
[]
no_license
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: sumVals = {0: -1} for i in range(len(nums)): nums[i] = nums[i]%p totSum = sum(nums)%p if totSum == 0: return 0 remSum = 0 answer = len(nums) for i in range(len(nums)): remSum = (remSum+nums[i])%p val = totSum if (remSum-totSum)%p in sumVals: answer = min(answer, i-sumVals[(remSum-totSum)%p]) sumVals[remSum] = i if answer == len(nums): return -1 return answer
true
106269e4efb8661c24196891c4d32389c39080e2
Python
joh47/python-hello-world
/hello.py
UTF-8
612
4.34375
4
[]
no_license
from random import randrange text = input("Guess a number from 1 to 10. \n") if(not text.isdigit()): print("You did not enter a digit.") exit() elif(not int(text) >= 1): print ("Your digit was not at least 1.") exit() elif(not (int(text) <= 10)): print ("Your digit was not smaller than 10.") exit() else: print("That was a digit between 1 and 10") print("Your guess is " + text) random_number = randrange(10) + 1 print("My guess was " + str(random_number)) if(random_number == int(text)): print("Hey rockstar! You got it!") else: print("Oops - better luck next time!")
true
87997d8d6aac02d3908aabd6bb780cd3ef23cd77
Python
maitrongnhan001/Learn-Python
/B3/function_arguments.py
UTF-8
132
2.859375
3
[]
no_license
def func( a, b = 5, c = 10) : print('a is: ', a, ', b is: ', b, ', c is: ', c) func(3, 7) func(25, c = 24) func(c = 25, a = 100)
true
a55166e80efde67845b732cea429b7e5c5ba41c6
Python
SamuelHaidu/pymusicsearch
/pyms.py
UTF-8
7,826
2.734375
3
[ "MIT" ]
permissive
__version__ = "0.2.0" __author__ = "Samuel Haidu" __license__ = "MIT" ''' Module for search music videos in youtube.com and get info in discogs.com You can: -Search videos and artists in youtube -Get the top100 in youtube music -Make a artist search in Discogs -Get the albuns of artist(listed in Discogs from url) -Get the tracks of album(listed in Discogs from url) BASED IN HTTP REQUEST, its not a api. If the sites change your webpage format the script can't work ''' from bs4 import BeautifulSoup import requests PARSER = 'html.parser' def YTSearchVideos(query): '''Search youtube videos and return the title, url, channel, thumbnail and duration of video''' query = query.replace(' ', '+') webdata = requests.get('http://www.youtube.com/results?q='+query+'&sp=EgIQAVAU', verify='cacert.pem').text soupdata = BeautifulSoup(webdata, PARSER) VideoList = [] for link in soupdata.findAll(attrs={'class':'yt-lockup-tile'}): # Get info from HTML tags if link.find('a').get('href')[0:36] == 'https://googleads.g.doubleclick.net/':continue videolink = 'https://www.youtube.com' + link.find('a').get('href') videotitle = link.find(attrs={'class':'yt-lockup-title'}).find('a').get('title') try: videoduration = link.find(attrs={'class':'yt-lockup-title'}).find('span').text[3:-1] videoduration = videoduration.split()[1] except:videoduration = '00:00' try:thumbnailurl = link.find(attrs={'class':'yt-thumb-simple'}).find('img').get('src') except:thumbnailurl = '' try:channelname = link.find(attrs={'class':'yt-lockup-byline'}).find('a').text except:channelname = '' try: channelurl = 'https://www.youtube.com' + link.find(attrs={'class':'yt-lockup-byline'}).find('a').get('href') except: channelurl = '' VideoList.append({'title': videotitle, 'link': videolink, 'duration': videoduration, 'channelname': channelname, 'channelurl': channelurl, 'thumbnail': thumbnailurl}) return VideoList def YTSearchMusicOfArtist(query): ''' Get the most famous music of artist from yotube if not found returns VideoList = []''' query = query.replace(' ', '+') webdata = requests.get("http://www.youtube.com/results?search_query=" + query, verify='cacert.pem').text soupdata = BeautifulSoup(webdata, PARSER) VideoList = [] try: for link in soupdata.findAll(attrs={'class':'watch-card'})[0].findAll(attrs={'class':'watch-card-main-col'}): videolink = 'http://www.youtube.com/' + link.find('a').get('href')[:21] videotitle = link.get('title') VideoList.append({'title':videotitle, 'link':videolink}) return VideoList except: return VideoList def getYTMusicTop(): ''' Get the top 100 music on youtube ''' playlisturl = "http://www.youtube.com/playlist?list=PLFgquLnL59alcyTM2lkWJU34KtfPXQDaX" webdata = requests.get(playlisturl, verify='cacert.pem').text soupdata = BeautifulSoup(webdata, PARSER) VideoList = [] for link in soupdata.findAll(attrs={'class':'pl-video'}): # Get info from HTML tags videotitle = link.get('data-title') videolink = 'http://www.youtube.com/watch?v=' + link.get('data-video-id') videoduration = link.find(attrs={'class':'timestamp'}).text thumbnailurl = link.find(attrs={'class':'yt-thumb-clip'}).find('img').get('data-thumb') VideoList.append({'title': videotitle, 'link': videolink, 'duration': videoduration, 'thumbnail': thumbnailurl}) return VideoList def artistSearch(query,limit=5): ''' Search artists in discogs.com and return name, image url and url of artist ''' query = query.replace(' ', '+') webdata = requests.get("http://www.discogs.com/search/?q=" + query + "&type=artist", verify='cacert.pem').text soupdata = BeautifulSoup(webdata, PARSER) artists = [] countlimit = 0 for link in soupdata.findAll(attrs={'class':'card'}): # Get info from HTML tags url = 'http://www.discogs.com' + link.find('a').get('href') name = link.find('h4').find('a').get('title') imageurl = link.find('img').get('data-src') artists.append({'name': name, 'url': url, 'image': imageurl}) countlimit += 1 if countlimit == limit:break return artists def getAlbunsFromArtist(artisturl): ''' Set the artist url from discogs and return the master albuns from artist ''' webdata = requests.get(artisturl, verify='cacert.pem').text soupdata = BeautifulSoup(webdata, PARSER) albuns = [] # Filter tags with have the class = card and master for link in soupdata.findAll(attrs={'class':'card','class': 'master'}): # Get info from HTML tags name = link.find(attrs = {'class': 'title'}).find('a').text url = 'http://www.discogs.com' + link.find(attrs = {'class': 'image'}).find('a').get('href') artistname = link.find(attrs = {'class': 'artist'}).find('a').text image = link.find(attrs = {'class': 'thumbnail_center'}).find('img').get('data-src') year = link.find(attrs = {'class': 'year'}).text country = link.find(attrs = {'class': 'country'}).find('span').text recorderlistHTML = link.find(attrs = {'class': 'label'}).findAll('a') # Get a list of HTML tags with recorders info recorders = '' for i in recorderlistHTML: recorders = recorders + i.text + ", " # Make a list of dict with the albuns in discogs page albuns.append({'name': name, 'url': url, 'artistname': artistname, 'image': image, 'year':year, 'country': country, 'recorder': recorders}) return albuns def getTracksFromAlbum(albumurl): ''' Set the album url from discogs and return the complete info from album ''' webdata = requests.get(albumurl, verify='cacert.pem').text soupdata = BeautifulSoup(webdata, PARSER) tracks = [] # Filter tag with have the class = playlist and after find tags that have class = tackslist_track soupdataPlaylist = soupdata.find(attrs = {'class': 'playlist'}).findAll(attrs = {'class': 'tracklist_track'}) # This loop gets the tacklist for link in soupdataPlaylist: tracknum = link.get('data-track-position') name = link.find(attrs = {'class': 'tracklist_track_title'}).text duration = link.find(attrs = {'class': 'tracklist_track_duration'}).find('span').text # Create a list of dict with name of track, number and duration tracks.append({'name': name, 'tracknum': tracknum, 'duration': duration}) genlist = soupdata.find(attrs={'class': 'profile'}).findAll(attrs={'itemprop': 'genre'})[0].findAll('a') stylelist = soupdata.find(attrs={'class': 'profile'}).findAll(attrs={'class': 'content'})[1].findAll('a') generes = '' styles = '' for i in genlist: generes = generes + i.text + ', ' for i in stylelist: styles = styles + i.text + ', ' albumgenre = generes albumstyle = styles albumname = soupdata.find(attrs={'class': 'profile'}).find('h1').findAll('span')[1].find('a').text albumartist = soupdata.find(attrs={'class': 'profile'}).find('h1').find('span').find('span').get('title') albumyear = soupdata.find(attrs={'class': 'profile'}).findAll(attrs={'class': 'content'})[2].findAll('a')[0].text coverurl = soupdata.find(attrs={'class': 'thumbnail_center'}).find('img').get('src') tracks.append({'genre':albumgenre, 'style':albumstyle, 'albumname': albumname, 'year': albumyear, 'cover': coverurl}) # Create the last dict, with all info of album return tracks
true
5c2616d1d6e6c50afc3b5bf9c8cf4133071b598b
Python
walker8088/easyworld
/EasyPython/wax/examples/dragdrop-2.py
UTF-8
3,697
3.21875
3
[]
no_license
# dragdrop-2.py # Demonstrates giving DnD capabilities to controls and # how to use the Clipboard # # Original by Jason Gedge. Modifications by Hans Nowak. from wax import * # One way to use *DropTargets is to override OnDropFiles or OnDropText. class MyFileDropTarget(FileDropTarget): def OnDropFiles(self, x, y, files): tb = self.window.tb tb.AppendText('Received:\n') for file in files: tb.AppendText(' - ') tb.AppendText(file.strip()) tb.AppendText('\n') class MyTextDropTarget(TextDropTarget): def OnDropText(self, x, y, text): tb = self.window.tb res, row, col = tb.HitTest((x, y)) tb.InsertText(tb.XYToPosition(row, col), text) def OnDragOver(self, x, y, d): row, col, tb = 0, 0, self.window.tb res, row, col = tb.HitTest((x, y)) tb.SetInsertionPoint(tb.XYToPosition(row, col)) return TextDropTarget.OnDragOver(self, x, y, d) class URLDropPanel(VerticalPanel): def __init__(self, *args, **kwargs): VerticalPanel.__init__(self, *args, **kwargs) lbl = Label(self, text='Drag a URL to the window below to load that URL') # Another way to use *DropTarget is to pass in an event. td = URLDropTarget(self, event=self.LoadURL) self.htmlwin = HTMLWindow(self) self.AddComponent(lbl, expand='h', border=5) self.AddComponent(self.htmlwin, expand='both', border=5) self.Pack() def LoadURL(self, x, y, d, url): print "** Loading:", url self.htmlwin.LoadPage(url) def tb_OnChar(self, event=None): pass class FileDropPanel(VerticalPanel): def __init__(self, *args, **kwargs): VerticalPanel.__init__(self, *args, **kwargs) lbl = Label(self, text='Drag some files into the box below') td = MyFileDropTarget(self) self.tb = TextBox(self, size=(300,300), multiline=1, hscroll=1) self.tb.OnChar = self.tb_OnChar self.AddComponent(lbl, expand='h', border=5) self.AddComponent(self.tb, expand='both', border=5) self.Pack() def tb_OnChar(self, event=None): pass class TextDropPanel(VerticalPanel): def __init__(self, *args, **kwargs): VerticalPanel.__init__(self, *args, **kwargs) lbl = Label(self, text='Type some text below and then\ndrag some other text into it!') td = MyTextDropTarget(self) self.tb = TextBox(self, size=(300,300), multiline=1) btn_copy = Button(self, text='Copy Text From Above', event=self.copy_OnClick) btn_paste = Button(self, text='Paste Text From Above', event=self.paste_OnClick) self.AddComponent(lbl, expand='h', border=5) self.AddComponent(self.tb, expand='both', border=5) self.AddComponent(btn_copy, expand='h', border=2) self.AddComponent(btn_paste, expand='h', border=2) self.Pack() def copy_OnClick(self, event=None): Clipboard.SetText(self.tb.GetStringSelection()) def paste_OnClick(self, event=None): cliptext = Clipboard.GetText() if cliptext != "": sel = self.tb.GetSelection() self.tb.Replace(sel[0], sel[1], cliptext) class MainFrame(Frame): def Body(self): nb = NoteBook(self, size=(300,300)) p1 = TextDropPanel(nb) p2 = FileDropPanel(nb) p3 = URLDropPanel(nb) nb.AddPage(p1, 'Text') nb.AddPage(p2, 'File') nb.AddPage(p3, 'Text (URL)') self.AddComponent(nb, expand='both') self.Pack() if __name__ == "__main__": app = Application(MainFrame, title='Drag/Drop Example') app.Run()
true
627e613357b18f06603ce5ca3c7db4c318e9ae33
Python
sakbayeme2014/client_server
/client_transfer.py
UTF-8
810
2.953125
3
[]
no_license
#!/usr/bin/env python import socket import sys if len(sys.argv) <=1: print "Usage : client_transfer.py <ip address> <file to receiving>" print "Usage : client_transfer.py <localhost> </var/receive.txt>" exit() nbytes = 4096 def client_transfer(): host = sys.argv[1] port = 50000 socket_object = socket.socket(socket.AF_INET , socket.SOCK_STREAM) socket_object.connect((host , port)) socket_object.send("hi server") file_object = open(sys.argv[2], "wb") print "file open" while True: print ("receiving data ...") info_object = socket_object.recv(nbytes) print ("info_object = %s" , (info_object)) if not info_object: break file_object.write(info_object) file_object.close() print ("Successfully get the file") socket_object.close() print("Connection close") client_transfer()
true
8bf9cdb850f42cc07ceda36f5a30068b49d63611
Python
LunaBlack/DecisionTree
/secondTest/trees.py
UTF-8
3,646
3.09375
3
[]
no_license
#!/usr/bin/env python # -*- coding: UTF-8 -*- # 代码来源:http://www.cnblogs.com/hantan2008/archive/2015/07/27/4674097.html # 该代码实现了决策树算法分类(ID3算法) # 该文件是ID3决策树算法的相关操作 from math import log import operator #计算给定数据集的香农熵 def calcShannonEnt(dataSet): numEntries = len(dataSet) labelCounts = {} for featVec in dataSet: currentLabel = featVec[-1] if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0 labelCounts[currentLabel] += 1 shannonEnt = 0.0 for key in labelCounts: prob = float(labelCounts[key])/numEntries shannonEnt -= prob*log(prob,2) return shannonEnt #按照给定特征划分数据集 #dataSet:待划分的数据集 #axis:划分数据集的特征--数据的第几列 #value:需要返回的特征值 def splitDataSet(dataSet, axis, value): retDataSet = [] for featVec in dataSet: if featVec[axis] == value: reducedFeatVec = featVec[:axis] #获取从第0列到特征列的数据 reducedFeatVec.extend(featVec[axis+1:]) #获取从特征列之后的数据 retDataSet.append(reducedFeatVec) return retDataSet #选择最好的数据集划分方式 def chooseBestFeatureToSplit(dataSet): numFeatures = len(dataSet[0])-1 baseEntropy = calcShannonEnt(dataSet) bestInfoGain = 0.0;bestFeature = -1 for i in range(numFeatures): featList = [example[i] for example in dataSet] uniqueVals = set(featList) newEntroy = 0.0 for value in uniqueVals: subDataSet = splitDataSet(dataSet, i, value) prop = len(subDataSet)/float(len(dataSet)) newEntroy += prop * calcShannonEnt(subDataSet) infoGain = baseEntropy - newEntroy if(infoGain > bestInfoGain): bestInfoGain = infoGain bestFeature = i return bestFeature #该函数用于找出出现次数最多的分类名称 def majorityCnt(classList): classCount = {} for vote in classList: if vote not in classCount.keys():classCount[vote] = 0 classCount[vote] += 1 sortedClassCount = sorted(classList.iteritems(), key=operator.itemgetter(1), reverse=True) #利用operator操作键值排序字典 return sortedClassCount[0][0] #创建树的函数 def createTree(dataSet,labels): classList = [example[-1] for example in dataSet] if classList.count(classList[0]) == len(classList): return classList[0] if len(dataSet[0]) == 1: return majorityCnt(classList) bestFeat = chooseBestFeatureToSplit(dataSet) bestFeatLabel = labels[bestFeat] myTree = {bestFeatLabel:{}} del(labels[bestFeat]) featValues = [example[bestFeat] for example in dataSet] uniqueVals = set(featValues) for value in uniqueVals: subLabels = labels[:] myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels) return myTree #创建数据集 def createDataSetFromTXT(filename): dataSet = [] labels = [] fr = open(filename) linenumber = 0 for line in fr.readlines(): line = line.strip() listFromLine = line.strip().split() lineset = [] for cel in listFromLine: lineset.append(cel) if(linenumber==0): labels=lineset else: dataSet.append(lineset) linenumber = linenumber+1 return dataSet,labels
true
f0d927de5b424295e6dca266439c3343a0aa172e
Python
AMANKANOJIYA/HacktoberFest2021
/Contributors/Aman Kanojiya/Hello.py
UTF-8
190
2.703125
3
[ "MIT" ]
permissive
print("Hello World !") print("I am Aman Kanojiya") print("I am From India") print("I am 2nd Year Student at IIT Dhanbad.") print("Email : aman.kanojiya4203@gmail.com") print("Github : https://github.com/AMANKANOJIYA")
true
49fd2519f1be9a2baf7384032451fe68b7599480
Python
crazyfables/Academics
/Python/New Scripts/myflask.py
UTF-8
410
2.65625
3
[]
no_license
""" By: Jessica Angela Campisi Date: 10/30/2019 Purpose: Create a web service that displays a chuck norris quote in html """ from flask import Flask from thechuck import get_chuck from mystory import Story app = Flask(__name__) @app.route('/') def home(): #return "<h1> {} </h1>".format(get_chuck()) myStory = Story() return myStory.returnStory() if __name__ == "__main__": app.run(debug=True, port=8080)
true
a24f4686d107e0711239764dbda4dd615602f99c
Python
fancy84machine/Python
/Projects/Supervised Learning/Diabetes+Machine+Learning+Pipeline.py
UTF-8
975
2.953125
3
[]
no_license
# coding: utf-8 # In[5]: import pandas as pd import numpy as np from sklearn.pipeline import Pipeline from sklearn.preprocessing import Imputer from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt df = pd.read_csv ('diabetes.csv') df.info() # In[6]: X = df.drop('diabetes', axis=1) y = df['diabetes'] # In[7]: #Imputing within a pipeline imp = Imputer (missing_values = 'NaN', strategy = 'mean', axis=0) logreg = LogisticRegression() steps = [('imputation', imp), ('logistic_regression', logreg)] pipeline = Pipeline (steps) X_train, X_test, y_train, y_test = train_test_split (X, y, test_size = 0.3, random_state = 42) pipeline.fit (X_train, y_train) y_pred = pipeline.predict (X_test) pipeline.score (X_test, y_test)
true
dbd63814376d7fed81b8beb1ecace1d6f293816f
Python
mail2manish/Blockchain-Based-Secure-billing-For-Hospitals-using-Python
/cam.py
UTF-8
2,600
2.703125
3
[]
no_license
from tkinter import* from PIL import Image,ImageTk import cv2 from tkinter import ttk,messagebox import os import sys win = Tk() #code for tkinter window in centre in screen window_width,window_height = 600,310 screen_width = win.winfo_screenwidth() screen_height = win.winfo_screenheight() position_top = int(screen_height / 2.2 - window_height / 2) position_right = int(screen_width / 2 - window_width / 2) win.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}') win.configure(bg ='#1b407a') canvas = Canvas( win, bg = "#0074bd", height = 310, width = 600, bd = 0, highlightthickness = 0, relief = "ridge") canvas.place(x = 0, y = 0) background_img = PhotoImage(file = f"patient_images/backgroundcam.png") background = canvas.create_image( 300.5, 122.0, image=background_img) img0 = PhotoImage(file = f"patient_images/imgcap.png") b0 = Button( image = img0, borderwidth = 0, highlightthickness = 0, command = lambda: take_copy(rgb), relief = "flat") b0.place( x = 108, y = 252, width = 105, height = 45) img1 = PhotoImage(file = f"patient_images/imgsave.png") b1 = Button( image = img1, borderwidth = 0, highlightthickness = 0, command = lambda : Save(), relief = "flat") b1.place( x = 403, y = 252, width = 105, height = 45) color = "red" color1 = "black" frame_1 = Frame(win,width = 240,height =190,bg = color).place(x=41,y=54) frame_2 = Frame(win,width = 240,height =190,bg = color1).place(x=320,y=54) v = Label(frame_1, width=240, height=190) v.place(x=41, y=54) print (sys.argv[1]) def take_copy(im): la = Label(frame_2, width=240, height=190) la.place(x=320, y=54) copy = im.copy() copy = cv2.resize(copy, (250, 250)) rgb = cv2.cvtColor(copy, cv2.COLOR_BGR2RGB) image = Image.fromarray(copy) imgtk = ImageTk.PhotoImage(image) image.save('patient_photo/{}.jpg'.format(sys.argv[1])) la.configure(image=imgtk) la.image = imgtk def select_img(): global rgb _, img = cap.read() img = cv2.resize(img, (250, 250)) rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image = Image.fromarray(rgb) imgtk = ImageTk.PhotoImage(image) v.configure(image=imgtk) v.image = imgtk v.after(10, select_img) def Save(): image = Image.fromarray(rgb) messagebox.showinfo("SUCCESS","Image Saved Successfully...!",parent=win) cap = cv2.VideoCapture(0) select_img() win.mainloop()
true
237a0d72903501dde1a91c5b4f3de7fb5e83bc7c
Python
ilshadrin/exel
/exel.py
UTF-8
1,418
3.609375
4
[]
no_license
''' читаем из файла data_1 данные и записываем их в эксель ''' import csv from openpyxl import Workbook def read_csv(filename): data=[] with open(filename, 'r', encoding='utf-8') as f: fields=['Stantion', 'street'] reader = csv.DictReader(f, fields, delimiter=',') for row in reader: data.append(row) return data def excel_write(data): workbook = Workbook() worksheet = workbook.active worksheet.title = "TestTestTest" # Задаем заголовок worksheet.cell(row=1, column=1).value='Станция' #заполняем лист значениями. cell - ячейка, row - строка, column - колонка. value - знаение, =Станция - значение 1ой яейки worksheet.cell(row=1, column=2).value='Улица' # Улица - значение второй ячейки row=2 for item in data: # записываем данные из файла data_1 в эксель с помощью цикла worksheet.cell(row=row, column=1).value=item['Stantion'] #ключи словаря fields worksheet.cell(row=row, column=2).value=item['street'] row+= 1 workbook.save('ExelTest.xlsx') # создаем эксель файл csv_data=read_csv('data_1.csv') excel_write(csv_data)
true
06db8f279bf359e5b30a6b60fce98a7c53e244f7
Python
hanntonkin/opty
/examples/pendulum_swing_up.py
UTF-8
3,373
3
3
[ "BSD-2-Clause" ]
permissive
"""This solves the simple pendulum swing up problem presented here: http://hmc.csuohio.edu/resources/human-motion-seminar-jan-23-2014 A simple pendulum is controlled by a torque at its joint. The goal is to swing the pendulum from its rest equilibrium to a target angle by minimizing the energy used to do so. """ from collections import OrderedDict import numpy as np import sympy as sym from opty.direct_collocation import Problem from opty.utils import building_docs import matplotlib.pyplot as plt import matplotlib.animation as animation target_angle = np.pi duration = 10.0 num_nodes = 500 save_animation = False interval_value = duration / (num_nodes - 1) # Symbolic equations of motion I, m, g, d, t = sym.symbols('I, m, g, d, t') theta, omega, T = sym.symbols('theta, omega, T', cls=sym.Function) state_symbols = (theta(t), omega(t)) constant_symbols = (I, m, g, d) specified_symbols = (T(t),) eom = sym.Matrix([theta(t).diff() - omega(t), I * omega(t).diff() + m * g * d * sym.sin(theta(t)) - T(t)]) # Specify the known system parameters. par_map = OrderedDict() par_map[I] = 1.0 par_map[m] = 1.0 par_map[g] = 9.81 par_map[d] = 1.0 # Specify the objective function and it's gradient. def obj(free): """Minimize the sum of the squares of the control torque.""" T = free[2 * num_nodes:] return interval_value * np.sum(T**2) def obj_grad(free): grad = np.zeros_like(free) grad[2 * num_nodes:] = 2.0 * interval_value * free[2 * num_nodes:] return grad # Specify the symbolic instance constraints, i.e. initial and end # conditions. instance_constraints = (theta(0.0), theta(duration) - target_angle, omega(0.0), omega(duration)) # Create an optimization problem. prob = Problem(obj, obj_grad, eom, state_symbols, num_nodes, interval_value, known_parameter_map=par_map, instance_constraints=instance_constraints, bounds={T(t): (-2.0, 2.0)}) # Use a random positive initial guess. initial_guess = np.random.randn(prob.num_free) # Find the optimal solution. solution, info = prob.solve(initial_guess) # Make some plots prob.plot_trajectories(solution) prob.plot_constraint_violations(solution) prob.plot_objective_value() # Display animation if not building_docs(): time = np.linspace(0.0, duration, num=num_nodes) angle = solution[:num_nodes] fig = plt.figure() ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2)) ax.grid() line, = ax.plot([], [], 'o-', lw=2) time_template = 'time = {:0.1f}s' time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) def init(): line.set_data([], []) time_text.set_text('') return line, time_text def animate(i): x = [0, par_map[d] * np.sin(angle[i])] y = [0, -par_map[d] * np.cos(angle[i])] line.set_data(x, y) time_text.set_text(time_template.format(i * interval_value)) return line, time_text ani = animation.FuncAnimation(fig, animate, np.arange(1, len(time)), interval=25, blit=True, init_func=init) if save_animation: ani.save('pendulum_swing_up.mp4', writer='ffmpeg', fps=1 / interval_value) plt.show()
true
c7cd71bf36faccf0f5c0a627b337667731cd13f1
Python
sudhanshu-jha/python
/python3/Python-algorithm/Hard/wordTransformer/wordTransformer_test.py
UTF-8
309
2.90625
3
[]
no_license
from wordTransformer import transform import pytest def test_wordTransformer(): dictionary = ["DAMP", "DICE", "DUKE", "LIKE", "LAMP", "LIME", "DIME", "LIMP"] start = "DAMP" stop = "LIKE" path = transform(start, stop, dictionary) assert path == ["DAMP", "LAMP", "LIMP", "LIME", "LIKE"]
true
3ffc5634c94e6acf7288dd2666776c87e639de51
Python
max-sixty/xarray
/xarray/core/dask_array_compat.py
UTF-8
2,383
2.671875
3
[ "Apache-2.0", "BSD-3-Clause", "CC-BY-4.0", "Python-2.0" ]
permissive
import warnings import numpy as np try: import dask.array as da except ImportError: da = None # type: ignore def _validate_pad_output_shape(input_shape, pad_width, output_shape): """Validates the output shape of dask.array.pad, raising a RuntimeError if they do not match. In the current versions of dask (2.2/2.4), dask.array.pad with mode='reflect' sometimes returns an invalid shape. """ isint = lambda i: isinstance(i, int) if isint(pad_width): pass elif len(pad_width) == 2 and all(map(isint, pad_width)): pad_width = sum(pad_width) elif ( len(pad_width) == len(input_shape) and all(map(lambda x: len(x) == 2, pad_width)) and all(isint(i) for p in pad_width for i in p) ): pad_width = np.sum(pad_width, axis=1) else: # unreachable: dask.array.pad should already have thrown an error raise ValueError("Invalid value for `pad_width`") if not np.array_equal(np.array(input_shape) + pad_width, output_shape): raise RuntimeError( "There seems to be something wrong with the shape of the output of dask.array.pad, " "try upgrading Dask, use a different pad mode e.g. mode='constant' or first convert " "your DataArray/Dataset to one backed by a numpy array by calling the `compute()` method." "See: https://github.com/dask/dask/issues/5303" ) def pad(array, pad_width, mode="constant", **kwargs): padded = da.pad(array, pad_width, mode=mode, **kwargs) # workaround for inconsistency between numpy and dask: https://github.com/dask/dask/issues/5303 if mode == "mean" and issubclass(array.dtype.type, np.integer): warnings.warn( 'dask.array.pad(mode="mean") converts integers to floats. xarray converts ' "these floats back to integers to keep the interface consistent. There is a chance that " "this introduces rounding errors. If you wish to keep the values as floats, first change " "the dtype to a float before calling pad.", UserWarning, ) return da.round(padded).astype(array.dtype) _validate_pad_output_shape(array.shape, pad_width, padded.shape) return padded if da is not None: sliding_window_view = da.lib.stride_tricks.sliding_window_view else: sliding_window_view = None
true
676b619cd44850b291e63108f6ba9352087f113e
Python
itaykbn/oop-class-assignment-1-zvika
/circle.py
UTF-8
262
3.40625
3
[]
no_license
from shape import Shape import math class Circle(Shape): def __init__(self, radius): self.radius = radius def perimeter(self): return 2 * math.pi * self.radius def area(self): return math.pi * (self.radius * self.radius)
true
a6f66005b3172974d3d2acb82a0161f4ed235483
Python
mjn-at/myNeuralNetwork
/coloredArray.py
UTF-8
189
2.96875
3
[]
no_license
""" creates a colored output of an array """ import numpy as np import matplotlib.pyplot as plt a = np.random.rand(3,3) - 0.5 print(a) plt.imshow(a, interpolation="nearest") plt.show()
true
0b246ecd2cdcf847cedd948a5e94adffa884cefb
Python
94akshayraj/AI-program
/ML ans/day3/MLR4.py
UTF-8
616
2.828125
3
[]
no_license
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error,mean_absolute_error data = pd.read_csv("/Users/spacslug/ML-Day1/ML ans/day3/data_mruder.txt") data = data.as_matrix() print (data) X = data[:,[1,2,3]] y = data[:,4] X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2) lr = LinearRegression() lr.fit(X_train,y_train) p = lr.predict(X_test) print(mean_absolute_error(y_test,p)) print(mean_squared_error(y_test,p)) print(np.sqrt(mean_squared_error(y_test,p)))
true
a6866311bb766c70271ee265f601afe57f54ae11
Python
lilianluong16/cogworks_team4
/songfp/fingerprinting.py
UTF-8
4,878
3.265625
3
[]
no_license
# This file contains functions for: # song fingerprinting (finding peaks) # fingerprint comparision (comparing peaks to those looked up in the database_ # determining the best match for a song sample # determining whether the best match is sufficient to identify the song import numpy as np import itertools import collections from scipy.ndimage.filters import maximum_filter from scipy.ndimage.morphology import generate_binary_structure, binary_erosion from scipy.ndimage.morphology import iterate_structure def find_peaks(song, freqs): """ Find the peaks in the two-dimensional array that describes a song Parameters: ---------- song: numpy.ndarray (MxN) the two dimensional array of Fourier-constants describing the song song[i,j] is the magnitude of the Fourier-constant for frequency i at time j Returns: -------- peaks: binary array (MxN) the binaray "mask" that identifies the locations of peaks peaks[i,j] is True if there is a local peak for frequency i at time j """ #generates proper neighborhood struct = generate_binary_structure(2, 1) neighborhood = iterate_structure(struct, 25) # this incorporates roughly 20 nearest neighbors #finds foreground ys, xs = np.histogram(song.flatten(), bins=len(freqs)//2, normed=True) dx = xs[-1] - xs[-2] cdf = np.cumsum(ys)*dx # this gives you the cumulative distribution of amplitudes cutoff = xs[np.searchsorted(cdf, 0.77)] foreground = (song >= cutoff) #generates boolean array of peaks that are both peaks and in the foreground peaks = np.logical_and((song == maximum_filter(song, footprint=neighborhood)), foreground) return peaks # In[82]: def find_fingerprint(peaks, freqs, times): """ Find the features (which are each a tuple of two peaks and the distance between them) of a song based on its peaks Parameters: ---------- peaks: binary array (MxN) the binary "mask" that identifies the locations of peaks peaks[i,j] is True if there is a local peak for frequency i at time j freqs: float array (MxN) the array in which freqs[k] is the real value of the frequency value in bin k times: float array (MxN) the array in which time[k] is the real value of the time value in bin k Returns: -------- song_fp: list of tuples (arbitrary length, all peaks in the song) the list of of tuples tuples of length three, each containing with two peaks and the distance between the two peaks of the form ((f1,f2,delta t), t1) """ song_fp_t = [] indices = np.argwhere(peaks == True)[::-1] comparisons = itertools.combinations(indices, 2) threshold = 30 filtered = itertools.filterfalse(lambda x: abs(x[1][1] - x[0][1]) > threshold, comparisons) for (f1, t1), (f2, t2) in filtered: song_fp_t.append(tuple([tuple([int(freqs[f1]), int(freqs[f2]), int(abs(t2 - t1))]), int(t1)])) return song_fp_t def get_matches(sample_fp_t, db): """ Find the features (which are each a tuple of two peaks and the distance between them) of a song based on its peaks Parameters: ---------- sample_fp: list of tuples (arbitrary length, all peaks in the sample) the list of tuples of length three, each containing with two peaks and the distance between the two peaks db: dictionary the dictionary with features as keys and song names as values Returns: -------- matches: list of tuples of song ids and time differences the list of song ids in the database that share features with the supplied sample and the amount of time between the feature occuring in the sample and in the """ matches = [] for feature, time in sample_fp_t: if feature in db: #feat[0] is the actual finger print of the form (f1,f2,delta t) match = db.get(feature) matches += [(match[x][0], int(match[x][1] - time)) for x in np.arange(len(match)) if int(match[x][1] - time) >= 0] #feat[1] is the time at which the feature occurs return matches def best_match(matches, displayc=False): """ Find the features (which are each a tuple of two peaks and the distance between them) of a song based on its peaks Parameters: ---------- matches: list of song names the list of song names in the database that share features with the supplied sample Returns: -------- best_match: song name the song name that occurs the most frequently in the list """ if len(matches) < 1: return None c = collections.Counter([x for x in matches]) if displayc: print(c) print(c.most_common(1)) threshold = 15 if c.get(c.most_common(1)[0][0]) < threshold: return None return c.most_common(1)[0][0][0]
true
464387a027a2592119b5dffc3e6b548b04ad2fdc
Python
stevekutz/py_graph_app
/plotdata3.py
UTF-8
996
3.25
3
[]
no_license
import numpy as np from scipy.interpolate import UnivariateSpline from matplotlib import pyplot as plt # generate data samples # data = scipy.stats.expon.rvs(loc=0, scale=1, size=1000, random_state=123) # define empty list data_list = [] # open file and read the content in a list with open('result_5000.txt', 'r') as f: filecontents = f.readlines() for line in filecontents: # remove linebreak which is the last character of the string val = line[:-1] # add item to the list # data.append(int(val)) data_list.append(float(val)) data = np.array(data_list) import numpy as np from scipy.interpolate import UnivariateSpline from matplotlib import pyplot as plt N = 1000 n = N//10 s = np.random.normal(size=N) # generate your data sample with N elements p, x = np.histogram(s, bins=n) # bin it into n = N//10 bins x = x[:-1] + (x[1] - x[0])/2 # convert bin edges to centers f = UnivariateSpline(x, p, s=n) plt.plot(x, f(x)) plt.show()
true
5d2b87039571ef3701b6262ae0eda8853a00cbbd
Python
ShantNarkizian/Distributed-sharded-kvstore
/test_assignment3_v2.py
UTF-8
12,641
2.6875
3
[]
no_license
import unittest import requests import time import os ######################## initialize variables ################################################ subnetName = "assignment3-net" subnetAddress = "10.10.0.0/16" replica1Ip = "10.10.0.2" replica1HostPort = "8082" replica1SocketAddress = replica1Ip + ":8080" replica2Ip = "10.10.0.3" replica2HostPort = "8083" replica2SocketAddress = replica2Ip + ":8080" replica3Ip = "10.10.0.4" replica3HostPort = "8084" replica3SocketAddress = replica3Ip + ":8080" view = replica1SocketAddress + "," + replica2SocketAddress + "," + replica3SocketAddress ############################### Docker Linux Commands ########################################################### def removeSubnet(subnetName): command = "docker network rm " + subnetName os.system(command) time.sleep(2) def createSubnet(subnetAddress, subnetName): command = "docker network create --subnet=" + subnetAddress + " " + subnetName os.system(command) time.sleep(2) def buildDockerImage(): command = "docker build -t assignment3-img ." os.system(command) def runReplica(hostPort, ipAddress, subnetName, instanceName): command = "docker run -d -p " + hostPort + ":8080 --net=" + subnetName + " --ip=" + ipAddress + " --name=" + instanceName + " -e SOCKET_ADDRESS=" + ipAddress + ":8080" + " -e VIEW=" + view + " assignment3-img" os.system(command) time.sleep(20) def stopAndRemoveInstance(instanceName): stopCommand = "docker stop " + instanceName removeCommand = "docker rm " + instanceName os.system(stopCommand) time.sleep(2) os.system(removeCommand) ################################# Unit Test Class ############################################################ class TestHW3(unittest.TestCase): ######################## Build docker image and create subnet ################################ print("###################### Building Dokcer image ######################\n") # build docker image buildDockerImage() ########################## Run tests ####################################################### def test_a_view_operations(self): # stop and remove containers from possible previous runs print("\n###################### Stopping and removing containers from previous run ######################\n") stopAndRemoveInstance("replica1") stopAndRemoveInstance("replica2") stopAndRemoveInstance("replica3") print("\n###################### Creating the subnet ######################\n") # remove the subnet possibly created from the previous run removeSubnet(subnetName) # create subnet createSubnet(subnetAddress, subnetName) #run instances print("\n###################### Running replicas ######################\n") runReplica(replica1HostPort, replica1Ip, subnetName, "replica1") runReplica(replica2HostPort, replica2Ip, subnetName, "replica2") runReplica(replica3HostPort, replica3Ip, subnetName, "replica3") # This operation checks that after each replica is spun up it knows the other replica's # IPs/Ports in it's view. # View-Get print("\n###################### Getting the view from replicas ######################\n") # get the view from replica1 response = requests.get( 'http://localhost:8082/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], view) # get the view from replica2 response = requests.get( 'http://localhost:8083/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], view) # get the view from replica3 response = requests.get( 'http://localhost:8084/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], view) # This operation puts a key:value in replica1. And wants a 201 to be returned. # Client-Key-Value-Put print("\n###################### Putting key1/value1 to the store ######################\n") # put a new key in the store response = requests.put('http://localhost:8082/key-value-store/key1', json={'value': "value1"}) self.assertEqual(response.status_code, 201) # We wait 10 seconds for the replica1 to broadcast its Put to replica2 and replica3 # Replica-Key-Value-Put print("\n###################### Waiting for 10 seconds ######################\n") time.sleep(10) # This operation does a client-get to all replicas to make sure the key:value from above # was sent and recieved by all replicas. # Client-Key-Value-Get print("\n###################### Getting key1 from the replicas ######################\n") # get the value of the new key from replica1 after putting the new key response = requests.get('http://localhost:8082/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['value'], 'value1') # get the value of the new key from replica2 after putting the new key response = requests.get('http://localhost:8083/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['value'], 'value1') # get the value of the new key from replica3 after putting the new key response = requests.get('http://localhost:8084/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['value'], 'value1') ######################################################################################################## # CUSTOM TEST *******DELETE KEY************** response = requests.delete('http://localhost:8082/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 200) print("\n###################### Getting key1 from the replicas after delete ######################\n") # get the value of the new key from replica1 after putting the new key response = requests.get('http://localhost:8082/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 404) # get the value of the new key from replica2 after putting the new key response = requests.get('http://localhost:8083/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 404) # get the value of the new key from replica3 after putting the new key response = requests.get('http://localhost:8084/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 404) ##################################################################################################### print("\n###################### Stopping and removing replica3 ######################\n") stopAndRemoveInstance("replica3") print("\n###################### Waiting for 10 seconds ######################\n") time.sleep(10) # This operation adds a key:value to replica1. We need to send it only to replica2 because # replica3 is gone. (We may use this action to update the view or we might just use a heartbeat) # Client-Key-Value-Put print("\n###################### Putting key2/value2 to the store ######################\n") # put a new key in the store response = requests.put('http://localhost:8082/key-value-store/key2', json={'value': "value2"}) self.assertEqual(response.status_code, 201) # Replica-Key-Value-Put print("\n###################### Waiting for 50 seconds ######################\n") time.sleep(50) # After waiting a sufficient amount of time for replication of data we check to make sure it worked # properly. # Client-Key-Value-Get print("\n###################### Getting key2 from the replica1 and replica2 ######################\n") # get the value of the new key from replica1 after putting the new key response = requests.get('http://localhost:8082/key-value-store/key2') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['value'], 'value2') # get the value of the new key from replica2 after putting the new key response = requests.get('http://localhost:8083/key-value-store/key2') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['value'], 'value2') # By this time replica1 and replica2's view should reflect the fact replica3 has crashed. # View-Delete print("\n###################### Getting the view from replica1 and replica2 ######################\n") # get the view from replica1 response = requests.get( 'http://localhost:8082/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], replica1SocketAddress + "," + replica2SocketAddress) # get the view from replica2 response = requests.get( 'http://localhost:8083/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], replica1SocketAddress + "," + replica2SocketAddress) print("\n###################### Starting replica3 ######################\n") runReplica(replica3HostPort, replica3Ip, subnetName, "replica3") print("\n###################### Waiting for 50 seconds ######################\n") time.sleep(50) # After we have restarted replica3 replica1 and replica2 should be aware that a new replica # has appeared and added it to their view. # View-Put print("\n###################### Getting the view from replicas ######################\n") # get the view from replica1 response = requests.get( 'http://localhost:8082/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], view) # get the view from replica2 response = requests.get( 'http://localhost:8083/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], view) # get the view from replica3 response = requests.get( 'http://localhost:8084/key-value-store-view') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['view'], view) # Replica3 was spun up with no knowledge of value:value1 and value:value2 so it needs to receive # the data from another replica. (We haven't spoken about this case yet. Maybe if we determine # a View-Put is necessary we can figure out which replica is new and send a series of Replica-Key-Value-Puts). # Client-Key-Value-Get print("\n###################### Getting key1 and key2 from replica3 ######################\n") # get the value of one of the keys from replica3 response = requests.get('http://localhost:8084/key-value-store/key1') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['value'], 'value1') # get the value of one of the keys from replica3 response = requests.get('http://localhost:8084/key-value-store/key2') responseInJson = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(responseInJson['value'], 'value2') # Client-Key-Value-Delete Test # Replica-Key-Value-Delete Test # (Maybe) Crash 2 replicas and restart them, then check consistency test # Spam Client-Key-Value-Put to test buffer (not sure if there is a real way to check buffer functionality) if __name__ == '__main__': unittest.main()
true
a134ebfec6e5f511d03b247240f9ce41c38bda39
Python
juoyi/linshi_demo
/bubble_demo.py
UTF-8
1,188
4.1875
4
[]
no_license
def bubble_sort(li): """ 冒泡排序: 每次都是相邻两个元素之间进行比较,较大者置后,一次大循环过后会将最大者放到最后,同时参与比较的数字减一 :param li: :return: """ for i in range(len(li)-1): # 外层循环,控制循环次数 for j in range(0, len(li)-1-i): # 内层循环,负责控制元素下标 if li[j] > li[j+1]: li[j], li[j+1] = li[j+1], li[j] return li def bubble_sub(li=[]): """ 排序思想: 第一次循环以第一个数为基准,依次与后面的所有数进行比较,如果后面的数比第一个小,就交换两者的位置,即:将较小数提前, 一次循环过后,数组中的最小数处于第一个位置 第二次循环会将数组中第二小的数放在第二个位置 以此类推 """ for i in range(len(li)-1): # 从第一个到倒数第二个数 for j in range(i+1, len(li)): # 从第二个数到最后一个数 if li[i] > li[j]: li[i], li[j] = li[j], li[i] return li if __name__ == '__main__': new_li = bubble_sort(li=[9,5,6,3,8,2,7,1,66,43]) print(new_li)
true
9efbe24b0ea50afc6729b05de7ebc04e929cd788
Python
dprpavlin/OuterBilliards
/ZoneRealPolygonsFor12Gon.py
UTF-8
6,378
2.671875
3
[]
no_license
from workWith12Gon import * from point2D import * from segmentIntersection import * from billiard import * from absqrtn import * from fractions import * import pygame, sys from pygame.locals import * def makeColorFromHash(h): r = h % 256 h /= 256 g = h % 256 h /= 256 b = h % 256 return (r, g, b) def inputEvents(events): for event in events: if (event.type == QUIT) or (event.type == KEYDOWN and event.key == K_ESCAPE): sys.exit(0) else: pass def waitEnd(): print('waiting for end', file=sys.stderr) while 1: inputEvents(pygame.event.get()) if __name__ == '__main__': pygame.init() size_x = 512 size_y = 512 * 4 window = pygame.display.set_mode((size_x, size_y)) pygame.display.set_caption('My own little world') screen = pygame.display.get_surface() c0 = MyPoint(Fraction(20), Fraction(-360)) c1 = MyPoint(Fraction(20), Fraction(20)) polygon = Get12gonFromSegment(c0, c1) DrawMyPolygon(screen, polygon, (0, 0, 120), 0) #DrawRayMyPoint(screen, MyPoint(Fraction(256), Fraction(256)), MyPoint(Fraction(1512), Fraction(512)), (0, 0, 120), 0) raysColor = (57, 179, 218) #print('polygon: ', polygon) DrawRayMyPoint(screen, polygon[0], polygon[1], raysColor, 1) DrawRayMyPoint(screen, polygon[1], polygon[2], raysColor, 1) DrawRayMyPoint(screen, polygon[3], polygon[2], raysColor, 1) DrawRayMyPoint(screen, polygon[4], polygon[3], raysColor, 1) DrawRayMyPoint(screen, polygon[5], polygon[4], raysColor, 1) DrawRayMyPoint(screen, polygon[6], polygon[5], raysColor, 1) firstComponent = getFirstComponent(polygon) #DrawMyPolygon(screen, firstComponent, (21, 43, 49), 0) zones = getZonesFrom12Gon(polygon) #print('Zones...: zones = ', zones) stableZones = getStableZonesFrom12Gon(polygon, zones) '''superPolygon = firstComponent.copy() polygons = splitGoodPolygonByZones(superPolygon, polygon, zones) for i in range(len(polygons)): DrawMyPolygon(screen, polygons[i], ((148 + 350*i) % 256, (462 + 240*i)%256, (78 + 60*i)%256), 0) pygame.display.flip() waitEnd() ''' for i in range(0, 4): DrawMyPolygon(screen, stableZones[i], ((148 + 350*i) % 256, (462 + 120*i)%256, (78 + 60*i)%256), 0) pygame.display.flip() center = (polygon[0] + polygon[6]) * MyCipher(Fraction(1, 2)) DrawPoint(screen, center, (234, 56, 78), 2) ukp = lineIntersection(polygon[1], polygon[2], polygon[6], polygon[5]) newc = reflect(center, ukp) DrawPoint(screen, ukp, (140, 20, 70), 3) newnewc = GetCenter(stableZones[0]) newmidc = GetCenter(stableZones[3]) pygame.display.flip() superPolygon = getFirstComponent(polygon) #superPolygon = getFirstComponent(polygon).copy() #for i in range(len(superPolygon)): # superPolygon[i] = polygon[1] + (superPolygon[i] - polygon[1]) * (newmidc.GetX() - polygon[1].GetX()) / (newc.GetX() - polygon[1].GetX()) for i in range(len(superPolygon)): superPolygon[i] = polygon[1] + (superPolygon[i] - polygon[1]) * (newnewc.GetX() - polygon[1].GetX()) / (newc.GetX() - polygon[1].GetX()) DrawMyPolygon(screen, superPolygon, (255, 255, 0), 0) pygame.display.flip() pygame.display.flip() pygame.image.save(screen, 'testSave.bmp') waitEnd() polygons = [zones[0], zones[1], zones[2]] num = 0 for i in range(1, len(stableZones[3])): if stableZones[3][i].GetY() < stableZones[3][num].GetY(): num = i tmp = [stableZones[3][num-1], stableZones[3][num-2], lineIntersection(polygon[0], polygon[1], polygon[5], polygon[4]) ] polygons.append(tmp) tmp = [lineIntersection(polygon[1], polygon[2], polygon[5], polygon[4]), stableZones[3][num - len(stableZones[3])], stableZones[3][num + 1 - len(stableZones[3])], stableZones[3][num + 2 - len(stableZones[3])] ] polygons.append(tmp) hps = tryMakeFirstReturnMap([superPolygon], superPolygon, polygon, zones, 20000) print('LENGTH: ', len(hps[0]), len(hps[1])) #for hp in hps[0]: #print(hp) # print(len(hp[0])) # DrawMyPolygon(screen, hp[0], (255, 0, 0), 1, makeColorFromHash(hp[1])) #print('=====') #for hp in hps[1]: #print(hp) # DrawMyPolygon(screen, hp[0], (0, 0, 255), 1, makeColorFromHash(hp[1])) print(len(hps[0]), ", ", len(hps[1])) print(len(hps[0]), ", ", len(hps[1]), file=sys.stderr) """for (int i = 0; i < (int)hps.first.size(); ++i) { PaintStarPolygonInner(screen, hps.first[i].first, 462 + 10*i, 98 + 20*i, 78 + 70*i, 0); DrawMyPolygon(screen, hps.first[i].first, 148 + 350*i, 20 + 120*i, 70 + 140*i, 0); } for (int i = 0; i < (int)hps.second.size(); ++i) { PaintStarPolygonInner(screen, hps.second[i].first, 148 + 10*i, 20*i, 70*i, 0); DrawMyPolygon(screen, hps.second[i].first, 112 + 350*i, 32 + 120*i, 253 + 140*i, 2); }""" print("FirstReturnMap To found\n") pols = [] #std::vector<MyPolygon> pols; for i in range(len(hps[0])): print('polygon', i) print(len(hps[0][i][0]), ":") for j in range(len(hps[0][i][0])): print(' ', hps[0][i][0][j]) print('end of polygon', i) pols.append(hps[0][i][0]) print('===================\n') starts = reverseAndTestZones(pols, superPolygon, polygon, zones) for i in range(len(starts)): print('reverse polygon ', i) print(starts[i][0], ';', starts[i][1]) for j in range(len(starts[i][0])): print(' ', starts[i][0][j]) print('end of reverse polygon ', i) for i in range(len(starts)): sys.stderr.write(str(i) + ' polygons painted from ' + str(len(starts)) + '\n') DrawMyPolygon(screen, starts[i][0], ((462+10*i)%256, (98+20*i)%256, (78+70*i)%256), 1, ((148+350*i)%256, (20+120*i)%256, (70+140*i)%256)) #for (int i = 0; i < (int)starts.size(); ++i) { # PaintStarPolygonInner(screen, starts[i].first, 462 + 10*i, 98 + 20*i, 78 + 70*i, 0); # DrawMyPolygon(screen, starts[i].first, 148 + 350*i, 20 + 120*i, 70 + 140*i, 0); #} pygame.display.flip() pygame.image.save(screen, 'testSave.bmp') #waitEnd()
true
39b4bc563539efd781d04a2617a4702da5abf97d
Python
CircuitBreaker437/PythonGeneralTools
/double_linked_list.py
UTF-8
3,418
4.21875
4
[]
no_license
# Filename: double_linked_list.py # Programmer: Marcin Czajkowski # Revision: 4.0 - Final working version - fixed references to nodes in linked list # in removeNode() method # Purpose: The purpose of this script is to create a doubly linked list example. # The single linked list can be achieved by removing the previous node reference. # Name: Node # Arguments: (object) - inhereting from object class # Purpose: This is a template for a node in a linked list class Node(object): #Constructor: def __init__(self, dataSet, next = None, prev = None): self.data = dataSet self.nextNode = next self.prevNode = prev #Getter for next node: def getNextNode (self): return self.nextNode #Setter for next node: def setNextNode (self, next): self.nextNode = next #Getter for previous node: def getPrevNode (self): return self.prevNode #Setter for previous node: def setPrevNode (self, prev): self.prevNode = prev #Getter for data: def getData (self): return self.data #Setter for data: def setData (self, dataSet): self.data = dataSet # Name: LinkedList # Arguments: (object) - inhereting from object class # Purpose: This class holds methods for LinkedList controls (getSize, addNode, removeNode, findNode) class LinkedList (object): #Constructor: def __init__(self, rootNode = None): self.root = rootNode self.size = 0 def getSize (self): return self.size def addNode (self, dataSet): newNode = Node (dataSet, self.root) if (self.root): self.root.setPrevNode(newNode) self.root = newNode self.size += 1 def removeNode (self, dataSet): thisNode = self.root while (thisNode): if thisNode.getData() == dataSet: next = thisNode.getNextNode() prev = thisNode.getPrevNode() if (next): next.setPrevNode(prev) if (prev): prev.setNextNode(next) else: self.root = thisNode self.size -= 1 #Confirmed that node was removed return True else: thisNode = thisNode.getNextNode() #Could not find the specified data - nothing removed return False def findNode (self, dataSet): thisNode = self.root while (thisNode): if (thisNode.getData() == dataSet): return dataSet else: thisNode = thisNode.getNextNode() return None #Testing print('Creating new list...') newList = LinkedList() print('Adding new node with data = 10 ...') newList.addNode(10) print('Adding new node with data = 20 ...') newList.addNode(20) print('Adding new node with data = 30 ...') newList.addNode(30) print('Adding new node with data = 40 ...') newList.addNode(40) print('Adding new node with data = 50 ...') newList.addNode(50) print('Adding new node with data = 60 ...') newList.addNode(60) print('Current list size is: ' + str(newList.getSize())) print('Removing node with data = 20. Node removed: ' + str(newList.removeNode(20))) print('Current list size is: ' + str(newList.getSize())) print('Removing node with data = 10. Node removed: ' + str(newList.removeNode(10))) print('Removing node with data = 20. Node removed: ' + str(newList.removeNode(20))) print('Current list size is: ' + str(newList.getSize())) print('Searching for node with data = 5: ' + str(newList.findNode(5))) print('Searching for node with data = 50: ' + str(newList.findNode(50)))
true
364e2a85707fb780a42ce1f18a0cfea7322b1107
Python
e3561025/pythonWebCatch
/exerciseTest/20190319test2.py
UTF-8
518
2.734375
3
[]
no_license
import tkinter as tk import numpy from tkinter import ttk root = tk.Tk() root.title('wnacg-download') root.geometry('200x200') #root.resizable() #禁止使用者調整大小 label = ttk.Label(root,text='hello world') label.pack() #pack是由上往下擺放 #label.grid(column=0,row=0) count=0 def clickOK(): global count count = count+1 label.configure(text='Click OK '+str(count)+' times') button = ttk.Button(root,text='OK',command=clickOK) button.pack() #button.grid(column=1,row=0) root.mainloop()
true
a6083db1f4b6789639e8a92bd306ec7eb79d6149
Python
lanzhiwang/common_algorithm
/sort/06_heap_sort/04.py
UTF-8
1,179
4.34375
4
[]
no_license
""" https://www.cnblogs.com/chenkeyu/p/7505637.html 在最小化堆中取出最小值: 在最小堆中,拿出一个最小值,也就是拿出第一个数 然后把最后一个数放到头的位置,这样树的结构就不会改变,而且操作简单 最后调整最小堆 原始最小堆:[1, 6, 4, 8, 7, 6, 5, 13, 12, 11] """ # 最小堆 def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] < unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] < unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) if __name__ == '__main__': # 1 6 4 8 7 6 5 13 12 11 min_heap = [1, 6, 4, 8, 7, 6, 5, 13, 12, 11] min = min_heap[0] print(min) min_heap[0] = min_heap.pop(-1) print(min_heap) # [11, 6, 4, 8, 7, 6, 5, 13, 12] heapify(min_heap, 0, len(min_heap)) print(min_heap) # [4, 6, 5, 8, 7, 6, 11, 13, 12]
true
3cdd1b579b41a0ea602f0a6eea9de2bfca3bf87b
Python
facelessg00n/BerlaTools
/berlaJoin.py
UTF-8
4,088
2.984375
3
[]
no_license
""" facelessg00n 2020 Made in Australia Imports data from CSV files output from BERLA iVE Outputs files for contact, calls and SMS data Device name and details added to contact, call and SMS files for easier analysis timestamps normalised Formatted with Black """ import os import pandas as pd import tqdm print("Berla format conversion\n") # --- Functions--- def timeConversion(inputPD): z = inputPD.keys().tolist() if "StartTime" in z: inputPD.rename(columns={"StartTime": "Orig_Timestamp"}, inplace=True) inputPD["StartTime"] = pd.to_datetime( inputPD["Orig_Timestamp"], errors="ignore", format="%m/%d/%Y %I:%M:%S.%f %p" ) return inputPD elif "DateTime" in z: inputPD.rename(columns={"DateTime": "Orig_Timestamp"}, inplace=True) inputPD["DateTime"] = pd.to_datetime( inputPD["Orig_Timestamp"], errors="ignore", format="%m/%d/%Y %I:%M:%S.%f %p" ) return inputPD else: print("else") raise invalidFile("Invalid input file") class invalidFile(Exception): pass # --- Import Files---- fileList = os.listdir(os.getcwd()) for x in tqdm.tqdm(fileList, desc="Loading files"): if x.endswith("Contact.csv"): contactPD = pd.read_csv(x) elif x.endswith("Attached Device.csv"): devicePD = pd.read_csv(x) elif x.endswith("Call Log.csv"): callLogPD = pd.read_csv(x) elif x.endswith("SMS.csv"): smsPD = pd.read_csv(x) else: pass outputFiles = [] # ----Format Contacts--- try: contactConvert = pd.merge( devicePD, contactPD, left_on=["UniqueNumber"], right_on=["DeviceIdentifier"], how="inner", ) contactConvert = contactConvert[ [ "UniqueString_x", "DeviceName", "DeviceIdentifier", "DeviceType", "Manufacturer", "Model", "UniqueString_y", "FirstName", "LastName", "Company", "PhoneNumber", "WorkNumber", "HomeNumber", "MobileNumber", "Email", ] ] outputFiles.append([contactConvert, "contactConvert"]) except: pass # -----Format calls---- try: callConvert = pd.merge( devicePD, callLogPD, left_on=["UniqueNumber"], right_on=["DeviceIdentifier"], how="inner", ) callConvert = timeConversion(callConvert) callConvert = callConvert[ [ "UniqueString_x", "DeviceName", "DeviceIdentifier", "DeviceType", "UniqueString_y", "OffsetApplied_x", "StartTime", "Orig_Timestamp", "PhoneNumber", "ContactName", "FlagsString_y", "TimestampType_y", ] ] outputFiles.append([callConvert, "callConvert"]) except: pass # ---Format SMS messages----- try: smsConvert = pd.merge( devicePD, smsPD, left_on=["UniqueNumber"], right_on=["DeviceIdentifier"], how="inner", ) smsConvert = timeConversion(smsConvert) smsConvert = smsConvert[ [ "UniqueString_x", "DeviceName", "DeviceType", "UniqueNumber", "Manufacturer", "InterfaceType", "OffsetApplied_x", "Orig_Timestamp", "DateTime", "To", "From", "Name", "Body", "ReadStatus", "UniqueString_y", "TimestampType_y", "TimestampConfidence_y", "NetOffset_y", ] ] smsConvert.rename(columns={"UniqueString_y": "UniqueString_SMS"}, inplace=True) outputFiles.append([smsConvert, "smsConvert"]) except: pass # Write out CSV files. for x in tqdm.tqdm(outputFiles, desc="Writing files"): x[0].to_csv("%s.csv" % x[1], index=False, date_format="%Y/%m/%d %H:%M:%S") print("\nComplete")
true
46b54cc8da3d5da66df7aad869fbd2168c1d4cde
Python
siddharthadtt1/Leet
/142-linked-list-cycle.py
UTF-8
709
3.546875
4
[]
no_license
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: #raise Exception('Linked list has less than two nodes') return None slow, fast = head.next, head.next.next while slow and fast and fast.next and slow != fast: slow = slow.next fast = fast.next.next # no cycle if slow != fast: return None # has the cycle, find the entrance of the circle. See Leet 287 slow = head while slow != fast: slow = slow.next fast = fast.next return slow
true
c9045316bf411632469bf91843337d99816e8e81
Python
kailash-manasarovar/GCSE_code
/gui_examples/exercise3.py
UTF-8
1,212
3.921875
4
[]
no_license
# CODE for EXERCISE 3 # ------------------- # This exercise introduces # * Difference border styles # * Pack options: side, fill, expand # # The aim of this exercise is to explore layout from tkinter import * import random app = Tk() # Create the top-level window app.title("GUI Example 3") # OPTIONALLY set the title # Borders and Background (many widgets, including Frames) # ---------------------- # bd - border width # Relief - border style (FLAT, RAISED, GROOVE, SUNKEN, RIDGE) # - FLAT (default) no border shows # # bg - background colour # bA = Label(app, text="A", width=12, bg='red', relief=GROOVE, bd=5) bB = Label(app, text="B", width=12, bg='yellow') bC = Label(app, text="C", width=12, bg='blue') bD = Label(app, text="D", width=12, bg='white') # Pack arguments # --------------- # # Fill: does the widget fill the space given to it # fill=Y # fill=X # fill=BOTH # # Expand: is more space give to widget, by its parent? # expand=0 (default) no epxansion # expand=1 expand - number gives relative expansion bA.pack(side='top',fill=X, expand=1) bB.pack(side='bottom') bC.pack(side='left', fill=Y, expand=1) bD.pack(side='right') app.mainloop() # Start the main loop
true
daadef673408a8771a21de3cca75173f3dc39884
Python
sunshineplan/web-crawler
/crawler/lib/output.py
UTF-8
586
2.71875
3
[]
no_license
#!/usr/bin/python3 # coding:utf-8 import os from csv import DictWriter def saveCSV(filename, fieldnames, content, path=''): path = path.strip('"') if path != '': if os.name == 'nt': path = path + '\\' else: path = path + '/' fullpath = path + filename fullpath = os.path.abspath(fullpath) with open(fullpath, 'w', encoding='utf-8-sig', newline='') as output_file: output = DictWriter(output_file, fieldnames, extrasaction='ignore') output.writeheader() output.writerows(content) return fullpath
true
37b1ef7321447f2952692f053c27f29358606548
Python
eduardogpg/flask_twitter
/app/__init__.py
UTF-8
424
2.703125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import app_config __author__ = 'Eduardo Ismael García Pérez' db = SQLAlchemy() def create_app(config_name): print "Enviroment " + config_name app = Flask(__name__) app.config.from_object(app_config[config_name]) db.init_app(app) @app.route('/') def index(): return "Hola Mundo desde un paquete!" return app
true
b3b44f0f317e4344183f8299b48830c36a78fa2e
Python
raymondlee00/softdev
/fall/17_csv2db/db_builder.py
UTF-8
1,686
2.890625
3
[]
no_license
#ray. lee. and junhee lee #SoftDev #skeleton :: SQLITE3 BASICS #Oct 2019 import sqlite3 #enable control of an sqlite database import csv #facilitate CSV I/O DB_FILE="discobandit.db" db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() #facilitate db ops # with open('students.csv', newline='') as studentscsvfile: # studentscsvreader = csv.DictReader(studentscsvfile) # for row in studentscsvreader: # print(row['name'], row['age'], row['id']) #========================================================== # < < < INSERT YOUR POPULATE-THE-DB CODE HERE > > > command = "CREATE TABLE IF NOT EXISTS courses(code TEXT, mark INTEGER, id INTEGER)" # test SQL stmt in sqlite3 shell, save as string c.execute(command) with open('courses.csv', newline='') as coursescsvfile: coursescsvreader = csv.DictReader(coursescsvfile) for row in coursescsvreader: print(row['code'], row['mark'], row['id']) c.execute("INSERT INTO courses VALUES (\"{}\", {}, {});".format(row['code'], row['mark'], row['id'])) command = "CREATE TABLE IF NOT EXISTS table students(name TEXT, age INTEGER, id INTEGER)" # test SQL stmt in sqlite3 shell, save as string c.execute(command) with open('students.csv', newline='') as studentscsvfile: studentscsvreader = csv.DictReader(studentscsvfile) for row in studentscsvreader: print(row['name'], row['age'], row['id']) c.execute("INSERT INTO students VALUES (\"{}\", {}, {});".format(row['name'], row['age'], row['id'])) #========================================================== db.commit() #save changes db.close() #close database
true
b92dddc6833efc2131302d090fe6d87523600396
Python
godspysonyou/everything
/alg/niukesuanfa/7_9checkcompletion.py
UTF-8
930
3.3125
3
[]
no_license
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class CheckCompletion: def chk(self, root): if not root: return False flag = False que = [] que.append(root) while(que): top = que.pop(0) if (top.left): que.append(top.left) if (top.right): que.append(top.right) if (not top.left and top.right): return False if (top.left and not top.right): if(flag): if(top.left or top.right): return False flag = True continue if(flag): if (top.left or top.right): return False return True if __name__ == '__main__': s = [1,2,3,4,5] s.remove(0) print(s)
true
e734096686293b08ba2a9a9995e7b46e295bbc11
Python
cherylchoon/soundcloud_clone
/apps/loginandreg/models.py
UTF-8
3,224
2.515625
3
[]
no_license
from __future__ import unicode_literals from django.db import models from django.contrib import messages from django.core.files.storage import FileSystemStorage from django.core.exceptions import ValidationError from django.core.validators import RegexValidator import bcrypt import datetime onlyLetters = RegexValidator(r'^[a-zA-Z ]+$', message='Must be letters only.') def validateLengthGreaterThanTwo(value): if len(value) < 3: raise ValidationError('Must be longer than 2 characters'.format(value)) class UserManager(models.Manager): def login(self, object): email = object['email'] password = object['password'] try: user = User.objects.get(email=email) pw_hash = bcrypt.hashpw(password.encode(), user.password.encode()) if pw_hash == user.password: return {'username': user.name, 'uid': user.id} except: return {'error': 'Username/Password does not match.'} def register(self, object, **kwargs): name = object['name'] email = object['email'] password = object['password'] age = object['age'] gender = object['gender'] pw_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt()) User.objects.create(name=name, email=email, password=pw_hash, age=age, gender=gender) user = User.objects.get(email=email) return {'uid': user.id, 'user_name':user.name} def update_user(self, info, files, **kwargs): confirm = info['confirm_current_password'] new_password = info['new_password'] new_pw_hash = bcrypt.hashpw(new_password.encode(), bcrypt.gensalt()) user = User.objects.get(id=info['updateid']) try: pw_hash = bcrypt.hashpw(confirm.encode(), user.password.encode()) if pw_hash == user.password: try: user.name = info['name'] user.gender = info['gender'] user.email = info['email'] user.password = new_pw_hash user.age = info['age'] user.image= files['picture'] user.description = info['description'] user.save() return {'success': 'User information has been updated!'} except: return {'error': 'ERROR'} except: return {'error': 'Username/Password does not match.'} class User(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other') ) name = models.CharField(max_length=55, validators=[validateLengthGreaterThanTwo, onlyLetters]) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) email = models.EmailField(null=True) password = models.CharField(max_length=100) age = models.IntegerField(null=True) image = models.FileField(upload_to='profileimage', default='profileimage/default-profile-picture.jpeg') description= models.TextField(max_length=2000, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager()
true
581d12cd0f32b5c6d9ad70afea17e2f27c161fda
Python
voltelxu/some
/word/word2labels.py
UTF-8
758
2.96875
3
[]
no_license
import re def word2lables(filename, outfile): file = open(filename, 'r') out = open(outfile, 'w+') data = "" for line in file: line = line.strip('\n') words = line.split(" ") for word in words: if len(word) < 3: continue if len(word) == 3: out.write(word + " S\n") data = data + word + " S\n" continue if len(word) > 3: for i in range(0, len(word), 3): if i == 0: out.write(word[i:3] + " B\n") data = data + word[i:3] + " B\n" elif i == len(word) - 3: out.write(word[i:i+3] + " E\n") data = data + word[i:i+3] + " E\n" else: out.write(word[i:i+3] + " M\n") data = data +word[i:i+3] + " M\n" #out.write(data) out.close() file.close() word2lables('data', 'lables')
true
a6032b68cc6712989d26898becc8b84b0864710c
Python
SongLepal/baekjoon.py
/5547.py
UTF-8
1,509
2.890625
3
[]
no_license
from sys import stdin from collections import deque ox = [ -1, -1, -1, 0, 1, 0] oy = [ -1, 0, 1, 1, 0, -1] ex = [ 0, -1, 0, 1, 1, 1] ey = [ -1, 0, 1, 1, 0, -1] def next(x, y, i): if y % 2 == 0: nx = x + ex[i] ny = y + ey[i] elif y % 2 == 1: nx = x + ox[i] ny = y + oy[i] return nx, ny def bfs_wall(): cnt = 0 while q: x, y = q.popleft() for i in range(6): nx, ny = next(x, y, i) if nx < 0 or ny < 0 or nx >= n or ny >= m: cnt += 1 continue if arr[nx][ny] == -1: cnt += 1 #continue return cnt def bfs_find(): while q: x, y = q.popleft() for i in range(6): nx, ny = next(x, y, i) if nx < 0 or ny < 0 or nx >= n or ny >= m: continue if arr[nx][ny] == 0: arr[nx][ny] = -1 q.append((nx, ny)) #continue n, m = map(int, stdin.readline().split()) _input = [] q = deque() for _ in range(m): _input.append(list(map(int, stdin.readline().split(' ')))) arr = list(map(list, zip(*_input))) for i in range(n): for j in range(m): if (i == 0 or j == 0 or (i + 1) == n or (j + 1) == m) and arr[i][j] == 0: arr[i][j] = -1 q.append((i, j)) bfs_find() for i in range(n): for j in range(m): if arr[i][j] == 1: q.append((i, j)) print(bfs_wall())
true